/* Product Listing based on Page Scroll */
/* Class Page */
var addCartProduct;
function Page() {
    /* Private variables */
    var __PAGE = 1,
        uniqueID = new Array(),
        __PRODUCTEND = false,
        __HOLD = false,
        viewType = 'grid',
		defaultPriceRanges={
		   '__priceRangeMin':(typeof __priceRangeMin!='undefined')?__priceRangeMin:0,
		   '__priceRangeMax':(typeof __priceRangeMax!='undefined')?__priceRangeMax:0
		},
        sortBy = default_catalog_listing;
    this.ajaxResponses = new Array();
    /* Methods */
    /* Function to get the page number */
    this.getPageNumber = function() {
            return __PAGE;
        }
        /* Function to increment the page number */
    this.setPageNumber = function(newVal) {
            __PAGE = (newVal >= '0') ? newVal : (__PAGE + 1);
        }
        /* Function to push the unique iD which is generated during the GetJSON function */
    this.setUniqueIDs = function(unique) {
            uniqueID.push(unique);
        }
        /* Function to retriev ethe unfique IDs */
    this.getUniqueIDs = function(unique) {
            return uniqueID;
        }
        /* Function to check the product list end or not */
    this.getProductsEndStatus = function() {
            return __PRODUCTEND;
        }
        /* Function to set the product end status is End and no product is vailable for Listing */
    this.setProductsEndStatus = function() {
        __PRODUCTEND = true;
    }
    this.resetProductsEndStatus = function() {
        __PRODUCTEND = false;
    }
    this.checkAjaxHold = function() {
        return __HOLD;
    }
    this.ajaxHold = function(bool) {
            __HOLD = bool;
        }
	/* Function to get the catalog product listing view mode */
    this.getViewType = function() {
            return viewType;
        }
        /* Function to switch view mode */
    this.setViewType = function(newViewType) {
            viewType = newViewType;
        }
        /* To get the catalog product listing sort by */
    this.getSortBy = function() {
            return sortBy;
        }
        /* To set sort by */
    this.setSortBy = function(newSortBy) {
        sortBy = newSortBy;
    }
	this.getPriceRanges = function() {
       return defaultPriceRanges;
    }
	/* To set number it items per page */
	this.setItems = function(newItems) {
        product_list_count = newItems;
    }
	/* To get the catalog product listing count */
	this.getItems = function() {
            return product_list_count;
        }	
    this.lazyLoad = function(uniqueID) {
        $("[uniqueid='" + uniqueID + "'] .lazy").lazyload({
            effect: "fadeIn",
			event : "sporty",
            threshold: -20
        });
		$("[uniqueid='" + uniqueID + "'] .lazy").trigger("sporty")
    }
}		
function Buy() {

    this.addtocart = function(obj, product_id,combo_id,source,product_sku,product_title,offerPrice) {
		if(_.where(cart['items'],{combo_id: combo_id}).length >0){
			jNotifyMe(lblAlreadyComboInCart,$('#modal-body-iframe').contents().find('#common_message'), "message_error"); 
			return;
		}
        var postData = new Array();
        var validate = true;
		var currentObject = this;
		
		if($.isArray(product_id)){
			var product_ids = product_id;
		}else{
			var product_ids = [product_id];
		}
		_.each(product_ids, function(product_id,key){
			var data = new Object();
			 var selected_options = [];
			data.product_id = product_id;
			
			if(typeof combo_id!='undefined' && combo_id>0){
				data.combo_id = combo_id;
				var objCustomOptions = $('#modal-body-iframe').contents().find('.custom_option_product_' + product_id);
			}else{
				data.combo_id = 0;
				var objCustomOptions = $('.custom_option_product_' + product_id);
			}
			
			
			objCustomOptions.each(function() {
				var title = $(this).attr('title');
				var optionObj = $(this).find('.custom_option_variants_element.active');
				if (optionObj.length > 0) {
					selected_options.push(optionObj.data());
				} else {
					jAlert((typeof lblSelectAvailableSize!='undefined')?lblSelectAvailableSize:'Please select an available size');
					validate = false;
				}
			});
			data.selected_options = selected_options;
			postData.push(data);
			
			if(obj.attr('soldout') != 'false'){
				validate = false;
			}
		});
		
        if (validate) {
				//START GOOGLE TAG
				if(typeof settingsEnableGoogleTag!='undefined' && settingsEnableGoogleTag == 'Yes'){
					dataLayer.push({
					  'event': 'addToCart',
					  'ecommerce': {
						'add': {                                
						  'products': [{                       
							'name': product_title,
							'id': product_sku,
							'price': offerPrice,
							'quantity': 1
						   }]
						}
					  }
					});
			   }
			   
				//END GOOGLE TAG
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/cart/ajaxAddtoCart/",
                data: {"data": postData},
                success: function(data) { 
					if($.isArray(product_id)){
						parent.window.hideModalPopup();
					} 
					if(typeof source!='undefined' && source == 'cart'){
						currentObject.updateCart();
					}else{
						updateCartData(data, "common_message",product_id,obj)
					}
					
					
					
                }
            });
        }
    }
	this.updateCart=function(){
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH + "/cart/ajaxUpdateCart/",
			data: { mode: 'update_cart'},
			success: function (data) 
			{
				try 
				{
					var x = jQuery.parseJSON(data);
				}	
				catch (e) 
				{
					window.location = location.href;
					return false;
				}
				if(x.isError=='Yes')
				{
					
					jNotifyShowWithClose(x.error,"common_message", "message_error"); 
				}
				else
				{
					$('#cart_ajax_section').html('');
					$('#cart_ajax_section').append(x.cartHtml);
					setPromoBlock(x);
					assignJsonDataToCartJS(x.cartData);
					updateCartNotification();
					jNotifyShowWithClose(x.error,"common_message", "message_success"); 
					if(typeof x.warnings!='undefined' && x.warnings!='')
					{
						jNotifyShowWithClose(x.warnings,"common_message", "message_error"); 
					}
				}
			}
		});
	}
	
	this.recalculateComboPrice=function(combo_id){
		var totalAmount 		= 0;
		var comboOfferAmount 	= 0;
		if(typeof catalogList!='undefined' && catalogList =='comboListing'){
			$('#modal-body-iframe').contents().find(".combo-price").each(function(){
				var offerprice 	= parseFloat($(this).attr('offerprice'));
				var updatedprice 	= parseFloat($(this).attr('updatedprice'));
				var discount 		= parseFloat($(this).attr('combooffer'));
				totalAmount+=offerprice;
				comboOfferAmount+= updatedprice*(100-discount)/100;
			});
		}
		
		$('#modal-body-iframe').contents().find("#totalAmount").html($.getFormattedCurrency(totalAmount, 'Full'));
		$('#modal-body-iframe').contents().find("#comboOfferAmount").html($.getFormattedCurrency(comboOfferAmount, 'Full'));
		var comboAvailable = true;
		$('#modal-body-iframe').contents().find(".productAvailable").each(function(){
			if($(this).val() == 'No'){
				comboAvailable=false
			}
		});
		if($('#modal-body-iframe').contents().find(".productAvailable").length == $('#modal-body-iframe').contents().find(".productAvailable.checked").length){
			if(comboAvailable){
				$('#modal-body-iframe').contents().find("#addToCart_combo_" + combo_id).removeClass('btn-default').addClass('btn-primary').attr('soldout', 'false').html('ADD TO CART');
			}else{
				$('#modal-body-iframe').contents().find("#addToCart_combo_" + combo_id).removeClass('btn-primary').addClass('btn-default').attr('soldout', 'true').html('SOLD OUT');
			}
		}
		
	}
    this.customoptionvariantselect = function(product_id, obj,combo_id,productAvailable) {
        obj.addClass('active').siblings().removeClass('active');
        var validate = true;
		var currentObject= this;
        var data = new Object();
        var selected_options = [];
        
		if(typeof combo_id!='undefined' && combo_id>0){
			var objCustomOptions = $('#modal-body-iframe').contents().find('.custom_option_product_' + product_id);
		}else{
			var objCustomOptions = $('.custom_option_product_' + product_id);
		}
		
		objCustomOptions.each(function() {
            var optionObj = $(this).find('.custom_option_variants_element.active');
            if (!optionObj.length > 0) {
                validate = false;
            } else {
                selected_options.push(optionObj.data());
            }
        });
		
		
		if(typeof isDeals !='undefined' && isDeals =='1'){
			return;
		}
        if (validate) {
            data.product_id = product_id;
            data.selected_options = selected_options;
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + "/catalog/ajaxGetCombinationPrice/",
                data: data,
                dataType: 'json',
                beforeSend: function() {},
                success: function(data) {
					if(typeof combo_id!='undefined' && combo_id>0){
						if (data['combinationPrice'] >= 0) {
							var defaultprice = parseFloat($('#modal-body-iframe').contents().find('.price_' + product_id).attr('defaultprice'));
							var combinationPrice = parseFloat(data['combinationPrice']);
							var updatedPrice = defaultprice + combinationPrice
							$('#modal-body-iframe').contents().find('.price_' + product_id).html($.getFormattedCurrency(updatedPrice, 'Full'));
							$('#modal-body-iframe').contents().find('.price_' + product_id).attr('updatedprice',updatedPrice);
						} else {
							var updatedPrice = $('#modal-body-iframe').contents().find('.price_' + product_id).attr('defaultprice');
							$('#modal-body-iframe').contents().find('.price_' + product_id).html($.getFormattedCurrency(updatedPrice, 'Full'));
							$('#modal-body-iframe').contents().find('.price_' + product_id).attr('updatedprice',updatedPrice);
						}
					}else{
						if (data['combinationPrice'] >= 0) { 
							var defaultprice = parseFloat($('#price_' + product_id).attr('defaultprice'));
							var combinationPrice = parseFloat(data['combinationPrice']);
							var updatedPrice = defaultprice + combinationPrice
							$('#price_' + product_id).html($.getFormattedCurrency(updatedPrice, 'Full'));
							$('#price_' + product_id).attr('updatedprice',updatedPrice);
						} else {
							var updatedPrice = $('#price_' + product_id).attr('defaultprice');
							$('#price_' + product_id).html($.getFormattedCurrency(updatedPrice, 'Full'));
							$('#price_' + product_id).attr('updatedprice',updatedPrice);
						}
					}
					if(typeof combo_id!='undefined' && combo_id>0){
						if (data['availableQuantity'] > 0) {
							$('#modal-body-iframe').contents().find("#productAvailable_"+product_id).addClass('checked').val('Yes');
						}else{
							$('#modal-body-iframe').contents().find("#productAvailable_"+product_id).addClass('checked').val('No');
						}
						
						currentObject.recalculateComboPrice(combo_id);
					}else{
						if (data['availableQuantity'] > 0) {
							$("#addToCart_" + product_id).attr('soldout', 'false').removeClass('btn-default').addClass('btn-primary').html('ADD TO CART');
						} else {
							$("#addToCart_" + product_id).attr('soldout', 'true').removeClass('btn-primary').addClass('btn-default').html('SOLD OUT');
						}
					}
					
                }
            });
        }
    }
}

/* Create an Object of Page Class */
var page = new Page();
var buy = new Buy();



$(document).ready(function() {
    autoHeight();
    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();
        }
    }
    var isocontainer = $("#prodListingUl");
	if(typeof Masonry == 'function'){
		var container = document.querySelector('#prodListingUl');
		var msnry = new Masonry( container, {
			  itemSelector: '.product-holder'
			});
	}
    
    $(document).on("click", ".sortby", function() {
        var thisObj = $(this);
        $(".FltrSort,.sort-select").text($(this).text());
		$(this).closest(".tabSelect").removeClass("active");
		$(this).closest(".mob_sort").toggleClass("sorToggle");
        $(this).closest('ul').removeClass('hidden-Mob');
        $('.FltrSort').removeClass('drop-up')
        $(".sortby").prev("span").removeClass("visible");
        thisObj.prev("span").addClass("visible");
        page.setSortBy(thisObj.attr('sortby'));
        page.setPageNumber(0);
        page.resetProductsEndStatus();
		initProductSearch();
    });
	$(document).on("click", ".items", function() {
        var thisObj = $(this);
		$(this).closest(".tabSelect").removeClass("active");
		$(this).closest(".mob_items").toggleClass("sorToggle");
        thisObj.prev("span").addClass("visible");
		$('.items').removeClass("active");
        thisObj.addClass("active");
        page.setItems(thisObj.attr('items'));
        page.setPageNumber(0);
        page.resetProductsEndStatus();
		initProductSearch();
	});
    $(document).on("click", ".clearAttributeSearch", function() {
        var thisRel = $(this).attr('rel');
        if ($(".searchAttrOptID[rel='" + thisRel + "']:checked").length > 0) {
            $(".searchAttrOptID[rel='" + thisRel + "']").attr("checked", false);
            $(".searchAttrOptID[rel='" + thisRel + "']").removeAttr("disabled");
            initProductSearch();
        }
    });
    $(document).on("click", ".searchAttrOptID", function() {
        initProductSearch();
    });
    createSlider();

    $(document).on("click", ".searchDiscountRange,.checkbox_categoryIDs,.checkbox_brandIDs,.checkbox_teamIDs,.checkbox_sportsIDs,.checkbox_competitionIDs,.checkbox_playerIDs", function() {
        initProductSearch();
    });
    $(document).on("click", ".clearPriceRange", function() {
        if (resetPriceRange()) {
            initProductSearch();
        }
    });
    $(document).on("click", ".clearDiscountRange", function() {
        if (resetDiscountSearch()) {
            initProductSearch();
        }
    });
    $(document).on("click", ".clearAllSearch", function() {
		if(searchKeyword!='')
		{
			var search	= '?keyword='+searchKeyword;
		}
		else
		{
			var search	='';
		}
		var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + search;
		window.location.href=newurl;
    });
    if ($(".listMenuScroll").length > 0) {
        $('.listMenuScroll').perfectScrollbar();
    }
    $(document).on('keyup',".attrSearchFilter",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() {
        clearBrandSearch();
        initProductSearch();
    }).on("click", "#clearTeams", function() {
        clearTeamSearch();
        initProductSearch();
    }).on("click", "#clearSports", function() {
        clearSportsSearch();
        initProductSearch();
    }).on("click", "#clearCategories", function() {
        clearCategorySearch();
        initProductSearch();
    }).on("click", "#clearCompetition", function() {
        clearCompetitionSearch();
        initProductSearch();
    })
    if (typeof __discountQueryString != 'undefined') {
        $("#searchDiscountRange_" + __discountQueryString).attr("checked", true);
    }
    $(document).on("click", ".filters-top-selected .deleteFilter", function() {
        var thisRel = $(this).attr('rel');
        var key = $(this).attr('key');
        switch (key) {
            case 'price':
                resetPriceRange();
                break;
            case 'discount':
                resetDiscountSearch();
                break;
			case 'brand':
               clearBrandSearch();
			    break;
			case 'team':
               clearTeamSearch();
			   	break;
			case 'sports':
               clearSportsSearch();
                break;
			case 'competition':
               clearCompetitionSearch(); 
                break;
			case 'player':
               clearPlayerSearch();
                break;
            default:
                $(".checkbox_" + key + "IDs[value='" + thisRel + "']").removeAttr('checked');
				
                $("#searchAttrOptID_" + thisRel).attr("checked", false);
        }
        if ($('#filters-top-selected_' + key).find('a').length == 1) {
            $('#filters-top-selected_' + key).remove();
        }
        $(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 + "']").attr("checked", false);
            initProductSearch();
        }
    });
    if (typeof __queryStringMode != 'undefined' && __queryStringMode > 0) {
        setNavOptions();
    }
  
	// for history url 
	var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
	$(window).bind('popstate', function (event) {
	  var initialPop = !popped && location.href == initialURL
	  popped = true
	  if (initialPop) return;

	});
  
});

function clearCategorySearch() {
	$(".category-heads").find('.hide').remove();
    $(".checkbox_categoryIDs").removeAttr('checked');
	categoryID ='';
    $(".li_categoryIDs").show();
    $("#filterCategories").val('').focus();
    return true;
}

function clearBrandSearch() {
    $(".checkbox_brandIDs").removeAttr('checked');
	brandID ='';
    $(".li_brandIDs").show();
    $("#filterBrands").val('').focus();
    return true;
}

function clearTeamSearch() {
    $(".checkbox_teamIDs").removeAttr('checked');
	teamID ='';
    $(".li_teamIDs").show();
    $("#filterTeams").val('').focus();
    return true;
}

function clearSportsSearch() {
    $(".checkbox_sportsIDs").removeAttr('checked');
	sportsID ='';
    $(".li_sportsIDs").show();
    $("#filterSports").val('').focus();
    return true;
}

function clearCompetitionSearch() {
    $(".checkbox_competitionIDs").removeAttr('checked');
	competitionID ='';
    $(".li_competitionIDs").show();
    $("#filterCompetitions").val('').focus();
    return true;
}

function clearPlayerSearch() {
    $(".checkbox_playerIDs").removeAttr('checked');
	playerID ='';
    $(".li_playerIDs").show();
    $("#filterPlayer").val('').focus();
    return true;
}

function lightbox_open() {
    //window.scrollTo(0,0);
    $("#CategoryPopup, #CategoryFade").fadeIn();
}

function lightbox_close() {
    $(".zoomContainer").hide();
    $("#CategoryPopup, #CategoryFade").fadeOut();
}

function setNavOptions(skipRefineBox) {
	skipRefineBox = typeof skipRefineBox=='undefined' || skipRefineBox==false?false:false
    var navDataObj = [];
    var attributeOptionIdString = '';
    var i = 1;
    var priceRangeMinForKey = '';
    var priceRangeMaxForKey = '';
    var priceRangeMin = '';
    var priceRangeMax = '';
    var discountRange = '';
    var attributeNavObj = {};
	
	if(typeof attrObjects!='undefined' && attrObjects.length){
		//var attrDataObj =  attrObjects .slice();
		var attrDataObj =  attrObjects .slice().join(':');
		attrDataObj =  attrDataObj
	}else{
		var attrDataObj = '';
	}
	var attributeNavObjHtml= "";
    if ($(".searchAttrOptID:checked").length > 0) {
        $(".searchAttrOptID:checked").each(function() {
            attributeOptionIdString = attributeOptionIdString + $(this).val() + '_';
            //attrDataObj.push($(this).val());
			attrDataObj = $('.searchAttrOptID:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
			// if(attrDataObj!=''){
				// if(attrDataObj.indexOf($(this).val())<0)
				// {
				// attrDataObj	=	attrDataObj+':'.concat(attrDataObjs);
				// }
			// }
			// else 
			// {
				// attrDataObj	=	attrDataObjs;
			// }
            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());
	priceMin = $.trim($("#price-min").val());
    priceMax = $.trim($("#price-max").val());
    discountRange = $.trim($("input[name='searchDiscountRange']:checked").val());
    if ($("#price-range").length > 0 && ((typeof priceRangeMin!='undefined' && priceRangeMin > 0) || (typeof priceRangeMax!='undefined' && priceRangeMax > 0))) {
        attributeNavObj['price'] = {};
        attributeNavObj['price'].values = [];
        attributeNavObj['price'].label = $("#price-amount-min").attr("refinehead");
        attributeNavObj['price'].values.push({
           // text: $("#price-amount").text(),
            text: (formatCurrency($.trim($("#price-amount-min").val())) +
                " - " + formatCurrency($.trim($("#price-amount-max").val()))),
            id: 'price'
        });
    }


    if (brandID !='') {
        var brandIDs = brandID;
    } else {
        var brandIDs = '';
    }

    var brandText = [];
    if ($(".checkbox_brandIDs:checked").length > 0) {
		 var brandIDs = '';
        if (typeof attributeNavObj['brand'] == 'undefined') {
            attributeNavObj['brand'] = {};
            attributeNavObj['brand'].values = [];
        }
        attributeNavObj['brand'].values = [];
        attributeNavObj['brand'].label = lblBrands;
        $(".checkbox_brandIDs:checked").each(function() {
			brandIDs = $('.checkbox_brandIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['brand'].values.push({
                text: $(this).attr('text'),
                id: this.value
            });
        });
    }


    if (teamID !='') {
        var teamIDs = teamID;
    } else {
        var teamIDs = '';
    }

    var teamText = [];
    if ($(".checkbox_teamIDs:checked").length > 0) {
		var teamIDs = '';
        if (typeof attributeNavObj['team'] == 'undefined') {
            attributeNavObj['team'] = {};
            attributeNavObj['team'].values = [];
        }
        attributeNavObj['team'].values = [];
        attributeNavObj['team'].label = lblTeams;
        $(".checkbox_teamIDs:checked").each(function() {
			teamIDs = $('.checkbox_teamIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['team'].values.push({
                text: $(this).attr('text'),
                id: this.value
            });
        });
    }



    if (sportsID !='') {
        var sportsIDs = sportsID;
    } else {
        var sportsIDs = '';
    }


    if ($(".checkbox_sportsIDs:checked").length > 0) {
		var sportsIDs = '';
        if (typeof attributeNavObj['sports'] == 'undefined') {
            attributeNavObj['sports'] = {};
            attributeNavObj['sports'].values = [];
        }
        attributeNavObj['sports'].values = [];
        attributeNavObj['sports'].label = lblSports;
        $(".checkbox_sportsIDs:checked").each(function() {
			sportsIDs = $('.checkbox_sportsIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['sports'].values.push({
                text: $(this).attr('text'),
                id: this.value
            });
        });
    }

    if (competitionID !='') {
        var competitionIDs = competitionID;
    } else {
        var competitionIDs = '';
    }


    if ($(".checkbox_competitionIDs:checked").length > 0) {
		var competitionIDs = '';
        if (typeof attributeNavObj['competition'] == 'undefined') {
            attributeNavObj['competition'] = {};
            attributeNavObj['competition'].values = [];
        }
        attributeNavObj['competition'].values = [];
        attributeNavObj['competition'].label = lblCompetitions;
        $(".checkbox_competitionIDs:checked").each(function() {
			competitionIDs = $('.checkbox_competitionIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['competition'].values.push({
                text: $(this).attr('text'),
                id: this.value
            });
        });
    }


    if (playerID !='') {
        var playerIDs = playerID;
    } else {
        var playerIDs = '';
    }

    if ($(".checkbox_playerIDs:checked").length > 0) {
		var playerIDs = '';
        if (typeof attributeNavObj['player'] == 'undefined') {
            attributeNavObj['player'] = {};
            attributeNavObj['player'].values = [];
        }
        attributeNavObj['player'].values = [];
        attributeNavObj['player'].label = lblPlayer;
        $(".checkbox_playerIDs:checked").each(function() {
			playerIDs = $('.checkbox_playerIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['player'].values.push({
                text: $(this).attr('text'),
                id: this.value
            });
        });
    }

    if (categoryID !='') {
        var categoryIDs = categoryID;
    } 
	
	if($(".category-heads").find('.hide').find('.checkbox_categoryIDs').length>0){
		var categoryIDs = '';
		var categoryObject = $(".category-heads").find('.hide').find('.checkbox_categoryIDs');
		categoryObject.each(function(){
			categoryIDs = $('.checkbox_categoryIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
		});
		
        
	}
	
	
	
    if ($(".checkbox_categoryIDs:checked").length > 0) {
		var categoryIDs = '';
        if (typeof attributeNavObj['category'] == 'undefined') {
            attributeNavObj['category'] = {};
            attributeNavObj['category'].values = [];
        }
        attributeNavObj['category'].values = [];
        attributeNavObj['category'].label = lblGearType;
        $(".checkbox_categoryIDs:checked").each(function() {
			categoryIDs = $('.checkbox_categoryIDs:checked').map(function()
			{
			return $(this).val();
			}).get().join(':');
            attributeNavObj['category'].values.push({
                text: $(this).attr('text'),
                id: 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'
        });
    }
	if(!_.isEmpty(attributeNavObj)){
		attributeNavObjHtml= "<span class='current-selected'>"+lblCurrenlySelected+"</span>";
	}
    $.each(attributeNavObj, function(attributeNavObjIndex, attributeNavObjValue) {
        attributeNavObjHtml = attributeNavObjHtml + '<div class="filters-top-selected" id="filters-top-selected_' + attributeNavObjIndex + '"><span class="filter-hd">';
        if (attributeNavObjValue.values.length < 1) {
            attributeNavObjHtml = attributeNavObjHtml + '<a class="deleteFilterHead" title="' + lblRemove + ' ' + attributeNavObjValue.label + '" href="Javascript:void(0);" rel=' + attributeNavObjIndex + ' key=' + attributeNavObjIndex + ' >';
        }
        attributeNavObjHtml = attributeNavObjHtml + attributeNavObjValue.label;
        if (attributeNavObjValue.values.length < 1) {
            attributeNavObjHtml = attributeNavObjHtml + '</a>';
        }
        attributeNavObjHtml = attributeNavObjHtml + ': </span>  ';
        $.each(attributeNavObjValue.values, function(index, valueObj) {
            attributeNavObjHtml = attributeNavObjHtml + '<a class="deleteFilter" title="' + lblRemove + '" href="Javascript:void(0);" rel=' + valueObj.id + '  key=' + attributeNavObjIndex + '>' + (valueObj.text).replace(/ *\([^)]*\) */g, "") + '</a>';
        });
        attributeNavObjHtml = attributeNavObjHtml + '</div>';
    });
	if(!skipRefineBox){
		if (attributeNavObjHtml != '') {
			$("#refined-box-content").html(attributeNavObjHtml).show();
			$(".filters-top-selected:last").css('border', '0');
		} else {
			$("#refined-box-content").html('').hide();
		}
	}
	
    navDataObj = {
        brandIDs: brandIDs,
        playerIDs: playerIDs,
        categoryIDs: categoryIDs,
        teamIDs: teamIDs,
        competitionIDs: competitionIDs,
        sportsIDs: sportsIDs,
        sortBy: page.getSortBy(),
        newarrival: typeof newarrival!='undefined'?newarrival:'' ,
		menuItemID: menuItemID,
        attribute_keys: typeof attribute_keys!='undefined'?attribute_keys.join(':'):'',
        product_list_count: page.getItems(),
        attrDataObj: attrDataObj,
        personalizable: personalizable,
        isDeals: isDeals,
		uniqueID: uniqueID,
		keyword: searchKeyword
    };
	
	if(priceRangeMin!=''){
		navDataObj['priceRangeMin']=priceRangeMin;
	}
	if(priceRangeMax!=''){
		navDataObj['priceRangeMax']=priceRangeMax;
	}
	if(discountRange!=''){
		navDataObj['discountRange']=discountRange;
	}
	if(priceMin!=''){
		navDataObj['priceMin']=priceMin;
	}
	if(priceMax!=''){
		navDataObj['priceMax']=priceMax;
	}	
		
    if (priceRangeMin)
        priceRangeMinForKey = priceRangeMin.replace(".", "_");
    if (priceRangeMax)
        priceRangeMaxForKey = priceRangeMax.replace(".", "_");
    var pageKey = attributeOptionIdString + page.getPageNumber() + page.getViewType() + page.getSortBy() + priceRangeMinForKey + priceRangeMaxForKey + discountRange + brandID + brandIDs;
    return [navDataObj, pageKey];
}

function initProductSearch() {
    page.setPageNumber(0);
    page.resetProductsEndStatus();
    var searchVar = setNavOptions();
    var key = searchVar[1];
    var paramData = searchVar[0];
    var uniqueID = paramData['uniqueID'];
	if(searchKeyword == ''){
		var url = GLOBAL_BASE_PATH + '/catalog/ajaxGetProducts/'
	}
	else{
		var url = GLOBAL_BASE_PATH + '/search/ajaxGetProducts/';
	}
	var queryStr = jQuery.param(searchVar[0]);
	queryStr = queryStr.match(/[^\&\=]+\=[^\&]+/g,'').join('&');
	if (history.pushState) {
	var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?'+queryStr;
	window.history.pushState({path:newurl},'',newurl);
	}
    $.ajax({
        url: url,
        type: "POST",
        cache: true, 
        data: searchVar[0],
        dataType: 'json',
        beforeSend: function() {
            page.ajaxHold(true);
            $(".pop_loader").removeClass('hide');
        },
        success: function(resHtml) {
            page.ajaxHold(false);
            $(".pop_loader").addClass('hide');
			page.setPageNumber(1);
			$(".productListing").empty().html(resHtml['productHtml']);
			$("#layeredNavigation").empty().html(resHtml['layeredNavigation']);
			if ($(".listMenuScroll").length > 0) {
				$('.listMenuScroll').perfectScrollbar();
			}
			$("#productsCount").empty().html(productsCountVar);
			page.lazyLoad(uniqueID);
        }
    });	
}

function resetPriceRange() {
    if ($("#price-range").length > 0) {
		var default_price= page.getPriceRanges();
       // if ($("#price-amount-min").val() != default_price.__priceRangeMin || $("#price-amount-max").val() != default_price.__priceRangeMax) {
            var $slider = $("#price-range");
            $slider.slider("values", 0, default_price.__priceRangeMin);
            $slider.slider("values", 1, default_price.__priceRangeMax);
            $("#price-amount").html(formatCurrency(default_price.__priceRangeMin) +
                " - " + formatCurrency(default_price.__priceRangeMax));
            $("#price-amount-min").val('');
            $("#price-amount-max").val('');
            return true;
        //}
    }
    return false;
}

function resetDiscountSearch() {
    if ($("input[name='searchDiscountRange']:checked").length > 0) {
        $("input[name='searchDiscountRange']").attr("checked", false);
        return true;
    }
    return false;
}

function resetAttributeSearch() {
    if ($(".searchAttrOptID:checked").length > 0) {
        $(".searchAttrOptID").attr("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);
}

function createSlider() {
        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)));
        }
    }
    //Fliter section 
$(document).ready(function(e) {
    //Filter
    $(document).on("click", '.FltrIco', function() {
        if ($(this).hasClass('drop-up')) {
            $(".prdctFilter").addClass("sorToggle");
            $(".prdctFilterMo").find(".drop-up").addClass("drop-up");
            $(this).removeClass("drop-up");
        } else {
            $(".prdctFilter").removeClass("sorToggle");
            $(".prdctFilterMo").find(".drop-up").removeClass("drop-up");
            $('.mob_sort').addClass("sorToggle");
            $(this).addClass("drop-up");
        }
    });
    //Sort By
    $(document).on("click", '.FltrSort', function() {
        if ($(this).hasClass('drop-up')) {
            $(".prdctFilterMo").find(".drop-up").addClass("drop-up");
            $('.mob_sort').addClass("sorToggle");
            $(this).removeClass("drop-up");
        } else {
            $(".prdctFilter").addClass("sorToggle");
            $(".prdctFilterMo").find(".drop-up").removeClass("drop-up");
            $('.mob_sort').removeClass("hidden-Mob sorToggle");
            $(this).addClass("drop-up");
        }

    });
    $(document).on("click", '.widget-tab-sel', function() {
        $(this).parent().toggleClass('open');
        //$(this).next('.hidden-Mob').slideToggle();
		$(this).next('ul').toggleClass("hidden-Mob");

    });

    $(document).on("click", '.FltrSctn .expand-clsps', function() {
        $(this).next(".list-wrap").toggleClass("sort_collapse");
        if ($(this).next(".list-wrap").hasClass("sort_collapse")) {
            $(this).parents(".FltrSctn").children(".expand-clsps").addClass('plus-ico');
        } else {
            $(this).parents(".FltrSctn").children(".expand-clsps").removeClass('plus-ico');
        }
    });
    $(document).on("click", '.sort-select', function() {
        $(this).parent().toggleClass('active');
    });
});