/*
   Main JS file, requires jQuery framework
   Version 1.5.3 -- GeoLocation disabled
   Version 1.5.4 -- InitProdImgColor() modified. Egor S.
   Version 1.5.5 --  modified. Egor S.
   Version 1.5.6 --  Insurance price added. Egor S.
   Version 1.5.7 -- Basket gifts added.
   Version 1.5.8 -- Basket gifts modified.
   Version 1.5.9 -- delivery mod. Egor S.
*/

var galstate = 0;
var chatWindow = null;
var shopHelperPosition = null;

(function($) {

	function InitSite()
	{
		if( $("#tab-block").length > 0)
			$("#tab-block").tabs();
			InitProductTabs();
		if( $("#fp-news"))	
			$("#fp-news").tabs();
			InitNewsTabs();
		if( $("#slides").length > 0) {
			InitPromoSlider();
			SlideTimer();
			}
		if( $("#q-a"))
			InitChat();
		if( $("#glr-toggle").length > 0)
			InitProductDetailSlide();
		if( $("#search-field"))
			InitSearchField();
		if( $("#cat-selector").length > 0)
			InitDropDownSelector();
		if( $("#cart"))
			InitInformerBasket();
		if( $("#gallery .thumb").length > 0)
			InitGallery();
		if( $(".ProductPropColor input").length > 0)
			InitProdImgColor();
  		if( $(".modal"))
			InitOpenWin();
		if( $("#sorting").length > 0)
			InitSorting();
		if( $("#nextstep").length > 0)
			InitOrderChange();	
		if ($("#gallery div").length > 1)
			$("#glr-toggle").fadeIn("slow");
		if ($(".Conf_row").length > 0)
			InitProdConfigColorRadio();
		//if ($("#phonenum"))
		//	GetLocation();
		if ($("#oem-warning").length > 0) 
			DisplayOem();
		if ($(".gift-row").length > 0)
			$(".gift-row").fadeIn(2000);
			
		$("#switchsp").click(function(){
			// Скрываем Москву
			
			$("#postmsk").hide();
			$("#postsp").show();
			
			$("#msklist").hide();
			$("#splist").show();
			
			$("#switchsp").hide();
			$("#switchmsk").show();
		});
		
		$("#switchmsk").click(function(){
			// Скрываем Москву
			
			$("#postsp").hide();
			$("#postmsk").show();
			
			$("#splist").hide();
			$("#msklist").show();
			
			$("#switchmsk").hide();
			$("#switchsp").show();
		});			

	if(window.pageYOffset > 62)
		$("#informer").css({"top":"0px"});
	$(window).scroll(
	function ()
	{	
		if ((!$.browser.msie) && (!$.browser.opera)) {
		if(window.pageYOffset < 62)
			$("#informer").css({"top":(62-window.pageYOffset)+"px"});
		if(window.pageYOffset > ($(document).height()-1400))
			$("#nextstep").css({"top":($(document).height()-1060)+"px"});
		else
			$("#nextstep").css({"top":(340+window.pageYOffset)+"px"});
		}
	});
		$(document).pngFix();
	}

	function InitPromoSlider()
	{
		$("#slider-btns li").click(function(){
			var alink = $(this).find("a").attr("href");
			window.location = alink;
		});
		$(".slide").click(function(){
			var alink = $(this).find("a").attr("href");
			window.location = alink;
		});
		$('#slider-btns li').hover(function() {
			var i		= $("#slider-btns li").index(this);
			var sSlide	= -940 * i + "px";
			$("H1").stop().animate({opacity: 0.05}, 400);			
			$("#sl-container").stop().animate({ marginLeft: sSlide }, 600, function() {$("H1").animate({opacity: 1.0}, 2000);} );
			var sSlideLine	= 281 * i + "px";
			$("#slider-active").stop().animate({ marginLeft: sSlideLine }, 600 );
    		$("#slider-btns").stopTime('controlled');
  			}, function() {
    		SlideTimer();
  });
	}
	
	function SlideTimer(){
	$("#slider-btns").everyTime("10s", 'controlled', function() {
	   $("H1").stop().animate({opacity: 0.05}, 400);
	   if (Number($("#sl-container").css("marginLeft").replace(/px/g, ''))%940==0)
	   		{
			if(Number($("#sl-container").css("marginLeft").replace(/px/g, ''))<=-1880)
			{
				sSlide = 0;
				sSlideLine = 0;
			}
			else
			{
				sSlide	= Number($("#sl-container").css("marginLeft").replace(/px/g, ''))-940;
				sSlideLine = Number($("#slider-active").css("marginLeft").replace(/px/g, '')) + 281;
			}
			$("#sl-container").stop().animate({ marginLeft: sSlide+'px' }, 600, function() {$("H1").animate({opacity: 1.0}, 2000);} );
			$("#slider-active").stop().animate({ marginLeft: sSlideLine+'px' }, 600 ); 
		}
	});
}

	function InitProductDetailSlide()
	{
		$("#glr-toggle div").click(function(){
			if ($("#gallery div").length < 2) {
			$("#glr-toggle").fadeOut("slow");
			}
			galstate = $("#glr-toggle div").index(this);
			var sSlide	= -350 * galstate + "px";
			$("#glr-toggle div").show();
			$("#glr-toggle div:eq("+ galstate +")").hide();
			$("#prod-slide").animate({ marginLeft: sSlide }, 600 );
		});
	}
	
	function InitChat()
	{
		$("#q-a").click(function(){
			if ((chatWindow == null) || (chatWindow.closed)) {
			chatWindow = window.open('/utilities/chat.html','chatWindow','toolbar=no, scrollbars=no, width=300, height=400, location=no, directories=no, status=no, menubar=no')
			} else {
			chatWindow.focus();
			}
	});
	}

	function InitSearchField()
	{
		var sVal	= "Поиск";
		if($.browser.msie){
     	$(".search div input").css("padding-top","0");
     	}
		$("#search-field").val( sVal );
		$("#search-field").focus(function(){
			if( $(this).val() == sVal )
			{
				$(this).val("");
				$(this).addClass("active");
			}
		});
		$("#search-field").blur(function(){
			if( $(this).val() == "" )
			{
				$(this).val(sVal);
				$(this).removeClass("active");
			}
		});
	}

	function InitDropDownSelector()
	{
		$("#cat-selector-btn").toggle(
			function()
			{
				var i	= $("#cat-selector-btn").index(this);
				$(this).addClass("on");
				$("#cat-selection:eq("+ i +")").fadeIn("fast");
			},
			function()
			{
				var i	= $("#cat-selector-btn").index(this);
				$(this).removeClass("on");
				$("#cat-selection:eq("+ i +")").fadeOut("fast");
			}
		);
	}


	function InitInformerBasket()
	{
		$(".ProductBtnAddBasket").click(function(){
			var loadid = $(this).parents(".Conf_row").attr("id");
			
			if(window.pageYOffset > 60)
				$("#informer").css({"top":"0px"});
			else
				$("#informer").css({"top":"62px"});
			
			var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
			
			var row = document.getElementById('cnt_' + id).name;
				
			// Переключаем индикатор
			
			/*
			// Скрываем все
			$('.indicator').each(function(){
				$(this).hide();
			});
			
			// Показываем текущий
							
			document.getElementById('ind_' + row).style.display = 'block';*/
			
			$.ajax({
				url: '/ajax/cart.php?id='+id,
				beforeSend: function(){
					$('#bcLoader_'+loadid).show();
				},
				success: function(data){
					$('#bcLoader_'+loadid).hide();
					$("#cart-slider").empty().append(data);
					$("#informer").fadeIn("fast");
					$("#cart").html(Number($("#cart").html()) + 1);
					$("#informer").oneTime("1s", function(){
						$("#cart-slider").stop().animate({ marginLeft: -94 + "px" }, 600 );
					});
					$("#informer").oneTime("3s", function(){
						$(this).fadeOut(2000);
						$("#cart-slider").stop().animate({ marginLeft: "0px" }, 100 );
					});
				}
			});
		});
		
		$(".ProductBtnPreOrder").click(function(){
			var loadid = $(this).parents(".Conf_row").attr("id");
			if(window.pageYOffset > 60)
				$("#informer").css({"top":"0px"});
			else
				$("#informer").css({"top":"62px"});
			var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
			
			var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
			
			var row = document.getElementById('cnt_' + id).name;
				
			// Переключаем индикатор
			
			// Скрываем все
			/*$('.indicator').each(function(){
				$(this).hide();
			});
			
			// Показываем текущий
							
			document.getElementById('ind_' + row).style.display = 'block';*/
			
			var pval = document.getElementById('icon_' + id).value;
			$.ajax({
				url: '/ajax/cart.php?id='+id,
				beforeSend: function(){
					if(pval == 1)
						$('#bcWarning_'+loadid).hide();	
					$('#bcLoader_'+loadid).show();
				},
				success: function(data){
					$('#bcLoader_'+loadid).hide();
					if(pval == 1)
						$('#bcWarning_'+loadid).show();
					$("#cart-slider").empty().append(data);
					$("#informer").fadeIn("fast");
					$("#cart").html(Number($("#cart").html()) + 1);
					$("#informer").oneTime("1s", function(){
						$("#cart-slider").stop().animate({ marginLeft: -94 + "px" }, 600 );
					});
					$("#informer").oneTime("3s", function(){
						$(this).fadeOut(2000);
						$("#cart-slider").stop().animate({ marginLeft: "0px" }, 100 );
					});
				}
			});
		});

$(".btn-order").click(function(){
			if(window.pageYOffset > 50)
				$("#informer").css({"top":"0px"});
			var id = $(this).attr("id");
			$.ajax({
				url: '/ajax/cart.php?id='+id,
				beforeSend: function(){},
				success: function(data){
					$("#cart-slider").empty().append(data);
					$("#informer").fadeIn("fast");
					$("#cart").html(Number($("#cart").html()) + 1);
					$("#cart-slider").stop().animate({ marginLeft: -94 + "px" }, 600 );
					$("#informer").oneTime("3s", function(){
						$(this).fadeOut(2000);
						$("#cart-slider").stop().animate({ marginLeft: "0px" }, 100 );
					});
				}
			});
		});

		$("#cart-container a").mouseover(function(){
		if ($("#cart").html() == "0") {
      	$("#informer").fadeIn("fast");
      	}
    	}).mouseout(function(){
      	$("#informer").fadeOut("slow");
    	});
	}

	function InitProductTabs()
	{
		$("#tab-selector a").click(function(){
			var i = $("#tab-selector a").index(this);
			var cnt = $("#tab-selector .inner").contents();
			$("#tab-selector .selected").replaceWith(cnt);
			$("#tab-selector a").eq(i).wrap("<div class='selected'><div class='inner'></div></div>");
		});
	}
	
	function InitNewsTabs()
	{
		$("#news-selector a").click(function(){
			if (!$(this).is(".link-all")) {
			var i = $("#news-selector a").index(this);
			var cnt = $("#news-selector .inner").contents();
			$("#news-selector .selected").replaceWith(cnt);
			$("#news-selector a").eq(i).wrap("<div class='selected'><div class='inner'></div></div>");
			}
		});
	}

	function DisplayOem()
	{
		$("#oem-warning").fadeIn("slow");
		$("#btn-pay-enabled").hide();
		$("#btn-pay-disabled").show();
		$("#oem-delete").click(function(){
			
			$.ajax({
				url: '/ajax/basket_del_oem.php',
				beforeSend: function(){
				},
				success: function(data){
				}
			});
			
			$(".oem-warning").parents(".product-row").fadeOut("slow", function() { $(this).empty();});
			$("#oem-warning").fadeOut("slow", function() {
			if ($(".row-del").length == 0) {
		  	$("#content-order").fadeOut("fast", function() {$("#content-empty").fadeIn("slow");});
		  	} else {
		  	$("#btn-pay-enabled").show();
		    $("#btn-pay-disabled").hide();}
		    UpdateOrderTotals();
		  	}); 
			return false;
		});
	}

	function InitGallery()
	{
		$("#gallery .thumb").livequery("click", function(){
		//window.alert("clicked!");
			var BigImgSrc = $(this).attr('id');
			//alert(BigImgSrc);
			$.ajax({
				url: '/ajax/gallery.php?ID_IMG=' + BigImgSrc,
				type: "GET",
				dataType: "text",
				beforeSend: function(){
					$('#glr-image').fadeOut("fast").empty();
					$("#i-loader").show();
				},
				success: function(data){
					$("#i-loader").hide();
					$("#glr-image").html(data);
					$("#glr-image").fadeIn("fast");
				}
			});
		});
	}
	
	function InitOrderChange()
	{
		  var qtyval = 0;
		  $(".btn-add").livequery('click', function() {
			var id = $(this).parents(".product").attr("id");
			var geturl = ('/ajax/addtoorder.php?id=' + id);
			$.ajax({
				url: geturl,
				beforeSend: function(){
					$("#Spinner").show();
					$("#"+id).remove();
				},
				success: function(data){
					$("#Spinner").fadeOut("slow");
					$(".product-row:last").after(data, function() { $(this).fadeIn("slow");});
					UpdateOrderTotals();
					if ($(".product").length == 0) {
					$("#offer").fadeOut("slow");
					}
				}
			});
			return false;
		});
		  $(".row-del").livequery('click', function() {
			  // А вот тут нужен вызов аяксового скрипта на удаление товара
		  if ($(".row-del").length == 1) {
		  $("#content-order").fadeOut("fast", function() { $("#content-empty").fadeIn("slow");});
		  } 
      	  var id = $(this).parents(".product-row").attr("id");
		  // Пишем аяксовый вызов
		  $.ajax({
				url: '/ajax/basket_del_row.php?id=' + id,
				beforeSend: function(){
				},
				success: function(data){
				  $("#"+id+" .btn-del").hide();
  				  $("#"+id+"_quant").val('0');
				  $("#"+id).fadeOut("slow", function() { $(this).empty();
				      if (($(".post-warning").length == 0) && ($(".oem-warning").length == 0)) {
					//	$("#oem-warning").fadeOut("slow");
						$("#btn-pay-disabled").hide();
						$("#btn-pay-enabled").show();	
   					 }
				  });
				  UpdateOrderTotals();
				}
			});
    });
    	$(".gift-del").livequery('click', function() { 
      	  var id = $(this).parents(".gift-row").attr("id");
      	  $("#"+id+" .btn-del").hide();
      	  $("#"+"ADD"+id).val("0");
      	  $("#"+id).fadeOut("slow");
   	});
    	$(".addservice").livequery('change', function() {

            var id = $(this).parents(".product-row").attr("id");
          pr = $("#"+id+"_price").html()
          var price = parseInt(pr);
      	  var sprice = parseInt($("#"+id+"_service").val());
      	  var quantity = parseInt($("#"+id+"_quant").val());

          if ($("#"+id+"_addservice").is(":checked")){
              if(pr != 'На заказ')
              {
                $("#"+id+"_price").html(price + sprice);
          	  $("#"+id+"_sum").html(price * quantity + sprice * quantity);
          	  UpdateOrderTotals();
              }

          // И еще аяксом записать в сессию
            $.ajax({
				url: '/ajax/basket_insurance.php?switch=on&id=' + id,
				beforeSend: function(){
                },
				success: function(data){
                }
			});
      	  }
      	  else {
              if(pr != 'На заказ')
              {
              $("#"+id+"_price").html(price - sprice);
          	  $("#"+id+"_sum").html(price * quantity - sprice * quantity);
          	  UpdateOrderTotals();
              }

          // И еще аяксом записать в сессию

            $.ajax({
				url: '/ajax/basket_insurance.php?switch=off&id=' + id,
				beforeSend: function(){
				},
				success: function(data){
				}
			});
      	  }

    	});
    	$(".paytype").change(function () {
    	  var id = $(this).attr("id");
      	  if (id == "pay-card" || id == "pay-card2") {
      	  $("#card-bw").hide();
      	  $("#card-color").show();
      	  } else {
      	  $("#card-bw").show();
      	  $("#card-color").hide();
      	  } 
    	});
    	
    	// ----------- Почтаматы - начало
    	
    	//Считаем общую сумму товаров
    	
    	var sum=0;
	$(".quant").each(function (i) {
    	  id = $(this).parents(".product-row").attr("id");
    	  price = $("#"+id+"_price").html();
		  if(price == 'На заказ') price = 0;
		  sum = sum + $(this).val() * price;
    	  });
    	  
    	// посчитали
    	
    	if(sum < 50000)
                var delivery = Math.round(sum*0.04);
            else
                var delivery = Math.round(sum*0.02);
                
        var html_moscow = '<option value="2" selected="selected">курьера</option><option value="1">постамата</option><option value="3">почты СПСР</option><option value="4">самовывоза</option>';
        var html_spb = '<option value="3" selected="selected">почты СПСР</option><option value="1">постамата</option>';
        var html_other = '<option value="3" selected="selected">почты СПСР</option><option value="1">постамата</option>';
        
        if(sum < 5000 && sum > 0)
        {
        	html_moscow = '<option value="2" selected="selected">курьера</option><option value="1">постамата</option><option value="4">самовывоза</option>';
        	html_spb = '<option value="1" selected="selected">постамата</option>';
        	html_other = '<option value="1" selected="selected">постамата</option>';
        }
        
        $("#dlregion").change(function () { 
    	  var i = $(this).attr("value");
    	  /*if (i == "3") {
    	  $("#dloption").hide();
    	  $("#dlhelp").hide();
    	  $("#postamat").hide();
    	  $("#courier").hide();
    	  $("#emspost").fadeIn("fast");
    	  $("#dloption").attr("value", 1);
    	  $("#shipping").html(delivery);
    	  $(".post-warning").fadeOut("fast");
    	  if ($(".oem-warning").length == 0) {
    	  $("#btn-pay-disabled").hide();
          $("#btn-pay-enabled").show();
    	  }
    	  UpdateOrderTotals();
    	  } else*/
    	  
    	  if (i == "2" || i == 3) {
    	  	$("#dlhelp").show();
    	  	$("#dloption").html(html_spb).show();
    	  	if(sum >= 5000)
    	  	{
	    		$("#emspost").fadeIn("fast");
	    	  	$("#courier").hide();
	    	  	$("#self").hide();
	    	  	$("#postamat").hide();
	    	  	$("#shipping").html(delivery);
	      	}
	      	else
	      	{
	      	  	$("#emspost").hide();
	    	  	$("#courier").hide();
	    	  	$("#self").hide();
	    	  	$("#postamat").fadeIn("fast");
	    	  	$("#shipping").html('400');
	      	}
/*    	  if ($(".post-warning").length > 0) {
    	  	//alert(123);
    	  	$(".post-warning").fadeIn("fast");
    	  	$("#btn-pay-enabled").hide();
		  	$("#btn-pay-disabled").show();
    	  }*/
    	  	UpdateOrderTotals();
    	  } else {
    	  	$("#dlhelp").show();
    	  	$("#dloption").html(html_moscow).show();
    	  	$("#emspost").hide();
    	  	$("#self").hide();
    	  	$("#courier").fadeIn("fast");
    	  	$("#postamat").hide();
/*    	  if ($(".post-warning").length > 0) {
    	  	//alert(456);
    	  	$(".post-warning").fadeIn("fast");
    	  	$("#btn-pay-enabled").hide();
		  	$("#btn-pay-disabled").show();
    	  }*/
    	  	if(sum < 5000)
    	  		$("#shipping").html('350');
    	  	else
    	  		$("#shipping").html('0');
    	  	UpdateOrderTotals();
    	  }
    	});
    	
    	$("#dloption").change(function () { 
    	  var i = $(this).attr("value");
    	  var post_ship = 200;
    	  if($("#dlregion").attr("value") == 3) post_ship = 350;
    	  if (i == "1") {
    	  $("#courier").hide();
    	  $("#emspost").hide();
    	  $("#self").hide();
    	  $("#shipping").html(post_ship);
    	  $("#postamat").fadeIn("fast");
    	  if ($(".post-warning").length > 0) {
    	  	//alert(789);
    	  	$(".post-warning").fadeIn("fast");
    	  	$("#btn-pay-enabled").hide();
		  	$("#btn-pay-disabled").show();
		  	
    	  }
    	  UpdateOrderTotals();
    	  } 
    	  else if (i == "2") {
    	  	if(sum < 5000) deliv = 350; else deliv = 0;
		  $("#postamat").hide();
    	  $("#emspost").hide();
    	  $("#self").hide();
    	  $("#shipping").html(deliv);
    	  $("#courier").fadeIn("fast");
    	  $(".post-warning").fadeOut("fast");
    	  if ($(".oem-warning").length == 0) {
    	  $("#btn-pay-disabled").hide();
		  $("#btn-pay-enabled").show();
		  }
		  UpdateOrderTotals();
    	  }
    	  else if (i == "4") {
    	  	var deliv = 0;
		  $("#postamat").hide();
    	  $("#emspost").hide();
    	  $("#courier").hide();
    	  $("#shipping").html(deliv);
    	  $("#self").fadeIn("fast");
    	  $(".post-warning").fadeOut("fast");
    	  if ($(".oem-warning").length == 0) {
    	  $("#btn-pay-disabled").hide();
		  $("#btn-pay-enabled").show();
		  }
		  UpdateOrderTotals();
    	  }
    	  else {
    	  $("#courier").hide();
    	  $("#postamat").hide();
    	  $("#self").hide();
    	  $("#shipping").html(delivery);
    	  $("#emspost").fadeIn("fast");
    	  $(".post-warning").fadeOut("fast");
    	  if ($(".oem-warning").length == 0) {
    	  $("#btn-pay-disabled").hide();
		  $("#btn-pay-enabled").show();
		  }
		  UpdateOrderTotals();
    	  }
    	});
    	
    	$("#selectpost").click(function() {
		  //PickPoint.open(GetPost,{notLink:true,cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa')});
		  
		  if(document.getElementById('rd'))
		  {
		  	  PickPoint.open(GetPost,{city:document.getElementById('rd').value,cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa','sizran')});
		  }
		  else
		  {
		  	PickPoint.open(GetPost,{cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa','sizran')});
		  }
		  return false;
		});
		$("#otherpost").click(function() {
		  //PickPoint.open(GetAnother);
		  /*PickPoint.open(GetAnother,{cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa','sizran')});*/
		  
		  if(document.getElementById('rd'))
		  {
		  	  PickPoint.open(GetAnother,{city:document.getElementById('rd').value,cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa','sizran')});
		  }
		  else
		  {
		  	PickPoint.open(GetAnother,{cities:new Array('moscow','petersburg','pskov','mosoblast','novosibirsk','saratov','ekaterinburg','kaluga','yaroslavl','archangelsk','nijniy_novgorod','Tolyatti','Samara','omsk','kazan','volgograd','perm','voronezh','rostov-na-donu','krasnodar','yfa','sizran')});
		  }
		  
		  return false;
		});
		
		// ----------------- Почтаматы конец
		
    	$(".quant").livequery('focus', function() {
         qtyval=$(this).val();
         id = $(this).parents(".product-row").attr("id");
    	});
    	$(".quant").livequery('blur', function() {
    	  var id = $(this).parents(".product-row").attr("id");
      	  var price = $("#"+id+"_price").html();
      	  if($("#"+id+"_quant").val()==0){
      	  $.ajax({
				url: '/ajax/basket_upd_row.php?id=' + id + '&cnt=0',
				beforeSend: function(){
				},
				success: function(data){
					$("#"+id+" .btn-del").hide();
				  $("#"+id).fadeOut("slow", function() { $(this).empty();
				  if (($(".post-warning").length == 0) && ($(".oem-warning").length == 0)) {
					//	$("#oem-warning").fadeOut("slow");
						$("#btn-pay-disabled").hide();
						$("#btn-pay-enabled").show();	
   					 }
				  });
				  if ($(".row-del").length == 1) {
				  $("#content-order").fadeOut("fast", function() { $("#content-empty").fadeIn("slow");});
				  }
				  UpdateOrderTotals(); 
				}
			});
    	}
    	else if($("#"+id+"_quant").val()>=1){
			$.ajax({
				url: '/ajax/basket_upd_row.php?id=' + id + '&cnt=' + $("#"+id+"_quant").val(),
				beforeSend: function(){
				},
				success: function(data){
					if(price == 'На заказ')
						$("#"+id+"_sum").html('На заказ');
					else
						$("#"+id+"_sum").html($("#"+id+"_quant").val()*price);
      				UpdateOrderTotals();
				}
			});

            if(document.getElementById(id+"_inssum"))
            {

                // И еще страховку пересчитать
                var insprice = parseInt($("#"+id+"_service").val());
          	    var quantity = parseInt($("#"+id+"_quant").val());

                $("#"+id+"_inssum").html(insprice * quantity);
            }


    	}
    	else {
    	  $("#"+id+"_quant").val(qtyval);
    	  UpdateOrderTotals();
    	}
    });
	}
	
	function UpdateOrderTotals()
	{
	var sum=0;
	$(".quant").each(function (i) {
    	  id = $(this).parents(".product-row").attr("id");
    	  price = $("#"+id+"_price").html();
		  if(price == 'На заказ') price = 0;
		  sum = sum + $(this).val() * price;
    	  });
    $("#total").html(sum);

    if (parseInt(sum) < 5000) {
    	if(document.getElementById('dlregion').value == 1 && document.getElementById('dloption').value == 2)
        	$("#shipping").html('350');
    } 
    if(document.getElementById('dloption').value == 3)
        {
            if(sum < 50000)
                var delivery = Math.round(sum*0.04);
            else
                var delivery = Math.round(sum*0.02);
            $("#shipping").html(delivery);
        }

	if(sum > 0)
    	$("#gtotal").html(sum + $("#shipping").html() * 1);
    else
    	$("#gtotal").html(sum);
 //   if ($(".oem-warning").length == 1) {
//		$("#oem-warning").fadeOut("slow");
//		$("#btn-pay-disabled").hide();
	//	$("#btn-pay-enabled").show();	
 //   }
    }

    function GetLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(renderPosition, renderError);
            } else {
                $('#phonenum').html('8 800 700-19-44');
            }
        }
        function renderPosition(position) {
            
            if (!window.count) window.count = 0;
            var urlJSON ='';
            
            count ++;
            var urlJSON = '/utilities/geonames.php?type=JSON&lat='+position.coords.latitude+'&lon='+position.coords.longitude;
            var urlXML  = '/utilities/geonames.php?type=XML&lat=' +position.coords.latitude+'&lon='+position.coords.longitude;
                
            // now get the XML reverse geo data
            $.getJSON(urlJSON, function(json) {

                /* Parse JSON objects */
                $.each(json.geonames,function(i,item) {
                	//window.alert(item.name);
                    if (item.name == 'Moscow') {
                    $('#phonenum').html('(495) 510-22-74');
                    } 
                });

            });
        }
        
        function renderError() {
            $('#phonenum').html('8 800 700-19-44');
        }

	function InitProdConfigColorRadio()
	{
		$('input[type=radio]').prettyCheckboxes({
			checkboxWidth: 15, // ширина checkbox
			checkboxHeight: 15, // высота checkbox
			className : 'prettyCheckbox', // css класс для checkbox
			display: 'inline' //  (inline or list)
			});
		$(".ColorPoint").each(function(){
			$(this).find('label.radio span.holder').css({
				"backgroundImage": "url('" + $(this).children('input').attr("value") + "')",
				"backgroundRepeat": "no-repeat",
				"backgroundPosition": "top left"});
		});
	}
	
	function InitProdImgColor()
	{
		$(".ProductPropColor input").livequery("click", function(){
			var ID_EL = $(this).attr('id');
			var color = $(this).parent().find('.color-name').html();
			var pnum = $(this).parent().find('.pnum').html();
			//window.alert(color);
			$(this).parents(".Conf_row").find('.color').html(color);
			$(this).parents(".Conf_row").find('.pn').html(pnum);
			$.ajax({
				url: '/ajax/gallery.php?ID_EL='+ID_EL,
				type: "GET",
				beforeSend: function(){
					$("#glr-image").fadeOut("fast").empty();
					$("#i-loader").show();
				},
				success: function(data){
					$("#i-loader").hide();
					$("#glr-image").html(data);
					$("#glr-image").fadeIn("fast");
				}
			});
			$.ajax({
				url: '/ajax/thumbs.php?ELEMENT_ID='+ID_EL,
				type: "GET",
				beforeSend: function(){
					$("#gallery").fadeOut("fast");
					$("#i-loader").show();
				},
				success: function(data){
					$("#i-loader").hide();
					$("#gallery").empty();
					$("#gallery").append(data);
					$("#gallery").fadeIn("fast");
					if ($("#gallery div").length > 1) {
					$("#glr-toggle").show();} else if (galstate == 0) {
					$("#glr-toggle").fadeOut("slow");
					}
				}
			});
			
			// Тут же переключаем индикатор
			
			var row = document.getElementById('cnt_' + ID_EL).name;
			
			// Скрываем все
			/*$('.indicator').each(function(){
				$(this).hide();
			});
			
			// Показываем текущий
			
//			alert($(this).parent('.ProductSelectByProp').find('.indicator'));
			
			document.getElementById('ind_' + row).style.display = 'block';*/

			// А тут будем с наличием работать
//			alert(ID_EL);
			
			var cnt = document.getElementById('cnt_' + ID_EL).value;
			var cto = document.getElementById('cto_' + ID_EL).value;
			var cls = document.getElementById('class_' + ID_EL).value;
			var pval = document.getElementById('icon_' + ID_EL).value;
			
			
			if(cto == 0)
			{
				if(cnt > 0)
				{
					document.getElementById('av_on_'+row).style.display = 'block';
					document.getElementById('av_off_'+row).style.display = 'none';
				}
				else
				{
					document.getElementById('av_off_'+row).style.display = 'block';
					document.getElementById('av_on_'+row).style.display = 'none';
				}
			}
			else
			{
				document.getElementById('av_off_'+row).style.display = 'none';
				document.getElementById('av_on_'+row).style.display = 'none';
			}
			if(pval == 1)
				document.getElementById('bcWarning_row_conf'+row).style.display = 'block';
			else
				document.getElementById('bcWarning_row_conf'+row).style.display = 'none';	
			document.getElementById('td_'+row).className = cls;
		});
		$(".ColorPoint label").mouseover(function(){
		var position = $(this).position();
      	$("#helper-color").css({"left":((position.left)-6)+"px"});
      	$("#helper-color").css({"top":((position.top)-20)+"px"});
      	$("#helper-color").show();
    	}).mouseout(function(){
      	$("#helper-color").hide();    	
    });
    
    $(".helperinfo img").mouseover(function(){
		var position = $(this).position();
      	$("#helper-info").css({"left":((position.left)-164)+"px"});
      	$("#helper-info").css({"top":((position.top)-87)+"px"});
      	$("#helper-info").show();
    	}).mouseout(function(){
      	$("#helper-info").hide();    	
    });
    
    $('div[id^="av_on_"]').mouseover(function(){
		shopHelperPosition =  $(this).position();
		HelperShopsShow();
    	}).mouseout(function(){

      	HelperShopsHide();
      });
	
	    $('div[id^="av_off_"]').mouseover(function(){
		shopHelperPosition =  $(this).position();
		HelperShopsShow();
    	}).mouseout(function(){

      	HelperShopsHide();
      });
		
		    $('div[id^="cto_"]').mouseover(function(){
		shopHelperPosition =  $(this).position();
		HelperShopsShow();
    	}).mouseout(function(){

      	HelperShopsHide();
      });
	}

function HelperShopsShow()
{
		var position = shopHelperPosition;
      	$("#helper-shops").css({"left":((position.left)+40)+"px"});
      	$("#helper-shops").css({"top":((position.top)-22)+"px"});
      	$("#helper-shops").show();
	}

function HelperShopsHide()
{
$("#helper-shops").hide();
	}


	function InitOpenWin()
	{
      $(".modal").livequery("click",
      function(){
         if($(this).parent().parent().attr('class')=='availability' && $(this).attr('id') != 'cto' && $(this).attr('id') != 'cto_basket')
            WinID = "availability";
         else
            WinID = $(this).attr('id');
		 switch(WinID)
         {
            case "review-popup":
               var id = document.getElementById('sid').value;
               //alert(id);               
               var WinName = '/popups/review.php?id=' + id;
               $("#dialog-table").css({"width":"684px"});
            break;
            case "reg-popup":
               var WinName = '/popups/reg.php';
               $("#dialog-table").css({"width":"684px"});
            break;
            case "loc-popup":
               var WinName = '/popups/shop-location.php?id='+$(this).parents('.shop').attr('id');;
               $("#dialog-table").css({"width":"784px"});
            break;
			case "lux-order":
               var WinName = '/popups/luxury.php';
               $("#dialog-table").css({"width":"784px"});
            break;
            case  "availability":
				var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
				
				var row = document.getElementById('cnt_' + id).name;
				
				// Переключаем индикатор
				
				// Скрываем все
				/*$('.indicator').each(function(){
					$(this).hide();
				});
				
				// Показываем текущий
								
				document.getElementById('ind_' + row).style.display = 'block';*/
				
				var WinName = '/popups/avail.php?id=' + id;
				$("#dialog-table").css({"width":"784px"});
            break;
            case  "cto":
				var WinName = '/popups/cto_info.php';
				$("#dialog-table").css({"width":"784px"});
            break;
            case  "cto_basket":
				var WinName = '/popups/basket_info.php';
				$("#dialog-table").css({"width":"784px"});
            break;
            case "login-popup":
               var WinName = '/popups/login.php';
               $("#dialog-table").css({"width":"684px"});
            break;
            default:
            	alert("File not found");
            break;
         }
            $.ajax({
            url: WinName,
					beforeSend: function(){
               			$("#popup-shadow").css({"height":$(document).height()+"px"});
                  		$("#popup-shadow").fadeIn("fast");
                  		$("#popup-win").css("top",($("body").height()-$("#popup-win").height())/2);
                  		$("#d-content").hide();
						$("#win-loader").fadeIn(0);
					},
               success: function(data){
                  $("#win-loader").fadeIn(0);
                  $("#win-loader").hide();
                  //$("#d-content").empty().append(data).fadeIn("slow");
                  $("#d-content").empty().append(data).fadeIn("slow", function () {$("#win-loader").fadeOut(30);});
/*                  alert($("#popup-win").height());
                  alert($("body").height());
                  alert($("body").height() - $("#popup-win").height());
                  alert(( $("body").height() - $("#popup-win").height() )/2);*/
/*                  if($("#popup-win").height()>=$("body").height())
                  	$("#popup-win").css("top","0");
                  else*/
                    $("#popup-win").css("top",($("body").height()-$("#popup-win").height())/2);
                    $("#popup-win").fadeIn("fast");
				  	$("div.close-win").livequery("click",
                      function()
							{
								$('#popup-win').animate({ opacity: "hide" }, "fast");
								$("#popup-shadow").animate({ opacity: "hide" }, "fast");
                      }
                   );
               }
            });
            return false;
      });
	}
	
	function InitSorting()
	{
		$("#sorting UL").each(function(i){
			var iPos	= $(this).position();
			$(".sortlabel:eq("+ i +")").css({ top: iPos.top });
		});
		$("#sorting SPAN").click(function(){
			var pos	= $(this).position();
			var i	= $("#sorting UL").index($(this).parent().parent());
			$("#sorting UL:eq("+ i +") SPAN").removeClass("selected");
			$(this).addClass("selected");
			$(".sortlabel:eq("+ i +")").animate({ top: pos.top }, "fast");
		});
	}

function GetPost(result){
	$("#addr-text").html(result['address']);
	 $("#addr-text").show();
	$("#address").attr("value", result['id']);
	$("#safe").attr("value", result['address']);
	$("#selectpost").hide();
	$("#otherpost").show();
	
	}
	
	function GetAnother(result){
	$("#addr-text").html(result['address']);
	$("#address").attr("value", result['id']);
	$("#safe").attr("value", result['address']);	
	
	}


////////////////////////////////////////////////////////////////////////////////
	$(document).ready( function(){ InitSite(); });
})(jQuery);
