
$(document).ready(function () {
	autoHeight();
	$(document).on("click",".qkView:not(.detail)", function(){
		var productAndOptionID = $(this).attr('rel');
		var productID = $(this).attr('productid');
		var checked = $("[rel=checkbox_compare_"+productID+"]").prop('checked');
		var geturl = '/index/ajaxQuickView/id/'+productAndOptionID+'/l/'+languageID+'/checked/'+checked+'/originCatalogID/'+originCatalogID;
		$.ajax({
			url: GLOBAL_BASE_PATH + geturl,
			method: "GET",
			cache: true,
			global: false,
			success: function(qvHtml) {
				$("#CategoryPopup").empty().html(qvHtml);	//Append the new HTML into listing DIV
				fn_change_options('', productID);
				lightbox_open();
			}
		});
	});
	
	jQuery.expr[":"].contains = jQuery.expr.createPseudo(function(arg) {
		return function( elem ) {
			return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
		};
	});


	
	
	
	
	window.document.onkeydown = function(e) {
		if(!e){ e = event; }
		if(e.keyCode == 27){ lightbox_close(); }
	}
	
	
	
	
	/* toggle : grid view  and list view */
	$(document).on("click",".gridView:not('.active'),.listView:not('.active')", function(){
		var thisObj = $(this);
		page.setViewType(thisObj.attr('id'));
		page.setPageNumber(0);
		page.resetProductsEndStatus();
		
		$(".gridView,.listView").removeClass('active');
		thisObj.addClass('active');
		
		if(!page.checkAjaxHold()){						
			var searchVar = setNavOptions();
			var key	= searchVar[1];
			if(typeof page.ajaxResponses[key] == 'undefined') 
			{
				var searchVar = setNavOptions();
				var paramData	=	searchVar[0];
				var uniqueID = paramData['uniqueID'];	
				$.ajax({
					url: GLOBAL_BASE_PATH + '/catalog/ajaxGetProducts/',
					type: "POST",
					cache: true,
					data: searchVar[0],
					beforeSend: function () {
						page.ajaxHold(true);
						$(".pop_loader").removeClass('hide');
					},
					complete:function(){
						page.ajaxHold(false);
						$(".pop_loader").addClass('hide');
					}
				}).done(function(resHtml) {
					if($.trim(resHtml) != ''){
						page.setPageNumber(1);
						$(".productListing").empty().html(resHtml);
						$("#productsCount").empty().html(productsCountVar);
						/* this function is declared in addtocompare.feature.js page */
						addToCompare.markCheckedItems();
						page.ajaxResponses[key] ={content:resHtml,uniqueID:uniqueID};
						page.lazyLoad(uniqueID);
					}
				});
			}else{
				page.setPageNumber(1);
				var theResponse = page.ajaxResponses[key];
				$(".productListing").empty().html(theResponse['content']);
				$("#productsCount").empty().html(productsCountVar);
				/* this function is declared in addtocompare.feature.js page */
				addToCompare.markCheckedItems();
				page.lazyLoad(theResponse['uniqueID']);
			}
			
		}	
	});

	
	$(document).on("click",".clearAttributeSearch", function(){
		var thisRel = $(this).attr('rel');
		if($(".searchAttrOptID[rel='"+thisRel+"']:checked").length>0)
		{
			$(".searchAttrOptID[rel='"+thisRel+"']").prop("checked",false);
			$(".searchAttrOptID[rel='"+thisRel+"']").removeAttr("disabled");
			initProductSearch();
		}	
	});
	$(document).on("click",".searchAttrOptID", function(){
		initProductSearch();
	});
	if($( "#price-range" ).length>0 && typeof __priceRangeMin != 'undefined' && typeof __priceRangeMax != 'undefined')
	{
		var range1=__priceRangeMin;		
		if(__priceRangeMinCustom)
		range1=__priceRangeMinCustom;
		
		var range2=__priceRangeMax;		
		if(__priceRangeMaxCustom)
		range2=__priceRangeMaxCustom;
		
		$( "#price-range" ).slider({
		  range: true,
		  min: __priceRangeMin,
		  max: __priceRangeMax,
		  values: [ range1, range2 ],
		  stop: function( event, ui ) {			
			initProductSearch();			
		  },
		  slide: function( event, ui ) {
			$( "#price-amount" ).html(formatCurrency(ui.values[ 0 ]) + " - " + formatCurrency(ui.values[ 1 ]) );
			$( "#price-amount-min" ).val(ui.values[ 0 ]);
			$( "#price-amount-max" ).val(ui.values[ 1 ]);
		  }
		});
		$( "#price-amount" ).html(formatCurrency($( "#price-range" ).slider( "values", 0 )) +
		  " - " + formatCurrency($( "#price-range" ).slider( "values", 1 )) );
	}
	$(document).on("click",".searchDiscountRange", function(){
		initProductSearch();
	});
	$(document).on("click","#applyNow", function(){
            initProductSearch($(this));
            $(".filter-contents").hide();
            
	});	
	$(document).on("change",".checkbox_brandIDs", function(){
		initProductSearch();
	});
	
	
	$(document).on("click",".clearPriceRange", function(){		
		if(resetPriceRange())
		{ 
			initProductSearch();
		}	
	});
	$(document).on("click",".clearDiscountRange", function(){		
		if(resetDiscountSearch())
		{ 
			initProductSearch();
		}	
	});
	$(document).on("click",".clearAllSearch", function(){		
		var resetPriceRangeVar = resetPriceRange();
		var resetDiscountSearchVar = resetDiscountSearch();
		var resetAttributeSearchVar = resetAttributeSearch();
		
		if(resetPriceRangeVar		
			|| resetDiscountSearchVar
			|| resetAttributeSearchVar)
		{	
			initProductSearch();
		}	
	});
	
	if($( ".listMenuScroll" ).length>0)
	{
		$('.listMenuScroll').perfectScrollbar();
	}	
	$(".attrSearchFilter").keyup(function(){
		var filter = $(this).val();
		var thisObj = $(this);
		var visibleCount = 0;
		thisObj.next(".listMenuScroll").find(".attrOptionList li").each(function(){
			if ($(this).text().search(new RegExp(filter, "i")) < 0) {
				$(this).fadeOut();
			} else {
				visibleCount++;
				$(this).show();			
			}
		});
		if(visibleCount>5)	
			thisObj.next(".listMenuScroll").perfectScrollbar();
		else
			thisObj.next(".listMenuScroll").perfectScrollbar('destroy');
	});
	
	$(document).on('keyup',"#filterBrands",function(){
		var val = this.value;
		$(".li_brandIDs").find("label:not(:contains("+val+"))").parent('li').hide();
		$(".li_brandIDs").find("label:Contains(" + val + ")").parent('li').show();
		if($(".li_brandIDs:visible").length >5)	
			$(this).next(".listMenuScroll").perfectScrollbar();
		else
			$(this).next(".listMenuScroll").perfectScrollbar('destroy');
	}).on("click","#clearBrands",function(){
		$(".li_brandIDs").show();
		$("#filterBrands").val('').focus();
	});
	
	
	
	if(typeof __discountQueryString != 'undefined')
	{
		$("#searchDiscountRange_"+__discountQueryString).prop("checked",true);
	}
	$(document).on("click",".filters-top-selected .deleteFilter", function(){
		var thisRel = $(this).attr('rel');
		if(thisRel=='price')
		{
			resetPriceRange();
		}
		else if(thisRel=='discount')
		{
			resetDiscountSearch();
		}
		else
		{
			$("#searchAttrOptID_"+thisRel).prop("checked",false);
		}
		$(this).remove();
		initProductSearch();
	});
	$(document).on("click",".filters-top-selected .deleteFilterHead", function(){
		var thisRel = $(this).attr('rel');
		$("#filters-top-selected_"+thisRel).remove();
		if($(".searchAttrOptID[rel='"+thisRel+"']:checked").length>0)
		{
			$(".searchAttrOptID[rel='"+thisRel+"']").prop("checked",false);
			initProductSearch();
		}	
	});
	if(typeof __queryStringMode!='undefined' && __queryStringMode>0)
	{
		setNavOptions();	
	}
});


	function lightbox_open(){
		//window.scrollTo(0,0);
		$("#CategoryPopup, #CategoryFade").fadeIn();
	}
	function lightbox_close(){
		$(".zoomContainer").hide();
		$("#CategoryPopup, #CategoryFade").fadeOut();
	}
	
	function setNavOptions()
	{	
		var navDataObj = [];
		var attrDataObj = [];
		var attributeOptionIdString  = '';
		var i = 1;
		var priceRangeMinForKey = '';
		var priceRangeMaxForKey = '';
		var priceRangeMin = '';
		var priceRangeMax = '';
		var discountRange = '';
		var attributeNavObj = {};
		var attributeNavObjHtml = '';
		if($(".searchAttrOptID").length>0)
		{
			$(".searchAttrOptID:checked").each(function(){
			attributeOptionIdString = attributeOptionIdString + $(this).val() + '_';
			attrDataObj.push({
				attribute: $(this).attr("rel"),
				option: $(this).val()
			});
			var thisRel = $(this).attr("rel");
			if(typeof attributeNavObj[thisRel]=='undefined')
			{
				attributeNavObj[thisRel] = {};
				attributeNavObj[thisRel].values = [];
			}
			attributeNavObj[thisRel].label = $(this).attr("refinehead");			
			attributeNavObj[thisRel].values.push({
				text: $(this).attr("refineval"),
				id: $(this).val()
			}); 
			});
		}			
		var uniqueID = +new Date;
		priceRangeMin = $.trim($( "#price-amount-min" ).val());
		priceRangeMax = $.trim($( "#price-amount-max" ).val());
		discountRange = $.trim($("input[name='searchDiscountRange']:checked").val());
		
		if($( "#price-range" ).length>0 && (priceRangeMin!=__priceRangeMin
			|| priceRangeMax!=__priceRangeMax))
		{
			attributeNavObj['price'] = {};
			attributeNavObj['price'].values = [];
			attributeNavObj['price'].label = $( "#price-amount-min" ).attr("refinehead");			
			attributeNavObj['price'].values.push({
				text: $( "#price-amount" ).html(),
				id: 'price'
			}); 
		
		}
		
		var brandIDs =[];
		if($(".checkbox_brandIDs:checked").length>0){
			$(".checkbox_brandIDs:checked").each(function(){
				brandIDs.push(this.value);
			});
		}
		
		if($("input[name='searchDiscountRange']:checked").length>0)
		{
			var searchDiscountRangeObj = $("input[name='searchDiscountRange']:checked")
			attributeNavObj['discount'] = {};
			attributeNavObj['discount'].values = [];
			attributeNavObj['discount'].label = searchDiscountRangeObj.attr("refinehead");			
			attributeNavObj['discount'].values.push({
				text: searchDiscountRangeObj.attr("refineval"),
				id: 'discount'
			});
		}
		
		$.each(attributeNavObj,function(attributeNavObjIndex, attributeNavObjValue){
			attributeNavObjHtml = attributeNavObjHtml + '<div class="filters-top-selected" id="filters-top-selected_'+attributeNavObjIndex+'">';
			if(attributeNavObjValue.values.length>1)
			{
				attributeNavObjHtml = attributeNavObjHtml + '<a class="deleteFilterHead" title="'+lblRemove+' '+attributeNavObjValue.label+'" href="Javascript:void(0);" rel='+attributeNavObjIndex+'>';
			}		
			attributeNavObjHtml = attributeNavObjHtml + attributeNavObjValue.label;
			if(attributeNavObjValue.values.length>1)
			{
				attributeNavObjHtml = attributeNavObjHtml + '</a>';
			}
			attributeNavObjHtml = attributeNavObjHtml +' : ';						
			$.each(attributeNavObjValue.values,function(index, valueObj){
				attributeNavObjHtml = attributeNavObjHtml + '<a class="deleteFilter" title="'+lblRemove+' '+valueObj.text+'" href="Javascript:void(0);" rel='+valueObj.id+'>'+valueObj.text+'</a>';
			});	
			attributeNavObjHtml = attributeNavObjHtml + '</div>';
		});		
		if(attributeNavObjHtml!='')
		{
			$("#refined-box-content").html(attributeNavObjHtml).show();						
			$(".filters-top-selected:last").css('border','0');						
		}
		else
		{
			$("#refined-box-content").html('').hide();
		}
		navDataObj=
					{
						page:page.getPageNumber(),
						userGroupID:userGroupID,
						viewType:page.getViewType(),
						categoryID:catIDAndSubcategories,
						brandIDs:brandIDs,
						sortBy:page.getSortBy(),
						keyword:searchKeyword,
						uniqueID:uniqueID,
						attrDataObj:attrDataObj,
						priceRangeMin:priceRangeMin,
						priceRangeMax:priceRangeMax,
						discountRange:discountRange,
                        parentCategoryID:originCatalogID,
                        brandID:brandID
					};
		if(priceRangeMin)			
		priceRangeMinForKey = priceRangeMin.replace(".","_");	
		if(priceRangeMax)			
		priceRangeMaxForKey = priceRangeMax.replace(".","_");	
		
		var pageKey = attributeOptionIdString+page.getPageNumber()+page.getViewType()+page.getSortBy()+priceRangeMinForKey+priceRangeMaxForKey+discountRange+brandID+brandIDs.join();	
		return [navDataObj,pageKey];
	}	
	function initProductSearch()
	{
	 if(_section!='mobile' || $(obj).attr("id")=="applyNow"){ 	
		page.setPageNumber(0);
		page.resetProductsEndStatus();
		var searchVar = setNavOptions();				
		var key	= searchVar[1];
		if(typeof page.ajaxResponses[key] == 'undefined') 
		{
			var paramData	=	searchVar[0];
			var uniqueID = paramData['uniqueID'];
			$.ajax({
				url: GLOBAL_BASE_PATH + '/catalog/ajaxGetProducts/',
				type: "POST",
				cache: true,
				data: searchVar[0],
				beforeSend: function () {
					page.ajaxHold(true);
					$(".pop_loader").removeClass('hide');
				},
				complete:function(){
					page.ajaxHold(false);
					$(".pop_loader").addClass('hide');
				}
			}).done(function(resHtml) {				
				if($.trim(resHtml) != ''){
					page.setPageNumber();
					$(".productListing").empty().html(resHtml);
					$("#productsCount").empty().html(productsCountVar);
					/* this function is declared in addtocompare.feature.js page */
					addToCompare.markCheckedItems();
					page.ajaxResponses[key] = {content:resHtml,uniqueID:uniqueID};
					/*var attributeListObj = $.parseJSON(attributeList);				
					$(".searchAttrOptID").attr("disabled","disabled");				
					$.each(attributeListObj,function(key) {
						$("#searchAttrOptID_"+key).removeAttr("disabled");
					});	*/
					page.lazyLoad(uniqueID);
				}
			});	
		}
		else
		{
			page.setPageNumber(1);
			var theResponse = page.ajaxResponses[key];
			$(".productListing").empty().html(theResponse['content']);
			$("#productsCount").empty().html(productsCountVar);
			/* this function is declared in addtocompare.feature.js page */
			addToCompare.markCheckedItems();
			page.lazyLoad(theResponse['uniqueID']);
		}
		//var scrollTop=$(".productListing").position().top;
		//$('html,body').animate({scrollTop:scrollTop},'slow');	
		}
	}
	function resetPriceRange() 
	{
		if($( "#price-range" ).length>0)
		{
			if($( "#price-amount-min" ).val()!=__priceRangeMin
			|| $( "#price-amount-max" ).val()!=__priceRangeMax)
			{
				var $slider = $("#price-range");
				$slider.slider("values", 0, __priceRangeMin);
				$slider.slider("values", 1, __priceRangeMax);
				$( "#price-amount" ).html(formatCurrency(__priceRangeMin) +
				  " - " + formatCurrency(__priceRangeMax) );
				$( "#price-amount-min" ).val(__priceRangeMin);
				$( "#price-amount-max" ).val(__priceRangeMax);	
				return true;
			}	
		}
		return false;
	}
	function resetDiscountSearch()
	{
		if($("input[name='searchDiscountRange']:checked").length>0)
		{
			$("input[name='searchDiscountRange']").prop("checked",false);	
			return true;
		}
		return false;
	}
	function resetAttributeSearch()
	{
		if($(".searchAttrOptID:checked").length>0)
		{	
			$(".searchAttrOptID").porp("checked",false);
			$(".searchAttrOptID").removeAttr("disabled");
			return true;
		}
		return false;
	}	
	function autoHeight() 
		{
		var maxHeight = 0;
   		$(".cateListing li").each(function(){
   			if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
    	});
  		$(".cateListing li").height(maxHeight);
	}	