$(
	function()
	{
		$("input[rel='inp_points']").numeric();
		$("input[rel='inp_points']").change(function(event)
		{
			if ($(this).val() % 50 != "")
			{
				$(this).val(0);
				return false;
			}
		});
    
    $(".search .btn").click(function(){
      $(".search form").submit();
    });
    				
		$(".search input").emptyText( ($(".search input").val() == "") ? "Поиск по магазину" : $(".search input").val(), "inp_inactive");

		$(".search input").keypress(
				function(e)
				{
					var code = (e.keyCode ? e.keyCode : e.which);
					if(code == 13) 
					{
						$(".search form").submit();
					}
				}
		);
		
		$(".search input").focus(
				function()
				{
					$(this).parent().css("background", "#ffffe9")
				}
		);
		$(".search input").blur(
				function()
				{
					if ($(this).val() == "" || $(this).val() == "Поиск по магазину" || $(this).val() == $(this).attr("data-initial"))
						$(this).parent().css("background", "#fff")
				}
		);
		
		
		$(".select-nest select").sexyCombo({
			triggerSelected: true,
			emptyText: "Производители",
    		autoFill: true,
    		suffix: "",
    		hiddenSuffix: "producer",
    		name: "producer",
    		value: 1
		});
		
		$("a[rel=fancybox]").fancybox();
		

		$("input[name=delivery]").click(function()
		{
			var allow = $(this).attr("data-payment-allow").split(",");
			$("#payment input").attr("disabled", "disabled");
			for (i in allow)
			{
				$("#payment input[value=" + allow[i] + "]").attr("disabled", "");
			}
			
			if ($("input[name=user_type][rel=jur]:checked").size() > 0)
			{
				$("#payment input[value=1], #payment input[value=3], #payment input[value=4], #payment input[value=5]").attr("disabled", "disabled");
			}
			$("#payment input:disabled").attr("checked", "");
		});
		
		$("input[name=user_type]").click(function()
		{
			var allow = $(this).attr("rel");
			
			$("#delivery input").attr("disabled", "disabled");
			
			$("#delivery input").each(function()
			{
				if ($(this).attr("data-user-allow").match(allow))
				{
					$(this).attr("disabled", "");
				}
			});
			$("#delivery input:disabled").attr("checked", "");
		});
		
		$(".i_numeric").each(function()
		{
			//$(this).emptyText($(this).attr("title"), "inp_inactive");
		})
		
		$(window).resize(function()
		{
			resizeFilter();
		});
		resizeFilter();
		

		$(".extended-filter").click(function()
		{
			if ($(".filter").attr("data-state") == "closed")
			{
				$(".filter").animate(
				{
					"height": $(".filter .wrapper").height() - 8 + "px"
				},
				{
					easing: 'easeOutExpo',
					duration: 500,
					queue: false,
					complete: function()
					{
						$(".filter").attr("data-state", "open");
						$(".extended-filter").html("Простой поиск");
						
						var date = new Date();
					    date.setTime(date.getTime() + 186624000000);
						$.cookie("data-state", "open", { path: "/", expires: date});
					}
				});
			}
			else
			{
				$(".filter").animate(
				{
					"height": "35px"
				},
				{
					easing: 'easeOutExpo',
					duration: 500,
					queue: false,
					complete: function()
					{
						$(".filter").attr("data-state", "closed");
						$(".extended-filter").html("Расширенный поиск");
						
						var date = new Date();
					    date.setTime(date.getTime() + 186624000000);
						$.cookie("data-state", "closed", { path: "/", expires: date});
					}
				});
			}
		});
		/*
		$(".filter").mouseleave(function()
		{
			$(this).animate(
			{
				"height": "35px"
			},
			{
				easing: 'easeOutExpo',
				duration: 500,
				queue: false
			});
		});
		*/
		
		$(".catalog-menu").accordion(
		{ 
			header: ".h-title", 
			autoHeight: false,
			collapsible: true,
			navigation: true,
			active: false
		});
		
		$(".catalog-menu .line").accordion(
		{ 
			header: ".h", 
			autoHeight: false,
			collapsible: true,
			navigation: true,
			active: false,
			navigationFilter: function () 
			{
				var l = location.href.split("/");
				
				if (l.length <= 5)
				{
					var res = -1;
				}
				else
				{
					var res0 = location.href.indexOf(this.href)
					var res1 = this.href.indexOf(location.href)
					var res = (res0 != -1) ? res0 : res1;
				}
			    return res != -1;
			}
		});
		

		$(window).resize(function() 
		{
			doResize();
		});
		
		
		if ($("#YMapsID").length > 0)
		{
			var map = new YMaps.Map(document.getElementById("YMapsID"));
			map.setCenter(new YMaps.GeoPoint(37.732896,55.884592), 15, YMaps.MapType.MAP);
			map.addControl(new YMaps.ToolBar());
			map.addControl(new YMaps.Zoom());
			map.addControl(new YMaps.MiniMap());
			map.addControl(new YMaps.TypeControl());
			var traffic = new YMaps.Traffic.Control();
			map.addControl(traffic);
			var placemark = new YMaps.Placemark(new YMaps.GeoPoint(37.732896,55.884592));
			placemark.name = "Термокит";
			placemark.description = "Пересечение Ярославского шоссе и МКАД (94км),<br />на территория Строительного рынка \"ТрактТерминал\"<br />павильон А9";
			map.addOverlay(placemark);
			placemark.openBalloon();
		}
		
		
		var n = 0;
		$(".slides .item").each(function()
		{
			n++;
			$(this).css("z-index", n);
			
			$(".slides .switches").append("<a href=\"/\" id=\"" + n + "\"><span></span>" + n + "</a>");
			$(".slides .switches #" + n).click(function()
			{
				showSlide( $(this).attr("id") );
				return false;
			});
		});
	}
	
);


var current_slide = 0;
var t_switch = null;
$(window).load(function()
{
	doResize();
	t_switch = window.setTimeout( "showSlide()", 10);	
});


function showSlide( i )
{	
	if (i)
	{
		current_slide = i - 1;
	}
	
	$(".slides .item:not(:eq(" + current_slide + "))").animate(
	{
		"opacity": 0.0
	},
	{
		duration: 500, 
		complete: function() 
					{ 
						$(this).css("z-index", "1");
					}
	});
				
	$(".slides .item:eq(" + current_slide + ")").animate(
	{
		"opacity": 1.0
	},
	{
		duration: 500, 
		complete: function() 
					{ 
						$(this).css("z-index", "10");
					}
	});

	// TODO 
	//$(".slides .switches a").removeAttr("class");
	//$(".slides #" + i).attr("class", "active");
	
	current_slide++;
	
	if (current_slide >= $(".slides .item").length)
	{
		current_slide = 0;
	}

	clearTimeout(t_switch)
	t_switch = window.setTimeout(  "showSlide()", 10000);	
}


function resizeFilter()
{
	$(".filter .wrapper").width(1);
	$(".filter .wrapper").width(340 * Math.floor($(".filter").width() / 340));
	
	if ($.cookie("data-state") != "open")
	{
		$(".filter").height(35);
	}
	else
	{
		$(".filter").height($(".filter .wrapper").height() - 8);
	}
	
	/*
	if ($(window).width() > 1300)
	{
		$(".icq").css("display", "block");
	}
	else
	{
		$(".icq").css("display", "none");
	}
	*/
}



$(window).load(function()
{
	doResize();
});




function doResize()
{
	var gallery_w = $(".overview").width();
	var item_w = $(".overview .item").width();
	var min_space_w = 10;
	
	var fits_amount =  Math.floor(gallery_w / (item_w + min_space_w * 2));
	var diff = gallery_w - fits_amount * (item_w + min_space_w * 2);
	
	while (diff < min_space_w)
	{
		fits_amount--;
		diff = gallery_w - fits_amount * (item_w + min_space_w * 2);
	}
	
	var margin = Math.floor(diff / 2 / fits_amount);
	

	$(".overview .item").css("marginLeft", margin )
	$(".overview .item").css("marginRight", margin )
}



function flash($obj, id)
{
	$obj.parent().parent().animate({"opacity": 0.2}, {
									easing: 	'easeOutExpo', 
									duration: 	1000,	
									queue: 		false, 
									complete: 	function() 
												{
										 			makeRequest('addToCart', id);
													$(this).animate({"opacity": 1}, {easing: 'easeOutExpo', duration: 1000})
												} 
								});
}


function strReplace(s, r, w)
{
	return s.split(r).join(w);
}

function addslashes(str) 
{
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) 
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function trim(str)
{ 
	str = str.replace(/&nbsp;/g, '');
	return str.replace(/(^\s+)|(\s+$)/g, '');
}


function isNumber(val) 
{
	return /^-?((\d+\.?\d?)|(\.\d+))$/.test(val);
}


function makeRequest(url) 
{
	var http_request = false;

	if (window.XMLHttpRequest) 
	{ // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			http_request.overrideMimeType('text/html');
			// Читайте ниже об этой строке
		}
	} 
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
			}
		}
	}


	if (!http_request) 
	{
		alert('Unfortunatly your browser doesn\'t support XMLHTTP.');
		return false;
	}

	http_request.onreadystatechange = function() 
	{ 
		if (http_request.readyState == 4)
		{
         if (http_request.status == 200)
			{
				
				var answer = eval('(' + http_request.responseText + ')');
				//alert(http_request.responseText);
				if (answer.callback[0] == "applyFilter")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
					}
					else if (answer.user_error.length > 0)
					{	
						
					}				
					else
					{
						//document.location.reload();
					}
				}
				
				
				else if (answer.callback[0] == "signUp")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
						
						$(".img_antibot").attr("src", "/antibot.php?rnd=" + Math.random() * 999999);
						$("#key").val("");
					}
					else
					{
						$("#form_signup").html(answer.content[0]);
					}
					$("#form_signup").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				
				else if (answer.callback[0] == "repeatSignup")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).parent().find(".d_error").html(this[0]);
						});	
					}
					else
					{
						$("#form_signup").html(answer.content[0]);
					}
				}
				
				else if (answer.callback[0] == "signIn")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
					}
					else
					{
						document.location = "/";
					}
					$("#form_signin").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				
				else if (answer.callback[0] == "amnesia")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
					}
					else
					{
						$("#form_amnesia").html(answer.content[0]);
					}
					$("#form_amnesia").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				else if (answer.callback[0] == "saveProfile")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().addClass("error");
						});
					}
					else
					{
						//$("#form_save_profile .sp_result").html(answer.content[0]);
						$.pnotify({
							pnotify_history: false,
							pnotify_notice_icon: "",
							pnotify_title: "Личные данные",
							pnotify_text: answer.content[0]
						});
					}
					$("#form_save_profile").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				else if (answer.callback[0] == "addToCart")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка заказа",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
						});
					}
					else
					{
						$("#cart_info").html(answer.content[0]);
						
						$.pnotify({
							pnotify_history: false,
							pnotify_notice_icon: "",
							pnotify_title: "Товар добавлен в корзину",
							pnotify_notice_icon: 'picon picon-mail-unread-new',
							pnotify_text: answer.result[0]
						});
					}
				}
				
				else if (answer.callback[0] == "delFromCart")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$("#" + this[1]).parent().find(".d_error").html(this[0]);
						});
					}
					else
					{
						$("#cart_info").html(answer.content[0]);
						$('#refresh_cart').submit();
					}
				}
				
				
				else if (answer.callback[0] == "sendOrder")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
					}
					else
					{
						$(".form_order").html(answer.content[0]);
						$(".d_order_summary").html("").hide();
						$("#cart_info").html(answer.cart_content[0]);
						$(".a_cart_prev_step").css("display", "none");
					}
					$("#submit").attr("disabled", "");
					$("#submit").html("оформить");
				}
				
				
				
				
				
				else if (answer.callback[0] == "orderCall")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
					}
					else
					{
						$(".form_order").html(answer.content[0]);
					}
					$(".a_confirm").attr("disabled", "");
					$(".a_confirm").html("попросить перезвонить");
				}
				
				
				
				else if (answer.callback[0] == "traceProduct")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
						});
					}
					else
					{
						$.pnotify({
							pnotify_history: false,
							pnotify_notice_icon: "",
							pnotify_title: "Наблюдение за товаром",
							pnotify_text: "Мы сразу же сообщим Вам, как только товар появится на складе."
						});
					}
				}
				

				else if (answer.callback[0] == "sendFeedback")
				{
					if (answer.system_error.length > 0)
					{
					}
					else if (answer.user_error.length > 0)
					{
						$.each(answer.user_error, function()
						{
							$.pnotify({
								pnotify_history: false,
								pnotify_notice_icon: "",
								pnotify_title: "Ошибка",
								pnotify_type: "error",
								pnotify_text: this[0]
							});
							
							$("#" + this[1]).parent().parent().addClass("error");
						});
						
						$(".img_antibot").attr("src", "/antibot.php?rnd=" + Math.random() * 999999);
						$("#key").val("");
					}
					else
					{
						$("#form_feedback").html(answer.content[0]);
					}
					$("#form_feedback").find("input[type=\"button\"]").attr("disabled", "");
				}
				
				else if (answer.callback[0] == "showOrderInfo")
				{
					if (answer.system_error.length > 0)
					{	
						var error = "<ul>";	
						$.each(answer.system_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Системная ошибка");
					}
					else if (answer.user_error.length > 0)
					{
						var error = "<ul>";	
						$.each(answer.user_error, function()
						{
							error += "<li>" +  this + "</li>";
						});
						error += "</ul>";
						jAlert(error, "Ошибка");
					}
					else
					{
						$.prompt( answer.content[0]);
					}
				}
			}
			else
			{
				alert("Не удалось получить ответ от сервера");
			}
		}
	};


	$("#curtain").css("display", "block");
	//************** ОБРАБАТЫВАЕМ КЛИКИ
	var args = "";
	for (var i = 0; i < arguments.length; i++)
	{
		args += "&p" + i + "=" + arguments[i];
	}
	
	http_request.open('POST', "/getAnswer.php", true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//http_request.setRequestHeader("Connection", "close");	
	http_request.send("q=" + url + args);
}

function applyFilter()
{
	var url = "";
	$("input[data-rel='filter']").each(function()
	{
		if ( $(this).val() != "" )
		{
			//url += "/"
			//alert("p")
		}
	});
}
