var coords=new Array();
$(document).ready(function(){
	if($("div.field:first input").attr("value")!="" && $("div.field:first textarea").attr("value")!=""){
		$("div.field:first label:first").addClass("invisible");
	}
	if($("div.field:last input").attr("value")!="" && $("div.field:last textarea").attr("value")!=""){
		$("div.field:last label:first").addClass("invisible");
	}
	$("div.field").bind("click", function() {
              fieldUpdate($(this));
			  if($(this).find("input").attr("id")=="login") 
			   { 
					$("#signup").css("opacity","1");					
					$("#loginreg").attr("value","");
					$("#loginreg").parent().find("label").removeClass("invisible");					
					$("#passreg").attr("value","");
					$("#passreg").parent().find("label").removeClass("invisible");					
					$("#passconfreg").attr("value","");
					$("#passconfreg").parent().find("label").removeClass("invisible");
					$("#kod").attr("value","");
					$("#kod").parent().find("label").removeClass("invisible");
					$("#loginreg").attr("disabled","disabled");
					$("#passreg").attr("disabled","disabled");
					$("#passconfreg").attr("disabled","disabled");
					$("#kod").attr("disabled","disabled");
					$("#login").attr("disabled","");
					$("#pass").attr("disabled","");
					$("#signin div[class!='rem']").css("opacity","0.2");
					$("#signin div[class='cb']").css("opacity","1");
					$("#signin span[class!='rem']").css("opacity","0.2");
			   }
			   if($(this).find("input").attr("id")=="loginreg") 
			   {
				   
					$("#signin div[class!='rem']").css("opacity","1");
					$("#signin span[class!='rem']").css("opacity","1");
					$("#signup").css("opacity","0.2");
					$("#login").attr("value","");
					$("#login").parent().find("label").removeClass("invisible");
					$("#pass").attr("value","");
					$("#pass").parent().find("label").removeClass("invisible");
					$("#loginreg").attr("disabled","");
					$("#passreg").attr("disabled","");
					$("#passconfreg").attr("disabled","");
					$("#kod").attr("disabled","");
					$("#login").attr("disabled","disabled");
					$("#pass").attr("disabled","disabled");
						
			   }
			    if($(this).find("input").attr("id")=="discountmax") 
			   {
				   $("#discountmax").attr("disabled","");
				   $("#price").attr("disabled","disabled");
				    $("#discount").attr("disabled","disabled");
					$("#disprice").attr("disabled","disabled");
					$("#discountmaxrub").attr("disabled","disabled");
					$("#distab").css("opacity","0.2");
					$("#divdismaxrub").css("opacity","0.2");
					$("#divdismax").css("opacity","1");
					$("#price").attr("value","");
				    $("#discount").attr("value","");
					$("#disprice").attr("value","");
					$("#discountmaxrub").attr("value","");
					$("#price").parent().find("label").removeClass("invisible");
					$("#discount").parent().find("label").removeClass("invisible");
					$("#disprice").parent().find("label").removeClass("invisible");
					$("#discountmaxrub").parent().find("label").removeClass("invisible");
					
			   }
			    if($(this).find("input").attr("id")=="discountmaxrub") 
			   {
				   $("#discountmaxrub").attr("disabled","");
				   $("#price").attr("disabled","disabled");
				    $("#discount").attr("disabled","disabled");
					$("#disprice").attr("disabled","disabled");
					$("#discountmax").attr("disabled","disabled");
					$("#distab").css("opacity","0.2");
					$("#divdismax").css("opacity","0.2");
					$("#divdismaxrub").css("opacity","1");
					$("#price").attr("value","");
				    $("#discount").attr("value","");
					$("#disprice").attr("value","");
					$("#discountmax").attr("value","");
					$("#price").parent().find("label").removeClass("invisible");
					$("#discount").parent().find("label").removeClass("invisible");
					$("#disprice").parent().find("label").removeClass("invisible");
					$("#discountmax").parent().find("label").removeClass("invisible");
					
			   }
			    if($(this).find("input").attr("id")=="price" || $(this).find("input").attr("id")=="discount" || $(this).find("input").attr("id")=="disprice") 
			   {
				   $("#discountmax").attr("disabled","disabled");
				    $("#discountmaxrub").attr("disabled","disabled");
				   $("#price").attr("disabled","");
				    $("#discount").attr("disabled","");
					$("#disprice").attr("disabled","");
					$("#distab").css("opacity","1");
					$("#divdismax").css("opacity","0.2");
					$("#divdismaxrub").css("opacity","0.2");
					$("#discountmax").attr("value","");
					$("#discountmaxrub").attr("value","");
					$("#discountmax").parent().find("label").removeClass("invisible");
					$("#discountmaxrub").parent().find("label").removeClass("invisible");
					
			   }
			     if($(this).find("input").attr("id")=="startactinp") 
			   {
				   $("#calcont").show("slow");
				   $("#separ").show("slow");
			   }
			   if($(this).find("input").attr("id")=="endactinp") 
			   {
				   $("#calcont").show("slow");
				   $("#separ").show("slow");
			   }
			   if($(this).find("input").attr("id")=="whereinp") 
			   {
				  if($("#whereinp").attr("value")=="") {$("#whereinp").attr("value",$("#city").text()+", "); sectchanged=1; $("#whereinp").parent().trigger('change');}
			   }
			  
					
		});
	$("#regbutton").bind("click",function() {
						testRegForm();
						});	
						/*
	$("div.field").bind("keypress change", function() {
		alert("blur");
			fieldUpdate($(this));
		});
		*/
		
	$("div.field input").bind("blur", function() {
		    if($(this).attr("value")=="") $(this).parent().find("label:first").removeClass("invisible");
			//fieldUpdate($(this));
		});
	$("div.field textarea").bind("blur", function() {
		    if($(this).attr("value")=="") $(this).parent().find("label:first").removeClass("invisible");
			//fieldUpdate($(this));
		});
	/*	
	$("div.field input").bind("blur", function() {
		$("#shint").css("display","none"); 
					 spos=0;
		});
		*/
	var spos=0;
	$("div.field").bind("keypress keyup change", function() {
		if($(this).find("input").attr("id")=="whatinp" && event.keyCode!=undefined && event.keyCode!=9) 
			   {
				 if($(this).find("form").attr("id")=="searchwhatcat") {openNexDiv();};
				 if($(this).find("input").attr("value").length>=3)
				 {
			     if(pageid!="out") $("#whereinp").parent().find("label:first").text("Введите адрес");
				 if(event.keyCode=="40"){
					 spos++;
					 $("#shint div").removeClass("mark");
					 if(spos<=$("#shint div").size()) {
						 $("#shint div:nth-child("+spos+")").addClass("mark");
						  if($(this).find("input").attr("rel")=="reg2") 
						  sendFromJSForReg($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
						  else {
							  sectidmain=$("#shint div:nth-child("+spos+")").attr("sectid")*1;
						  subidmain=$("#shint div:nth-child("+spos+")").attr("subid")*1;
						  sendFromJS($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
						  }
						 }
						 else {
							 spos=1;
							 $("#shint div:nth-child("+spos+")").addClass("mark");
							 if($(this).find("input").attr("rel")=="reg2") 
							  sendFromJSForReg($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
							  else {
								  sectidmain=$("#shint div:nth-child("+spos+")").attr("sectid")*1;
						  subidmain=$("#shint div:nth-child("+spos+")").attr("subid")*1;
							  sendFromJS($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
							  }
							 
						 }
						 return;
				 }
				  if(event.keyCode=="38"){
					 spos--;
					 $("#shint div").removeClass("mark");
					 if(spos>=1) {
						 $("#shint div:nth-child("+spos+")").addClass("mark");
						  if($(this).find("input").attr("rel")=="reg2")
						 sendFromJSForReg($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
						 else
						 {
					      sectidmain=$("#shint div:nth-child("+spos+")").attr("sectid")*1;
						  subidmain=$("#shint div:nth-child("+spos+")").attr("subid")*1;
						  sendFromJS($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
						 }
						 }
						 else {
							 spos=spos=$("#shint div").size();
							 $("#shint div:nth-child("+spos+")").addClass("mark");
							 if($(this).find("input").attr("rel")=="reg2")
							  sendFromJSForReg($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
							  else {
								  sectidmain=$("#shint div:nth-child("+spos+")").attr("sectid")*1;
						  subidmain=$("#shint div:nth-child("+spos+")").attr("subid")*1;
							  sendFromJS($("#shint div:nth-child("+spos+")").attr("sectid")*1,$("#shint div:nth-child("+spos+")").attr("subid")*1);
							  }
						 }
						 return;
				 }
				 if(event.keyCode=="13"){
					 
					 if(spos!=0) 
					 {
						 $(this).find("input").attr("value",$("#shint div:nth-child("+spos+")").text());
						  $("#whatsectid").attr("value",$("#shint div:nth-child("+spos+")").attr("sectid")*1);
						  $("#whatsubid").attr("value",$("#shint div:nth-child("+spos+")").attr("subid")*1);
						  sectchanged=1;
					 }
					 else {
						 /*
						 $("#lupago").bind("click",function(){
							 document.location.href="discounts.php?sectid="+sectidmain+"&subid="+subidmain+"&sort=0";
						 });
						 */
						//$("#mainwhatform").submit(); 
						return; 
					 }
					 $("#shint").css("display","none");
					  $("#shint").html("");
					 // if(spos==0) location.href="discounts.php?search="+$(this).find("input").attr("value");
					 
					  spos=0;
					  return;
				 }
				 $.post("lib/getshint.php",{keyword:$(this).find("input").attr("value")},function(data){
					 if(data!="0") {
						 $("#shint").html("");
						 keywords=data.split('}{');
						 for(i=0;i<keywords.length;i++){
							 if(keywords[i]!="0")  {
								 keywordtext=keywords[i].split('|');
								 $("#shint").append("<div class='shintsdiv' sectid='"+keywordtext[1]+"' subid='"+keywordtext[2]+"'>"+keywordtext[0]+"</div>");
								 
							 }
						 }
						 $("div [class!=shinsdiv]").bind("click",function(){
							 $("#shint").css("display","none");	
					         $("#shint div").removeClass("mark");
							  spos=0;
						 });
						 $("#shint div").bind("click",function(){
							 sectidmain=$(this).attr("sectid")*1;
						  subidmain=$(this).attr("subid")*1;
							 sendFromJS(sectidmain,subidmain);
						 $("#whatinp").bind("blur",function(){});
						 $("div [class!=shinsdiv]").bind("click",function(){});	 
						 sectchanged=1;
					spos=0;
					$("#whatinp").attr("value",$(this).text());
					$("#shint").css("display","none");	
					$("#shint div").removeClass("mark");
				});
				
						 $("#shint").css("display","block");
						 if(pageid=="out") {$("#shint").width($("#whatinp").width()+7);}
						 
						 }
						 else {
							 $("div [class!=shinsdiv]").bind("click",function(){});
							 $("#shint").css("display","none");
							 $("#shint div").removeClass("mark");
							 spos=0;
						 }
				 });
				 }
				 else {
					 $("#shint").css("display","none"); 
					 spos=0;
				 }
			   }
			   if($(this).find("form").attr("id")=="searchplaces" && event.keyCode!=undefined && event.keyCode!=9) {
				   if($(this).find("form input").attr("value")!=""){
					   openNexDiv();
					    $(this).find("label:last").removeClass("invisible");
						$("#placeinp").removeClass("invisible");
				   }
				   else {
					   openNexDiv();
					   $(this).find("label:last").addClass("invisible");
					   $("#placeinp").addClass("invisible");
				   }
				   
			   }
			  if($(this).find("input").attr("id")=="whereinp" || ($(this).find("input").attr("id")=="whatinp" && $("#whereinp").attr("value")!="")){
				  if($("#whereinp").attr("value")=="" && onfirstadresschange) {$("#whereinp").attr("value",$("#city").text()+", "); sectchanged=1; onfirstadresschange=0;}
				  /*
				   if (geocoder && $("#map_canvas1").css("display")=="none" ) {
                    geocoder.getLatLng(
                    $("#city").text(),
                      function(point) {
                            if (!point) {
			
                                } else {
			                    $("#maploaderstring").css("display","block");
			                      $("#map_canvas1").css("display","block");
		                      initialize();
			                 map.setCenter(point, 15);
                                   }
		                   });
				   }
				   */
				 if($("#whereinp").attr("value")!="" && sectidmain && subidmain) {
					 if(event.keyCode==44 || event.keyCode==32 || event.keyCode==13 || sectchanged==1)
					 {
					  $.post("lib/getplaces.php",{address:trim($("#whereinp").attr("value")),sectid:sectidmain,subid:subidmain,city:$("#city").text()},function(data){
						  if(data!="|||||||||")
						  {
							  sectchanged=0;
							  $("#maploaderstring").css("display","block");
							  $("#map_canvas1").css("display","block");
							  initialize();
							  var dataarr=data.split("|||");
							  var addresses=dataarr[0].split("{|}");
							  var names=dataarr[1].split("{|}");
							  var ids=dataarr[2].split("{|}");
							  var coordsarr=dataarr[3].split("{|}");
							  markernums=0;
							  summarkers=0;
							 for(var i=0; i<addresses.length; i++)
								  {
								 markernums++;
  								 createMarker(coordsarr[i],addresses[i],names[i]+"<br><a href='discounts.php?advid="+ids[i]+"'>Открыть</a>",i);
								  }	  
						}	
						else {
							geocoder.getLatLng(
                    trim($("#whereinp").attr("value")),
                      function(point) {
                            if (!point) {
			
                                } else {
			                    $("#maploaderstring").css("display","block");
			                      $("#map_canvas1").css("display","block");
		                      initialize();
			                 map.setCenter(point, 10);
                                   }
		                   });
						}
					  });
					 }
				 }
				 //else $("#map_canvas1").css("display","none");
				}
			  
			fieldUpdate($(this));

			if(event.keyCode==9 && !($(this).find("input").attr("value")=="" || $(this).find("textarea").attr("value")=="")){
				  var nexttab=($(this).find("input").attr("tabindex")*1+1);
				  if(!nexttab) nexttab=($(this).find("textarea").attr("tabindex")*1+1);
				 $("input[tabindex='"+nexttab+"']").focus();
				 $("textarea[tabindex='"+nexttab+"']").focus();
			  }
			  
		});
		
	$("#searchwhatcat input").bind("blur",function(){
		$("#shint").css("display","none");
		$("#shint").html("");
		spos=0;
	});
	$("#whereoutlabel").bind("click", function(){
		showAddress($(this).parent().find("input").attr("value"));
	});
	$("div.sortarrows img").bind("mouseover",function(){
		if($(this).attr("active")==0){
			if($(this).attr("src")=="images/sa_up.jpg") $(this).attr("src","images/sa_active_up.jpg");
			if($(this).attr("src")=="images/sa_down.jpg") $(this).attr("src","images/sa_active_down.jpg");
		}
	});
	$("div.sortarrows img").bind("mouseout",function(){
		if($(this).attr("active")==0){
			if($(this).attr("src")=="images/sa_active_up.jpg") $(this).attr("src","images/sa_up.jpg");
			if($(this).attr("src")=="images/sa_active_down.jpg") $(this).attr("src","images/sa_down.jpg");
		}
	});
function sendFromJS(value,subid) {
	//var value = spos;//$("#whatinp").attr("value");
    var movie = (navigator.appName.indexOf("Microsoft")!=-1 ? window : document)["rabbitbanner"]    
    movie.sendFromJS(value,subid);    
}
function sendFromJSForReg(value,subid) {
	//var value = spos;//$("#whatinp").attr("value");
    var movie = (navigator.appName.indexOf("Microsoft")!=-1 ? window : document)["rabbitbanner"]    
    movie.sendFromJSForReg(value,subid);    
}
function fieldUpdate(el){
	el.find("label:first").addClass("invisible");
	el.find("input").focus();
	el.find("textarea").focus();
   // if(el.find("input").attr("value")=="") el.find("label:first").removeClass("invisible");
	/*-
	if(el.find("label:first").attr("id")=="where") {$("#Grid").css("visibility","hidden"); $("iframe").show("slow");}
	else {$("#Grid").fadeIn("slow"); $("iframe").hide("slow");}
	*/
}
$("td.sect").bind("click",function() {
	popup=$("div.PopupSect");
	width=this.offsetWidth;
	widthpopup=233;
	leftpopup=Math.round(getOffset(this).left+(width-widthpopup)/2)+4;
	toppopup=getOffset(this).top+30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
	$.post("lib/getdata.php", {type:2},
	function(data){
		$("div.PopupSect").html(data);
		$("div.PopupSect img").bind("click",function() {
	      $("div.PopupSect").css("display","none");
        });
		$("div.PopupSect").css("display","block");
	});
});

$("table.SectionGridReg td[class!='']").bind("click",function() {
	popup=$("div.PopupSect");
	width=this.offsetWidth;
	widthpopup=233;
	leftpopup=Math.round(getOffset(this).left+(width-widthpopup)/2)+4;
	toppopup=getOffset(this).top+30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
	$.post("lib/getdata.php", {type:2,sectid:$(this).attr("sectid")},
	function(data){
		$("div.PopupSect").html(data);
		$("div.PopupSect img").bind("click",function() {
	      $("div.PopupSect").css("display","none");
        });
		$("div.PopupSect a").bind("click",function() {
	      $("div.Searchwhat").text($("td.sect1over").text()+" - "+$(this).text());
		  $.post("regserv.php", {type:1,sectid:$(this).attr("sectid"),subid:$(this).attr("subid")},
	function(data){
		$("div.PopupSect").css("display","none");
		$("#arrow").attr("src","images/regarrow_r.png");
			$("#arrow").css("cursor","pointer");
			$("#arrow").bind("mouseover",function() {this.src='images/regarrow_ro.png';})
			$("#arrow").bind("mouseout",function() {this.src='images/regarrow_r.png';})
			$("#arrow").bind("click",function() {reg2();});
	});
        });
		$("div.PopupSect").css("display","block");
	});
	$("td.sect1").removeClass("sect1over");
	$("td.sect1over").removeClass("sect1over");
	$(this).addClass("sect1over");
});

$("textarea.areatext").bind("keypress keyup change",function() {
	str=$(this).attr("value");
	num=$(this).attr("maxsize");
	labelchar=$(this).parent().find("label:last")
	if(str.length>num) {labelchar.css("color","red"); labelchar.html("Превышение количества знаков: "+(str.length-num));}
	else {labelchar.css("color","#C4C4C4"); labelchar.html("Осталось знаков: "+(num-str.length));}
});
$("#discount").bind("keypress keyup change", function(){
$("#disprice").parent().find("label:first").addClass("invisible");
if($("#discount").attr("value")!=""){
var price=$("#price").attr("value");
	price=price.replace(/\s+/g,'');
$("#disprice").attr("value",Math.round(price*(100-$("#discount").attr("value"))/100));	
}
else {
	$("#disprice").parent().find("label:first").removeClass("invisible");
	$("#disprice").attr("value","");
}
});
$("#disprice").bind("keypress keyup change", function(){
$("#discount").parent().find("label:first").addClass("invisible");
if($("#disprice").attr("value")!=""){
if($("#price").attr("value")!="") {
	var price=$("#price").attr("value");
	price=price.replace(/\s+/g,'');
	var disprice=$("#disprice").attr("value");
	disprice=disprice.replace(/\s+/g,'');
	$("#discount").attr("value",100-Math.round((disprice/price)*100));
}
else $("#discount").attr("value",0);
}
else {
	$("#discount").parent().find("label:first").removeClass("invisible");
	$("#discount").attr("value","");
}
});
$("#price").bind("keypress keyup change", function(){
	if($("#discount").attr("value")!="") {
		var price=$("#price").attr("value");
	     price=price.replace(/\s+/g,'');
		$("#disprice").parent().find("label:first").addClass("invisible");
		$("#disprice").attr("value",Math.round(price*(100-$("#discount").attr("value"))/100));
	}
});
$("#map_canvas").bind("mouseover",function(){
	mapMove(1);
});
$("div.Content").bind("mouseover",function(){
	startx=(getClientWidth()-196)+"px";
	if($("#map_canvas").css("left")=="543px")
	{
	 $("#map_canvas").animate({"left": startx,"width":"196px"}, "slow");
	 $("#mapshad").animate({"left": startx}, "slow");
	 $("td.price span").fadeIn("slow");
	 $("td.discount span").fadeIn("slow");
	 $("td.coupon span").fadeIn("slow");
	 $("td.remain span").fadeIn("slow");
	 $("td.toptitle span").fadeIn("slow");
	 $("div.Content").animate({"opacity":1});
	}
});
$("#changeCity").bind("click",function(){
    $("#citystep1").css("display","none");
	$("#citystep2").fadeIn("slow");
	$("#citytd").html(citystr);
});
var cityhintcur=-1;
var cityhintlast=0;
var cityInChange=0;
$("#cityinp").bind("click",function(){
if(!cityInChange) {cityInChange=1; $(this).attr("value","");}	
});
$("#cityinp").bind("keypress keyup change",function(){
	if($("#cityinp").attr("value")=="") {$("#cityhint").html(""); return;}
	if(event.keyCode==38)
	{
		if(cityhintcur<=cityhintlast){
		if(cityhintcur!=cityhintlast) cityhintcur++;
		$("#cityhint"+cityhintcur).addClass("mark");
		$("#cityhint"+(cityhintcur-1)).removeClass("mark");	
		$(this).attr("value",$("#cityhint"+cityhintcur).text());
		setCaretPosition(this,$(this).attr("value").length);	
		}
		return;	
	}
	if(event.keyCode==40)
	{
		if(cityhintcur>=0){
			if(cityhintcur) cityhintcur--;
		$("#cityhint"+cityhintcur).addClass("mark");
		$("#cityhint"+(cityhintcur+1)).removeClass("mark");	
		$(this).attr("value",$("#cityhint"+cityhintcur).text());
		setCaretPosition(this,$(this).attr("value").length);
		}
		return;	
	}
	if(event.keyCode==13) {
		$("#cityhint").html("");
		return;
	}
	$("#cityhint").html("");
	$.post("lib/getcities.php",{city:$("#cityinp").attr("value")},function(data){
		if(data!="0") {
	cityhintcur=-1;
    cityhintlast=0;
	var dataarr=data.split("|");
	cityhintlast=dataarr.length-1;
	for(var i=0;i<dataarr.length;i++)
	{
	$("#cityhint").prepend('<div style="height:20px; width:100%" id="cityhint'+i+'">'+dataarr[i]+'</div>');	
	}
	$("#cityhint").css("width",$("#cityhint").parent().width()+1);
	$("#cityhint").css("left",$("#cityhint").parent().position().left-1);
		}
	});
	
});
$("#searchwhatcat").bind("submit",function(){
	return false;
	var lastnum=$("#whatcategory div:first span").attr("num")*1;
	if($("#whatcategory").text()=="") lastnum=0;
	$("#whatcategory").css("visibility","visible");
	$("#whatcategory").html('<div id="whatcat'+lastnum+'"><span num="'+lastnum+'">'+$(this).find("input").attr("value")+'</span><a href="javascript:void(0)" onclick="removeWhatCat('+lastnum+');"><img src="images/close.png" style="vertical-align:middle; margin-right:5px; margin-top:8px" align="right" onmouseover="this.src=\'images/closeover.png\'" onmouseout="this.src=\'images/close.png\'"></a></div>');
	$(this).find("input").attr("value","");
	openNexDiv();
	return false;
});
$("#placeinp input").bind("focus",function(){
	var lastnum=$("#places div:first span").attr("num")*1+1;
	if($("#places").text()=="") lastnum=1;
	$("#places").prepend('<div id="places'+lastnum+'"><span num="'+lastnum+'">'+$("#searchplaces").find("input").attr("value")+'</span><a href="javascript:void(0)" onclick="removePlaces('+lastnum+');"><img src="images/close.png" style="vertical-align:middle; margin-right:5px; margin-top:5px" align="right" onmouseover="this.src=\'images/closeover.png\'" onmouseout="this.src=\'images/close.png\'"></a></div>');
	getCoords($("#searchplaces").find("input").attr("value"),lastnum);
	$("#searchplaces").find("input").attr("value","");
	$("#searchplaces").find("input").focus();
	$("#searchplaces").parent().find("label:first").removeClass("invisible");
	$("#searchplaces").parent().find("label:first").html("Добавить еще адрес?");
	$("#searchplaces").parent().find("label:last").addClass("invisible");
	$("#placeinp").addClass("invisible");
	$("#footersizer").css("height",($("#footersizer").height()+20)+"px");
	openNexDiv();
});
   $("input.cb").hide().after("<div class=\"cb\"></div>");
   $(":checked").next().addClass("checked");
   $("div.cb").click(function () {
      var input_cb = $(this).prev("input")
      if (input_cb.is(':checked'))
      {
         $(this).removeClass("checked");
         input_cb.attr('checked', false);
      }
      else 
      {
         $(this).addClass("checked");
         input_cb.attr('checked', true);
      }
   });
   $("#map_canvas").css("left",($("body").width()-196)+"px");
    $("#mapshad").css("left",($("body").width()-196)+"px");
   $("#map_canvashold").css("height",($(window).height()-100-$("#map_canvashold").parent().offset().top)+"px");
   $("#map_canvashold").css("width",($(document).width()-543)+"px");
});
    function changeSize(){
	startx=($("body").width()-196)+"px";
	if($("#map_canvas").css("left")=="543px")
	{
	 $("#map_canvas").animate({"left": startx,"width":"196px"}, "slow");
	 $("#mapshad").animate({"left": startx}, "slow");
	 $("td.price span").fadeIn("slow");
	 $("td.discount span").fadeIn("slow");
	 $("td.coupon span").fadeIn("slow");
	 $("td.remain span").fadeIn("slow");
	 $("td.toptitle span").fadeIn("slow");
	 $("div.Content").animate({"opacity":1});
	}
	else{
	$("#map_canvas").css("left",($("body").width()-196)+"px");
	$("#mapshad").css("left",($("body").width()-196)+"px");
    $("#map_canvashold").css("height",(getClientHeight()-100)+"px");
	}
	}
	
function recieveFromFlash(sectid, subid) {
	$("div.Searchwhat").text(sectid+":"+subid);
	 $.post("regserv.php", {type:1,sectid:sectid,subid:subid},
	function(data){
		$.post("baza.php", {type:1,sectid:sectid,subid:subid},
	function(data){
		var dataarr = data.split('|');
		$("#whatinp").attr("value",dataarr[0]+" "+dataarr[1]);
		$("#whatinp").parent().parent().find("label:first").addClass("invisible");
		openNexDiv();
	});
	});
}
function mapMove(t)
{
	endwidth=(getClientWidth()-543)+"px";
	if($("#map_canvas").css("left")==(getClientWidth()-196)+"px")
	{
	 $("#map_canvas").animate({"left": "543px", "width": endwidth}, "slow");
	 $("#mapshad").animate({"left": "543px"}, "slow");
	 $("td.price span").fadeOut("slow");
	 $("td.discount span").fadeOut("slow");
	 $("td.coupon span").fadeOut("slow");
	 $("td.remain span").fadeOut("slow");
	 $("td.toptitle span").fadeOut("slow");
	 $("div.Content").animate({"opacity":0.5});
	}
}
function openNexDiv()
{
	if($("div.Searchwhat").html()!="&nbsp;" && $("#whatinp").attr("value")!="" && $("#searchplaces input").attr("value")!="" && curdat!="00" && curdat1!="00") {
			$("#arrow").attr("src","images/regarrow_r.png");
			$("#arrow").css("cursor","pointer");
			$("#arrow").bind("mouseover",function() {this.src='images/regarrow_ro.png';})
			$("#arrow").bind("mouseout",function() {this.src='images/regarrow_r.png';})
			$("#arrow").bind("click",function() {reg2();});
			$("#nextdiv span").css("color","#000000");
			$("#nextarr").attr("src","images/regarrow_rb.png");
			$("#nextdiv span").bind("mouseover",function() {this.style.color='#f7911e'; $("#nextarr").attr("src","images/regarrow_ro.png");})
			$("#nextdiv span").bind("mouseout",function() {this.style.color='#000000'; $("#nextarr").attr("src","images/regarrow_rb.png");})	
	}
	else {
		$("#arrow").attr("src","images/regarrow_rg.png");
			$("#arrow").bind("mouseover",function() {;})
			$("#arrow").bind("mouseout",function() {;})
			$("#arrow").bind("click",function() {reg2();});
			$("#nextdiv span").css("color","#c9c9c9");
			$("#nextarr").attr("src","images/regarrow_rg1.png");
			$("#nextdiv span").bind("mouseover",function() {;})
			$("#nextdiv span").bind("mouseout",function() {;})	
	}
}
function removeWhatCat(whatid)
{
	$("#whatcat"+whatid).remove();
	$("#whatcategory").css("visibility","hidden");
}
function removePlaces(placeid)
{
	$("#places"+placeid).remove();
	for(var i=placeid; i<coords.length-1; i++){
		coords[i]=coords[i+1];
		if(i)
		{
		$("#places"+(i+1)).attr("id","places"+i);
		$("#places"+i+" span").attr("num",i);
		$("#places"+i+" a").attr("onclick","removePlaces("+i+");");
		$("#places"+i+" a").bind("click",function(){
			removePlaces(i);
		});
		}
	}
	coords.pop();
	if($("#places").text()=="") $("#searchplaces").parent().find("label:first").html("Где? Укажите ГОРОД, улицу, дом");
	openNexDiv();
}


function checkClick(){
	/*
	startx=(getClientWidth()-196)+"px";
	if($("#map_canvas").css("left")=="543px")
	{
	 $("#map_canvas").animate({"left": startx,"width":"196px"}, "slow");
	 $("#mapshad").animate({"left": startx}, "slow");
	 $("td.price span").fadeIn("slow");
	 $("td.discount span").fadeIn("slow");
	 $("td.coupon span").fadeIn("slow");
	 $("td.remain span").fadeIn("slow");
	 $("td.toptitle span").fadeIn("slow");
	 $("div.Content").animate({"opacity":1});
	}
	*/
}

function reg2() {
	
	if($("div.Searchwhat").html()=="&nbsp;"){
		var strpop='Вы не выбрали категорию товара или услуги.';
$("#poperror").html(strpop);
		showTable(1);
		return;
	}
	if($("#whatinp").attr("value")==""){
		var strpop='Вы не выбрали категорию товара или услуги (ЧТО?).<br><br>По выбранной Вами категории товара или услуги пользователи будут находит Ваше объявление. Поэтому для эффективности проведения Вашей акции очень важно указать ее правильно.';
$("#poperror").html(strpop);
		showTable(1);
		return;
	}
	if($("#places").html()=="" && $("#searchplaces input").attr("value")==""){
		var strpop='Вы не указали место оказания услуги / продажи товара (ГДЕ?).<br><brЭто необходимо для того, чтобы пользователям сайта было легче найти это место и купить указанный в акции товар / услугу. Вы можете указать несколько адресов, что увеличит количество обращений к Вам.<br><br>Сначала укажите город, затем улицу и номер дома.';
$("#poperror").html(strpop);
		showTable(1);
		return;
	}
	if(curdat=="00" || curdat1=="00"){
		var strpop='Вы не указали место сроков проведения акции (в календаре).<br><br>Акция со скидками не может длиться постоянно, тогда она перестанет быть акцией. Пользователю необходимо понимать, в какой промежуток времени идет акция. Первая отмеченная дата указывает начало акции, вторая – ее окончание.';
$("#poperror").html(strpop);
		showTable(1);
		return;
	}
	var lastnum=$("#whatcategory div:first span").attr("num")*1+1; 
	var whatcat="";
	for(i=0;i<lastnum;i++){
		if($("#whatcat"+i).find("span").text()!=""){
		whatcat+=$("#whatcat"+i).find("span").text();
		if(i!=lastnum-1) whatcat+="|";
		}
	}
	lastnum=$("#places div:first span").attr("num")*1+1;
	var places="";
	if($("#searchplaces input").attr("value")!="") {
		places+=$("#searchplaces input").attr("value");
	if($("#places").html()!="") places+="|";
    else lastnum=1;
	}
	for(i=0;i<lastnum;i++){
		if($("#places"+i).find("span").text()!=""){
		places+=$("#places"+i).find("span").text();
		if(i!=lastnum-1) places+="|";
		}
	}
	if(curmon=="00") curmon=-1;
	if(curmon1=="00") curmon1=-1;
		if (geocoder) {
        geocoder.getLatLng(
          $("#searchplaces input").attr("value"),
          function(point) {
			  if($("#searchplaces input").attr("value")!=""){
			  if(point) coords[0]=point;
			  else  coords[0]="(0,0)";
			  }
			  else {
				 for(var i=0; i<coords.length-1; i++){
		          coords[i]=coords[i+1]; 
				 }
				 coords.pop();
			  }
			  /*
			  var coordsstr="";
			  for(var i=1;i<coords.length;i++)
			  {
				  if(i!=1) coordsstr+="|";
				 coordsstr+=coords[i];
			  }
			  */
			  var coordsstr=coords.join("|");
			  //alert(coords.length);
	        $.post("insertadv.php", {step:2,keywords:$("#whatinp").attr("value"),places:places,startact:curyear+"-"+(curmon+1)+"-"+curdat+" 00:00:00",endact:curyear1+"-"+(curmon1+1)+"-"+curdat1+" 00:00:00",coords:coordsstr},
	function(data){
		location.replace("reg.php?step=3");
	});
		  });
	}
}

function reg3() {
	if($("#maintext").attr("value")=="")
	{
		$("#poperror").html("Вы не ввели основной текст");
		showTable(1);
		return;
	}
	if($("#detailtext").attr("value")=="")
	{
		$("#poperror").html("Вы не ввели детализацию объявления");
		showTable(1);
		return;
	}
	if($("#descripttext").attr("value")=="")
	{
		$("#poperror").html("Вы не ввели описание предложения");
		showTable(1);
		return;
	}
	$.post("insertadv.php", {step:3,maintext:$("#maintext").attr("value"),detailtext:$("#detailtext").attr("value"),descripttext:$("#descripttext").attr("value"),sitename:$("#sitename").attr("value")},
	function(data){
		$("form").submit();
		//location.replace("reg.php?step=4");
	});
}

function reg4() {
	var price=$("#price").attr("value");
	price=price.replace(/\s+/g,'');
	if(((price=="" && $("#discount").attr("value")=="") || (price=="" && $("#disprice").attr("value")=="") || ($("#discount").attr("value")=="" && $("#disprice").attr("value")=="")) && $("#discountmax").attr("value")=="" && $("#discountmaxrub").attr("value")==""){
		showTable(1);
		return;
	}
	$.post("insertadv.php", {step:4,price:price,discount:$("#discount").attr("value"),discountmax:$("#discountmax").attr("value"),discountmaxrub:$("#discountmaxrub").attr("value"),couponprice:$("#couponprice").attr("value"),startact:$("#startactinp").attr("value"),endact:$("#endactinp").attr("value"),condtext:$("#condtext").attr("value")},
	function(data){	
		location.replace("reg.php?step=5");
	});
}

function reg5() {
	$.post("insertadv.php", {step:5},
	function(data){
		location.replace("reg.php?step=6");
	});
	
}
function getReg2() {
	$.post("getadv.php", {step:2},
	function(data){
		if(data!=""){
			data=data.replace(/&#034;/g,"\"");
			data=data.replace(/&#039;/g,"'");
			var dataarr = data.split('}{');
			if(dataarr[0]!=" ")
			{
				/*
				$("#whatcategory").css("visibility","visible");
			var whatcat=dataarr[0].split('|');
			for(i=0;i<whatcat.length;i++){
				$("#whatcategory").prepend('<div id="whatcat'+i+'"><span num="'+i+'">'+whatcat[i]+'</span><a href="javascript:void(0)" onclick="removeWhatCat('+i+');"><img src="images/close.png" style="vertical-align:middle; margin-right:5px; margin-top:8px" align="right" onmouseover="this.src=\'images/closeover.png\'" onmouseout="this.src=\'images/close.png\'"></a></div>');
			}*/
			$("#whatinp").attr("value",dataarr[0]);
			$("#whatinp").parent().parent().find("label:first").addClass("invisible");
			}
			if(dataarr[1]!=" ")
			{
			var places=dataarr[1].split('|');
			coords=dataarr[5].split('|');
						
			$("#searchplaces input").attr("value",places[0]);
			$("#searchplaces").parent().find("label:first").html("Добавить еще адрес?");
			$("#searchplaces").parent().find("label:first").addClass("invisible");
			$("#placeinp").removeClass("invisible");
			for(i=1;i<places.length;i++){
				$("#places").prepend('<div id="places'+i+'"><span num="'+i+'">'+places[i]+'</span><a href="javascript:void(0)" onclick="removePlaces('+i+');"><img src="images/close.png" style="vertical-align:middle; margin-right:5px; margin-top:5px" align="right" onmouseover="this.src=\'images/closeover.png\'" onmouseout="this.src=\'images/close.png\'"></a></div>');
			}
			$("#searchplaces").parent().find("label:first").html("Добавить еще адрес?");
			$("#searchplaces").parent().find("label:last").removeClass("invisible");
			
			}
			if(dataarr[3]!=" " && dataarr[4]!=" ")
			{
			  datetemp=dataarr[3].split(' ');
			  datest=datetemp[0].split('-');
			  curdat=datest[2].substring(0,datest[2].length);
			  curmon=datest[1].substring(0,datest[1].length)-1;
			  curyear=datest[0];
			  ccm=curmon;
			  ccy=curyear;
			  datetemp=dataarr[4].split(' ');
			  datest=datetemp[0].split('-');
			  curdat1=datest[2].substring(0,datest[2].length);
			  curmon1=datest[1].substring(0,datest[1].length)-1;
			  curyear1=datest[0];
			  ccm1=curmon1;
			  ccy1=curyear1;
			  prepcalendar('',curmon,curyear,1);
			  prepcalendar('',curmon1,curyear1,2);
			}
			if(dataarr[0]!=" " && dataarr[1]!=" " && dataarr[2]!=" ")
			{
			  openNexDiv();
			}	
		}
	});
}

function getReg3() {
	$.post("getadv.php", {step:3},
	function(data){
		if(data!=""){
			data=data.replace(/&#034;/g,"\"");
			data=data.replace(/&#039;/g,"'");
			dataarr = data.split('|');
			if(dataarr[0]!="") {$("#maintext").attr("value",dataarr[0]); $("#maintext").parent().find("label:first").addClass("invisible");}
			if(dataarr[1]!="") {$("#detailtext").attr("value",dataarr[1]); $("#detailtext").parent().find("label:first").addClass("invisible");}
		    if(dataarr[2]!="") {$("#descripttext").attr("value",dataarr[2]); $("#descripttext").parent().find("label:first").addClass("invisible");}
			if(dataarr[3]!="www." && dataarr[3]!="") {$("#sitename").attr("value",dataarr[3]); $("#sitename").parent().find("label:first").addClass("invisible");}	
		}
	});
}

function getReg4() {
	$.post("getadv.php", {step:4},
	function(data){
		if(data){
			data=data.replace(/&#034;/g,"\"");
			data=data.replace(/&#039;/g,"'");
			dataarr = data.split('|');
			if(dataarr[5]=="0")
			{
			if(dataarr[0]!="0") {
				$("#price").attr("value",dataarr[0]); 
				$("#price").parent().find("label:first").addClass("invisible");
				$("#divdismax").css("opacity","0.2");
				$("#divdismaxrub").css("opacity","0.2");
				}
			if(dataarr[1]!="0") {
				$("#discount").attr("value",dataarr[1]); 
				$("#discount").parent().find("label:first").addClass("invisible");
				$("#disprice").parent().find("label:first").addClass("invisible");
				$("#disprice").attr("value",Math.round($("#price").attr("value")*(100-$("#discount").attr("value"))/100));
				$("#divdismax").css("opacity","0.2");
				$("#divdismaxrub").css("opacity","0.2");
				}
			if(dataarr[6]!="0") {
				
				$("#discountmaxrub").attr("value",dataarr[6]); 
				$("#discountmaxrub").parent().find("label:first").addClass("invisible");
				$("#divdismax").css("opacity","0.2");
				$("#distab").css("opacity","0.2");
				}
			}
			else
			{
				$("#discountmax").attr("value",dataarr[5]); 
				$("#discountmax").parent().find("label:first").addClass("invisible");
				$("#distab").css("opacity","0.2");
			}
			if(dataarr[2]!="0000-00-00 00:00:00"){
				datetemp=dataarr[2].split(' ');
				datest=datetemp[0].split('-');
				$("#startactinp").attr("value",datest[2]+"-"+datest[1]+"-"+datest[0]);
				$("#startactinp").parent().find("label:first").addClass("invisible");
			    curdat=datest[2].substring(0,datest[2].length);
			    curmon=datest[1].substring(0,datest[1].length)-1;
			    curyear=datest[0];
			    ccm=curmon;
			    ccy=curyear;
				prepcalendar('',curmon,curyear,1);
			}
			if(dataarr[3]!="0000-00-00 00:00:00"){
				datetemp=dataarr[3].split(' ');
				datest=datetemp[0].split('-');
				$("#endactinp").attr("value",datest[2]+"-"+datest[1]+"-"+datest[0]);
				$("#endactinp").parent().find("label:first").addClass("invisible");
				curdat1=datest[2].substring(0,datest[2].length);
			  curmon1=datest[1].substring(0,datest[1].length)-1;
			  curyear1=datest[0];
			  ccm1=curmon1;
			  ccy1=curyear1;
			  prepcalendar('',curmon1,curyear1,2);
			}
			if(dataarr[4]!="") {$("#condtext").attr("value",dataarr[4]); $("#condtext").parent().find("label:first").addClass("invisible");}
			if(dataarr[7]!="0") {$("#couponprice").attr("value",dataarr[7]); $("#couponprice").parent().find("label:first").addClass("invisible");}
		}
	});
}

function testRegForm()
	{
		if($("#loginreg").attr("value")=="")
		{
			$("#poperror").text("Вы не ввели логин");
			showTable(1);
			return;
		}
		if($("#passreg").attr("value")=="")
		{
			$("#poperror").text("Вы не ввели пароль");
			showTable(1);
			return;
		}
		if($("#passreg").attr("value")!=$("#passconfreg").attr("value")){
			
						 $("#poperror").text("Повторный пароль не совпадает с первым");
			             showTable(1);
			             return;
		}
		if($("#kod").attr("value")=="")
		{
			$("#poperror").text("Вы не ввели код");
			showTable(1);
			return;
		}
		isLoginReg($("#loginreg").attr("value"),$("#kod").attr("value"));
		return;	
	}
	function isLoginReg(login,kod)
	{
		$.post("regserv.php", {type:2,login:login,kod:$("#randpic").find("img").attr("id"),kod1:$("#kod").attr("value")},
	function(data){
		dataarr=data.split("|");
		if(dataarr[0]=="1") {$("#poperror").text("Введенный логин существует в базе");
			             showTable(1);
			             return;}
		if(dataarr[1]=="0") {$("#poperror").text("Введенный неверный код");
			             showTable(1);
			             return;}
		var remember=0;
		if($("#remember").attr("checked")==true) remember=1;
		$.post("reguser.php", {login:$("#loginreg").attr("value"),pass:$("#passreg").attr("value"),remember:remember,kod:$("#randpic img").attr("id")},
	function(data){
				if(data=="1") location.replace("reg.php?step=2");
				if(data=="2") location.replace("myplans.php");
	});
	});
}

function pauseAdv(advid){
	$.post("editserv.php", {type:9,advid:advid},
	function(data)
	{
		location.reload();
	});
}

function stopAdv(advid){
	$.post("editserv.php", {type:1,advid:advid},
	function(data)
	{
		location.reload();
	});
}
	
function startAdv(advid){
	$.post("editserv.php", {type:2,advid:advid},
	function(data)
	{
		location.reload();
	});
}

function deleteAdv(advid){
	popup=$("div.PopupSect1");
	el=document.getElementById("deletebut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
		$("div.PopupSect1").html('<br><br><center>Вы уверены, что хотите удалить акцию?<br><br><br><button onclick="delAdv('+advid+');">Удалить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
}
function changeAdvPrice(advid){
	popup=$("div.PopupSect1");
	el=document.getElementById("changepricebut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
		$("div.PopupSect1").html('<br><br><center>Цена<br><br><input value="'+$("#price"+advid).attr("realvalue")+'" id="pricenew"><br><br><button onclick="chAdvPrice('+advid+');">Сохранить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
		$("#pricenew").focus();
}
function changeAdvDiscount(advid){
	popup=$("div.PopupSect1");
	el=document.getElementById("changediscountbut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
		$("div.PopupSect1").html('<br><br><center>Скидка<br><br><input value="'+$("#discount"+advid).attr("realvalue")+'" id="discountnew"><br><br><button onclick="chAdvDiscount('+advid+');">Сохранить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
		$("#discountnew").focus();
}
function changeAdvDiscountPrice(advid){
	popup=$("div.PopupSect1");
	el=document.getElementById("changediscountpricebut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
		$("div.PopupSect1").html('<br><br><center>Цена после скидки<br><br><input value="'+$("#discountprice"+advid).attr("realvalue")+'" id="discountpricenew"><br><br><button onclick="chAdvDiscountPrice('+advid+');">Сохранить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
		$("#discountpricenew").focus();
}
function changeAdvDates(advid){
	popup=$("div.PopupSect1");
	el=document.getElementById("changedatebut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
		$("div.PopupSect1").html('<br><br><center>Период<br><br><table><tr><td>C: </td><td><input value="'+$("#datestart"+advid).text()+'" id="startactinp" onfocus="this.select();lcs(this,1)" onclick="page=\'editacts\'; event.cancelBubble=true;this.select();lcs(this,1)"></td></tr><tr><td>По: </td><td><input value="'+$("#dateend"+advid).text()+'" id="endactinp" onfocus="this.select();lcs(this,2)" onclick="page=\'editacts\'; event.cancelBubble=true;this.select();lcs(this,2)"></td></tr></table><br><br><button onclick="chAdvDates('+advid+');">Сохранить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
}
function changeAdvCategory(advid,sectid,subid){
	popup=$("div.PopupSect1");
	el=document.getElementById("changecatbut"+advid);
	width=el.offsetWidth;
	widthpopup=233;
	leftpopup=getOffset(el).left+20;
	toppopup=getOffset(el).top-30;
	popup.css("left",leftpopup);
	popup.css("top",toppopup);
	$.post("baza.php",{type:5},function(data){
		var dataarr=data.split("|");
		var str="<select id='catsect' onchange='changeAdvCategory("+advid+",this.selectedIndex,0);'>";
		for(var i=0;i<dataarr.length;i++){
			ch="";
			if(i==sectid) ch=" selected";
			str+="<option value='"+i+"' "+ch+">"+dataarr[i]+"</option>";
		}
		str+="</select>";
	    $.post("baza.php",{type:6,sectid:sectid},function(data1){
			var dataarr1=data1.split("|");
			str+="<br><select id='catsub'>";
		for(var i=0;i<dataarr1.length;i++){
			ch="";
			if(i==subid) ch=" selected";
			str+="<option value='"+i+"' "+ch+">"+dataarr1[i]+"</option>";
		}
		str+="</select>";
		$("div.PopupSect1").html('<br><br><center>Категории<br><br>'+str+'<br><br><button onclick="chAdvCategory('+advid+');">Сохранить</button><button onclick="closeChPopup();">Отмена</button></center>');
		$("div.PopupSect1").css("display","block");
		$("#discountpricenew").focus();
		});
	});
}
function closeChPopup() {
	 $("div.PopupSect1").css("display","none");
}

function delAdv(advid){
	$.post("editserv.php", {type:3,advid:advid},
	function(data){
		location.reload();
        });
}
function chAdvPrice(advid){
	$.post("editserv.php", {type:4,advid:advid,price:$("#pricenew").attr("value")},
	function(data){
		location.reload();
        });
}
function chAdvDiscount(advid){
	$.post("editserv.php", {type:5,advid:advid,discount:$("#discountnew").attr("value")},
	function(data){
		location.reload();
        });
}
function chAdvDiscountPrice(advid){
	$.post("editserv.php", {type:6,advid:advid,discountprice:$("#discountpricenew").attr("value")},
	function(data){
		location.reload();
        });
}
function chAdvDates(advid){
	$.post("editserv.php", {type:7,advid:advid,startact:$("#startactinp").attr("value"),endact:$("#endactinp").attr("value")},
	function(data){
		location.reload();
        });
}
function chAdvCategory(advid){
	$.post("editserv.php", {type:8,advid:advid,sectid:$("#catsect").attr("value"),subid:$("#catsub").attr("value")},
	function(data){
		location.reload();
        });
}

function deletePictureFromReg(){
	$.post("upload.php",{act:"del"},function(data){
		if(data==1) {
			$("#pictdel").parent().find("label:first").text("Добавить изображение");
			$("#pictdel").parent().find("label:first").removeClass("invisible");
			$("#pictdel").addClass("invisible");
		}
	});
}

function moveup() {
	topcont=$("#menucont").css("top");
	topcont = topcont.replace(/([a-z])/g,"");
	topcont=Math.round(topcont)-5;
	$("#menucont").css("top",topcont);
}

function movedown() {
	topcont=$("#menucont").css("top");
	topcont = topcont.replace(/([a-z])/g,"");
	topcont=Math.round(topcont)+5;
	$("#menucont").css("top",topcont);
}

function saveCity(){
	setCookie("city", $("#cityinp").attr("value"), "Fri, 2-May-2015 23:59:59 GMT", "/");
	$('#citystep2').css('display','none'); 
	$('#cityhint').html(""); 
	$('#cityhint').css("width","0px");
	$('#citystep1').fadeIn('slow');
	$('#city').text($("#cityinp").attr("value"));
						   $("#whereinp").attr("value",$("#city").text()+", "); sectchanged=1; $("#whereinp").parent().trigger('change');
}

function disSearch(){
	if(sectchanged)
	{
	$("#sectidinp").attr("value",sectidmain);
	$("#subidinp").attr("value",subidmain);
	}
	else {
	$("#sectidinp").attr("value","0");
	$("#subidinp").attr("value","0");	
	$("#searchactive").attr("value","1");
	}
	if(pageid=="out") document.getElementById("disform").submit();
	else document.getElementById("mainwhatform").submit();
}

function openSharesocial(id)
{
	var elid="";
	if(id!=undefined) elid=id;
	if($("#sharesocial"+elid).css("display")=="none") {
		$("#sharesocial"+elid).css("display","block");
		setCookie("shareopened", "1", "Fri, 2-May-2015 23:59:59 GMT", "/");
	}
	else {
		$("#sharesocial"+elid).css("display","none");
		setCookie("shareopened", "0", "Fri, 2-May-2015 23:59:59 GMT", "/");
	}
}
function openDescripts(id)
{
	var elid="#descripts"+id;
	var eltoclose="#conditions"+id;
	if($(elid).css("display")=="none") {$(elid).css("display","block"); $(eltoclose).css("display","none");}
	else $(elid).css("display","none");
}
function openConditions(id)
{
	var elid="#conditions"+id;
	var eltoclose="#descripts"+id;
	if($(elid).css("display")=="none") {$(elid).css("display","block"); $(eltoclose).css("display","none");}
	else $(elid).css("display","none");
}

function getOffsetSum(elem) {
    var top=0, left=0
    while(elem) {
        top = top + parseFloat(elem.offsetTop)
        left = left + parseFloat(elem.offsetLeft)
        elem = elem.offsetParent        
    }
    
    return {top: Math.round(top), left: Math.round(left)}
}
function getOffsetRect(elem) {
    // (1)
    var box = elem.getBoundingClientRect()
    
    // (2)
    var body = document.body
    var docElem = document.documentElement
    
    // (3)
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
    
    // (4)
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0
    
    // (5)
    var top  = box.top +  scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft
    
    return { top: Math.round(top), left: Math.round(left) }
}

function getOffset(elem) {
    if (elem.getBoundingClientRect) {
        // "правильный" вариант
        return getOffsetRect(elem)
    } else {
        // пусть работает хоть как-то
        return getOffsetSum(elem)
    }
}
function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}
 
function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function showTable(num)
{
document.getElementById("ov").style.display="block";
document.getElementById("tab"+num).style.display="block";
}
function hideTable(num)
{
document.getElementById("ov").style.display="none";
document.getElementById("tab"+num).style.display="none";
}
function getRandomArbitary(min, max)
{
  return Math.floor(Math.random() * (max - min) + min);
}
function getCaretPosition (ctrl) {
 
	var CaretPos = 0;
	// IE Support
	if (document.selection) {
 
		ctrl.focus ();
		var Sel = document.selection.createRange ();
 
		Sel.moveStart ('character', -ctrl.value.length);
 
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}
 
function setCaretPosition(ctrl, pos)
{
 
	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
  trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;    // Ё
trans[0x451] = 0xB8;    // ё

var escapeOrig = window.escape;
window.escape = function(str)
{
  var ret = [];
  for (var i = 0; i < str.length; i++)
  {
    var n = str.charCodeAt(i);
    if (typeof trans[n] != 'undefined')
      n = trans[n];
    if (n <= 0xFF)
      ret.push(n);
  }
  return escapeOrig(String.fromCharCode.apply(null, ret));
}
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
function inmass(looking_for, list){
    for(i in list){
        if(looking_for == list[i]){
            return true;
        }
    }
    return false;
}
function ltrim(inp) {
	var ptrn = /\s*((\S+\s*)*)/;
	return inp.replace(ptrn, "$1");
}
// Убирает пробельные символы справа
function rtrim(inp) {
	var ptrn = /((\s*\S+)*)\s*/;
	return inp.replace(ptrn, "$1");
}
// Убирает пробельные символы с обоих концов
function trim(inp) {
	return ltrim(rtrim(inp));
}


