$(document).ready(function() {
	// alert("browse.js loaded");
	
	var refineActive;	
	var CAT = "cat";
	var SIZE= "size";
	var COLOR = "color";
	var BRAND= "brand";
	var CAT_BRAND= "catBrand";

       $('.firstLevelRefineCat').each(function(i,e){
          var items = $(e).parent().find('input.secondLevelInputRefineCat[type=checkbox]');
          if (items.length) {
            setTimeout(function(){
               items.prettyCheckboxes();
            },300 * i);
         }
       });
 
       $.each([function(){
         $('input.firstLevelInputRefineCat[type=checkbox]').prettyCheckboxes();
       },
       function(){
         $('input.catBrandFacetCheckBox[type=radio]').prettyCheckboxes();
       },
       function(){
         $('input.secondLevelInputPrettyCheckbox[type=checkbox]').prettyCheckboxes();
       },
       function(){ 
           $('input.thirdLevelInputPrettyCheckbox[type=checkbox]').prettyCheckboxes();
       },
       function(){
         $('input.colorFacetCheckbox[type=checkbox]').prettyCheckboxes({display: 'inline'});
       },
        function(){
         $('input.sizeFacetCheckbox[type=checkbox]').prettyCheckboxes({display: 'inline'});
       },
       function(){
         $('input.brandFacetCheckbox[type=checkbox]').prettyCheckboxes();
       }], function(i,e){
          setTimeout(function(){
            e.call();
          },i*150);
       });       
      
       //$('.chbrand .refineOneCol input[type=checkbox]') //.prettyCheckboxes()
       //$('.refineCategory .refineOneCol input[type=checkbox]') //.prettyCheckboxes();
       
       //$('.sideCont .refineSize input[type=checkbox]').prettyCheckboxes({display: 'inline'});
       //$('.sideCont .refineOneCol input[type=radio]').prettyCheckboxes();
	
	 if ($.urlParam("addFacet") != 0) {
   	    var arr = $.urlParam("addFacet").split(/[:|]+/)
	    $.each(arr, function () {
      		$('input[value="' + this + '"]').attr("checked", true);
	      $("label[for=" + $('input[value="' + this + '"]').attr("id") + "]").addClass("checked");
	    })
	    $('.checked').each(function (i, e) {
	      var ul = $(e).parents('ul:eq(0)')
	      ul.siblings('label').addClass('checked')
	      ul.show();
	      $(e).siblings('.ul-thirdlevel').show();
	    })
	    $('.ul-thirdlevel').each(function (i, e) {
	      var ul = $(e);
	      if (ul.find('.checked').length == 0 && !ul.siblings('label').hasClass('checked')) {
	        ul.hide()
	      }
	    })
	 }

	/*
	 * clearFunctionBrandPage
	 */
	$.clearFunctionBrandPage = function() {
		$("label.secondLevelPrettyCheckbox ").removeClass("checked");
		$("input.secondLevelInputPrettyCheckbox ").attr('checked', false);
		$("label.sizePrettyCheckbox").removeClass("checked");
		$("input.sizeFacetCheckbox").attr('checked', false);
		$("label.colorPrettyCheckbox").removeClass("checked");
		$("input.colorFacetCheckbox").attr('checked', false); 
	}
	
	$(".catBrandPrettyCheckbox" ).each( function(){
		
		if ($(this).hasClass("checked")){ 

			refineActive = CAT_BRAND;

			$.clearFunctionBrandPage();
			
			$("div.secondLevel").hide();
			
			var _for = $(this).attr("for") ;
			var _cat = $("input[id=" + _for + "]").val();

			$(".refineProductClass").show();
			$("div#" + _cat).show();
		}
	});


	$.loadBrowseSection = function () {
		// refresh the pageAvailable after getting the results
		var location = window.location.hash;
		
		$.loadShoppingPageBrowsed();
	}
	
	/**
	 * Used to changed the last Shopping page Browsed in the profile.
	 */
	$.loadShoppingPageBrowsed = function(){
		$.ajax({ url: "/browse/contents/submitShoppingPageBrowsed.jsp", data: ({shoppingPageBrowsed: document.URL.split('#')[0] + parent.location.hash})});
	}
	
	/**
	 * This method is used to set the default sort property and order.
	 */
	$.setDefaultSortBy = function (defaultSort, defaultSortProp, defaultSortOrder){
		$(".sortBy option[sort='"+defaultSort+"'][sortProp='"+defaultSortProp+"'][sortOrder='"+defaultSortOrder+"']").attr("selected", "selected");
	}
	

	$.getFilter = function(checkboxName, facetId) {
		var temp = "";
		
		$("input[class*='" + checkboxName + "']:checked").each(function(count) {
  
			if (count > 0) {
				temp += "|" + $(this).val();
			}
			else {
				temp = ":" + $(this).val();
			}
		});
		if(temp==""){
			return undefined;
		}
		return facetId + "" + temp;
	}
 
	
	$.getPriceFilter = function(facetId) {
		var temp = undefined;
		
		temp = $("#refinementPrice").val();
		
		if (temp == undefined) {
			return temp;
		}
		
		return facetId + ":" + $("#refinementPrice").val();
	}
	
	$.productCatalogSelected = function (){
	  var selection = "false";
	   $(".secondLevel > ul li .secondLevelPrettyCheckbox" ).each( function(){		    	
		   if ($(this).hasClass("checked")){ 
			   selection =  "true";
		   }
	   });
	   $(".secondLevel > ul li .thirdLevelPrettyCheckbox" ).each( function(){		    	
		   if ($(this).hasClass("checked")){ 
			   selection =  "true";
		   }
	   });
	   return selection;
	}
	
	$.isCategoryLandingPage = function (){
		var selectedCategory = $("#breadCrumb .current").text() ;
		var categoryId = $("#browseContent").attr("categoryId");
		var inSearchPage = $("#browseContent").attr("inSearchPage");
		var coreMetricsSearch = $("#browseContent").attr("coreMetricsSearch");
		var firsttrail = $("span#trail").attr("firsttrail");
		
		var sizeFilter 				= $.getFilter("sizeFacetCheckbox", $("span#sizeAddFacet").text());
		var brandFilter				= $.getFilter("brandFacetCheckbox",$("span#brandAddFacet").text());
		var colorFilter				= $.getFilter("colorFacetCheckbox",$("span#colorAddFacet").text());
		var priceFilter				= $.getPriceFilter($("span#priceAddFacet").text());
		
		if($("input#brandPage").val() == "true"){
			
			var categoryFilter			= $.getFilter("catBrandFacetCheckBox",  $("span#catAddFacet").text() );
			var categoryProductFilter 	= $.getFilter("catFacetCheckBox",  $("span#catAddFacet").text());
		    var secondThirdLevelSelection	= $.productCatalogSelected();
		    
		    if (secondThirdLevelSelection == "true"){
			  categoryFilter = categoryProductFilter 
		    }
		    
		} else {
			var categoryFilter			= $.getFilter("catFacetCheckBox",  $("span#catAddFacet").text() );
		}
		
		var goToPage	= ($("#pagesType").text() == ""?1:$("#pagesType").val());
		var pageSize	= $(".pageSize:first").val();
		var sort		= $(".sortBy:first option:selected").attr("sort");
		var sortProp 	= $(".sortBy:first option:selected").attr("sortProp");
		var sortOrder 	= $(".sortBy:first option:selected").attr("sortOrder");
		//addFacet = $("#browseContent").attr("addfacet");
		//firsttrail = $("span#trail").attr("firsttrail");
				
		if(sizeFilter != undefined || colorFilter != undefined || categoryFilter!= undefined || brandFilter != undefined || goToPage != 1 || pageSize != 36 || sort != 'numprop' || sortProp !='sortPriority' || sortOrder != 'descending'){
			return false;
		}
		
		return true;
	}
	 
	$.buildFacetParameter = function (selectedFacet){
	
		var map = {};
		// Load search params
		
		var selectedCategory = $("#breadCrumb .current").text() ;
		var categoryId = $("#browseContent").attr("categoryId");
		var inSearchPage = $("#browseContent").attr("inSearchPage");
		var coreMetricsSearch = $("#browseContent").attr("coreMetricsSearch");
		var firsttrail = $("span#trail").attr("firsttrail");
		
		var sizeFilter 				= $.getFilter("sizeFacetCheckbox", $("span#sizeAddFacet").text());
		var brandFilter				= $.getFilter("brandFacetCheckbox",$("span#brandAddFacet").text());
		var colorFilter				= $.getFilter("colorFacetCheckbox",$("span#colorAddFacet").text());
		var priceFilter				= $.getPriceFilter($("span#priceAddFacet").text());
		
		if($("input#brandPage").val() == "true"){
			
			var categoryFilter			= $.getFilter("catBrandFacetCheckBox",  $("span#catAddFacet").text() );
			var categoryProductFilter 	= $.getFilter("catFacetCheckBox",  $("span#catAddFacet").text());
		    var secondThirdLevelSelection	= $.productCatalogSelected();
		    
		    if (secondThirdLevelSelection == "true"){
			  categoryFilter = categoryProductFilter 
		    }
		    
		} else {
			var categoryFilter			= $.getFilter("catFacetCheckBox",  $("span#catAddFacet").text() );
		}

	    var addFacet = firsttrail + (sizeFilter == undefined ? "" : ":" + sizeFilter) + (categoryFilter == undefined ? "" : ":" + categoryFilter) + (brandFilter == undefined?"":":" + brandFilter) + (colorFilter == undefined ? "" : ":" + colorFilter) + (priceFilter == undefined ? "" : ":" + priceFilter);
		$("span#trail").text(addFacet);

		var goToPage	= $("#selectpagesType").text();
		var pageSize	= $(".pageSize:first").val();
		var sort		= $(".sortBy:first option:selected").attr("sort");
		var sortProp 	= $(".sortBy:first option:selected").attr("sortProp");

		if(typeof selectedFacet != 'undefined' && selectedFacet.toLowerCase() == 'NEW ARRIVALS'.toLowerCase()){
			//the customer selects the category from the side bar
			sortProp = "startDate";
		}else if(typeof selectedCategory != 'undefined' && selectedCategory.toLowerCase() == 'NEW ARRIVALS'.toLowerCase()){
			//the customer selects the category from the top menu
			sortProp = "startDate";
		}

		var sortOrder 	= $(".sortBy:first option:selected").attr("sortOrder");
		var secondSortOrder = $(".sortBy:first option:selected").attr("secondSort");
		
		//addFacet = escape(addFacet); //let's try to fix the bug when filtering by a brand with an apostrophe
		addFacet = addFacet.replace(/%3A/g, ':'); // we don't want ':' to be escaped
		addFacet = addFacet.replace(/%20/g, ' ');
		addFacet = addFacet.replace(/'/g, "\'");

		map['categoryId']=categoryId;
		map['inSearchPage']=inSearchPage;
		map['coreMetricsSearch']=coreMetricsSearch;
		map['addFacet']=addFacet;
		map['goToPage']=goToPage;
		map['pageSize']=pageSize;
		map['sort']=sort;
		map['sortProp']=sortProp;
		map['sortOrder']=sortOrder;
		map['secondSortOrder']=secondSortOrder;
		map['nsraction']='handleDisplayProducts';
		map['test']='12';
		
		//console.log(map['addFacet']);

		return $.convertMapToQuery(map);
	}
	
	$.loadHistory = function(hash){		
		$.history.load((hash));
	}
		
	/**
	 * loadBrowseBrandSection
	 * 	param filterRefinements - used to determine if the system must filter the refinements
	 * 	
	 */
	 $.loadBrowseProductSection = function (facetparameters, refreshPriceSlider){
			$("#browseContent").empty();
			// Load Images..
			$("#browseContent").prepend("<div id='brand-wait-images'/>");
			
			$.ajax({
				  url: '/browse/contents/common/browseProductAsXML.jsp',
				  type: 'GET',
				  dataType: 'xml',
				  cache: false,
				  data : facetparameters, 
				  success: function(data) {
					$("#browseContent").html($(data).find('response').eq(0).text());					
					$("#productNbr").text($("#ResultsCount").val());
					
					if (refreshPriceSlider == "true")
						$.loadPriceSliderSection();
					
					//rerendering the sort option page and the side bar page with the current hash
					ajaxNavigationStateReload(window.location.hash, refineActive);				
					$.loadShoppingPageBrowsed();
				  }
			});		
		}
	 
	 $.loadPriceSliderSection = function () {		 
		 var min = $("#searchPriceFacetValues > span:first").text();
		 var max = $("#searchPriceFacetValues > span:last").text();
				 
		 min = min.split("-");
		 max = max.split("-");
				 
		 min = parseFloat(min[0]);
		 max = parseFloat(max[1]);

		 $("#minAmount").text(min);
		 $("#maxAmount").text(max);

		 $("#refinementPriceMin").val(min);
		 $("#refinementPriceMax").val(max);
		 
		 $("#slider-range").data("min.slider", min);
		 $("#slider-range").data("max.slider", max);
		 
		 $("a[name='slider_handle_end']").attr("style","left: 100%;");
		 $("a[name='slider_handle_start']").attr("style","left: 0%;");
		 
		 $("#priceGap").text("$"+min + " - " + "$"+max);
		 $("#productNbr").text($("#ResultsCount").val());
	 }
	 
	 /**
	  * displayNavigation function
	  */
	 displayNavigation = function() {
		var goToPage		= $("#selectpagesType").text();
		var lastPageNumber	= parseInt($(".totalPages:first").text());
		
		/**
		  * Show and hide paging buttons
		  */
		 if(goToPage < lastPageNumber){
			 if(goToPage > 1){
				 $("div.previous").removeClass("hidden");
				 $("div.next").removeClass("hidden");
			 }
			 else{
				 $("div.previous").addClass("hidden");
				 $("div.next").removeClass("hidden");
			 }
		 } 
		 else if(goToPage == lastPageNumber){
			 if(lastPageNumber == 1){
				 $("div.previous").addClass("hidden");
				 $("div.next").addClass("hidden");
			 }
			 else{
				 $("div.next").addClass("hidden");
				 $("div.previous").removeClass("hidden");
			 }
		 }
		 
		 if ($("label.checked").length > 0) {
			 $("div.clearFilters").show()
		 } else {
			 $("div.clearFilters").hide()
		 }
	}
	 
	/**
	 * Event on click on a product
	 */
	 $("div.inner").click(function(){
		 var productUrl = $(this).find("a.productUrl").attr("href");
		 window.location = productUrl;
	 });
		 
		 
	 /**
	  * Event on click on previous page button
	  */
	 $("div.previous").live('click', function(e){
		 e.preventDefault();
		 var goToPage = parseInt($("#selectpagesType").text());
		 if(goToPage > 1){
			 $("#selectpagesType").text(goToPage-1);
			 var hash = $.buildFacetParameter();
			 $.loadHistory(hash);
			 window.scrollTo(0,0);
			 return false;
		 }
	 });
		 
	 /**
	  * Event on click on next page button
	  */
	 $("div.next").click(function(e){
		 e.preventDefault();
		 var goToPage = parseInt($("#selectpagesType").text()) + 1;
		 var lastPageNumber = parseInt($(".totalPages:first").text());
		 if(goToPage <= lastPageNumber){
			 changeSelectedPage(goToPage);
			 var hash = $.buildFacetParameter();
			 $.loadHistory(hash);
			 window.scrollTo(0,0);
			 return false;
		 }

	 });
		 
	    /**
	     * Event on change on the page number drop-down
	     */   
	    $(".pageNum").change(function (e) {  
	    	var val = $(e.target).val();    	
		    changeSelectedPage(val);
		    var hash = $.buildFacetParameter();
			 $.loadHistory(hash);
			 window.scrollTo(0,0);
			 return; 
	    });

	    
	 /**
	  * Event on change on the pageSize drop-down
	  */
	 $(".pageSize").change(function(){
		 var value = $(this).val();
		 $("span#selectItemsPerPage").text(value);
		 $("span#selectfooterItemsPerPage").text(value);
		 
		 $(".pageSize").each(function(){
			 $(this).val(value);
		 });
		 changeSelectedPage("1");
		 //$.loadBrowseProductSection(false);
		 var hash = $.buildFacetParameter();
		 $.loadHistory(hash);
		 window.scrollTo(0,0);
		 $("span.clearPrice").trigger("click");
		 return; 
		
		 
	 });
		 
	 /**
	  * Event on change on the sort options drop-down
	  */
	 $(".sortBy").change(function(){
		 var value = $(this).val();
		 $("span#selectType").text(value);
		 $("span#selectfooterType").text(value);
		 
		 $(".sortBy").each(function(){
			 $(this).val(value);
		 });
		 changeSelectedPage("1");
		 $("span.clearPrice").trigger("click");
		 var hash = $.buildFacetParameter();
		 $.loadHistory(hash);
		 window.scrollTo(0,0);
		 return; 
		 
	 });
	 
	 
	 /** 
	  * Bind click event for clearFilters link
	  */
	 $("div.clearFilters, span.clearAll").click(function(e) {
		e.preventDefault();
		changeSelectedPage("1");
		$(".sideCont").find("label").removeClass("checked");
		$(".sideCont").find("input").attr('checked', false);
		//$("#refinementPrice").val("0-1000");
		// $(".refineProductClass").hide();
		// $("#refine2ndLevelFilterContainer").hide();
 
		$("span.clearPrice").trigger("click");
		
		$(".secondLevelPrettyCheckbox").attr("style","text-decoration:none;color:#666666");
		$(".thirdLevelPrettyCheckbox").attr("style","text-decoration:none;color:#666666");
		$(".secondLevelRefineCat").attr("style","text-decoration:none;color:#666666");
		$(".firstLevelRefineCat").attr("style","text-decoration:none;color:#666666");
		
		 var hash = $.buildFacetParameter();
		 $.loadHistory(hash);
		 window.scrollTo(0,0);
		 return false; 
		 
	 });
 

	 $("span.clear").click(function(e) {
		e.preventDefault();
		
		changeSelectedPage("1");
		$(this).parents(".filterContainer").find(".sideCont").find("label").removeClass("checked");
		$(this).parents(".filterContainer").find(".sideCont").find("input").attr('checked', false);
		$("span.clearPrice").trigger("click");
		
		var hash = $.buildFacetParameter();
		$.loadHistory(hash);
		window.scrollTo(0,0);
		return false;
	 });

	 $("span.clearPrice").click(function(e) {
		 e.preventDefault();
		 
		 changeSelectedPage("1");
		 //$("#refinementPrice").val("0-10000");
		 
		 var hash = $.buildFacetParameter();
		 $.loadHistory(hash);
		 window.scrollTo(0,0);
		 return false;
	 });
	 
	 $(".brandFacetCheckbox").click(function(){
		 
		 refineActive = BRAND;
		 changeSelectedPage("1");
		 if ($(this).children("a").length > 0) {
		 	$("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		 }
		 $("span.clearPrice").trigger("click");
		 var hash = $.buildFacetParameter();
		 return $.loadHistory(hash);
	 })

	$(".colorFacetCheckbox").click(function(){
		refineActive = COLOR;
	 			
		 changeSelectedPage("1");
		if ($(this).children("a").length > 0) {
			$("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		}
		$("span.clearPrice").trigger("click");
		var hash = $.buildFacetParameter();
		return $.loadHistory(hash);
	 })
	 
	$(".sizeFacetCheckbox").click(function(){
		refineActive = SIZE;
		 changeSelectedPage("1");
		if ($(this).children("a").length > 0) {
			$("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		}
		$("span.clearPrice").trigger("click");
		var hash = $.buildFacetParameter();
		return $.loadHistory(hash);
	 })
	 
	 
	// NAV CHANGES items #2,5,16,20 here
	 
	$(".catFacetCheckBox").click(function( ){
		refineActive = CAT;
		 changeSelectedPage("1");
		if ($(this).children("a").length > 0) {
			$("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		}
		var hash = $.buildFacetParameter();
		
		$("span.clearPrice").trigger("click");
		return $.loadHistory(hash);

	 })
	 
	$(".catBrandFacetCheckBox").click(function( ){
		refineActive=CAT_BRAND;
		 changeSelectedPage("1");
		if ($(this).children("a").length > 0) {
			$("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		}
		$("span.clearPrice").trigger("click");
		
		$(".secondLevelPrettyCheckbox").attr("style","text-decoration:none;color:#666666");
		$(".thirdLevelPrettyCheckbox").attr("style","text-decoration:none;color:#666666");
		$(".secondLevelRefineCat").attr("style","text-decoration:none;color:#666666");
		$(".firstLevelRefineCat").attr("style","text-decoration:none;color:#666666");
		
		var hash = $.buildFacetParameter();
		return $.loadHistory(hash);

	 })
	 
	 $(".secondLevelInputPrettyCheckbox").click(function ( ) {
		 if ($(this).parent('li').children('ul').children('li').length > 0)
		 {
			 if (!(($(this).is(':checked')) && $(this).parent('li').children('ul').is(":visible")))
			 {
				 $(this).parent('li').children('ul').toggle();
				 $(this).parent('li').toggleClass('selected');
				 
				 $(this).parent('li').children('ul').children('li').children('label').removeClass("checked");
				 $(this).parent('li').children('ul').children('li').children('input').attr('checked', false);
			 }
		 }
	 })
	 
	 $(".thirdLevelInputPrettyCheckbox").click(function( ) { 
		 $(this).parent('li').parent('ul').parent('li').children('label').removeClass("checked");
		 $(this).parent('li').parent('ul').parent('li').children('input').attr('checked', false);
	 })
	 
	 $(".firstLevelInputRefineCat").click(function ( ) {
		 if ($(this).parent('li').children('ul').children('li').length > 0)
		 {
			 if (!(($(this).is(':checked')) && $(this).parent('li').children('ul').is(":visible")))
			 {
				 $(this).parent('li').children('ul').toggle();
				 $(this).parent('li').toggleClass('selected');
				 
				 $(this).parent('li').children('ul').children('li').children('label').removeClass("checked");
				 $(this).parent('li').children('ul').children('li').children('input').attr('checked', false);
			 }
		 }
	 })
	 
	 $(".secondLevelInputRefineCat").click(function( ) { 
		 $(this).parent('li').parent('ul').parent('li').children('label').removeClass("checked");
		 $(this).parent('li').parent('ul').parent('li').children('input').attr('checked', false);
	 })
	 
	 // END NAV CHANGES item #5

	 $("#refinementPrice").change(function(){
		 changeSelectedPage("1");
		 if ($(this).children("a").length > 0) {
			 $("#browseContent").attr("coreMetricsSearch",$(this).children("a:first").attr("value"));
		 }
		 var hash = $.buildFacetParameter();
		 return $.loadHistory(hash, "false");
	 })
	 
	$(".catBrandPrettyCheckbox").click(function(){		
		$("div.secondLevel").hide();
		$.clearFunctionBrandPage()
		var _for = $(this).attr("for") ;
		var _cat = $("input[id=" + _for + "]").val();
 
		var hasClass = $("input.catBrandInputPrettyCheckbox[id=" + _for + "]").hasClass("disabledChecbox");
		
		$(".refineProductClass").show();
		$("#refine2ndLevelFilterContainer").show();
		$("div#" + _cat).show();
		
		$("#refine2ndLevelFilterContainer").find(".clear").trigger("click");
	});
	 
	
	function load(hash, loadPrice) {
		if (hash) {			
			var tmp = $.convertQueryToMap(hash);
			if (loadPrice == "false") {
				$.loadBrowseProductSection(tmp, "false");
			}
			else {
				$.loadBrowseProductSection(tmp, "true");
			}
		} 
		else {		
			if(!$.isCategoryLandingPage()){
				$("#browseContent").empty();
				// Load Images..
				$("#browseContent").prepend("<div id='brand-wait-images'/>");
				
				var defaulthash = $.buildFacetParameter();
				
				$.ajax({
					  url: '/browse/contents/common/browseProductAsXML.jsp',
					  type: 'GET',
					  dataType: 'xml',
					  cache: false,
					  data : defaulthash, 
					  success: function(data) {
						$("#browseContent").html($(data).find('response').eq(0).text());
						ajaxNavigationStateReload(defaulthash, refineActive);				
						$.loadShoppingPageBrowsed();
                                                //resetPrice();
					  }
				});		
			}
			 $.loadShoppingPageBrowsed();
		}
	}
		
	$.loadPriceSliderSection();
	$.history.init(load, {unescape: true});	
});


