// поисковая форма
var url = "/nedvijimost/substep.p3";

jQuery(document).ready(function(){
    // PrettyPhoto
    $("a[rel^='pp']").prettyPhoto({
		show_title:false,
		allow_resize: true,
		slideshow:false,
		social_tools:''
	});


	$(".menu li[!.cm] > ul").addClass("d_none");

	$(".menu li ul").each(function (i){
		var pa = $(this).parent();
		pa.addClass("wi");
		if(pa.hasClass("cm")){
			pa.prepend('<span>-</span>');
		} else {
			pa.prepend('<span>\+</span>');
		}
	});
	$(".menu span").click(function(){
		var li = $(this).parent();
		li.parent().find("li.cm").removeClass("cm");

		if($(this).html()!='-'){
			li.parent().find("ul").slideUp(600);
			li.parent().find("span").html("+");
			li.find("ul:first").slideDown(600);
			$(this).html("-");
		} else {
			$(this).parent().find("ul").slideUp("slow");
			$(this).parent().find("span").html("+");
			$(this).html("+");
		}
	});

	polzunki();
	$(".switch h3").click(function(){
		if(!$(this).hasClass("cur")){
			$(".switch h3").removeClass("cur");
			$(".switch .form-bot, .hint").removeClass("d_none");
			$("#call-back small").addClass("d_none");
			var clh3 = $(this);
			clh3.addClass("cur");
			$(".switch i.rb").css("display","none");
			$(".switch > .rtf > div:eq(0)").slideDown(600);
		} else {
			$(".switch h3").removeClass("cur");
			$("#call-back small").removeClass("d_none");
			$(".switch > .rtf > div:eq(0)").slideUp(0);
			$(".switch > .rtf > div:eq(1)").slideUp(0);
			$(".switch .form-bot").addClass("d_none");
			$(".switch i.rb").css("display","block");
		}
		return false;
	});
	$("#sendSS").click(function(){
		var sto = "/search/?ss="+$('#SSF').val();
		window.location.href=sto;
	});
	$("#SSF").keypress(function (e) {
		if ($(this).val()!='' && e.which == 13){
			var sto = "/search/?ss="+$(this).val();
			window.location.href=sto;
		}
	});
	$(".formstep li").live("click", function(){
		next($(this));
	});
	jQuery(".formstep select").live("change", function(){
		$(".hint").remove();
//		$(".supplylist").remove();
		$(".find").remove();
		selnext($(this));
	});
	$("#sf").submit(function(){
		return false;
	});
	$("#scale input, #scalesurf input, #scaleearth input").live("blur", function(){
		var ppid = $(this).parent().attr("id");
		recalcpol("#"+ppid);
	});
	$("#scale input, #scalesurf input, #scaleearth input").live("keypress", function (e) {
		if (e.which == 13){
			var ppid = $(this).parent().attr("id");
			recalcpol("#"+ppid);
		}
	});
	$("#send").live("click", function(){
		var contacts = $(".hint .contacts textarea").val();
		var regEmail = /[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/;
		var regNum = /[-+]?[0-9]*\.?[0-9]+/;
		if(!contacts.toUpperCase().match(regEmail) && !contacts.match(regNum)){
			alert('Укажите пожалуйста ваш Email или телефон для связи с вами!');
			$(".hint .contacts label").addClass("red");
			$(".hint .contacts textarea").focus();
			return false;
		}
		if(contacts.length>5){
			$("#send").css("display","none");
			$(".cut").animate({ opacity: 0.2 }, 1000,  function(){
				var posttext = $(".cut .text").text();
				var contacts = $("#contacts").val();
				var postdata = "msend=1&mb="+posttext+"&mc="+contacts;
/* replace questions */
				var postdata = postdata.replace(/\?/g,"|Q|");
				var postdata = postdata.replace(/%/g,"|perc|");
				var postdata = postdata.replace(/</g,"|qo|");
				var postdata = postdata.replace(/>/g,"|qc|");
/* and finds another adverts */
				$(".find li.it input, .find tr.it input").each(function (i){
					postdata = postdata+"&addadv="+$(this).val();
				});

				var postdata = unescape(postdata);
//				alert(postdata);

				$(".contacts").fadeOut(0);
				$(".addadv").remove();
				$(".cut .text").html("<h1>Подождите пожалуйста, идёт отправка вашей заявки</h1>");
				$(".cut").animate({ opacity: 1 }, 1000);
				var meth = "post";
				if ($.browser.mozilla){
					meth = "get";
				}
/* ajax post if succes done next */
				jQuery.ajax({
					type: meth,
					url: url,
					data: postdata,
					success: function(html){
						$(".cut").animate({ opacity: 0.5, left:"3000px" }, 2000,  function(){
							$(".hint").fadeOut(0);
							$("body").animate({scrollTop: $('#sf').attr('offsetTop')}, 0);
							$(".form > div:gt(2)").filter(".formstep").remove();
							$(".find").remove();
//							$(".supplylist").remove();
						});
					}
				});
			});
		} else {
//			$(".hint .contacts label").addClass("red");
			$(".hint .contacts textarea").focus();
		}
	});
	$('.hint .contacts textarea').live('keypress', function (e) {
		var thv = $(this).val();
		if(thv.length>5){
//			$(".hint .contacts label").removeClass("red");
			$("#send").css("opacity","1");
			$(".contacts").removeClass("arr");
		} else {
//			$(".hint .contacts label").addClass("red");
			$("#send").css("opacity","0.2");
			$(".contacts").addClass("arr");
		}
	});
	$(".find li, .find tr").live("mouseout", function(){
		$(this).removeClass("light");
	});
	$(".find li, .find tr").live("mouseover", function(){
		$(this).addClass("light");
	});
	$(".find li, .find tr").live("click", function(){
		if($(this).hasClass("it")){
			$(this).removeClass("it");
/*
			if($(".find li.it, .find tr.it").length>0){
				$(".addadv").html('Ещё меня заинтересовали '+$(".find li.it, .find tr.it").length+' предложений');
			} else {
				$(".addadv").remove();
			}
*/
		} else {
			$(this).addClass("it");
/*
			if($(".addadv").html()){
				$(".addadv").html('Ещё меня заинтересовали '+$(".find li.it, .find tr.it").length+' предложений');
			} else {
				$(".text").after('<span class="addadv">Ещё меня заинтересовало одно предложение</span>');
			}
*/
		}
		if($(".find li.it, .find tr.it").length>0){
			setEnd(1);
		}
	});
});


function next(curli){
//	alert($(".formstep:has("+curli+")"));
	if(curli.attr("class")!='selected'){
		$("#send").css("display","none");
		var ul = curli.parent();
		var step = ul.parent();
/* pos after */
		var olderpos = $(".form > div").index(step);
		ul.parent().find("li").removeClass("selected");
		ul.parent().find("ul").removeClass();
		ul.parent().find("ul").addClass("oneline");
		curli.addClass("selected");

		var stepid = step.attr("id");

		var curpos = ul.parent().find("li, tr").index(curli)+1;
		var steppos = stepid.substring(4);
		ul.addClass("sel_"+steppos+"_"+curpos);

		/* go to sup query */
		var url = "/nedvijimost/substep.p3";
		var postdata = "step="+steppos+"&select="+curpos;

		postdata = postdata+preparedata(olderpos);

		//alert(postdata);

		jQuery.ajax({
			type: "get",
			url: url,
			data: postdata,
			success: function(html){
/* remove old  */
				$(".form > div:gt("+olderpos+")").filter(".formstep").remove();
				$(".hint").remove();
//				$(".supplylist").remove();
				$(".find").remove();
//				$("#send").prependTo('#sf')
//				$(".botcut").html($("#send").html());
//				$("#send").before(html);
				$("#sf .apto").append(html);
				$(".hint").insertAfter("#sf .tr-form");
//				$(".hint").insertAfter('#sf');
				setEnd();
/* find adverts */
				finds();
				polzunki();

				$("#step6 input").autocomplete("/nedvijimost/metro.p3", {
					delay:10,
					minChars:2,
					matchSubset:1,
					autoFill:true,
					matchContains:1,
					cacheLength:10,
					selectFirst:true,
					maxItemsToShow:10
				});
			}
		});
	}
}

function finds(){
//	$(".find").insert(".find-here");
//	$(".find").insertAfter("#sf");
	$(".find").prependTo('.find-here')
//	var sval = $(".find li, .find tr").length;
//	if(sval>0){
//		$(".supplylist b").html(sval);
//		$(".supplylist").fadeIn(600);
//		$(".supplylist a").click(function () {
//			$("body").animate({scrollTop: $('.supplylist').attr('offsetTop')+200}, 0);
//		});
//	}
}

function selnext(curse){
	var step = curse.parent();
	var steppos = step.attr("id").substring(4);
	var curpos = curse.val();
	var olderpos = $(".form > div").index(step);
	var url = "/nedvijimost/substep.p3";
	var postdata = "step="+steppos+"&select="+curpos;

	postdata = postdata+preparedata(olderpos);

	jQuery.ajax({
		type: "get",
		url: url,
		data: postdata,
		success: function(html){
/* remove old  */
			$(".form > div:gt("+olderpos+")").filter(".formstep").remove();
//			$("#send").before(html);
			$("#sf .apto").append(html);
			$(".hint").insertAfter("#sf .tr-form");
//			step.after(html);
			finds();
			polzunki();
//alert($(".form div").index(step));
/*
			jQuery(".form > div:gt("+olderpos+") li").click(function(){
				next($(this));
			});
*/
		}
	});
}

function nextscale(pid){
	/* prepare data to send */
	var step = $(pid).parent();
/* pos after */
	var olderpos = $(".form > div").index(step);
	var senddata = preparedata(olderpos);

	jQuery.ajax({
		type: "get",
		url: url,
		data: senddata,
		success: function(html){
/* remove old  */
//			$(".form > div:gt("+olderpos+")").filter(".formstep").remove();
			$(".hint").remove();
//			$(".supplylist").remove();
			$(".find").remove();
//			alert(step.html());
//			$("#send").before(html);
			$("#sf .apto").append(html);
			$(".hint").insertAfter("#sf .tr-form");
//			pid.not().after(html);
			setEnd();
/* find adverts */
			finds();
		}
	});

//	alert(senddata);
}

function setEnd(now){
	if($(".setEnd").html() || now){
		$(".setEnd").remove();
		$("#send").css("display","block").css("opacity","0.2");
		$(".contacts").addClass("arr");
		$(".hint .contacts").html('<label for="contacts">Как с вами связаться, пожелания:</label><textarea name="contacts" id="contacts"></textarea>');
	}
}

function preparedata(olderpos){
	/* prepare data to send */
	var formdata = '';
	$(".form > div:lt("+olderpos+")").filter(".formstep").find(".selected").each(function (i){
		var st = $(this).parent().parent().attr("id");
		var stp = st.substring(4);

		formdata = formdata+"&st_"+stp+"="+$(this).attr("value");
	});
	$(".form > div:lt("+olderpos+")").filter(".formstep").find(".select").each(function (i){
		var st = $(this).parent().attr("id");
		var stp = st.substring(4);
		formdata = formdata+"&st_"+stp+"="+$(this).val();
	});
	$("#scale :input, #scalesurf :input, #scaleearth :input").each(function (i){
		var idi = $(this).parent().attr("id");
		var cname = $(this).attr("class");
		formdata = formdata+"&sca_"+idi+"_"+cname+"="+$(this).val();
	});
	return formdata;
}


function polzunki(){
	$(".lowpolzun, .hipolzun").draggable({
		axis: "x",
		containment: [387,1,810,1],
//		grid: [2,10],
 		stop: function(event, ui) {
			var ppid = $(this).parent().attr("id");
			$(".lowpolzun, .hipolzun").removeClass("zbig");
/* check position */
			var lp = $('#'+ppid+' .lowpolzun');
			var hp = $('#'+ppid+' .hipolzun');

			var hpos = hp.css("left"); var hpp = hpos.length-2;
			var lpos = lp.css("left"); var lpp = lpos.length-2;
			var hpos = Number(hpos.substring(0,hpp));
			var lpos = Number(lpos.substring(0,lpp));

			if(lpos > hpos){
				changepos("#"+ppid);
			}
			recalcsum("#"+ppid);
			/* post to form data */
			nextscale("#"+ppid);
		},
		start: function(event, ui) {
			$(this).addClass("zbig");
		},
		drag: function(event, ui) {
			var ppid = $(this).parent().attr("id");
			recalcsum("#"+ppid);
//			$("#test").html(ui.offset.left);
		}
	});
}

function changepos(pid){
	var lpn = $(pid+" .lowpolzun");
	var hpn = $(pid+" .hipolzun");
	var leftlpn = hpn.css("left");
	lpn.addClass("hipolzun").removeClass("lowpolzun");
	hpn.css("left",leftlpn).addClass("lowpolzun").removeClass("hipolzun");
}

function recalcpol(pid){
	var lp = $(pid+" .lowpolzun");
	var hp = $(pid+" .hipolzun");

	var lpos = getcoo($(pid+" .low").val(),pid);
	var hpos = getcoo($(pid+" .hi").val(),pid);

	if(lpos > hpos){
		changepos("#"+pid);
		var lval = $(pid+" .low").val();
		var hval = $(pid+" .hi").val();

		$(pid+" .hi").val(lval);
		$(pid+" .low").val(hval);
	}

	lp.css("left",lpos);
	hp.css("left",hpos);

/* post to form data */
	nextscale(pid);
}

function getcoo(pos,pid){
	val = 0;
	pos = Number(pos);

	switch (pid){
	case "#scalesurf":
		if(pos<=50){
			val = pos*23/50;
		}
		if(pos>50 && pos<=100){
			pos = pos - 50;
			val = pos*80/50+23;
		}
		if(pos>100 && pos<=400){
			pos = pos - 100;
			val = pos*240/300+103;
		}
		if(pos>400 && pos<1001){
			pos = pos - 400;
			val = pos*80/600+343;
		}
		if(pos>=1000){
			val = 424;
		}
	break;
	case "#scaleearth":
		if(pos<=1){
			val = pos*23/1;
		}
		if(pos>1 && pos<=5){
			pos = pos - 1;
			val = pos*80/4+23;
		}
		if(pos>5 && pos<=10){
			pos = pos - 5;
			val = pos*100/5+103;
		}
		if(pos>10 && pos<=20){
			pos = pos - 10;
			val = pos*50/10+203;
		}
		if(pos>20 && pos<=140){
			pos = pos - 20;
			val = pos*150/120+253;
		}
		if(pos>140 && pos<156){
			pos = pos - 140;
			val = pos*20/15+403;
		}
		if(pos>=155){
			val = 424;
		}
	break;
	default:
		if(pos<=1000000){
			val = pos*26/1000000;
		}
		if(pos>1000000 && pos<=5000000){
			pos = pos - 1000000;
			val = pos*160/4000000+26;
		}
		if(pos>5000000 && pos<=13000000){
			pos = pos - 5000000;
			val = pos*160/8000000+186;
		}
		if(pos>13000000 && pos<28000000){
			pos = pos - 13000000;
			val = pos*80/15000000+346;
		}
		if(pos>=28000000){
			val = 424;
		}
	}
	val = val + 77;
	if(val<=0){
		val = '77';
	}
	return Math.round(val);
}


function recalcsum(pid){
	var lp = $(pid+" .lowpolzun");
	var hp = $(pid+" .hipolzun");
	var hpos = hp.css("left"); var hpp = hpos.length-2;
	var lpos = lp.css("left"); var lpp = lpos.length-2;
	var hpos = Number(hpos.substring(0,hpp)-77);
	var lpos = Number(lpos.substring(0,lpp)-77);

	/* get val */
	var lval = getval(lpos,pid);
	var hval = getval(hpos,pid);

	$(pid+" .hi").val(hval);
	$(pid+" .low").val(lval);
}

function getval(pos,pid){
	val = 0;
	pos = Number(pos);

	switch (pid){
	case "#scalesurf":
		if(pos<23){
			val = pos*2.18;
		}
		if(pos>22 && pos<=103){
			pos = pos - 22;
			val = pos*0.625+50;
		}
		if(pos>103 && pos<=343){
			pos = pos - 102;
			val = pos*1.25+100;
		}
		if(pos>343 && pos<423){
			pos = pos - 342;
			val = pos*7.5+400;
		}
	break;
	case "#scaleearth":
		if(pos<23){
			val = pos*0.03;
		}
		if(pos>22 && pos<=203){
			pos = pos - 22;
			val = pos*0.05+1;
		}
		if(pos>203 && pos<=253){
			pos = pos - 203;
			val = pos*0.2+10;
		}
		if(pos>253 && pos<423){
			pos = pos - 253;
			val = pos*0.8+20;
		}
	break;
	default:
		if(pos<=26){
			val = pos*40000;
		}
		if(pos>26 && pos<=186){
			pos = pos - 26;
			val = pos*25000+1000000;
		}
		if(pos>186 && pos<=347){
			pos = pos - 186;
			val = pos*50000+5000000;
		}
		if(pos>347 && pos<423){
			pos = pos - 347;
			val = pos*210526+13000000;
		}
	}
	if(pos>=423){
		val = '0';
	}
	return Math.round(val);
}

