var compareCount=0;
var itemTimeout;
var that;
var stillHover=0;
var itemWidth;
var isCategory = 1;
var focused;
var domn;
var filterData = new Object();
function getProdNum(){
	$("#priceForm input[name=get]").prop("disabled",false);
	dat = $("#priceForm").serialize()+'&get='+encodeURIComponent($("#priceForm").attr('data-get'));
	$("#priceForm input[name=get]").prop("disabled",true);
	$("#prodNum").hide();
	$.ajax({
	  type: 'POST',
	  data: dat,
	  url: "/functions/category_build_query.php?json=1&filtered=1",
	  success: function(data){
		if(data==null){
			$("#prodNum").html("Увы, товаров
 не найдено").fadeIn();
		}else{
			$("#prodNum").html("Найдено "+data+" товара(ов)").fadeIn();
		}
	  },
	  dataType: "json"
	});
}
function getFilterLink(){
	$.ajax({
	  type: 'POST',
	  data: 'data='+encodeURIComponent(JSON.stringify(filterData))+'&url='+encodeURIComponent(window.location.search),
	  url: "/json/category_getFilterLink.php?jsonLoad=1",
	  success: function(data){
console.log(data);
		on_history(function(){
			locationIsJSON=1;
			ind = History.getCurrentIndex()+1;
			History.pushState(ind,"", data);
		});
	  },
	  dataType: "json"
	});
}
$(function () {
//	$(window).resize(function(){
//		$(".cat_submenu").sly('reload');
//	});
/*
	  (function() {
	    var $frame = $(".cat_submenu");
	    var $slidee = $frame.children('ul').eq(0);
	    var $wrap = $frame;
	    $frame.sly({
	      horizontal: 1,
	      itemNav: 'basic',
	      smart: 1,
	      mouseDragging: 1,
	      touchDragging: 1,
	      releaseSwing: 1,
	      startAt: 0,
	      scrollBar: $wrap.find('.scrollbar'),
	      scrollBy: 1,
	      activatePageOn: 'click',
	      speed: 300,
	      elasticBounds: 1,
	      easing: 'easeOutExpo',
	      dragHandle: 1,
	      dynamicHandle: 1,
	    });
	  }());
	$('#aviaslider').aviaSlider({
		blockSize: {height: 250, width:900},
		betweenBlockDelay:60,
		animationSpeed:900,
		autorotationSpeed:5,
		display: 'all',
		autorotation: true,
		transition: 'fade'
	});
*/
/*
		if($.cookie('note_options_agree')!=1){
			setTimeout(function(){ $(".note.options_agree").slideDown(); },1500);
		}
		$("#note_options_agree").click(function(){
			$.cookie('note_options_agree', '1', { expires: 7, path: '/' });
			$(".note.options_agree").slideUp();
			return false;
		});
*/
	var cars = new Array;
	$(".csTitle").click(function(){
		if($(this).hasClass('active')){
		}else{
			$("#"+$(this).attr('data-parent')+" .csTitle").removeClass('active');
			$(this).addClass('active');
			$("#"+$(this).attr('data-parent')+" .cContent").addClass('hidden');
			$(".cContent#"+$(this).attr('data-for')).removeClass('hidden');
			return false;
		}
	});
$(".filterBlock .filter_row.disabled").find("input[type=radio]").prop('disabled',true);
$(".filterBlock .filter_row .optionActive").click(function(){
	parent = $(this).parent("label").parent(".filter_title").parent(".filter_row");
	if($(this).is(':checked')){
		parent.find("input[type=radio]").prop('disabled',false);
		parent.removeClass('disabled');
	}else{
		parent.find("input[type=radio]").prop('disabled',true);
		parent.addClass('disabled');
	}
});
$(".filterBlock .filter_row .filter_variants label").click(function(){
	parent = $(this).parent(".filter_variants").parent(".filter_row");
	parent.removeClass('disabled');
	$(parent).find("input[type=checkbox]").prop('checked',true);
	$(this).parent().find("input[type=radio]").prop('disabled',false);
	$(this).find("input[type=radio]").prop('checked',true);
	getProdNum();
});
//	 $('.zoom').zoom();
	 $('.scroll-link').click(function(){
		$('html, body, .content').animate({scrollTop: $("[name="+this.hash.substr(1)+"]").offset().top}, 300);
		return false;
	 });
//$("input[name=op74_589]").click();
	itemWidth = $(".catProds .item").width()+20;
	catProdWidth();
	$(window).resize(catProdWidth);
//	$(".addToCart").click(function(){$(".cart").removeClass('inactive');});
	$(".ctrl_products_cmp").change(function(){
		if($(this).attr('checked'))
		{
			compareCount=compareCount+1;
			productName = "
"+$("form[data-rel="+$(this).val()+"] .title a").html()+"
";
			$(".compareProds").append(productName);
			if(compareCount>1){ $(".compareWindow").fadeIn(); }
		}else{
			compareCount=compareCount-1;
			$(".compare"+$(this).val()).remove();
		}
		if(compareCount<2){
			$(".compareWindow").fadeOut();
		}
	});
if(isIOS!=true){
/*
	$(".item").mouseout(function(){
	clearTimeout(itemTimeout);
	focused = '';
	that = this;
	itemTimeout = setTimeout(function(){
		if(stillHover==0){
		$(".prodDesc").removeClass('shown');
		}
	},25);
	});
	$(".item").mouseover(function(){
	focused = this;
	clearTimeout(itemTimeout);
	if(that!=this){ $(".prodDesc").removeClass('shown'); }
		$(".prodDesc",this).addClass('shown');
	});
*/
	var innerDescTimeout;
	$(".prodDesc").mouseout(function(){
		that = this;
	
		clearTimeout(innerDescTimeout);
		innerDescTimeout = setTimeout(function(){
			$(".neposredstvennoDesc").animate({'height':'46px'});
			$(".prodDesc").removeClass('active');
		},100);
		clearTimeout(itemTimeout);
		focused = '';
		itemTimeout = setTimeout(function(){
			if(stillHover==0){
				$(".prdbrief_options").slideUp();
			}
		},250);
	});
	var focused;
	$(".prodDesc").mouseover(function(){
		focused = this;
		that = this
		clearTimeout(innerDescTimeout);
		clearTimeout(itemTimeout);
		if($(this).children(".prdbrief_options").html() && $(this).children(".prdbrief_options").html().replace(/\t/g, '').length>10){
			$(this).children(".prdbrief_options").slideDown();
		}
		blockHeight = $("#desc"+$(this).attr('data-pid')).innerHeight()+10;
		if(blockHeight>100){blockHeight=100;}
		if(blockHeight>46){
			innerDescTimeout = setTimeout(function(){
				$("#outDesc"+$(focused).attr('data-pid')).animate({'height':blockHeight+'px'});
			},100);
		}
		$(focused).addClass('active');
	});
}
	$("select").focus(function(){
		if(itemTimeout){
			stillHover = 1;
		}
	});
	$("select").blur(function(){ if(itemTimeout){ stillHover = 0; } });
	$("select").change(function(){ if(itemTimeout){ stillHover = 0; } });
	$(".moreless.more").click(function(){
		$(this).addClass('inactive');
		$(".lastPart").fadeIn();
		$(".moreless.less").removeClass('inactive');
	   return false;
	});
	$(".moreless.less").click(function(){
		$(this).addClass('inactive');
		$(".lastPart").fadeOut();
		$(".moreless.more").removeClass('inactive');
	   return false;
	});
	$(".ml.more").click(function(){
		$(this).addClass('inactive');
		$(".lastPart2").fadeIn();
		$(".ml.less").removeClass('inactive');
	   return false;
	});
	$(".ml.less").click(function(){
		$(this).addClass('inactive');
		$(".lastPart2").fadeOut();
		$(".ml.more").removeClass('inactive');
	   return false;
	});
});
function catProdWidth2() {
		$(".phone").html(itemWidth);
}
var filterOpened = 0;
var filt = 0;
function catProdWidth() {
	cpWidth = $(".catProds").width();
	if(cpWidthitemWidth && $(".catProds .item").length>3)
	 {
		adAfter=4;
		marginVal = contentWidth4-itemWidth;
		$(".betweenHor").css('width',marginVal-2+'px');
		$(".catProds").css('padding-left','0');
	 }
	else if(contentWidth3>itemWidth && $(".catProds .item").length>2)
	 {
		adAfter=3;
		marginVal = contentWidth3-itemWidth;
		$(".betweenHor").css('width',marginVal-4+'px');
		if($("#device").val()!=1){
			$(".catProds").css('padding-left','10px');
		}
	 }
	else
	 {
		adAfter=2;
		marginVal = contentWidth2-itemWidth;
		$(".betweenHor").css('width',marginVal-4+'px');
		if($("#device").val()!=1){
			$(".catProds").css('padding-left','10px');
		}
	 }
	$(".catAd").insertAfter('.order'+adAfter);
}
function hideFilter(){
	$(".filter").removeClass('hidden');
	$(".filter").addClass('hidden');
	$(".filterButton").removeClass('filtersShown');
	$(".filterButton").addClass('filtersHides');
}
function showFilter(){
	$(".filter").removeClass('hidden');
	$(".filterButton").addClass('filtersShown');
	$(".filterButton").removeClass('filtersHides');
}
var bannersWidth = 0;
var totalBanners = 0;
var dom = 'ergotronica.ru';
var category_pointed = new Array();
function delArrayElements(element, index, array) {
	if(index){ delete category_pointed[index]; }
}
function getString(el) {
   if(el.length>0){
	str = '';
	el.forEach(function(element,index,array){
		if(index){ str = str + 'e[' + index + ']=' + element + '&'; }
	});
	return str;
   }
   return false;
}
function send_statistic(){
	if(category_pointed.length>0){
		data = getString(category_pointed);
		if(data!=false){
		   $.ajax({
			  type: 'POST',
			  data: data,
			  url: "/json/statistics.php?action=pointed",
			  dataType: "json",
		   });
		}
		category_pointed.forEach(delArrayElements);
	}
	setTimeout(send_statistic,2500);
}
function includeContentPosition(){
	var position=0;
	$(".snippet-list .pageNo[data-page=1] .snippet-cell").each(function(i,e){
		firstEl = $(".snippet-list .pageNo[data-page=1] .snippet-cell:eq(0)");
		margins = parseFloat($(firstEl).css('margin-left'))+parseFloat($(firstEl).css('margin-right'));
		width = parseFloat($(firstEl).width()+margins);
		if($(this).hasClass('includeElement')){
			if(perLine>1){
				if($(this).hasClass('some')){ splitEls = Math.floor(perLine*0.33); minus=8; }else
				if($(this).hasClass('half')){ splitEls = Math.floor(perLine*0.5); minus=5; }else
				if($(this).hasClass('most')){ splitEls = Math.floor(perLine*0.66); minus=6; }else
				if($(this).hasClass('full')){ splitEls = perLine-1; minus=6; }else
				{ splitEls = 0; }
				includeWidth=(splitEls+1);
				atRight = perLine-(position+1);
				if(atRight>=splitEls){
					$(this).width(width*splitEls+width-minus);
				}else{
					el = $(this);
					$(this).remove();
					$(el).insertAfter(".snippet-list .pageNo[data-page=1] .snippet-cell:eq("+(i-(splitEls-atRight)-1)+")").width(width*splitEls+width-minus);
				}
			}
		}
		if(position+10){ determ='&'; }else{ determ='?'; }
   url = href+determ+"jsonLoad=1&content=lazyLoad";
   $.ajax({
	  type: 'GET',
	  url: url,
	  success: function(data){
		locationIsJSON=1;
		History.pushState(History.getCurrentIndex()+1,"", href);
//		window.location = href;
		$(".snippet-list").append(data[0]);
		$(".catNavi").replaceWith(data[1]);
		$(".catNaviHeader").replaceWith(data[2]);
		$("title").html(data[3]);
		ajaxLoading=0;
	  },
	  async: true,
	  dataType: "json"
   });
}
function reloadListing(href){
   ajaxLoading=1;
   e = href.substr(1).split('?');
   if(e[1]!=undefined && e[1].length>0){ determ='&'; }else{ determ='?'; }
   url = href+determ+"jsonLoad=1&content=whole_listing";
   $.ajax({
	  type: 'GET',
	  url: url,
	  success: function(data){
		locationIsJSON=1;
		ind = History.getCurrentIndex()+1;
		if(href.split(domn).length==1){
			jsonPages[ind] = domn + href;
		}else{
			jsonPages[ind] = href;
		}
		clicked_fn();
		History.pushState(ind,"", href);
//		window.location = href;
		$("div.category").replaceWith(data[0]);
		$("title").html(data[3]);
		ajaxLoading=0;
//		mainmenuOnLoad();
		lazyLoadImgs();
	  },
	  async: true,
	  dataType: "json"
   });
}
function str_replace ( search, replace, subject ) {	// Replace all occurrences of the search string with the replacement string
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Gabriel Paderni
	if(!(replace instanceof Array)){
		replace=new Array(replace);
		if(search instanceof Array){//If search	is an array and replace	is a string, then this replacement string is used for every value of search
			while(search.length>replace.length){
				replace[replace.length]=replace[0];
			}
		}
	}
	if(!(search instanceof Array))search=new Array(search);
	while(search.length>replace.length){//If replace	has fewer values than search , then an empty string is used for the rest of replacement values
		replace[replace.length]='';
	}
	if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
		for(k in subject){
			subject[k]=str_replace(search,replace,subject[k]);
		}
		return subject;
	}
	for(var k=0; k-1){
			subject = subject.replace(search[k], replace[k]);
			i = subject.indexOf(search[k],i);
		}
	}
	return subject;
}