/* Default filters to be displayed on page -  */
var defaultFilters = {
    Set : function(key,value) {this[key] = value;},
    Get : function(key) {return this[key];}
}
/* to store the json response for various filters selected */
var saveJsonResponse = {
    Set : function(key,value) {this[key] = value;},
    Get : function(key) {return this[key];},
    Remove : function() {
    			for (var key in this) { 
    				if(key!="Set" && key !="Get" && key!="Remove") {
    					this[key]=null;
    				}
    			}
    }
}
/* Update corresponding entries, if new filters are to be added 
E.g., Update filter_mens_color, if new filter attribute is to be added to this filter
New value to be wrapped up within '|'
*/
/*Shoe Finder Phase 2:
Filter Color is disabled for Kids Category
*/
defaultFilters.Set("filter_mens_color","|beige / tan|black|blue|bronze|brown|clear|gold|gray|green|multi-color|off-white|orange|pink|purple|red|silver|white|yellow|");
defaultFilters.Set("filter_mens_size","|5|5.5|6|6.5|7|7.5|8|8.5|9|9.5|10|10.5|11|11.5|12|12.5|13|14|15|16|17|");
defaultFilters.Set("filter_mens_style","|athletic|boots|casual|dress|loafers|oxfords|sandals|skate|sneakers|work & safety|");
defaultFilters.Set("filter_womens_color","|beige / tan|black|blue|bronze|brown|clear|gold|gray|green|multi-color|off-white|orange|pink|purple|red|silver|white|yellow|");
defaultFilters.Set("filter_womens_size","|4|4.5|5|5.5|6|6.5|7|7.5|8|8.5|9|9.5|10|10.5|11|11.5|12|12.5|13|14|15|");
defaultFilters.Set("filter_womens_style","|athletic|ballet flats|boots|casual|dress|fashion sneakers|loafers|pumps|sandals|work & safety|");
/*defaultFilters.Set("filter_kids_color","|beige / tan|black|blue|bronze|brown|clear|gold|gray|green|multi-color|off-white|orange|pink|purple|red|silver|white|yellow|");*/
defaultFilters.Set("filter_kids_size","|00|0|1|1.5|2|2.5|3|3.5|4|4.5|5|5.5|6|6.5|7|7.5|8|8.5|9|9.5|10|10.5|11|11.5|12|12.5|13|13.5|");
defaultFilters.Set("filter_kids_style","|athletic|ballet flats|boots|casual|clogs|dress|fashion sneakers|flip-flops|loafers|mules & slides|oxfords|pre-walk|sandals|school & uniform|skate|slippers|");
defaultFilters.Set("filter_kids_agegender","|newborns & infants|boys|toddlers|girls|");
defaultFilters.Set("filter_work_safety_color","|beige / tan|black|blue|bronze|brown|clear|gold|gray|green|multi-color|off-white|orange|pink|purple|red|silver|white|yellow|");
defaultFilters.Set("filter_work_safety_size","|5|5.5|6|6.5|7|7.5|8|8.5|9|9.5|10|10.5|11|11.5|12|12.5|13|14|15|16|17|");
defaultFilters.Set("filter_work_safety_style","|electrical hazard|fire boots|heat resistant|metatarsal guard|puncture resistant|slip resistant (non-skid)|static dissapating|");

var productCount=0;
var verticalName;
var categoryName;
var subcategoryName;
var filters = [];
var filterParam="no filter";
var filterSubcatParam="no filter";
var lastFilterParam="no filter";
//Phase-2
var lastSubcatParam="no filter";
var lastSelectedFilter="";
var fromResultsPage=false;
var hldHtmlCurtain = "<div id=\"shoeCurtain\">";
hldHtmlCurtain +="</div>";<!--/shoeCurtain-->
hldHtmlCurtain += "<div id=\"shoeCurtainIE\"/>";
var ajaxSubcats = [];

$(document).ready(function() {
		var pageName = $('input#pageName').attr('value');
		verticalName = $('input#vName').attr('value');
		categoryName = $('input#cName').attr('value');
		var hldHtml = "<div id=\"shoeFinder\">";
		hldHtml += "<ul id=\"shoetab\">";
		
	    if(pageName=="vertical") {
	    	hldHtml +="<li class=\"show\">Shoes for everyone.</li>";
	   		enabledCategoryArray=finderEnabledCategories.split(";");
			for( i=0;i<enabledCategoryArray.length;i++){
				hldHtml +="<li class=\""+convertShoeFinderCategory(enabledCategoryArray[i])+"\" ><a class=\""+convertShoeFinderCategory(enabledCategoryArray[i])+"\" id=\""+enabledCategoryArray[i]+"\" href=\"javascript:;\">";
				if(enabledCategoryArray[i]=='Mens' || enabledCategoryArray[i]=='Womens') {
					hldHtml +=enabledCategoryArray[i].substring(0,enabledCategoryArray[i].length-1)+"</a></li>";
				} else {
					hldHtml +=enabledCategoryArray[i]+"</a></li>";
				}
			}
	    }
	    if(pageName=="category"){
		    hldHtml +="<li class=\"show\">";
		    if(categoryName=='Mens' || categoryName=='Womens') {
				hldHtml +=categoryName.substring(0,categoryName.length-1);
			} else {
				hldHtml +=categoryName;
			}
		    hldHtml +="</li>";
		}
	    hldHtml += "<li class=\"icon\">";
		hldHtml += "<a href=\"javascript:;\" class=\"stopTab\">Shoe Finder</a>";
		hldHtml += "</li>";
		hldHtml += "</ul>";
		hldHtml +="<div id=\"wrapper\">";
		hldHtml +="<div id=\"filterContainer\">";
		hldHtml +="<div id=\"filterContent\">";
		hldHtml +="<span class=\"clearFilter\" style=\"display:'none'\"><a href=\"javascript:;\">Clear All</a></span>";
		hldHtml +="<div id=\"callFilters\">";
		if(pageName=="vertical") {
			<!--/ajax call this div in-->
			hldHtml +="<div id=\"defaultIntro\" style=\"height:136px;\">";
			for( i=0;i<enabledCategoryArray.length;i++){
				hldHtml +="<div class=\""+convertShoeFinderCategory(enabledCategoryArray[i])+"\">";
				hldHtml +="<a id=\""+enabledCategoryArray[i]+"\" href=\"javascript:;\">"+enabledCategoryArray[i]+"</a></div>";
			}
			hldHtml +="</div>";
			<!--/end of ajax called div-->
		}
		hldHtml +="</div>";	   
	    hldHtml +="</div>";<!--/filterContent-->
		hldHtml +="</div>";<!--/filterContainer-->
		hldHtml +="<div id=\"filterCurve\">";
		hldHtml +="<a href=\"javascript:findClick();\"><img class=\"findShoeBtn\" src=\""+imagePath+"img/buttons/find_shoes_button.gif\" alt=\"Find my Shoes\"/></a>";
		hldHtml +="<p id=\"shoesfound\">";
		hldHtml +="<span id=\"shoetotal\">";
		hldHtml +="</span>&nbsp;items found</p>";
		hldHtml +="<span class=\"state collapse\"><a href=\"javascript:;\">Collapse</a></span>";
		hldHtml +="</div>";<!--/filterCurve-->
		hldHtml +="</div>";<!--wrapper-->
		hldHtml+= '<div id="noResultsCurtain" style="display:none">\n';
		hldHtml+= '<div id="noresults" style="display:none">\n';
		hldHtml+= '    <p><b>We were unable to find a product match based on the criteria you selected.</b></p>\n';
        hldHtml+= '    <p>Try selecting different criteria or select a different combination to find a product you like</p>\n';
        hldHtml+= '    <br clear="all">\n';
        hldHtml+= '    <input id="prevResults" type="image" src="'+imagePath+'img/buttons/btn_prev_results.gif" value="Show previous results" onClick="getPreviousResults();"><input id="filterClear" type="image" src="'+imagePath+'img/buttons/btn_clear_filter.gif" value="Clear options" onClick="clearFilters();">\n';
		hldHtml+= '</div>\n';
  		hldHtml +="</div>";<!--/shoeFinder-->
  		$('body').append(hldHtml);
  			var shoeLinks='<map name=\"Map\" id=\"Map\">';
		    shoeLinks+= '<area shape=\"rect\" coords=\"117,112,203,152\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&amp;sbv=Skechers\" alt=\"Skechers\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"46,112,108,153\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&amp;sbv=Adidas\" alt=\"Adidas\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"209,113,292,152\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&amp;sbv=New+Balance\" alt=\"New Balance\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"297,114,423,154\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&sbv=Converse\" alt=\"Converse\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"429,108,524,153\" href=\"http://www.sears.com/shc/s/c_10153_12605_Shoes_Womens?sbf=Brand&amp;sbv=Mia+Amore&amp;sLevel=1\" alt=\"Amore\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"529,113,627,155\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&amp;sbv=Dockers\" alt=\"Dockers\" />';
		    shoeLinks+= '<area shape=\"rect\" coords=\"635,114,746,158\" href=\"http://www.sears.com/shc/s/v_10153_12605_Shoes?sbf=Brand&amp;sbv=Wolverine\" alt=\"Wolverine\" />';
		  	shoeLinks+= '</map>';

		/*moving div#sheFinderbranding below A3 Ads*/
  		/*$('div#finderContainer').prepend('<div id=\"shoeFinderbranding\"><img src=\"'+imagePath+'img/backgrounds/shoefinder_background_layer.jpg\" border=\"0\" usemap=\"#Map\" />'+shoeLinks+'</div>');*/
		$('<div id=\"shoeFinderbranding\"><img src=\"'+imagePath+'img/backgrounds/shoefinder_background_layer.jpg\" border=\"0\" usemap=\"#Map\" />'+shoeLinks+'</div>').insertBefore("#carousel_home");
		/*this will place the top position for the shoeFinder based on the div#shoeFinderbranding placement*/
		var finderTop = $('div#shoeFinderbranding').offset();
		$('div#shoeFinder').css('top', finderTop.top);
		
		if ( $.browser.msie && ($.browser.version == 6) ) {
			$('ul#shoetab li.show').css("width","40.3%");
		}
        var tabContainers = $('div#shoeFinder div#wrapper');
		if ( $('div#defaultIntro').html() ) {
			$('ul#shoetab li:first').addClass('defaultTitle');
			$('img.findShoeBtn').hide();
			$('p#shoesfound').hide();
			$('span.collapse').css('paddingTop','20px');
		}
		$('span.clearFilter').hide();
		/*call - on click the tabs  the class is sent to function tabOrder... if the tab list has the class stopTab
		then the shoe finder should be closed.. thus disable the click function*/
		$('ul#shoetab li a').unbind('click').click(function(){
			if ($(this).hasClass('stopTab')) {
					return false;
			}
			filterParam="no filter";
			lastFilterParam="no filter";
			//phase-2
			lastSubcatParam="no filter";
			filterSubcatParam="no filter";
			lastSelectedFilter="";
			//saveJsonResponse.Remove();
			var foo = $(this).attr('class');
			categoryName = $.trim($(this).attr("id"));
			tabOrder(foo);
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();
			makeAjaxCall(verticalName,categoryName,"","","AjaxCall");
			$('span.clearFilter').hide();
		});
		
		/*call - on click the default scree buttons -  the class is sent to function tabOrder*/
		$('div#defaultIntro div').unbind('click').click(function(){
			var foo1 = $(this).attr('class');
			categoryName = $.trim($(this).find('a').attr("id"));
			tabOrder(foo1);
			/* On click of category/filter a curtain is shown with loading animation*/
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();
			makeAjaxCall(verticalName,categoryName,"","","AjaxCall");	
		});
	
		var categoryTitle = $('ul#shoetab li:hidden a').html();
		if ( categoryTitle == 'Women' ) {
			if( $.browser.msie) {
				if ($.browser.version == 6) {
					$('ul#shoetab li.show').css("width","50.4%");
					}
				if ($.browser.version == 7) {
					$('ul#shoetab li.show').css("width","50.8%");
				}
			}else{
				$('ul#shoetab li.show').css("width","50.7%");
			}
		}
		if ( categoryTitle == 'Men' || categoryTitle == 'Kids') {
			if( $.browser.msie && ($.browser.version == 6) ) {
				$('ul#shoetab li.show').css("width","48.3%");
			}else{
				$('ul#shoetab li.show').css("width","48.7%");
			}
		}
		if ( categoryTitle == 'Work & Safety') {
			if( $.browser.msie && ($.browser.version == 6) ) {
				$('ul#shoetab li.show').css("width","54.4%");
			}else{
				$('ul#shoetab li.show').css("width","54.7%");
			}
		}
		
		/*Clear all - removes .selected class from the filters*/
		$('span.clearFilter').click(function(){
			clearFilters();
		});
	
		/*open and close function for Shoe Finder Container*/
		finderOpen($('span.state, p#shoesfound, li.icon'));
		
		if(location.href.indexOf("#")>=0  && (location.href.indexOf("#") < location.href.length-1)){
			var	removedHash=location.hash.replace("#","");
			categoryName=undoCleanFilterParam(removedHash.split("$$")[0].replace("cName=",""));
			subcategoryName=undoCleanFilterParam(removedHash.split("$$")[1].split("&&")[0].replace("subcat_filters=ageGender",""));
			filterParam=cleanFilterParam(undoCleanFilterParam(removedHash.split("$$")[1].split("&&")[1]));
			filterSubcatParam=cleanFilterParam(subcategoryName);
			fromResultsPage=true;
			if(pageName=="vertical") {
				tabOrder(convertShoeFinderCategory(categoryName));
			}
			/* On click of category/filter a curtain is shown with loading animation*/
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();
		    makeAjaxCall(verticalName,categoryName,filterParam,filterSubcatParam,"AjaxCall");
		} else if(pageName=="category") {
			/* On click of category/filter a curtain is shown with loading animation*/
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();
		    makeAjaxCall(verticalName,categoryName,"","","AjaxCall");
		}
});



/*shoe finder can be open or closed from three areas... this keeps a flag so all three work properly*/
var openFinder;
var finderOpen = function(el) {
	$(el).unbind('click').click(
	function() {
		if (openFinder == 0) {
			$('ul#shoetab li a').removeClass('stopTab');
			$('div#filterContainer').slideDown('fast');		
			$('span.state').removeClass('expand').addClass('collapse');
			$('span.state').find('a').blur();
			$('span.collapse').css('paddingTop','0px');
			$('div#filterCurve').css('marginTop','0px');
			if ( $('ul#shoetab li:first').hasClass('defaultTitle') ) {
				$('a img.findShoeBtn').hide();
				$('p#shoesfound').hide();
				$('span.collapse').css('paddingTop','20px');
			}else{
				$('a img.findShoeBtn').show();
				$('p#shoesfound').show();
			}
			openFinder = 1;
		}else{
			$('ul#shoetab li a').addClass('stopTab');
			$('div#filterContainer').slideUp('fast');
			$('span.state').removeClass('collapse').addClass('expand');
			$('span.state').find('a').blur();
			$('span.expand').css('paddingTop','23px');
			$('div#filterCurve').css('marginTop','-22px');
			$('a img.findShoeBtn').hide();
			$('p#shoesfound').hide();
			openFinder = 0;
		}
	});
};

/*gets the class from the element sent and then reorders the tabs based on the class*/
var tabOrder = function(elClass) {
	$('ul#shoetab li:first').removeClass('defaultTitle');
	//$('span.clearFilter').show();
	$('a img.findShoeBtn').show();
	$('p#shoesfound').show();
	$('span.collapse').css('paddingTop','0px');
	
	var chosen = $('ul#shoetab li.' + elClass);
	var title = $(chosen).find('a').text();
	if ( title == 'Women') {
		if( $.browser.msie) {
			if ($.browser.version == 6) {
				$('ul#shoetab li.show').css("width","50.4%");
			}
			if ($.browser.version == 7) {
				$('ul#shoetab li.show').css("width","50.8%");
			}
		}else{
			$('ul#shoetab li.show').css("width","50.7%");
		}
	}
	if ( title == 'Men' || title == 'Kids') {
		if( $.browser.msie && ($.browser.version == 6) ) {
			$('ul#shoetab li.show').css("width","48.3%");
		}else{
			$('ul#shoetab li.show').css("width","48.7%");
		}
	}
	if ( title == 'Work & Safety') {
		if( $.browser.msie && ($.browser.version == 6) ) {
			$('ul#shoetab li.show').css("width","54.4%");
		}else{
			$('ul#shoetab li.show').css("width","54.7%");
		}
	}
	
	$(chosen).not('.show').hide();
	$('ul#shoetab li:eq(0)').html(title);
	$('ul#shoetab li:hidden').not(chosen).show();

	return false;
};

/*adding .selected for filter choices clicked on - .selected will provide the background*/
var pickMe = function(el) {
	if($(el).attr("class")!="notAvailable") {
		lastSelectedFilter=$(el).attr("id");
		$(el).toggleClass('selected');
		if($('div#callFilters').find('a.selected').length>0){
			$('span.clearFilter').show();
		} else {
			clearFilters();
			return;
		}
		/* On click of category/filter a curtain is shown with loading animation*/
		$('body').append(hldHtmlCurtain);
		shoeLoadingGif();
		preFilterShoeFinder();
	}
};

/*------Style display function -----*/
var reorder = function(el){
	$(el).unbind('click').click(function(){
			var chosen = $(this);
			var chosenContent = $(chosen).html();
			$(chosen).remove();
			$('ul#styleChoices li:eq(0)').before('<li style="display:none">' + chosenContent + '</li>');
			$('ul#styleChoices li:eq(0)').fadeIn('slow');
			stylesSelected($('ul#styleChoices li span a'));
			reorder($('ul#styleChoices li:gt(5)'));
			$('ul#styleChoices li:gt(5)').slideUp('fast');
			$('div#styleFilter p a').removeClass().addClass('sizeMore');
			moreStyles = 0;
			$('ul#styleChoices li span a').filter('.selected').each(function () { 
				var chosen = $(this).parents('li');
				var chosenContent = $(chosen).html();
				$(chosen).remove();
				$('ul#styleChoices li:eq(0)').before('<li style="display:none">' + chosenContent + '</li>');
				$('ul#styleChoices li:eq(0)').fadeIn('slow');
				stylesSelected($('ul#styleChoices li span a'));
				reorder($('ul#styleChoices li:gt(5)'));
				$('ul#styleChoices li:gt(5)').slideUp('fast');
				$('div#styleFilter p a').removeClass().addClass('sizeMore');
				moreStyles = 0;
			});
	});
};

/*Open and Close for style filter*/
var moreStyles = 0;
var viewStyles = function(el) {	
	$(el).unbind('click').click(
	function() {
		if (moreStyles == 0) {
			$('ul#styleChoices li:gt(5)').show();
			$('div#styleFilter p a').removeClass().addClass('sizeLess');
			$('div#styleFilter p a.sizeLess').css('paddingTop','5px');
			if ( $.browser.msie && ($.browser.version == 7) ) {
				$('div#styleFilter p a.sizeLess').css('paddingTop','4px');
			}
			moreStyles = 1;
		}else{
			$('ul#styleChoices li:gt(5)').hide();
			$('div#styleFilter p a').removeClass().addClass('sizeMore');
			if( $.browser.msie) {
				$('div#styleFilter p a.sizeMore').css('paddingTop','0px');
			}
			moreStyles = 0;
		}
		$(this).blur();
	});
};

var stylesSelected = function(el){
	$(el).unbind('click').click(function() {
		if($(this).attr("class")!="notAvailable") {
			lastSelectedFilter=$(this).attr("id");
			$(this).toggleClass('selected');
			if($('div#callFilters').find('a.selected').length>0){
				$('span.clearFilter').show();
			} else {
				clearFilters();
				return;
			}
			$('ul#styleChoices li:gt(5)').removeClass('hidden');
			/* On click of category/filter a curtain is shown with loading animation*/
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();
			preFilterShoeFinder();
		} else {
			return false;
		}
	});	
};



/*----- Size row display function:
Function takes the index of the Size li and get its modulos (this gives the li column position), 
based on the remainder that variable will be used by the switch to run one of the 6 cases 
that set a range of li items to show based on the list index chosen------*/
var sizeShown = function(el) {
	$(el).unbind('click').click( function() {
		$('ul#sizeChoices li').removeClass('hidden');
		var test = $(this).find('span a');
		$(test).blur();
		if ($(test).hasClass('selected') && !fromResultsPage) {
			pickMe ($(test));
			return false;
		}else{
			var placing = $(el).index(this);
			if ( placing <=5 ) {
				if(!fromResultsPage) {
					pickMe ($(test));
				}
				$('ul#sizeChoices li:gt(17)').hide();
				$('div#sizeFilter p a').show();
				$('div#sizeFilter p a').removeClass().addClass('sizeMore');
				moreNumbers = 0;
			}
			if ( placing >= 6 ) {
				if(!fromResultsPage) {
					pickMe ($(test));
				}
				var n = placing%6;
				switch (n) {
					case 0:
						var min = placing-6;
						var max = placing+11;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
					case 1:
					
						var min = placing-7;
						var max = placing+10;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
					case 2:
						var min = placing-8;
						var max = placing+9;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
					case 3:
						var min = placing-9;
						var max = placing+8;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
					case 4:
						var min = placing-10;
						var max = placing+7;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
					case 5:
						var min = placing-11;
						var max = placing+6;
						$('ul#sizeChoices li').hide();
						$('ul#sizeChoices li').filter( function(index) {
							return index >= min && index <= max;
						})
						.show();
						$('div#sizeFilter p a').show();
						$('div#sizeFilter p a').removeClass().addClass('sizeMore');
						moreNumbers = 0;
						break;
				}
			}
		}
	});
};

/*Open and Close for size filter*/
var moreNumbers = 0;
var viewSizes = function(el) {
	$(el).unbind('click').click(
	function() {
		$('ul#sizeChoices li').removeClass('hidden');
		if (moreNumbers == 0) {
			$('ul#sizeChoices li').show();
			$('div#sizeFilter p a').removeClass().addClass('sizeLess');
			$('div#sizeFilter p a.sizeLess').css('paddingTop','5px');
			if ( $.browser.msie && ($.browser.version == 7) ) {
				$('div#sizeFilter p a.sizeLess').css('paddingTop','4px');
			}
			moreNumbers = 1;
		}else{
			if($('ul#sizeChoices li:gt(17) a').hasClass('selected')) {
				if($('div#kidsAgeGenderFilter:has("ul#agegenderChoices")') && $('ul#sizeChoices li:gt(17) a').hasClass('selected')) {
					$('ul#sizeChoices li:lt(12)').hide();
				} else {
					$('ul#sizeChoices li:lt(6)').hide();
				}
			}else{
				$('ul#sizeChoices li:gt(17)').hide();	
			}
			$('div#sizeFilter p a').removeClass().addClass('sizeMore');
			if( $.browser.msie) {
				$('div#sizeFilter p a.sizeMore').css('paddingTop','0px');
			}
			moreNumbers = 0;
		}
		$(this).blur();
	});
};

/*Shoe Finder Phase 2 : A new parameter with Subcategories selected is passed*/ 	 
function makeAjaxCall(vName,cName,filtersSelected,filterSubcatsSelected,actionType){
	var sName="View All";
	if(cName=="Work & Safety") {
		sName = cName;
		cName = "Mens";
	}
	vName = cleanFilterParam(vName);
	cName = cleanFilterParam(cName);
	sName = cleanFilterParam(sName);
	if(filtersSelected=="no filter") {
		filtersSelected="";
	}
	/*Phase-2 Shoe Finder Enhancement*/
	if(filterSubcatsSelected == "no filter") {
		filterSubcatsSelected="";
	}
		
	if(actionType=="AjaxCall"){
				
		if(filtersSelected == null || filtersSelected == "" || fromResultsPage) {
			var url="BrowseSubCategoryBody?storeId=10153&catalogId=12605&vName="+vName+"&cName="+cName+"&sName="+sName+"&"+filtersSelected+"&pav=0&shoeFinder=true&subcat_filters="+filterSubcatsSelected;
			$.ajax({
				url:url,
      			dataType:"json",
      			success:fnGenerateFilterDiv,
      			error:errorFunction,
      			timeout:25000
			});
		} else {
			var url="BrowseSubCategoryBody?storeId=10153&catalogId=12605&vName="+vName+"&cName="+cName+"&sName="+sName+"&"+filtersSelected+"&pav=0&shoeFinder=true&subcat_filters="+filterSubcatsSelected;   
	 		$.ajax({
				url:url,
      			dataType:"json",
      			success:mergeFilters,
      			error:errorFunction,
      			timeout:20000
			});
		}
	}
	else{
		var url="BrowseSubCategory?storeId=10153&catalogId=12605&vName="+vName+"&cName="+cName+"&sName="+sName+"&"+filtersSelected+"&shoeFinder=true&subcat_filters="+filterSubcatsSelected;   
		window.location=url;
	}
}
/* This function is executed for the First time to display All the Filters/Subcategories */
function generateShoeFinder(resp){
	jsonResponse = resp['subCatJson'];
	productCount = jsonResponse.prodCnt;
	if(productCount > 0) {
		var filter =new Array(jsonResponse.filter);
		var subCatJson=new Array(jsonResponse.categories);
		
		if(filter != null && subCatJson != null){
			var cName=convertShoeFinderCategory(categoryName);
			var filterParamForBackBtn = undoCleanFilterParam(filterParam)+"^";
			for(i=0;i<jsonResponse.filter.length;i++){
				if(jsonResponse.filter[i].fn == "Color" || jsonResponse.filter[i].fn == "Size" || 
						(categoryName != "Work & Safety" && jsonResponse.filter[i].fn == "Style") || 
							(categoryName == "Work & Safety" && jsonResponse.filter[i].fn == "Safety")){
						if(!(categoryName == "Kids" && jsonResponse.filter[i].fn == "Color"))
							{
					filterName = jsonResponse.filter[i].fn;
					var filterNameForBackBtn = filterName;
					if(filterName == "Safety") {
						filterName = "Style";
					}
					var count=0;
					for(j=0;j<jsonResponse.filter[i].fv.length;j++){
						if(defaultFilters.Get("filter_"+cName+"_"+filterName.toLowerCase()).indexOf("|"+fnRemoveAmp(jsonResponse.filter[i].fv[j].fvn.toLowerCase())+"|") != -1 
												&& (jsonResponse.filter[i].fv[j].fvc > 0 || fromResultsPage)){
							var id=$.trim(fnRemoveAmp(jsonResponse.filter[i].fv[j].fvn));
							var classToBeSet="";
							if(fromResultsPage) {
								var endOfFilter = -1;
					            var indexOfFilterName = filterParamForBackBtn.indexOf("filter="+filterNameForBackBtn+"|") >=0 ?
					                                    filterParamForBackBtn.indexOf("filter="+filterNameForBackBtn+"|") : (filterParamForBackBtn.indexOf("^"+filterNameForBackBtn+"|") >= 0 ? 
					                                    filterParamForBackBtn.indexOf("^"+filterNameForBackBtn+"|")+1 : -1);
								if(indexOfFilterName >= 0) {
               						endOfFilter = filterParamForBackBtn.indexOf("^",indexOfFilterName);
               						var filterValues=stringTrim(id);
                    				var indexOfFilterValues = filterParamForBackBtn.indexOf("|"+filterValues+"|",indexOfFilterName) >=0 ?
                                                filterParamForBackBtn.indexOf("|"+filterValues+"|",indexOfFilterName)+1 : (filterParamForBackBtn.indexOf("|"+filterValues+"^",indexOfFilterName) >= 0 ? 
                                                filterParamForBackBtn.indexOf("|"+filterValues+"^",indexOfFilterName)+1 : -1);
									if(indexOfFilterValues>=0 &&
                               					(endOfFilter ==-1 || (endOfFilter > indexOfFilterValues))) {
                               			classToBeSet="class=\"selected\" ";
                               			$('span.clearFilter').show();
                               		}
								}
								if(classToBeSet=="" && jsonResponse.filter[i].fv[j].fvc == 0) {
									classToBeSet="class=\"notAvailable\" ";
										}
									}
									var fvIdx=jsonResponse.filter[i].fv[j].fvIdx;
									if(filterName == "Style"){
										var filterId=fnConvertStyle(id.toLowerCase());
									}
									else{
										var filterId=fnConvert(id.toLowerCase());
									}
									var hldHtml = "<li><span id=\"filter_"+cName+"_"+filterId+"\"><a id=\"fvIdx"+fvIdx+"\" "+classToBeSet+"title=\""+id+"\" href=\"javascript:;\" >"+id+"</a></span></li>";
									$('#'+filterName.toLowerCase()+'Choices').append(hldHtml);
									count++;
								}
							}
							if(count > 18 && filterName == "Size"){
								hldHtml = "<p><a href=\"javascript:;\" class=\"sizeMore\">view sizes</a></p>";
								$('#'+filterName.toLowerCase()+'Filter').append(hldHtml);
							}
							if(count > 6 && filterName == "Style"){
								hldHtml = "<p><a href=\"javascript:;\" class=\"sizeMore\">view sizes</a></p>";
								$('#'+filterName.toLowerCase()+'Filter').append(hldHtml);	
							}
					}
				}
			}
			/* Shoe Finder Phase 2 : This section is to handle the Kids Subcategories on Load */
			if(categoryName == "Kids"){			
				filterName = "ageGender";
				var filterNameForBackBtn = filterName;
				var kidsSubcatHtml ='<li><span id="filter_kids_newborns_infants">'
					+'<a href="javascript:;" title="Newborns &amp; Infants" id="catIdx_newborns_infants" class="notAvailable">'
					+'Newborns & Infants</a>'
					+'</span></li>'
					+'<li><span id="filter_kids_boys">'
					+'<a href="javascript:;" title="Boys" id="catIdx_boys" class="notAvailable">'
					+'Boys</a>'
					+'</span></li>'
					+'<li><span id="filter_kids_toddlers">'
					+'<a href="javascript:;" title="Toddlers" id="catIdx_toddlers" class="notAvailable">'
					+'Toddlers</a>'
					+'</span></li>'
					+'<li><span id="filter_kids_girls">'
					+'<a href="javascript:;" title="Girls" id="catIdx_girls" class="notAvailable">'
					+'Girls</a>'
					+'</span></li>';
				/* On load for Kids we display All Subcategories but as Unavailbale*/
				
				$('#'+filterName.toLowerCase()+'Choices').append(kidsSubcatHtml);
				/* This section will enable the Subcategories as returned from Mercado */	
				for(k=0;k<jsonResponse.categories.length;k++){
				    				    
					if(defaultFilters.Get("filter_"+cName+"_"+filterName.toLowerCase()).indexOf("|"+fnRemoveAmp(jsonResponse.categories[k].cn).toLowerCase()+"|") != -1 
											|| fromResultsPage){
						
						var id=$.trim(fnRemoveAmp(jsonResponse.categories[k].cn));
						var classToBeSet="";
						var filterId=fnConvertStyle(id.toLowerCase());
						$('a#catIdx_'+filterId).removeClass();
						/*Back button implementation to retain the Subcat's selected */
						if(fromResultsPage) {
							var removedHash=location.hash.replace("#","");
							filterSubcatParamBackButton=undoCleanFilterParam(removedHash.split("$$")[1].split("&&")[0])+"^";
							
							var endOfFilter = -1;
							var indexOfFilterName = filterSubcatParamBackButton.indexOf("subcat_filters="+filterNameForBackBtn+"|") >=0 ?
													filterSubcatParamBackButton.indexOf("subcat_filters="+filterNameForBackBtn+"|") : (filterSubcatParamBackButton.indexOf("^"+filterNameForBackBtn+"|") >= 0 ? 
													filterSubcatParamBackButton.indexOf("^"+filterNameForBackBtn+"|")+1 : -1);
							if(indexOfFilterName >= 0) {
								endOfFilter = filterSubcatParam.indexOf("^",indexOfFilterName);
								var filterValues=stringTrim(id);
								var indexOfFilterValues = filterSubcatParamBackButton.indexOf("|"+filterValues+"|",indexOfFilterName) >=0 ?
											   filterSubcatParamBackButton.indexOf("|"+filterValues+"|",indexOfFilterName)+1 : (filterSubcatParamBackButton.indexOf("|"+filterValues+"^",indexOfFilterName) >= 0 ? 
											   filterSubcatParamBackButton.indexOf("|"+filterValues+"^",indexOfFilterName)+1 : -1);
								if(indexOfFilterValues>=0 &&(endOfFilter ==-1 || (endOfFilter > indexOfFilterValues))) {
										classToBeSet="class=\"selected\" ";
										$('span.clearFilter').show();
										$('a#catIdx_'+filterId).addClass("selected");
								}
							}

						}
						
					}
				}
			}

		}
		/*default state for Style Filter*/
		$('ul#styleChoices li:gt(5)').hide();
		/*default state for Size Filter*/
		$('ul#sizeChoices li:gt(17)').hide();
		/*display selected shoe style choosen */
		reorder($('ul#styleChoices li:gt(5)'));
		/*open and close style filter*/
		viewStyles($('div#styleFilter p a'));
		/*styleSelected toggles .selected class for the style filter to the a tag so that the selected css bg image can be toggled on and off*/
		stylesSelected($('ul#styleChoices li span a'));
		/*display selected shoe size in center row*/
		sizeShown($('ul#sizeChoices li'));
		/*open and close size filter*/
		viewSizes($('div#sizeFilter p a'));
		/* Reorder styles, when loading the page using back button */
		$('ul#styleChoices li:gt(5) span a.selected').each(function() {
			$(this).parent().parent().click();
		});
		/* Reorder styles, when loading the page using back button */
		$('ul#sizeChoices li span a.selected').each(function() {
			$(this).parent().parent().click();
		});
				
		/*Shoe Finder Phase 2 : pickMe toggles the .selected class to the a tag so that the selected css bg image can be toggled on and off*/
		$('ul#colorChoices li span a, ul#agegenderChoices li span a').unbind('click').click(function() {
			pickMe($(this));
		});
		
		if(fromResultsPage) {
			fromResultsPage=false;
		} 
		$('#shoetotal').html(productCount);
		/* to save the prod count for selected filter is hash map*/
		jsonResponse.products="";
		//saveJsonResponse.Set(filterParam,jsonResponse);
		removeShoeLoadingGif();

	}
	else {
		$('span#shoetotal').html("0");
		removeShoeLoadingGif();

		var height = $(window).height();
		var width = $(window).width();
		var curtainHeight = $('#shoeFinder').height();
		var curtainWidth = $('#shoeFinder').width();
		$('div#noResultsCurtain').show().css('width', curtainWidth ).css('height', curtainHeight+15 );
		$('div#noresults').show();
		$('input#filterClear').hide();
	}
}


function fnConvert(value){
	var val="";
	for(n=0;n<value.length;n++){
		var value1=value.charAt(n);
	    if(value1 == "/" || value1 == "." || value1 == "&"){
			value1="_";
		}
		else if(value1 == " " || value1 == "-" ){
			value1="";
		}
		val=val+value1;
	}
	return val;
}
function fnRemoveAmp(value){
	return value.replace("&amp;", "&");
}

function fnConvertStyle(value){
	var val="";
	value = value.replace(" & ", "&");
	for(n=0;n<value.length;n++){
		var value1=value.charAt(n);
	    if(value1 == "/" || value1 == "." || value1 == "&" ||value1 == " " ){
			value1="_";
		}
		else if(value1 == "-" || value1 == "(" || value1 == ")"){
			value1="";
		}
		val=val+value1;
	}
	return val;
}

function fnGenerateFilterDiv(jsonResponse){
		
	    var hldHtml = "";
	    /*Shoe Finder Phase 2 :To display Age/Gender Subcategories for Kids*/
	    if("Kids" == categoryName){
			hldHtml +="<div id=\"kidsAgeGenderFilter\">";
		    hldHtml +="<h6>Age/Gender</h6><div style=\"display:none\">Age/Gender</div>";
		    hldHtml +="<ul id=\"agegenderChoices\">";
		    hldHtml +="</ul>";
		    hldHtml +="</div>";
		}
			hldHtml +="<div id=\"styleFilter\">";
		    hldHtml +="<h6>Style</h6><div style=\"display:none\">Style</div>";
			hldHtml +="<ul id=\"styleChoices\">";
		   	hldHtml +="</ul>";
		    hldHtml +="</div>";
		/*Shoe Finder Phase 2 : To display Color Filter in Shoe Finder for categories except Kids */    
		if(!("Kids" == categoryName)){ 
		    hldHtml +="<div id=\"colorFilter\">";
		    hldHtml +="<h6>Color</h6><div style=\"display:none\">Color</div>";
		    hldHtml +="<ul id=\"colorChoices\">";
		    hldHtml +="</ul>";
		    hldHtml +="</div>";
		}
		    hldHtml +="<div id=\"sizeFilter\">";
		    hldHtml +="<h6>Size</h6><div style=\"display:none\">Size</div>";
		    hldHtml +="<ul id=\"sizeChoices\">";
		    hldHtml +="</ul>";
		    hldHtml +="</div>";

	    $('#callFilters').html(hldHtml);
	    generateShoeFinder(jsonResponse);	    
}


function convertShoeFinderCategory(enabledCategory){
	var enabledCategoryFormatted=enabledCategory.toLowerCase();
	if(enabledCategory.indexOf("&")!=-1){
		enabledCategoryFormatted=enabledCategoryFormatted.replace(/ & /,'_');
	}
	return enabledCategoryFormatted;
}
/* Iterates through the filters and forms an array of filters that are selected currently */
function preFilterShoeFinder(){
	filters = [];
	$('div#callFilters div').each(function(i){
		var title = $(this).find('div').text();
		if(title == "Style"){
			if(categoryName == "Work & Safety") {
				title = "Safety";
			}
		}
		/*Shoe Finder Phase 2 : For Creating filterparameter when subcategories are selected */
		else if(title == "Age/Gender"){
			title="ageGender";
		}
		filters.push({ 'title': title, 'selected': [] });
		var values = [];
		$(this).find('a.selected').each(function(){
			values.push( $(this).text());
		});
		filters[i].selected = values;
	});
	createFilterParam();
}

function createFilterParam() {
	/* Initilaize flag to true so that we append the filter name only once for every element in Filter */
	var firstFilterFlag=true;
	lastFilterParam=filterParam;
	//phase-2
	lastSubcatParam=filterSubcatParam;
	/*Reset the value of filterParam*/
	filterParam="";
	filterSubcatParam="";
	/* Append to filterParam */
	if(filters!="" && filters.length!=0) {
		filterParam=filterParam.concat("filter=");
		$(filters).each(function(i){
			if(filters[i].selected!=""){
				if(firstFilterFlag==false){		
					filterParam=filterParam.concat("^");
				}
				/* Check whether the filter name is empty or null */
				var getFilterName=stringTrim(filters[i].title);
				if(getFilterName=="ageGender"){
						/* Append the filters[].selected[] list */
						$(filters[i].selected).each(function(j){	
							if(filterSubcatParam!=""){filterSubcatParam+="|";}
							filterSubcatParam=filterSubcatParam+stringTrim(filters[i].selected[j]);						
						});						
				}
				else{
				/* If filter name is present add the filter options */
				if(getFilterName != null && getFilterName.length > 0){
					filterParam=filterParam.concat(getFilterName);
					/* Append the filters[].selected[] list */
					$(filters[i].selected).each(function(j){									
						filterParam=filterParam+"|"+stringTrim(filters[i].selected[j]);						
						/* Specific to Price(not removing "(") */
						while(filters[i].selected[j].indexOf('$')>=0){
							filters[i].selected[j]=filters[i].selected[j].replace('$','');					
						}
					});						
					}
					/* Set flag to false */
					firstFilterFlag=false;					
				}
			}
		});		
		filterParam=cleanFilterParam(filterParam);
		/*Shoe Finder Phase 2 : To use selected Subcategories as parameter*/
		filterSubcatParam=cleanFilterParam(filterSubcatParam);
	}
	setHash();
	/*var jsonResponse=saveJsonResponse.Get(filterParam);
	if(typeof jsonResponse!='undefined' && jsonResponse!=null && jsonResponse!="") {
		mergeFilters(jsonResponse);
	} else {*/
	    makeAjaxCall(verticalName,categoryName,filterParam,filterSubcatParam,"AjaxCall");	
	//}
}

/*Trims and Replace all the spaces in a string with '+'*/
function stringTrim(inpText) {
    // Trim
    inpText=$.trim(inpText);
    // Replacing ' ' with '+'
    while(inpText.indexOf(" ")>=0){
        inpText=inpText.replace(" ","+");
    }
    return inpText;
}


// Replaces the special characters with corresponding escape characters. 
function cleanFilterParam(inputString) {
	/*Using escape function to eliminate invalid characters */
	inputString=escape(stringTrim(inputString));
	
	/*Replace all '%3F' characters with '?' */
	while(inputString.indexOf('%3F')>=0){
		inputString=inputString.replace('%3F','?');
	}

	/*Replace all '%3D' characters with '=' */
	while(inputString.indexOf('%3D')>=0){
		inputString=inputString.replace('%3D','=');
	}

	/*Replace all '%u2122' characters with '%26%23153%3B' */
	while(inputString.indexOf('%u2122')>=0){
		inputString=inputString.replace('%u2122','%26%23153%3B');
	}

	/*Replace all '%AE' characters with '%26reg%3B' */
	while(inputString.indexOf('%AE')>=0){
		inputString=inputString.replace('%AE','%26reg%3B');
	}
	return inputString;
}
/*Replaces the escaped characters with corresponding special characters.*/
function undoCleanFilterParam(inputString) {      
    /*Replace all '%u2122' characters with '%26%23153%3B' */
    while(inputString.indexOf('%26%23153%3B')>=0){
        inputString=inputString.replace('%26%23153%3B','%u2122');
    }

    /*Replace all '%AE' characters with '%26reg%3B' */
    while(inputString.indexOf('%26reg%3B')>=0){
        inputString=inputString.replace('%26reg%3B','%AE');
    }
    /*Using unescape function to eliminate invalid characters */
    inputString=unescape(inputString);
    return inputString;
}

//merge filters
		/*Shoe Finder Phase-2*/
function mergeFilters(resp) {
	//saveJsonResponse.Set(filterParam,jsonResponse);
	jsonResponse = resp['subCatJson'];
	productCount = jsonResponse.prodCnt;
	if( jsonResponse.prodCnt > 0) {
		ajaxSubcats=jsonResponse.categories;
		for(i=0;i<jsonResponse.filter.length;i++){
			if((categoryName != "Kids" && jsonResponse.filter[i].fn == "Color")|| jsonResponse.filter[i].fn=="Size" || (categoryName != "Work & Safety" && jsonResponse.filter[i].fn == "Style") 
					|| (categoryName == "Work & Safety" && jsonResponse.filter[i].fn == "Safety")){
				for(j=0;j<jsonResponse.filter[i].fv.length;j++) {
					
					if(document.getElementById("fvIdx"+jsonResponse.filter[i].fv[j].fvIdx)){
						var thisButton = document.getElementById("fvIdx"+jsonResponse.filter[i].fv[j].fvIdx);
						if($(thisButton).attr("class")!="selected") {
							if(jsonResponse.filter[i].fv[j].fvc==0) {
								//disble the fitler display
								$(thisButton).attr("class", "notAvailable");
							} else {
								$(thisButton).attr("class","");
							}
						}
					}
				}
			}
		}
		/*Shoe Finder Phase-2*/
		/* If the count of shoes under a particular sub-cat is zero for some selected style/size
		 filter then that sub-cat is disabled*/
		if(ajaxSubcats){			
			/*Make the class of all the sub-cats(which are not selected) as 'Not Available' initially*/
			$("div#kidsAgeGenderFilter ul#agegenderChoices li span a").each(function () { 
				var chosen = $(this);
				if(fnStartsWith(chosen.attr('id'),"catIdx_") && chosen.attr('class')!='selected'){
					chosen.attr("class", "notAvailable");
				}
			});
			//If the subcats are present in the mercado response, then enable them.
			for(i=0;i<ajaxSubcats.length;i++){
				var filterValueName = $.trim(fnRemoveAmp(ajaxSubcats[i].cn));
				if(document.getElementById("catIdx_"+fnConvertStyle(filterValueName.toLowerCase()))){
					var thisButton = document.getElementById("catIdx_"+fnConvertStyle(filterValueName.toLowerCase()));
					if($(thisButton).attr("class")!="selected") {
						$(thisButton).attr("class","");
					}
				}
			}
		}
		$('#shoetotal').html(productCount);
		removeShoeLoadingGif();
	} else {
		removeShoeLoadingGif();

		var height = $(window).height();
		var width = $(window).width();
		var curtainHeight = $('#shoeFinder').height();
		var curtainWidth = $('#shoeFinder').width();
		$('div#noResultsCurtain').show().css('width', curtainWidth ).css('height', curtainHeight+15 );
		$('div#noresults').show();
		$('input#filterClear').show();
	}
}

/*Shoe Finder Phase 2 : Position the loading gif to the shoefinder only*/
function shoeLoadingGif() {
	//the click on div shoeFinder is for display purpose... real loading functionality is determined by IT
	
		var curtainHeight = $('#shoeFinder').height() +25;
		var curtainWidth = $('#shoeFinder').width();
		$('#shoeCurtain, #shoeLoading, #shoeCurtainIE').css('width', curtainWidth ).css('height', curtainHeight );
		//onload of the shoeLoadingGif() function the p#shoeFound html is swapped out for the loading image
		$('p#shoesfound').html('<span id="shoeLoading"></span>');
		//IE allows the click thru to happen on the curtain layer... disable click on the shoeCurtain
		$('#shoeCurtainIE').click(function() { 
			return false;
		});
		

}

/* Shoe Finder Phase 2 : This is created to swap the found item count back in.*/
function foundItems() {
	
	$('p#shoesfound').html('<span id="shoetotal">'+productCount+'</span> items found');
}
/* Shoe Finder Phase 2 : To remove the curtain after success/failure of Ajax */
function removeShoeLoadingGif(){
	var timeOut = setTimeout('foundItems()', 500);
	$('#shoeCurtain').remove();		
	$('#shoeCurtainIE').remove();
}

function clearFilters(){
	$('div#filterContainer li a').removeClass('selected');
	$('div#filterContainer li a').removeClass('notAvailable');
	$('span.clearFilter').hide();
	filterParam="no filter";
	$('div#noResultsCurtain').hide();
	$('div#noresults').hide();
	setHash();
	//var jsonResponse=saveJsonResponse.Get(filterParam);
	/* to get the prod count at page load*/
	if(typeof jsonResponse!='undefined' && jsonResponse!=null && jsonResponse!="") {
		$('#shoetotal').html(jsonResponse.prodCnt);
	} else {
		/* On clear all a curtain is shown with loading animation*/
		$('body').append(hldHtmlCurtain);
		shoeLoadingGif();
		makeAjaxCall(verticalName,categoryName,"","","AjaxCall");
	}
}
function getPreviousResults(){
	filterParam=lastFilterParam;
	filterSubcatParam=lastSubcatParam;
	if(lastSelectedFilter != "") {
		$('div#callFilters a#'+lastSelectedFilter).toggleClass('selected');
	}
	$('div#noResultsCurtain').hide();
	$('div#noresults').hide();
	if(document.getElementById('ajaxError')){$('div#ajaxError').remove();}
	//Shoe Finder Phase 2 
	$('body').append(hldHtmlCurtain);
	shoeLoadingGif();
	makeAjaxCall(verticalName,categoryName,filterParam,filterSubcatParam,"AjaxCall");
	setHash();
}
function errorFunction() {
	removeShoeLoadingGif();
	
	var height = $(window).height();
	var width = $(window).width();
	var curtainHeight = $('#shoeFinder').height();
	var curtainWidth = $('#shoeFinder').width();
	$('div#noResultsCurtain').show().css('width', curtainWidth ).css('height', curtainHeight+15 );
	// Ajax error pop up
	if(!document.getElementById('ajaxError')) {
		var ajaxPopup= '<div id="ajaxError">\n';
			ajaxPopup+= '	<p><b>We were unable to process your request.  Please try again.</b></p>\n';
			ajaxPopup+= '	<p>If you are using FireFox and this continues to fail, there may be a conflict with one of the following:</p>\n';
			ajaxPopup+= '	<ul>';
			ajaxPopup+= '	<li><img src="'+imagePath+'img/icons/bullet_circle.gif"/>&nbsp;&nbsp;RealPlayer Browser Record Plugin</li>';
			ajaxPopup+= '	<li><img src="'+imagePath+'img/icons/bullet_circle.gif"/>&nbsp;&nbsp;Talkback Plugin</li>';
			ajaxPopup+= '	</ul>\n';	
			ajaxPopup+= '	<p>Click on Continue Anyway to try again or Previous Results to go back to the previous page. </p>';	
			ajaxPopup+= '	<br clear="all">\n';
			ajaxPopup+= '	<input id="tryAgain" type="image" src="'+imagePath+'img/buttons/continueAnyway_btn.jpg" value="Try Again"><input id="prevResultsAjaxError" type="image" src="'+imagePath+'img/buttons/previousResults_btn.jpg" value="Show previous results">\n';
			ajaxPopup+= '</div>\n';
		$('div#shoeFinder').append(ajaxPopup);
		$('input#tryAgain').click(function() {
			$('div#noResultsCurtain').hide();
			$('div#ajaxError').remove();
			/* On ajax error a curtain is shown with loading animation*/
			$('body').append(hldHtmlCurtain);
			shoeLoadingGif();		 
			makeAjaxCall(verticalName,categoryName,filterParam,filterSubcatParam,"AjaxCall");
		});
		$('input#prevResultsAjaxError').click(function() {
			 getPreviousResults();
		});
	}	
}
// to redirect the page to sub cat page on click of 'find my shoes'
function findClick() {
	makeAjaxCall(verticalName,categoryName,filterParam,filterSubcatParam,"Reload");
}
/*Shoe Finder Phase 2 : Appending subcategories selected to URL after hash(#) to implement back buttton*/
function setHash(){
	if(filterParam!="no filter" && filterParam!="" && ( filterSubcatParam =="no filter" || filterSubcatParam=="")) {
		location.replace(location.href.substring(0,location.href.indexOf("#"))+"#cName="+undoCleanFilterParam(categoryName)+"$$subcat_filters=ageGender&&"+undoCleanFilterParam(filterParam));
	} else if(filterParam!="no filter" && filterParam!="" && filterSubcatParam !="no filter" && filterSubcatParam !="" ) {
		location.replace(location.href.substring(0,location.href.indexOf("#"))+"#cName="+undoCleanFilterParam(categoryName)+"$$subcat_filters=ageGender|"+undoCleanFilterParam(filterSubcatParam)+"&&"+undoCleanFilterParam(filterParam));
	} else if((filterParam=="no filter" || filterParam=="") && filterSubcatParam !="no filter" && filterSubcatParam !="" ) {
		location.replace(location.href.substring(0,location.href.indexOf("#"))+"#cName="+undoCleanFilterParam(categoryName)+"$$subcat_filters=ageGender|"+undoCleanFilterParam(filterSubcatParam));
	} else {
		location.replace(location.href.substring(0,location.href.indexOf("#"))+"#");
	}
}

function fnStartsWith(value, startVal){
	var subSection = value.substring(startVal.length,0);

	if(subSection == startVal ){
		return true;
	}

	return false;
}

