$(document).ready(function(){
	if ($.browser.msie){IEpngFix();}
	
	var maxWidth = 1280; // max width
	var minWidth = 1000; // min width
	var selector = $("#main"); // selector
	
	var windowWidthTemp = 0;
	var windowWidth = 0;
	

	if($.browser.msie){
		mmwidth();
		$(window).resize(function(){
								windowWidth = $(window).width();
								if (windowWidth != windowWidthTemp){
									windowWidthTemp = windowWidth;mmwidth();
									}});}
	function mmwidth(){
		$(selector).css({width:100+"%"});
		bodyWidth = $(window).width();
		if (bodyWidth < minWidth){
			$(selector).width(minWidth);
		}else{
			if (bodyWidth > maxWidth){
				$(selector).width(maxWidth);
			}else{
				$(selector).width(98+"%");
			}}};

	//png fix for ie
	function IEpngFix(){
		if ($.browser.msie){
			var transparentImage = "/i/transparent.gif";
			
			oImg = $("img[src$=.png]");
			lImg = $("img[src$=.png]").length;
			
			for (i=0;i<lImg;i++){
				srcImg = $(oImg[i]).attr("src");
				$(oImg[i]).attr({src:transparentImage});
				oImg[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + srcImg + "',sizingMethod='scale')";
				oImg[i].style.display = "inline-block";
			}
		}
	}
	inputValue();
	function inputValue(){
		var asInitVals = new Array;
		var input = $("input.inputinit")
		$(input).each( function (i) {
			asInitVals[i] = $(this).val();
		});
		$(input).focus( function () {
			if ( $(this).hasClass("inputinit")){
				$(this).removeClass();
				$(this).val("");
			}
		});
		$(input).blur( function (i) {
			if ( !(jQuery.trim($(this).val()))){
				$(this).addClass('inputinit');
				$(this).val(asInitVals[$(input).index(this)]);
			}
		});
	}

// catalog tovar height fix

	$(window).load(function(){
								tovarHeightFix();
							});
	$(window).resize(function(){
								tovarHeightFix();
							});


function tovarHeightFix(){
	var tovar = $(".catalog .tovar .content");
	var tovhead = $(".catalog .tovar .content .tovhead");
	var maxTovH = $(tovar[0]).height();
	var screenWidth = $("body").width();
	var nM, aM;
	var massTovar = new Array();
	var massTovhead = new Array();
	$(tovhead).height("auto");
	$(tovar).height("auto");
	if (tovar.length){

		if (screenWidth<1250){
			kolVo = 2;
			nM = tovar.length;
			aM = nM/kolVo;
			aM = Math.floor(aM);
//			rM = nM - aM*kolVo;

			for (i=0;i<aM+1;i++){
				massTovar[i] = new Array();
				massTovhead[i]= new Array();
			}
			k=0;
			for (i=0;i<aM+1;i++){
					for (j=0;j<kolVo;j++){
						massTovar[i][j]=tovar[k];
						massTovhead[i][j] = tovhead[k]
						k++;
					}
				}
				
			for (i=0;i<aM+1;i++){
					maxTovH = 0;
					for (j=0;j<kolVo;j++){
						if (massTovar[i][j]){
							maxTovHtmp = $(massTovar[i][j]).height();
						}else{maxTovHtmp = 0}
						if (maxTovHtmp > maxTovH){
							maxTovH = maxTovHtmp;
						}
					}
					for (j=0;j<kolVo;j++){
						$(massTovar[i][j]).height(maxTovH);
					}
					maxTovheadH = 0;
					for (j=0;j<kolVo;j++){
						if (massTovhead[i][j]){
							maxTovheadHtmp = $(massTovhead[i][j]).height();
						}else{maxTovheadHtmp = 0};
						if (maxTovheadHtmp > maxTovheadH){
							maxTovheadH = maxTovheadHtmp;
						}
					}
					for (j=0;j<kolVo;j++){
						$(massTovhead[i][j]).height(maxTovheadH);
					}
				}
			}else{
				kolVo = 3;
				nM = tovar.length;
				aM = nM/kolVo;
				aM = Math.floor(aM);
//				rM = nM - aM*kolVo;
	
				for (i=0;i<aM+1;i++){
				massTovar[i] = new Array();
				massTovhead[i]= new Array();
			}
			k=0;
			for (i=0;i<aM+1;i++){
					for (j=0;j<kolVo;j++){
						massTovar[i][j]=tovar[k];
						massTovhead[i][j] = tovhead[k]
						k++;
					}
				}
				
			for (i=0;i<aM+1;i++){
					maxTovH = 0;
					for (j=0;j<kolVo;j++){
						if (massTovar[i][j]){
							maxTovHtmp = $(massTovar[i][j]).height();
						}else{maxTovHtmp = 0};
						if (maxTovHtmp > maxTovH){
							maxTovH = maxTovHtmp;
						}
					}
					for (j=0;j<kolVo;j++){
						$(massTovar[i][j]).height(maxTovH);
					}
					maxTovheadH = 0;
					for (j=0;j<kolVo;j++){
						if (massTovhead[i][j]){
							maxTovheadHtmp = $(massTovhead[i][j]).height();
						}else{maxTovheadHtmp = 0};
						if (maxTovheadHtmp > maxTovheadH){
							maxTovheadH = maxTovheadHtmp;
						}
					}
					for (j=0;j<kolVo;j++){
						$(massTovhead[i][j]).height(maxTovheadH);
					}
				}
			}
			}
	};
          
  $("#ask").toggle(
    function(){
            $(".ask").slideDown();
            $(this).addClass("askopen");
        },
    function(){
            $(".ask").slideUp();
            $(this).removeClass("askopen");
  });
	tabs();
	function tabs(){
		var tabButton = $(".tabsholder .tabs li");
		var tabButtonLength = $(tabButton).length;
		var tabItem = $(".tabsholder .tabsitem .tab");
		var tabItemLength = $(tabItem).length;
		var thisIndex;

		$(tabItem).hide();
		for (i=0; i<tabButtonLength; i++){
			if ($(tabButton[i]).hasClass("active")){
				$(tabItem[i]).show();
			}
		}
		$(tabButton).find("a").click(function(event){ event.preventDefault();});
		$(tabButton).click(function(){
										thisIndex = $(tabButton).index(this);
										$(this).parent().find("li").removeClass("active");
										$(this).addClass("active");
										$(this).parent().next().find(".tab").hide();
										$(tabItem[thisIndex]).show();
									});
	}
  incValue();
	cartValue();
	incValueLoad(".colors");
  
	var shopcard = ".shopcart .table";
	cartPreLoad(shopcard);
	
	var arrKolvo = new Array;
	removTov(shopcard);
  
	function removTov(table){
		var thisTr = $(table + ' tbody tr');
		var thisTrLength = $(thisTr).length;
		var thisCheckbox = $(thisTr).find("input:checkbox ");
		$(thisCheckbox).change(function(){
			var checked = false;
			checked = $(this).attr("checked");
			indexCheck = $(thisCheckbox).index(this);
			thisCount = $(thisTr[indexCheck]).find("input.count");
			if (checked){
				arrKolvo[indexCheck] = $(thisCount).val();
				$(thisCount).val("0");
				incValueLoad(shopcard);
			}else{
				$(thisCount).val(arrKolvo[indexCheck]);
				incValueLoad(shopcard);
			}
			var checked3;
			for (i=0;i<thisTrLength; i++){
				checked2 = $(thisCheckbox[i]).attr("checked");
				checked3 =checked3 || checked2;
				if(i==thisTrLength-1){
					if(checked3){$(".reload").show();}else{$(".reload").hide();}
				}
			}
		});
	}
  
  function cartPreLoad(table){
    var thisTr = $(table + ' tbody tr');
    var thisTrLength = $(thisTr).length;
    var courentPrice;
    var courentKolvo;
    var allPriceNds = 0;
    var thisCheckbox = $(thisTr).find("input:checkbox");
    var checked3;  
    
    for (i=0;i<thisTrLength; i++){
      checked2 = $(thisCheckbox[i]).attr("checked");
      checked3 =checked3 || checked2;
      if(i==thisTrLength-1){
        if(checked3){$(".reload").show();}else{$(".reload").hide();}
      }
    }
  }
  
  
  function addCommas(nStr){
//    nStr = nStr.replace(",", ".");
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + '&nbsp;' + '$2');
    }
    
    return x1 + x2;
  }
  
  function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
  }
  
  function strToInt(nStr){
    if(nStr!=''){      
      nStr = nStr.replace(",", ".");    

      var rgx = /(\s+)/;
      while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '');
      }
      
      return nStr*1;
    }else return 0;
  }
  
	function incValueLoad(table){		
		var thisTr = $(table + ' tbody tr');
		var thisTrLength = $(thisTr).length;
		var courentPrice;
		var courentKolvo;
		var allPriceNds = 0;
		var thisCheckbox = $(thisTr).find("input:checkbox ");
		var checked3;
		
		for (i=0;i<thisTrLength;i++){
				courentPrice = $(thisTr[i]).find(".cena1 span").text();
				courentKolvo = $(thisTr[i]).find(".count").val();
				courentCena = $(thisTr[i]).find(".cena2 span");
        
        if(strpos(courentPrice,'формируется',0)===false){
          courentPrice = strToInt(courentPrice);
                  
          $(thisTr[i]).find(".cena1 span").html(addCommas(courentPrice));
          
				  courentPrice = (courentPrice*courentKolvo).toFixed(2);
				  $(courentCena).html(addCommas(courentPrice));
				  allPriceNds = (allPriceNds*1 + courentPrice*1).toFixed(2);
        }
		}
		if (table == shopcard){
			allPrice(allPriceNds);			
		}
		for (i=0;i<thisTrLength; i++){
			checked2 = $(thisCheckbox[i]).attr("checked");
			checked3 =checked3 || checked2;
			if(i==thisTrLength-1){
				if(checked3){$(".reload").show();}else{$(".reload").hide();}
			}
		}
	}
  
  function fuckinDelButton(table){    
    var thisTr = $(table + ' tbody tr');
    var thisTrLength = $(thisTr).length;
    var courentPrice;
    var courentKolvo;
    var allPriceNds = 0;
    var thisCheckbox = $(thisTr).find("input:checkbox ");
    var checked3;
    
    for (i=0;i<thisTrLength; i++){
      checked2 = $(thisCheckbox[i]).attr("checked");
      checked3 =checked3 || checked2;
      if(i==thisTrLength-1){
        if(checked3){$(".reload").show();}else{$(".reload").hide();}
      }
    }
  }
  
	function allPrice(withNDS){
		
		var nonds = $(".nonds span");
		var noNDS=0;
		var nds = $(".nds span");
		var NDS=0;
		var ndsPercent = $(".nds").attr("nds");
		var withnds = $(".withnds span");
		
		$(withnds).html(addCommas(withNDS));
    
		noNDS = ((withNDS*100)/(ndsPercent*1+100)).toFixed(2);    
		$(nonds).html(addCommas(noNDS))

		NDS = (withNDS - noNDS).toFixed(2);
		$(nds).html(addCommas(NDS));
	}
  
  function cartValue(){
    var incVal;
    $('.shopcart .plus').click( function(){
      id = $(this).attr('pid');
      thisInc = $(this).parent().prev();
      incVal = $(thisInc).val();
      shag = $(thisInc).attr('shag');
      if(shag.length > 1){
        sh = shag.split('.');
        sh_length = sh[1].length;
      }
      else{
        sh_length = 0;
      }
      shag = shag*1;
      
      incVal = ((incVal*1) + (shag*1)).toFixed(sh_length);
      
      if (incVal == 0){
        $(this).parent().parent().parent().parent().find("input:checkbox").trigger('click');
      }
      else{
        $(this).parent().parent().parent().parent().find("input:checkbox").attr({"checked":""});
        fuckinDelButton(shopcard);
      }
      
      $(thisInc).val(incVal);
      thisTr = $(this).parent().parent().parent().parent();
      
      $.getJSON('/ajax/rcart/',{item_id:id, itm_count:incVal},function(data){
        $('.prices span').html(addCommas(data.total_price));
        $("#cart").html(data.cart_html);
        $(".optskid").html(data.cart_percent);
        $.each(data.prices, function(index, tov){
          price = tov.price;
          item_price = tov.item_price;
          id = tov.id;
          $("#cena_"+id).html(addCommas(price));
          $("#total_"+id).html(addCommas(item_price));
        })

      })
    })
    
    $('.shopcart .minus').click( function(){
      id = $(this).attr('mid');
      thisInc = $(this).parent().prev();
      incVal = $(thisInc).val();
      shag = $(thisInc).attr('shag');
      if(shag.length > 1){
        sh = shag.split('.');
        sh_length = sh[1].length;
      }
      else{
        sh_length = 0;
      }
      shag = shag*1;
      if (incVal > 0){
        incVal = ((incVal*1) - (shag*1)).toFixed(sh_length);
        
        if (incVal == 0){
          $(this).parent().parent().parent().parent().find("input:checkbox").trigger('click');
          fuckinDelButton(shopcard);
        }
        
        $(thisInc).val(incVal);
        thisTr = $(this).parent().parent().parent().parent();
        
        $.getJSON('/ajax/rcart/',{item_id:id, itm_count:incVal},function(data){
          $('.prices span').html(addCommas(data.total_price));
          $("#cart").html(data.cart_html);
          $(".optskid").html(data.cart_percent);
          $.each(data.prices, function(index, tov){
            price = tov.price;
            item_price = tov.item_price;
            id = tov.id;
            $("#cena_"+id).html(addCommas(price));
            $("#total_"+id).html(addCommas(item_price));
          })
        })
      }
                  
    });
    
    var valBefore;
    $(".shopcart .count").focus(function(e){valBefore = $(this).val();});
    $(".shopcart .count").keyup(function(e){
      if ((( 48 <= e.which) && (e.which <= 57)) || (( 96 <= e.which) && (e.which <= 105)) || (e.which == 8)||(e.which == 39)||(e.which == 37)||(e.which == 46)||(e.which == 27)||(e.which == 17) || (e.which == 16) || (e.which == 110)){
        thisKolvo = $(this).val();
        thisTr = $(this).parent().parent().parent();
        id = $(thisTr).find('.minus').attr('mid');
        $.getJSON('/ajax/rcart/',{item_id:id, itm_count:thisKolvo},function(data){
          $('.prices span').html(addCommas(data.total_price));
          $("#cart").html(data.cart_html);
          $(".optskid").html(data.cart_percent);
          $.each(data.prices, function(index, tov){
            price = tov.price;
            item_price = tov.item_price;
            id = tov.id;
            $("#cena_"+id).html(addCommas(price));
            $("#total_"+id).html(addCommas(item_price));
          })
        })

        valBefore = $(this).val();
        if (valBefore == 0){
          $(this).parent().parent().parent().find("input:checkbox").trigger('click');
        }else{
          $(this).parent().parent().parent().find("input:checkbox").attr({"checked":""});
        }
        fuckinDelButton(shopcard);
      }else{
          $(this).val(valBefore);
      }
    });
  }
  
	function incValue(){
		var incVal;
		$('.colors .plus').click( function(){
			thisInc = $(this).parent().prev();
      incVal = $(thisInc).val();
      shag = $(thisInc).attr('shag');
      
      if(shag.length > 1){
        sh = shag.split('.');
        sh_length = sh[1].length;
      }
      else{
        sh_length = 0;
      }
      
			shag = shag*1;
      
      incVal = ((incVal*1) + (shag*1)).toFixed(sh_length);
      
			$(thisInc).val(incVal);
			thisTr = $(this).parent().parent().parent().parent();
                  
      thisPrice = $(thisTr).find(".cena1 span").text();      
      thisPrice = strToInt(thisPrice);
			thisPrice = (thisPrice*incVal).toFixed(2);
			$(thisTr).find(".cena2 span").html(addCommas(thisPrice));
//			incValueLoad('.colors');
 	  })
    
		$('.colors .minus').click( function(){
			thisInc = $(this).parent().prev();
			incVal = $(thisInc).val();
      shag = $(thisInc).attr('shag');
      if(shag.length > 1){
        sh = shag.split('.');
        sh_length = sh[1].length;
      }
      else{
        sh_length = 0;
      }
      shag = shag*1;
			if (incVal > 0){
        incVal = ((incVal*1) - (shag*1)).toFixed(sh_length);
        
				$(thisInc).val(addCommas(incVal));
				thisTr = $(this).parent().parent().parent().parent();
                    
				thisPrice = $(thisTr).find(".cena1 span").text();
        thisPrice = strToInt(thisPrice);
				thisPrice = (thisPrice*incVal).toFixed(2);
				$(thisTr).find(".cena2 span").html(addCommas(thisPrice));
      }
									
		});
		
		var valBefore;
		$(".colors .count").focus(function(e){valBefore = $(this).val();});
		$(".colors .count").keyup(function(e){
			if ((( 48 <= e.which) && (e.which <= 57))||(( 96 <= e.which) && (e.which <= 105))||(e.which == 8)||(e.which == 39)||(e.which == 37)||(e.which == 46)||(e.which == 27)||(e.which == 17)||(e.which == 16)){
				thisKolvo = $(this).val();
				thisTr = $(this).parent().parent().parent();

				thisPrice = $(thisTr).find(".cena1 span").text();
        thisPrice = strToInt(thisPrice);
				thisPrice = (thisPrice*thisKolvo).toFixed(2);
				$(thisTr).find(".cena2 span").html(addCommas(thisPrice));        
			}else{
					$(this).val(valBefore);
			}
		});
	}
  
	$(".shopby .button").toggle(
								function(){
										$(".ask").slideDown();
									},
								function(){
										$(".ask").slideUp()
									}
								);
	$('.zakaznuber').toggle(
			function(){
				$(this).addClass("aaa");
				$(".aaa span").addClass('open');
				$(this).find("em").css({display:"none"});
				$(this).next().slideDown("slow");
			},
			function(){
				$(this).find("em").css({display:"block"});
				$(".aaa span").removeClass('open');
				$(this).removeClass("aaa");
				$(this).next().slideUp("slow");
			}
		)
	

catalogtov();
function catalogtov(){
	var tovar = $(".catalogtov .cattovar");
	var maxTovH = $(tovar[0]).height();
	
	if (tovar.length){
		 maxTovH = 0;
		for (i=0;i<tovar.length;i++){
			maxTovHtmp = $(tovar[i]).height();
			if (maxTovHtmp > maxTovH){
				maxTovH = maxTovHtmp;
			}
		}
	}
	maxTovH = maxTovH;
	$(".catalogtov .cattovar").height(maxTovH);
}


tovarVariantsSelect();
function tovarVariantsSelect(){
	var ajaxlink;
//	var asd;
	$(".tovar .variants select").change(function(){
    thisTovar = $(this).parent().parent().parent().parent();
		thisTovarInfo = $(this).parent().parent();
		ajaxlink = $(this).find("option:selected").attr("ajaxlink");
    var hhh = $(this).parents('.content').height();
    $(this).parents('.content').prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
    $("#tov_overlay").height(hhh);
		$.getJSON(ajaxlink, function(data){
			$(thisTovar).find(".tovhead").html(data.tovhead);
			$(thisTovar).find(".more").attr({"href":data.more});
			$(thisTovar).find(".img").html(data.img);
			$(thisTovar).find(".code").replaceWith(data.code);
			$(thisTovar).find(".price").html(data.price);
      $(thisTovar).find(".inputinit").attr({"id":data.newid});
      
      $(thisTovar).find(".incard").attr({"fid":data.id});
      $(thisTovar).find(".button").attr({"sid":data.id});
      
      if(data.is_not_sell==1){
        $(thisTovar).find('.incard').remove();
        $(thisTovar).find('.button').remove();
        $(thisTovarInfo).append('<span class="incard incard-not"> в корзину</span>');
        $(thisTovarInfo).append('<span class="button button-not">в корзину<em></em></span>');
      }
      else{
        if($(thisTovar).find('span.incard')){
          $(thisTovar).find('span.incard').remove();
          $(thisTovarInfo).append('<a href="javascript:void(0);" class="incard" fid="'+data.id+'" title="Добавить в корзину"> в корзину</a>');
        }
        if($(thisTovar).find('span.button')){
          $(thisTovar).find('span.button').remove();
          $(thisTovarInfo).append('<a href="javascript:void(0);" class="button" sid="'+data.id+'" title="Добавить в корзину">в корзину<em/></a>');
        }
				$(thisTovar).find(".button").html(data.u_name);
        if(data.in_card_count > 0){
          if(!$(thisTovar).find(".incard").hasClass('incardtrue')){
            $(thisTovar).find(".incard").addClass('incardtrue');
          }
        }
        else{
          if($(thisTovar).find(".incard").hasClass('incardtrue')){
            $(thisTovar).find(".incard").removeClass('incardtrue');
          }
        }
      }
      
			tovarHeightFix();
			$("#tov_overlay").remove();
      
      add2Cart();
	  });
  });
}

tovarVariantsSelect2();
function tovarVariantsSelect2(){
  var ajaxlink;
//  var asd;
  
  $("#chage_item_item").change(function(){    
      thisTovar = $(this).parent().parent().parent().parent();
      ajaxlink = $(this).find("option:selected").attr("ajaxlink");

      var hhh = $(this).parents('.content').height();
      $(this).parents('.content').prepend('<div id="tov_overlay" class="tov_overlay" ></div>');
      $("#tov_overlay").height(hhh);
      
      $(".content-holder #content").load(ajaxlink, function(){         
        tovarVariantsSelect();
        tovarVariantsSelect2();
        tovcarusel();
        tabs();
        add2Cart();
        
        $("#ask").toggle(
          function(){
                  $(".ask").slideDown();
                  $(this).addClass("askopen");
              },
          function(){
                  $(".ask").slideUp();
                  $(this).removeClass("askopen");
        });
        
        incValue();
        incValueLoad(".colors");
      });
  });
}

tovcarusel();
function tovcarusel(){
	var src2;
		$("#tovcarusel a").click(function(event){ event.preventDefault();});
		$("#tovcarusel a").click(function(){
      
      src_g_big = $("#tovar .leftc .img img").attr('src');
      src_g_small = $("#tovar .leftc .img img").attr('src2');
      
      src_c_big = $(this).attr("href");
		  src_c_small = $(this).children().attr("src");
      
      $("#tovar .leftc .img img").attr({"src":src_c_big})
		  $("#tovar .leftc .img img").attr({"src2":src_c_small})
      
      $(this).attr({"href":src_g_big});
      $(this).children().attr({"src":src_g_small});
	  });
	}
});


