$(document).ready(function()
	{
		makeAjaxStep(1, false);
		testGuestBookForm(true);

		
		$(".r3_Tabs2 a").live("click", function()
		{
			var id_elem = $(this).attr("id");
			var id_content = id_elem + "_content";

			$(".content_container").hide();
			$("#" + id_content).show();

			$(".r3_Tabs2 td").removeClass("active");
			$(this).parent().addClass("active");
		}
		);

		$("#clear_form").click(function()
			{
				$.ajax({
								type: "POST",
								url: "/80",
								cache: false,
								dataType: "json",
								data: "ajax=1&clear=true",
								async: false,
								success:        function(msg)
												{
													$("#steps").html(msg[1]);
													$("#form_step").html(msg[0]);
													makeAjaxStep(1);
												}
								});
			}
		);

		$(".order_link").live("click", function()
		{
			var id_elem = $(this).attr("id");
			var id_item = id_elem.split("_");
			var id_cont = "order_" + id_item[2];
			$.ajax({
				type: "POST",
				url: "/order/30/addtocart",
				cache: false,
				data: "ajax=1&oper=additem&item_id="+id_item[2],
				async: false,
				success:        function(msg)
								{
									$("#Cart").html(msg);
									//$("#Cart").addClass("full");
									$("#" + id_cont).show();
								}
			});
		}
		);
		
		$("#a_lower_40").click(function() {
			$("#lower_40").dialog({
					bgiframe: true,
					modal: true,
					autoOpen: false,
					resizable: false,
					width: 350
			//opacity: 0.7
			});
			$("#lower_40").dialog('open');
		});
		
		$("#truba_full_img").click(function() {
			$("#truba_full").dialog({
					bgiframe: true,
					modal: true,
					autoOpen: false,
					resizable: false,
					width: 700
			//opacity: 0.7
			});
			$("#truba_full").dialog('open');
		});
		
		$("#truba_full_img").live("mouseover", function() {
			$(this).css("cursor", "pointer");
		});
		
		$("#truba_full_img").live("mouseout", function() {
			$(this).css("cursor", "");
		});
		
		
		
		$(".temperature").live("click", function() {
			$("#temperature").val($(this).attr("id"));
			$(".temperature").removeClass("selectorActive");
			$(".temperature").addClass("selectorInactive");
			$(this).removeClass("selectorInactive");
			$(this).addClass("selectorActive");
			
		});
		
		$(".material").live("click", function() {
			$("#material").val($(this).attr("id"));
			$(".material").removeClass("selectorActive");
			$(".material").addClass("selectorInactive");
			$(this).removeClass("selectorInactive");
			$(this).addClass("selectorActive");
			
		});
		
		$("#diameter").change(function() {
			var re = /^([0-9]+)$/i;
			var cstring = $(this).val();
			if(re.test(cstring)) {
				$("#er_diam").hide();
				if((cstring > 108) || (cstring < 25)) {
					$("#a_diam").show();
				}
				else {
					$("#a_diam").hide();
				}
				
			}
			else {
				if(cstring)
					$("#er_diam").show();
				else
					$("#er_diam").hide();						
			}	
		});
		
		$("#izolation").change(function() {
			var re = /^([0-9]+)$/i;
			var cstring = $(this).val();
			if(re.test(cstring)) {
				$("#er_izol").hide();
				if(cstring < 20) {
					$("#a_izol").show();
				}
				else {
					$("#a_izol").hide();
				}
				
			}
			else {
				if(cstring)
					$("#er_izol").show();
				else
					$("#er_izol").hide();	
			}	
		});
		
		$("#length_tr").change(function() {
			var re = /^([0-9]+)$/i;
			var cstring = $(this).val();
			if(re.test(cstring)) {
				$("#er_length").hide();
			}
			else {
				if(cstring)
					$("#er_length").show();
				else
					$("#er_length").hide();	
			}	
		});
		
		$("#calculate_b").click(function() {
			$(this).attr("disabled", "disabled");
			$("#results_calc").replaceWith('<div id="results_calc" style="width:100%;text-align:center"><img src="/images/spinner.gif" /></div>');
			$.ajax({
				type: "POST",
				url: "/areaheating/teplovod/90",
				cache: false,
				data: "ajax=1&nolink=true&calculate=true&temperature="+$("#temperature").val()+"&material="+$("#material").val()+"&diameter="+$("#diameter").val()+"&izolation="+$("#izolation").val()+"&length="+$("#length_tr").val(),
				async: true,
				success:        function(msg)
								{	
									$("#calculate_b").removeAttr("disabled");
									
									$("#results_calc").replaceWith('<div id="results_calc">'+msg+'</div>');
								}
			});
			//alert('s');
		});
		
		$("#order_b").live("mouseover", function() {
			$(this).css("cursor", "pointer");
		});
		
		$("#order_b").live("mouseout", function() {
			$(this).css("cursor", "");
		});
		
		$("#order_b").live("click", function() {
			$(this).replaceWith('<div id="order_b" style="width:100%;text-align:center"><img src="/images/spinner.gif" /></div>');			
			$.ajax({
				type: "POST",
				url: "/order/30/addtocart",
				cache: false,
				data: "ajax=1&oper=additem&item_id="+$("#selected_item_ids").val(),
				async: false,
				success:        function(msg)
								{
									$("#order_b").replaceWith('<div style="text-align:center;width:100%"><p>Ваш выбор добавлен в <a href="/order">Корзину</a></p></div>');
									$("#Cart").html(msg);
									$("#Cart").addClass("full");
								}
			});	
		});
		
	}
);
function getMapContent(reg, city)
{
	$("#mapdata").hide();
	$("#waiting").show();
	$.ajax({
				type: "POST",
				url: "/buy/1/mapcontent",
				cache: false,
				data: "ajax=true&reg=" + reg + "&city="+city,
				async: false,
				success:        function(msg)
								{
									$("#mapdata").html(msg);
									$("#waiting").hide();
									$("#mapdata").show();
									if(city)
										location.hash = "#"+city;
									if(reg)
										location.hash = "#"+reg;
								}
			});
}

function testGuestBookForm(init)
{

	$("#error_message").hide();
	$("#error_email").hide();

	if(!init)
		{
			var flag = 0;

			var re = /\S+/;
			if(!($("#message").val().match(re)))
				{
					$("#error_message").show();
					flag = 1;
				}
			if($("#needemail").attr("checked"))
				{
					if(!($("#author_email").val().match(re)))
						{
							$("#error_email").show();
							flag = 1;
						}
				}
			if(!flag)
				{
					$("#guest_form").submit();
				}
		}
}
function loadSections(id)
{
	var hash = location.hash;
	if(hash != "")
		id = hash.substring(1);

	var id_content = id + "_content";
	$("#" + id_content).show();
	$("#" + id).parent().addClass("active");
}

function compare(current_id)
{

}

function rewriteSteps()
{
	var current_step    = $("#formshop_current_step").val();
	var completed_steps = "";
	for(var j = 1; j < current_step; j++)
		{
			if(completed_steps)
				completed_steps += ",";
			completed_steps += j;
		}
	//$("#formshop_completed_steps").val(completed_steps);

	initSteps(current_step, completed_steps);
}

function checkForm(step)
{
	if(step == 1)
		return checkForm1();
	if(step == 2)
		return checkForm2();
	if(step == 3)
		return checkForm3();
	if(step == 4)
		return checkForm4();
}

function checkForm1()
{
	var flag_ok = false;
	var flag_rooms = false;
	for(var i = 1; i < 8; i++)
		{
			var id_elem = "room_" + i;
			var id_elem_count = "room_" + i + "_count";
			var id_elem_error = "room_" + i + "_error";
			if($("#" + id_elem).attr("checked") == true)
				{
					var count = $("#" + id_elem_count).val();
					var re = /^([1-9]+)$/i;
					if(re.test(count))
						{
							//скрываем ошибку в поле, если она была показана
							$("#" + id_elem_error).hide();
							flag_ok = true;
						}
					else
						{
							$("#" + id_elem_error).show();
							flag_rooms = true;
						}
				}
			else
				{
					//скрываем ошибку в поле, если она была показана
					$("#" + id_elem_error).hide();
				}
		}
	if(flag_ok == false)
		{
			$("#form1_error").show();
			if(flag_rooms == false)
				$("#form1_error_global").show();
		}
	else
		{
			//скрываем все ошибки в форме
			$("#form1_error").hide();
			$("#form1_error_global").hide();
			return true;
		}
}

function checkForm2()
{
	var flag_ok = true;

	var re = /^([0-9\.\,]+)$/i;

	$(".pad > input[type='text']").each(function()
		{
			if(re.test($(this).val()))
				{
					var id_error = $(this).attr("id") + "_error";
					//скрываем ошибку в поле, если она была показана
					$("#" + id_error).hide();
				}
			else
				{
					var id_error = $(this).attr("id") + "_error";
					$("#" + id_error).show();
					flag_ok = false;
				}
			$(this).val($(this).val().replace(",", "."));
		}
	);

	if(flag_ok == false)
		{
			$("#form2_error").show();
		}
	else
		{
			//скрываем все ошибки в форме
			$("#form2_error").hide();
			return true;
		}
}

function checkForm3()
{
	return true;
}

function checkForm4()
{
	var flag_ok = true;
	var re = /\S+/;
	var re_email = /^([A-z0-9_\-]+\.)*[A-z0-9_\-]+@([A-z0-9][A-z0-9\-]*[A-z0-9]\.)+[A-z]{2,4}$/i;
	$("input[type='text']").each(function()
		{
			var re_test = re;
			if($(this).attr("id") == "email")
				re_test = re_email;

			if(re.test($(this).val()))
				{
					var id_error = $(this).attr("id") + "_error";
					//скрываем ошибку в поле, если она была показана
					$("#" + id_error).hide();
				}
			else
				{
					var id_error = $(this).attr("id") + "_error";
					$("#" + id_error).show();
					flag_ok = false;
				}
		}
	);

	if(flag_ok == false)
		{
			$("#form4_error").show();
		}
	else
		{
			//скрываем все ошибки в форме
			$("#form4_error").hide();
			return true;
		}
}

function initSteps(current_step, completed_steps)
{
	$("#formshop_steps > li").eq(current_step - 1).addClass("current");

	var labelcontents = new Array();
	var parcontents   = new Array();

	labelcontents[labelcontents.length] = 'Шаг 1';
	labelcontents[labelcontents.length] = 'Шаг 2';
	labelcontents[labelcontents.length] = 'Шаг 3';
	labelcontents[labelcontents.length] = 'Шаг 4';
	parcontents[parcontents.length] = 'Выбрать<br>помещения';
	parcontents[parcontents.length] = 'Вид обогрева,<br>тип установки';
	parcontents[parcontents.length] = 'Подобрать<br>варианты';
	parcontents[parcontents.length] = 'Купить<br>теплый пол';
	//Инициализация
	for(var i = 1; i < 5; i++)
		{
			var elem = $("#formshop_steps > li").eq(parseInt(i - 1));
			elem.removeClass("completed");
			elem.removeClass("active");
			$("#"+elem.attr("id")+" > label").eq(0).html(labelcontents[i-1]);
			$("#"+elem.attr("id")+" > p").eq(0).html(parcontents[i-1]);
		}
	if(completed_steps)
		{
			var steps = completed_steps.split(",");
			var max_completed_step = steps[steps.length - 1];
			for(var i = 0; i < steps.length; i++)
				{
					var elem = $("#formshop_steps > li").eq(parseInt(steps[i]) - 1);
					elem.addClass("completed");
					var labelcontent = $("#"+elem.attr("id")+" > label").eq(0).html();
					labelcontent = '<a id="formshop_step' + steps[i] + '">' + labelcontent + '</a>';
					var parcontent = $("#"+elem.attr("id")+" > p").eq(0).html();
					parcontent = '<a id="formshop_step' + steps[i] + '_l">' + parcontent + '</a>';

					$("#"+elem.attr("id")+" > label").eq(0).html(labelcontent);
					$("#"+elem.attr("id")+" > p").eq(0).html(parcontent);
				}

			if(max_completed_step < 4)
				{
					var next_step_active = parseInt(max_completed_step) + 1;
					var elem = $("#formshop_steps > li").eq(parseInt(next_step_active) - 1);
					elem.addClass("active");
					var labelcontent = $("#"+elem.attr("id")+" > label").eq(0).html();
					labelcontent = '<a id="formshop_step' + next_step_active + '">' + labelcontent + '</a>';
					var parcontent = $("#"+elem.attr("id")+" > p").eq(0).html();
					parcontent = '<a id="formshop_step' + next_step_active + '_l">' + parcontent + '</a>';

					$("#"+elem.attr("id")+" > label").eq(0).html(labelcontent);
					$("#"+elem.attr("id")+" > p").eq(0).html(parcontent);
				}
		}
}

function makeAjaxStep(step, ajax)
{
	if(ajax == true)
		{
			$.ajax({
				type: "POST",
				url: "/80",
				cache: false,
				data: "ajax=1&steps="+step,
				async: false,
				success:        function(msg)
								{
									$("#steps").html(msg);
								}
			});

			$.ajax({
				type: "POST",
				url: "/80",
				cache: false,
				data: "ajax=1&step="+step,
				async: false,
				success:        function(msg)
								{
									$("#form_step").html(msg);
								}
			});
		}

	var current_step    = $("#formshop_current_step").val();
	var completed_steps = $("#formshop_completed_steps").val();

	initSteps(current_step, completed_steps);
	initForm(current_step);

	$("#button_next_step").val(current_step);

	$("a").mouseover(function()
			{
				$(this).css("cursor", "pointer");
			}
	);

	$("#formshop_step1").click(function()
			{
				makeAjaxStep(1, true);
			}
		);

		$("#formshop_step1_l").click(function()
			{
				makeAjaxStep(1, true);
			}
		);

		$("#formshop_step2").click(function()
			{
				makeAjaxStep(2, true);
			}
		);

		$("#formshop_step2_l").click(function()
			{
				makeAjaxStep(2, true);
			}
		);

		$("#formshop_step3").click(function()
			{
				makeAjaxStep(3, true);
			}
		);

		$("#formshop_step3_l").click(function()
			{
				makeAjaxStep(3, true);
			}
		);

		$("#formshop_step4").click(function()
			{
				makeAjaxStep(4, true);
			}
		);

		$("#formshop_step4_l").click(function()
			{
				makeAjaxStep(4, true);
			}
		);

		//кнопочка, по которой происходит сабмит любой формы
	   $("#button_next").live("click", function()
			{
				if(current_step == $("#button_next_step").val())
					{
						if(checkForm(current_step))
							{
								var id_form = "formstep_" + current_step;
								$.ajax({
								type: "POST",
								url: "/80",
								cache: false,
								dataType: "json",
								data: $("#"+id_form).serialize() + "&ajax=1&form="+current_step,
								async: false,
								success:        function(msg)
												{
													$("#steps").html(msg[1]);
													$("#form_step").html(msg[0]);
													makeAjaxStep(current_step + 1);
												}
								});
							}
					}
			}
	   );
}

function initForm(step)
{
	if(step == 1)
		initForm1();
	if(step == 2)
		initForm2();
	if(step == 3)
		initForm3();
	if(step == 4)
		initForm4();
}

function initForm1()
{
	$(".buttons_wrapper").show();
	for(var i = 1; i < 8; i++)
		{
			var id_elem = "room_" + i;
			var id_target = id_elem + "_count";

			if($("#" + id_elem).attr("checked") == true)
				{
					$("#"+id_target).removeAttr("disabled");
				}
			else
				{
					$("#"+id_target).attr("disabled", "disabled");
				}
		}

	//чекбоксы на прослушку
	$("#inputs_container > p > input[type='checkbox']").click(function()
			{
				var id = $(this).attr("id");
				var id_target = id + "_count";
				if($(this).attr("checked") == true)
					{
						$("#"+id_target).removeAttr("disabled");
					}
				else
					{
						$("#"+id_target).attr("disabled", "disabled");
					}
//После каждого нажатия надо проверить форму
				checkForm(1);

			}
	);

   //Первая форма - текстовые поля ввода количества помещений
   $("#inputs_container > p > span > input[type='text']").blur(function()
		{
			//После каждого нажатия на кнопку надо проверить форму
			checkForm(1);
			compare($(this).attr("id"));
		}
   );

   //Если их меняют, то надо блокировать переход по шагам без отправки формы
   $("#inputs_container > p > span > input[type='text']").mouseup(function()
		{
			checkForm(1);
			compareSteps($(this).attr("id"));
		}
   );

   //Если их меняют, то надо блокировать переход по шагам без отправки формы
/*   $("#inputs_container > p > span > input[type='text']").keyup(function()
		{
			checkForm(1);
			compareSteps($(this).attr("id"));
		}
   );*/

   //checkForm(1);
}

function initForm2()
{
	$(".buttons_wrapper").show();
	$(".AdviceList").hide();
	//Чекбокс тушит активный выбор терморегулятора
	$(".pad > input[type='checkbox']").each(function()
		{
				var id = $(this).attr("id");
				var id_target = id.substring(2);
				if($(this).attr("checked") == true)
					$("#" + id_target).attr("disabled", "disabled");
				else
					$("#" + id_target).attr("disabled", "");
		}
	);

	$(".advice > a").click(function()
		{
			$("#" + $(this).attr("id") + "_list").toggle();
		}
	);

	$(".advice_thermo > a").click(function()
		{
			$("#" + $(this).attr("id") + "_list").toggle();
		}
	);

	//Вторая форма - текстовые поля ввода площади
	$(".pad > input[type='text']").blur(function()
		{
			//После каждого нажатия на кнопку надо проверить форму
			checkForm(2);
			//rewriteSteps($(this).attr("id"));
		}
	);

   //Если их меняют, то надо блокировать переход по шагам без отправки формы
	$(".pad > input[type='text']").mouseup(function()
		{
			checkForm(2);
			//rewriteSteps($(this).attr("id"));
		}
	);

	//Чекбокс тушит активный выбор терморегулятора
	$(".pad > input[type='checkbox']").click(function()
		{
				var id = $(this).attr("id");
				var id_target = id.substring(2);
				if($(this).attr("checked") == true)
					$("#" + id_target).attr("disabled", "disabled");
				else
					$("#" + id_target).attr("disabled", "");
		}
	);

   //Если их меняют, то надо блокировать переход по шагам без отправки формы
	/*$(".pad > input[type='text']").keyup(function()
		{
			checkForm(2);
			//rewriteSteps($(this).attr("id"));
		}
	);*/

   //checkForm(2);

}

function initForm3()
{
	$(".buttons_wrapper").show();
	$(".desc_short").hide();

	$(".advice > a").click(function()
		{
			$("#" + $(this).attr("id") + "_list").toggle();
		}
	);

	//при нажатии на радиобаттон, подсветить строку

	$(".radio_wrapper > input").click(function()
		{
			//со всех убрать подсветку
			var id_active = $(this).attr("id").split("_");
			//получили табличку, в которой произошел клик
			var table_id = id_active[0] + "_" + id_active[1] + "_table";
			$("#" + table_id + " td").removeClass("selected");

			//подсветить соответствующие td
			$("#" + $(this).attr("id") + "_td1").addClass("selected");
			$("#" + $(this).attr("id") + "_td2").addClass("selected");


		}
	);

   //checkForm(3);
}

function initForm4()
{
	$(".buttons_wrapper").hide();
	$.ajax({
				type: "POST",
				url: "/order/30/showcart",
				cache: false,
				data: "ajax=1&oper=showcart",
				async: false,
				success:        function(msg)
								{
									$("#Cart").html(msg);
									//$("#Cart").addClass("full");
								}
			});
}
function OpenSubMenu(){
	var loc  = document.location.href.split("/");
	l = loc.length;
	le = l-2;

	if (document.getElementById(loc[3])) {
		document.getElementById(loc[3]).style.display ="block";
	}
	if (document.getElementById(loc[le])) {
		document.getElementById(loc[le]).className += " active";
	}
}
