﻿var isSlided = false;
var isSlidedBasket = false;
var isBasketSlided = false;
var isOpeningMenu = false;
var showWindow;
var newProductWindow;
$(document).ready(
	function () {
		onResize();
		$(window).resize(onResize);
		TopMenu();

		$("body").click(
			  function () {
			  	if (isSlided) {
			  		$("#slide").animate({ marginTop: "-80px" }, 150);
			  		isSlided = false;
			  		$("#slidebtn").css("background", "url(/Images/slide_button_info.png)");
			  	}
			  }
		);

		$('div#product_fotos a.product_img').flyout();

		//$('div.productImage a.product_img').flyout();

		$('a.buybtn').bind("click", function (e) {
			if (isSlidedBasket) {
				HideBasket(e);
			}
			var count = 1;
			var attr = $(this).attr("multi");
			var IsMulty = attr == undefined ? false : true;
			if (IsMulty) {
				count = parseInt(attr);
			}
			AddToBasket(this, count, true, e);
			//AddToBasket(this, 1, true, e);
			Purchese(true);
		});


		$('#menu_and_basket div#basket').click(
			function (e) {
				if (isSlidedBasket) {
					HideBasket(e);
				}
				else {
					ShowBasket(e);
					isSlidedBasket = true;
				}
				return false;
			}
		);

		$("a#miniAdd").live("click",
			function (e) {
				var elem = $(this);
				var productId = elem.attr("product");
				var productPrice = elem.attr("price");

				var goodcount = 1;
				var attr = $(this).attr("multi");
				var IsMulty = attr == undefined ? false : true;
				if (IsMulty) {
					goodcount = parseInt(attr);
				}
				AddToBasket(this, goodcount, false);

				var div = elem.parent().parent();
				var count = div.find("span.c");
				var productCount = parseInt(count.text());
				count.text(productCount + goodcount);

				var prCount = $("#basket_info strong.productCount");
				var prPrice = $("#basket_info strong.productsPrice");

				var iCount = parseInt(prCount.text()) + goodcount;
				var iPrice = parseInt(prPrice.text()) + parseInt(productPrice) * goodcount;

				prCount.text(iCount);
				prPrice.text(iPrice);
			}
		);

		$("a#miniDel").live("click",
			function (e) {
				var elem = $(this);
				var productId = elem.attr("product");
				var productPrice = elem.attr("price");

				var goodcount = 1;
				var attr = $(this).attr("multi");
				var IsMulty = attr == undefined ? false : true;
				if (IsMulty) {
					goodcount = parseInt(attr);
				}
				DeleteToBasket(this, goodcount);

				var div = elem.parent().parent();
				var count = div.find("span.c");
				var productCount = parseInt(count.text());
				if ((productCount - goodcount) == 0) {
					div.css("display", "none");
				}

				count.text(productCount - goodcount);

				var prCount = $("#basket_info strong.productCount");
				var prPrice = $("#basket_info strong.productsPrice");

				var iCount = parseInt(prCount.text()) - goodcount;
				var iPrice = parseInt(prPrice.text()) - parseInt(productPrice) * goodcount;

				if (iCount == 0) {
					document.getElementById('basket_info').innerHTML = "<div style='padding-left:20px;height:20px;vertical-align:top'>Ваша корзина пуста!<br/></div>";
					$('#basket_submit').css("display", "none");
					HideBasket(e);
				}
				else {
					prCount.text(iCount);
					prPrice.text(iPrice);
				}


			}
		);

		$("#btnCompare").live("click", function (e) {
			productIDs = "";
			groupId = $(this).attr("href").replace("#", "");
			if (groupId.length > 0) {
				$("input[name='compareCheckBox']").each(JoinProductId);
				if (productIDs.length > 0) AddToCompare(productIDs);
			}
			return false;
		});

		//  Обработка выбора городов
		$("#townList").hover(function () {
			var position = $("#townList").position();
			var block = $("#subcontent");
			//block.css("top", (position.top + 15) + "px");
			//block.css("left", (position.left + $("#townList").width() - 66) + "px");
			block.css("top", "170px");
			block.css("left", "90px");
			block.show();
			return false;
		}, function () {
			timerOnce = window.setTimeout(function () {
				$("#subcontent").hide();
			}, 100);
		});

		$("#subcontent").hover(function () {
			if (timerOnce != undefined) {
				window.clearTimeout(timerOnce);
			}
		}, function () {
			$("#subcontent").hide();
		});
		// END  Обработка выбора городов
	}
);


var groupId = '';
var productIDs = '';
var sMessage = "Не удалось добавить товар в список сравнения. Попробуйте ещё раз.";

 function JoinProductId(intIndex) {
	if ($(this).attr("checked")) {
		if (productIDs.length > 0) productIDs += ",";
		productIDs += $(this).val();
	}
}

function AddToCompare(products) {

	$.get("/ajax/AddToCompare.aspx?product.id=" + productIDs + "&category.id=" + groupId + "&rnd=" + Math.random(),
	function (data) {
		if (data == "1") {
			var wnd = window.open('/compare-' + groupId + '/', '_compare' + groupId);
			wnd.focus();
		}
		else {
			alert(sMessage);
		}
	});

	var wnd2 = window.open('/compare-' + groupId + '/', '_compare' + groupId);
	wnd2.focus();

	return false;
}

function HideBasket(e) {
	if (($("#basket_sidebox").is(":visible"))) {
		$("#basket_arrow").css("background", "url(/Images/basket_button_arrow_bottom.png)");
		isSlidedBasket = false;
		$("#basket_sidebox").hide("slow");
	}
}

function ShowBasket(e) {
	e.stopPropagation();
	e.stopImmediatePropagation();
	if (($("#basket_sidebox").is(":hidden"))) {
		$("div.basket_boxbody").load("/GetBasketItems.aspx?r=" + Math.random(), null, function () {
			$("#basket_arrow").css("background", "url(/Images/basket_button_arrow_top.png)");
			isSlidedBasket = true;
			$("#basket_sidebox").show("slow");
		});
	}
}

function AddToBasket(elem, goodcount, usePopup, e) {
	var popUp = $("#basket_sidebox");
	var aElem = $(elem);
	var productId = aElem.attr("product");
	var productPrice = parseInt(aElem.attr("price")) * goodcount;
	var buyimg = aElem.children('img.buyimg');
	var buyimg = aElem.children('img.buyimg');
	var isHaveImage = false;
	if (buyimg.length > 0) {
		isHaveImage = true;
	}
	var IsUHT = aElem.attr("uht") == undefined ? false : true;
	var IsSale = aElem.attr("sale") == undefined ? false : true;
	var IsDiscount = aElem.attr("discount") == undefined ? false : true;
	var urlModifers = '', aText;

	if (IsUHT) {
		if (isHaveImage) {
			buyimg.attr("src", "/images/ajax-loader-green.gif");
		}
		urlModifers += '&uht=1';
	}
	else if (isHaveImage) {
		buyimg.attr("src", "/images/ajax-loader.gif");
	}
	else {
		aText = aElem.html();
		if (usePopup) aElem.html("<img src='/images/ajax-loader.gif' />");
	}
	if (IsSale) {
		urlModifers += '&sale=1';
	}
	if (IsDiscount) {
		urlModifers += '&discount=1';
	}

	$.get("/Basket/AddToBasket.aspx?product=" + productId + "&count=" + goodcount + "&rnd=" + Math.random() + urlModifers,
		function (data) {
			if (data == "1") {
				if (IsDiscount) {
					var i = 1;
				}
				else {
					var prCount = $("#basket_count_product");
					var prPrice = $("span#amount_to_paid");

					var count = parseInt(prCount.text()) + goodcount;
					var price = parseInt(prPrice.text()) + productPrice;

					$("#basket_count_product").text(count);
					$("span#product_count").text(count);
					$("span#amount_to_paid").text(price);
				}

				if (IsUHT && isHaveImage) {
					buyimg.attr("src", "/images/buy_button_green.png");
				}
				else if (IsDiscount && isHaveImage) {
					buyimg.attr("src", "/images/bron_button.png");
				}
				else if (isHaveImage) {
					buyimg.attr("src", "/images/button_purchase.jpg");
				}

				$("#tarcker").html('<img src="http://mixmarket.biz/tr.plx?e=3779415&r=' + escape(document.referrer) + '&t=' + (new Date()).getTime() + '" width="1" height="1"/>');

			}
			else {
				alert("Ошибка при добавлении в корзину. Попробуйте снова через несколько минут.");
			}
		}
	);
}


function DeleteToBasket(elem, goodcount) {
	var productId = $(elem).attr("product");
	var productPrice = parseInt($(elem).attr("price")) * goodcount;
	var buyimg = $(elem).children('img.buyimg');
	var currentCount = parseInt($(elem).attr("count"));
	var IsUHT = $(elem).attr("uht") == undefined ? false : true;
	var IsSale = $(elem).attr("sale") == undefined ? false : true;
	var urlModifers = '';
	if (IsUHT) {
		urlModifers += '&uht=1';
	}
	if (IsSale) {
		urlModifers += '&sale=1';
	}
	$.get("/Basket/DeletFromBasket.aspx?product=" + productId + "&count=" + goodcount + "&rnd=" + Math.random() + urlModifers,
			function (data) {
				if (data == "1") {
					var prCount = $("#basket_count_product");
					var prPrice = $("span#amount_to_paid");

					var count = parseInt(prCount.text()) - goodcount;
					var price = parseInt(prPrice.text()) - productPrice;

					$("#basket_count_product").text(count);
					$("span#product_count").text(count);
					$("span#amount_to_paid").text(price);
					if (count == 0) Purchese(false);
				}
				else {
					alert("Ошибка при удалении из корзины. Попробуйте снова через несколько минут.");
				}
			});
};

function TopMenu() {
	$("#slidebtn").click(
		function () {
			if (isSlided) {
				$("#slide").animate({ marginTop: "-80px" }, 150);
				isSlided = false;
				$("#slidebtn").css("background", "url(/Images/slide_button_info.png)");
			}
			else {
				$("#slide").animate({ marginTop: "0px" }, 150);
				isSlided = true;
				$("#slidebtn").css("background", "url(/Images/slide_button_info_close.png)");
			}
			return false;
		}
	);
}

// Product View page tabs click event.
function TabClick(type) {
	if (type == 'Prop') {
		$('#tab_property .button1').css('display', 'block');
		$('#tab_property a').css('display', 'none');

		$('#tab_foto .button1').css('display', 'none');
		$('#tab_foto a').css('display', 'block');

		$('#propeties').css('display', 'block');
		$('#product_fotos').css('display', 'none');
	}
	else {
		$('#tab_property .button1').css('display', 'none');
		$('#tab_property a').css('display', 'block');

		$('#tab_foto .button1').css('display', 'block');
		$('#tab_foto a').css('display', 'none');

		$('#propeties').css('display', 'none');
		$('#product_fotos').css('display', 'block');
	}
	return false;
}

function Purchese(On) {
	if (On) {
		$('#product_descript').css('display', 'none');
		$('#product_price').css('display', 'none');
		$('#product_properties').css('display', 'none');
		$('#similar_product').css('display', 'none');
		$('#product_popular').css('display', 'block');
		$('#product_order_completed').css('display', 'block');
	}
	else {
		$('#product_descript').css('display', 'block');
		$('#product_price').css('display', 'block');
		$('#product_properties').css('display', 'block');
		$('#similar_product').css('display', 'block');
		$('#product_popular').css('display', 'none');
		$('#product_order_completed').css('display', 'none');
	}

	return false;

}


var resizeTimer = null;
var resizeInterval = 3000;

function resizeHandler() {
	dresizeTimer = Math.random();
}

var onLoadFlag = true;

function onResize() {
	if (resizeTimer != null) {
		clearTimeout(resizeTimer);
		resizeTimer = null;
	}
	var bodyWidth = $("body").outerWidth();
	var slide = $("#slide");

	var width = $("#middle").innerWidth();

	var blocks = parseInt((width - 40) / 250);
	var blockWidth = parseInt((width - 40) / blocks);

	if (document.getElementById("showwindow") != null && onLoadFlag) {
		showWindow = $("#showwindow");
		showWindow.html('<img src="/Images/ajax-loader_win.gif" />');

		$.get("/ShowWindow/GetShowWindow.aspx?type=bottomProd&rowcount=1&columncount=10"
			+ "&rnd=" + Math.random(),
			function (data) {
				showWindow.html('');
				showWindow.append(data);
				resizeProductBlock("#showwindow div.bottom_product_item", blocks, blockWidth);
			}
		);
	}
	if (!onLoadFlag)
		resizeProductBlock("#showwindow div.bottom_product_item", blocks, blockWidth);



	var catW = $("#prod_menu").outerWidth();
	if (catW == undefined)
		catW = $("#content_left").outerWidth();

	$("#content").css("width", width - (catW + 20) - 30 + "px");

	var contentWidth = $("#new_product .sidebox").innerWidth();
	var newProductBlocks = parseInt((contentWidth - 25) / 230);
	var newProductBlocksWidth = parseInt((contentWidth - 25) / newProductBlocks);

	if (document.getElementById("new_product_showwindow") != null && onLoadFlag) {
		newProductWindow = $("#new_product_showwindow");
		newProductWindow.html('<img src="/Images/ajax-loader_win.gif" />');

		$.get("/ShowWindow/GetShowWindow.aspx?type=newProduct&count=8"
			+ "&rnd=" + Math.random(),
			function (data) {
				newProductWindow.html('');
				if (data.toString().length > 0) {
					newProductWindow.append(data);
					resizeProductBlock("#new_product_showwindow div.new_product_item", newProductBlocks, newProductBlocksWidth);
				}
				else
					$('#new_product').css("visibility", "hidden");
			}
		);
	}
	if (!onLoadFlag)
		resizeProductBlock("#new_product_showwindow div.new_product_item", newProductBlocks, newProductBlocksWidth);

	if (document.getElementById("product_descript") != null) {
		var productInfoWidth = $("#content").width() - $("#productInfo div.productImage").outerWidth() - $("#product_price").outerWidth()
		$("#product_descript").css("width", productInfoWidth - 35 + "px");
	}


	if ($("#product_catalog dd.product_catalog_item") != undefined) {
		contentWidth = $("#content").outerWidth();
		var catalogProductBlocks = parseInt((contentWidth - 30) / 230);
		var catalogProductBlocksWidth = parseInt((contentWidth - 30 - catalogProductBlocks * 30) / catalogProductBlocks);
		$("#product_catalog dd.product_catalog_item").css("width", catalogProductBlocksWidth + "px");
	}

	resizeTimer = setTimeout("resizeHandler()", resizeInterval);

	onLoadFlag = false;
}


function resizeProductBlock(containerID, count, newwidth) {

	var divs = $(containerID);

	if (divs[0] == undefined) return;
	for (i = 0; i < divs.length; i++) {
		if (i < count) {
			divs[i].style.display = 'block';
		}
		else {
			divs[i].style.display = 'none';
		}
	}
	//alert(containerID);
	//alert(count);
	//alert(newwidth);
	$(containerID).css("width", newwidth + "px");
}


function SelectDeliveryType(type, obj) {
	var sel_value = $(obj).val();
	//alert(sel_value);
	var sFull = "#divFull" + type;
	var sAddres = "#divAddress" + type;
	var sInfo = "#divDeliveryInfo" + type;
	$(sFull).show();
	$(sAddres).hide();
	$(sInfo).hide();
	if (sel_value == 0) {
		$(sFull).hide();
	}
	if (sel_value == 1) {
		$(sAddres).show();
	}
	if (sel_value == 2) {
		$(sInfo).show();
	}
}

function SelectPayMethod() {
	var sel_value = $(".ddPayMethod option:selected").val();
	$("#payBlock").hide();
	$("#bankBlock").hide();
	$("#noncashBlock").hide();
	$("#card").hide();
	if (sel_value == 1) {
		$("#payBlock").show("slow");
	}
	if (sel_value == 2) {
		$("#bankBlock").show("slow");
	}
	if (sel_value == 3) {
		$("#noncashBlock").show("slow");
	}
	if (sel_value == 4) {
		$("#card").show("slow");
	}
}

var sumPrice;
function RebindBasket() {
	sumPrice = 0;
	$("tr.basket_tr").each(GetRowMoney);
	if (sumPrice == 0) {
		$("#notData").show();
		$("#basket_info_table").hide();
		$("#divCash").hide();
	}
	else {
		$("td.footer .price").html(StringPrice(sumPrice));
	}
	return false;
}

function StringPrice(Price, d, s) {
	if (arguments.length == 2) { s = " "; }
	if (arguments.length == 1) { s = " "; d = "."; }
	Price = Price.toString();
	a = Price.split(d);
	x = a[0];
	y = a[1];
	z = "";
	if (typeof (x) != "undefined") {
		for (i = x.length - 1; i >= 0; i--)
			z += x.charAt(i);
		z = z.replace(/(\d{3})/g, "$1" + s);
		if (z.slice(-s.length) == s)
			z = z.slice(0, -s.length);
		x = "";
		for (i = z.length - 1; i >= 0; i--)
			x += z.charAt(i);
		if (typeof (y) != "undefined" && y.length > 0)
			x += d + y;
	}
	return x;
}

//function getContent(ObjTest) {
//    var s = "";
//    var Obj = ObjTest;
//    for (var i in Obj)
//        s += i + '=' + Obj[i] + ';   typeof=' + typeof (Obj[i]) + '<BR>';
//    //alert(s);
//    var win = window.open('', 'test');
//    win.document.write(s);
//}


function GetRowMoney(intIndex) {
	var row = $(this);
	var priceForOne = parseInt(row.find(".tbPrice").attr("value"));
	var oldCount = parseInt(row.find(".oldCount").attr("value"));
	var multi = parseInt(row.find(".multi").attr("value"));
	var id = parseInt(row.find(".id").attr("value"));
	var name = row.find(".id").attr("value");

	var IsUHT = row.attr("uht") == undefined ? false : true;
	var IsSale = row.attr("sale") == undefined ? false : true;

	var urlModifers = '';
	if (IsUHT) {
		urlModifers += '&uht=1';
	}
	if (IsSale) {
		urlModifers += '&sale=1';
	}

	var chkSelect = row.find("input:checkbox").attr("checked");
	if (chkSelect)
		var productCount = parseInt(row.find(".tbCount").attr("value"));
	else
		var productCount = 0;

	if (productCount < 0) {
		productCount = productCount * (-1);
		row.find(".tbCount").attr("value", productCount);
	}

	var productsAdded = productCount - oldCount;

	if (productCount % multi == 0) {

		if (productsAdded > 0) {
			$.ajax({
				url: '/Basket/AddToBasket.aspx?product=' + id
			 + '&count=' + productsAdded + '&rand=' + Math.random() + urlModifers,
				success: function (data) {
					if (data == "1") {
						row.find(".oldCount").attr("value", productCount);
						row.find("span.price").text((StringPrice(productCount * priceForOne)));
						var fullCount = parseInt($("#basket_count_product").text());
						$("#basket_count_product").text(fullCount + productsAdded);

						$("#tarcker").html('<img src="http://mixmarket.biz/tr.plx?e=3779415&r=' + escape(document.referrer) + '&t=' + (new Date()).getTime() + '" width="1" height="1"/>');
					}
				}
			});
		}
		if (productsAdded < 0) {
			$.post(
			'/Basket/DeletFromBasket.aspx?product=' + id + '&count=' + productsAdded + '&rand=' + Math.random() + urlModifers,
			function (data) {
				if (data == "1") {

					if (productCount <= 0) {
						row.hide();
					}
					else {
						row.find(".oldCount").attr("value", productCount);
						row.find("span.price").text((StringPrice(productCount * priceForOne)));
					}

					var fullCount = parseInt($("#basket_count_product").text());
					fullCount = (fullCount + productsAdded) <= 0 ? 0 : (fullCount + productsAdded);
					$("#basket_count_product").text(fullCount);

					if ((fullCount - productsAdded) <= 0) {
						$("div.EmptyData").show();
					}
				}
			}
		);
		}
	}
	else {
		alert("Колличество продуктов этого типа в корзине должно быть кратно " + multi);
		row.find(".tbCount").attr("value", oldCount);
		productCount = oldCount;
	}

	var priceForRow = productCount * priceForOne;
	sumPrice += priceForRow;
}

function SetCity(isOn) {
	if (isOn)
		$("div.related div.absCityList").show();
	else
		$("div.related div.absCityList").hide();
}


//var sMessage = "Не удалось добавить товар в список сравнения. Попробуйте ещё раз.";
//var sMessage = "Not data.";

//function AddToCompare(products) {

//	$.get("/ajax/AddToCompare.aspx?product.id=" + productIDs + "&category.id=" + groupId + "&rnd=" + Math.random(),
//		function (data) {
//			if (data == "1") {
//				var wnd = window.open('/compare-' + groupId + '/', '_compare' + groupId);
//				wnd.focus();
//			}
//			else {
//				alert(sMessage);
//			}
//		});

//	var wnd2 = window.open('/compare-' + groupId + '/', '_compare' + groupId);
//	wnd2.focus();

//	return false;
//}

//function AddCompare(obj, idProducta) {
//	if (obj.getAttribute('selected') == null) {
//		obj.setAttribute('selected', 1);
//		obj.innerHTML = "добавлено в сравнение <img style='display:inline-block' src='/Images/arrow_list.png' />";
//	}
//	else {
//		alert('Второй раз');
//	}
//}
