/*
   Main JS file, requires jQuery framework
   Version 1.5.3 -- GeoLocation disabled 
*/

var galstate = 0;
var chatWindow = 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(window.pageYOffset > 49)
		$("#informer").css({"top":"0px"});
	$(window).scroll(
	function ()
	{	
		if ((!$.browser.msie) && (!$.browser.opera)) {
		if(window.pageYOffset < 49)
			$("#informer").css({"top":(49-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 > 50)
				$("#informer").css({"top":"0px"});
			var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
			$.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 );
					});
				}
			});
		});

$(".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();});
				  UpdateOrderTotals(); 
				}
			});      	  
    });
    	$(".addservice").livequery('change', function() { 
      	  var id = $(this).parents(".product-row").attr("id");
      	  var price = parseInt($("#"+id+"_price").html());
      	  var sprice = parseInt($("#"+id+"_service").val());
      	  var quantity = parseInt($("#"+id+"_quant").val());
      	  if ($("#"+id+"_addservice").is(":checked")){			  
      	  $("#"+id+"_price").html(price + sprice);
      	  $("#"+id+"_sum").html(price * quantity + sprice * quantity);
      	  UpdateOrderTotals();
      	  }
      	  else {			  
      	  $("#"+id+"_price").html(price - sprice);
      	  $("#"+id+"_sum").html(price * quantity - sprice * quantity);
      	  UpdateOrderTotals();
      	  } 
    	});
    	$(".paytype").change(function () { 
    	  var id = $(this).attr("id");
      	  if (id == "pay-card") {
      	  $("#card-bw").hide();
      	  $("#card-color").show();
      	  } else {
      	  $("#card-bw").show();
      	  $("#card-color").hide();
      	  } 
    	});
    	$(".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 ($(".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();  
				}
			});      	  
    	}
    	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) {
        $("#shipping").html('200');
    } else {
        if(document.getElementById('rd').value == 2)
        {
            if(sum < 50000)
                var delivery = Math.round(sum*0.03);
            else
                var delivery = Math.round(sum*0.015);
            $("#shipping").html(delivery);
        }
        else
        {
            $("#shipping").html('0');
        }
    }

    $("#gtotal").html(sum + $("#shipping").html() * 1);
    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").append(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");
					}
				}
			});

			// А тут будем с наличием работать
//			alert(ID_EL);
			
			var cnt = document.getElementById('cnt_' + ID_EL).value;
			var cto = document.getElementById('cto_' + ID_EL).value;
			var row = document.getElementById('cnt_' + ID_EL).name;
			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';
			}
		});
		$(".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();
    });
	}



	function InitOpenWin()
	{
      $(".modal").livequery("click",
      function(){
         if($(this).parent().parent().attr('class')=='availability')
            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  "availability":
				var id = $(this).parents(".Conf_row").find('.ProductPropColor input:checked').attr("id");
				//alert(id);
				 var WinName = '/popups/avail.php?id=' + id;
				$("#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("slow");
					},
               success: function(data){
                  $("#win-loader").hide();
                  $("#d-content").empty().append(data).fadeIn("slow");
                  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");
		});
	}




////////////////////////////////////////////////////////////////////////////////
	$(document).ready( function(){ InitSite(); });
})(jQuery);
