/* Variable Declaration - Starts Here */
var prepaidCellCookieOnPageLoad='false'; 
var prepaidCell='false'; 
var prePaidZip;
var prePaidNoResults='false';
/* Variable for MULTIPLE SELECTION OPTION & Dynamic Category Page */
var multipleSelectEnabled;
var dynamicCategoryPage;
var dynamicCategoryName="";

/* Declare variable to hold filter options in URL */
var filterParam="";
 
/* Declare variable to hold pagination URL attrivbtnbutes */
var paginationParam="";
var defaultPaginationParam="";

/* Declaring the filter Map */
var filters = [];

/* Variable for checking no results */
var hasNoResults=false;

/* Declare variable lastFilter and initialize it to null string */
var lastFilter="";

// Variable to store quick view data
var overviewQV='';
var reviewsQV='';

// Variable
var firstTimeFlag=true;
var subCatProductCount;
var pageNo;
var start;
var end;

//to remove the selected sort option from drop down
var selectedSortOption='';
var request;
var subCatpageNum;
var compareParam='';
var prodCountCompare=0;
//var maxCompares=11;   This variable is initialized in SubCat and Keyword Dyna Headers
partNumberValues=new Array(maxCompares);
var sortOptionsValues='';
var sortOptionsNames='';
var currentSortOption='';
var countSelected=0;
var lastUnselectedFlag=false;
var urlAfterAjaxCall='';
var filterParamAfterAjaxCall='';
var minDisplayPerPage;
var fromProductPage=false;
var pavValue;
var fvIdxAjaxArray = [];
var defaultMinPriceValue;
var defaultMaxPriceValue;
var jsonProducts;
var urlFilterParameterOnLoad="";
var previousResultsFilterParam="";
var cs=0;
var omFilter="";
var indexOfP=""
var autoProd=false;
//  To store previous value of shop by dropdown
var prevshopByVal="";
var nameOfStores="KmartMyGofer";

var zoomedImg = new Image();

// Sorting and applying pagination at product block using json
var parentSize;
var childProdArray = new Array();
var pidxZero=new Array();
var pavThreshold;
var remoteUrl;
var pIdx = new Array();
var fvIdx = new Array();
var viewItems;  
var prodPageIdxs = new Array();
var pageNumber = 1;
var primaryRequest;
var filterNameList = new Array();
var minPrice;
var maxPrice;
var maxFinalPrice;
var filterValue = '';
var starValue='';
var lastKey = "";
var currentKey = "";
var nonSubCatFlag=false;
var isAjaxOver = false;
var ajaxTimeOut = false;
var hasUserAction = false;
var boxPrefix = 'prod';
var fvIdxInitialArray = [];
var showXFormatNewWinPop = true;
var jsonFlag = false;
// Global Variables for tracking vert,cat,subcat and keyword
var vName;
var cName;
var sName;
var keyword;
		
var ddItemPartNumArr = new Array();
//Kmart SPU shop by Flow
var shopBy = "";
var staticPopUpName="";
//User Input Price Enhancement
userInputPrice=false;
//Flag to confirm QuickView (Regional Availibility) 
var qvpartnumber='';
//Flag to confirm SPU (Regional Availibility)
flagSPU='N';
/* Variable Declaration - Ends Here */
//Search within Search Val
var searchWithinSearch = "";
/* Code for lazyLoad Setup - Starts Here */
var lazyLoad = {
	constants : { 
		loaded:0, 
		setsLoaded:1, 
		maxSets:function(){return Math.ceil(jsonProducts.products.length/lazyLoad.constants.toload)}, 
		killswitch:false, 
		dist:2300, 
		initial:13, 
		toload:12 
	},
	instance : {
		loaded: 0,
		setsLoaded: 1,
		maxSets: function(){return Math.ceil(jsonProducts.products.length/lazyLoad.constants.toload)}
	},
	resetInstance : function(){
		var g = this
		g.instance.loaded = g.constants.loaded
		g.instance.setsLoaded = g.constants.setsLoaded
		g.instance.maxSets = g.constants.maxSets()
	},
	ini: function(){
		var g = this
		g.resetInstance()
		initialLoad = g.constants.initial > jsonProducts.products.length ? (jsonProducts.products.length+1) : g.constants.initial 

		// Added as part of 08_19 Softline swatch enhancement. Call function to clear off carosels
	    if(typeof clearCarousels != 'undefined') clearCarousels();
		//Function to eliminate Products which are not Get It Now in "Get it Now" Tab.
		//Generate DDItmList if RA is turned ON
		if(jsonProperties.regAvail == "true"){
		generateDDItemList(jsonProducts, false, 1, (jsonProducts.products.length+1));
		}
					
		if(g.constants.killswitch){
			$('#results').html(jsonDisplayProd(jsonProducts, false, 1, false))
			updateProds();
		}else{
			$('#results').html(jsonDisplayProd(jsonProducts, false, 1, initialLoad))
			updateProds();
			g.instance.loaded = g.constants.initial
			window.onscroll = function(){
				var a = g.dims()
				if((a.h - a.s) < g.constants.dist && ((g.instance.setsLoaded)<g.instance.maxSets)){
					g.instance.setsLoaded+=1
					$('#results').append(jsonDisplayProd(jsonProducts, false, g.instance.loaded, (g.instance.loaded+g.constants.toload)))
					g.instance.loaded+=g.constants.toload
					updateProds();
				}
			}
						
		}	
	},
	dims : function(){
		return {
			h: Math.max(document.body.scrollHeight, document.body.offsetHeight),
			s: Math.max(document.documentElement.scrollTop, document.body.scrollTop)
		}
	}
}


/* lazyload ends - update prods begins */
var updateProds = function(div) {
	qvBtn();
	greatPricePop();

	if((jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))) && ((getCookieValue("gridIndicator")=="false") || ($('div#results').attr('class') == 'row'))){
						$("div.price").find("div.availGrd").attr("style","display: none");
	    				$("div.info").find("div.availRow").attr("style","display: block");
	}
	
	$("a.mapLink").click(function(){mapClick(this)});
	if(typeof allRegiSS !='undefined' && allRegiSS.length >0 ){
		var zippCook1 = getCookie('zipCode');
		if(zippCook1 !=''){doAjax(zippCook1,storeId);$('.localPrice a').addClass('localPSel');	}


		$(".localPrice").unbind().hover(function() {
			$saveStory = $(this).prev();							
			$('.morePrice').hide(0);
			offsetL = $(this).offset();
			$('.morePrice').show().css({ top: offsetL.top + 23, left: offsetL.left - 92 }); 
			$('.localPrice a').removeClass('over');	
			$(this).find('a').addClass('over');
			clearTimeout(foT);	
		}, function() {
			foT = setTimeout(function(){
				$('.morePrice').fadeOut();
				$('.localPrice a').removeClass('over');			
			},500);	
		});	
	}

	initCompareCheckBox();

	$("div#results").find("a").each(function(i) {
	    if (this.rel=='emailMe') {
		this.onclick = function (){
		    mePop(this.getAttribute('info'),this.rel);
		};
	    }
	    if (this.rel=='storePickup')    {
		this.onclick = function (){
		    mePop(this.getAttribute('info'),this.rel);
		};
	    } 
	});
	/* Available for Pre-order - dynamic pop-up */
	if(typeof dynamicPopupPath != 'undefined' && typeof dynpop != 'undefined'){
	   $(function(){$('div.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
	}
	
	// Cross Format Change
	if($("div.CFphoto").length>0) {
			crossFmtLaunch();
	}
	//Invoke the repainting logic for displaying the availability message.
	if(jsonProperties.regAvail == "true"){
	readyOnLoad();
			if(fnChkZipCode()){
				if((DDItemList != "") && (DDItemList != null)){
					repaintRegAvial(availValues,ddItemPartNumArr);
					}
				}
			}
}

/* Code for lazyLoad Setup - Ends Here */


/* Code for AJAX Setup - Starts Here */
$.ajaxSetup( {
	timeout : 20000
});

// Ajax error pop up
var ajaxPopup= '<div id="ajaxError" style="display:none">\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="'+jspStoreImgDir+'img/icons/bullet_circle.gif"/>&nbsp;&nbsp;RealPlayer Browser Record Plugin</li>';
	ajaxPopup+= '	<li><img src="'+jspStoreImgDir+'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="'+jspStoreImgDir+'img/buttons/continueAnyway_btn.jpg" value="Try Again"><input id="prevResultsAjaxError" type="image" src="'+jspStoreImgDir+'img/buttons/previousResults_btn.jpg" value="Show previous results">\n';
	ajaxPopup+= '</div>\n';	
// Ajax error pop up Null Results
var ajaxPopupNullResults= '<div id="ajaxError" style="display:none">\n';
	ajaxPopupNullResults+= '	<p><strong>We were unable to find a product match based on the criteria you selected.</strong></p>\n';
	ajaxPopupNullResults+= '	<p>Try selecting different criteria or select a different combination to find a product you like.</p>\n';	
	ajaxPopupNullResults+= '	<br clear="all">\n';
	ajaxPopupNullResults+= '    <input id="prevResultsAjaxError" type="image" src="img/btn/btn_previous_results.gif" value="Show previous results">&nbsp;&nbsp;&nbsp;\n';
	ajaxPopupNullResults+= '    <input id="clearFields" type="image" src="img/btn/btn_clear.gif" value="Clear Fields">\n';
	ajaxPopupNullResults+= '</div>\n';		
	

/* Code for AJAX Setup - Ends Here */

/* Kmart SPU STARTS HERE */

//This function generates ksn SpuEligible and ksn SpuOnly lists
 var spuONLYProductArray = new Array();
 
 function addSpuOnlyEntryQV(partNumber, ksn,saveStory){
           var spuProduct=new Object();
          spuProduct.ksn=ksn;
          spuProduct.partNumber=partNumber;
          spuProduct.avail='';
          spuProduct.ss=saveStory;
          spuONLYProductArray[partNumber]=spuProduct;
 
 
 }
 
 function updateSpuOnlyEntryQV(partNumber){
           var prodObject=spuONLYProductArray[partNumber];
         if(prodObject!='undefined' && prodObject!=null){
             var ksnProduct=prodObject.ksn;
             var size=jsonRegPriceAvi.pco;
         
            for(var availCounter=0;availCounter<size;availCounter++){
              var ksn=jsonRegPriceAvi.price[availCounter].pId;
              if(ksnProduct==ksn){
              prodObject.avail=jsonRegPriceAvi.price[availCounter].avl;
              if(jsonRegPriceAvi.price[availCounter].rpr!=null && jsonRegPriceAvi.price[availCounter].rpr!='undefined'&& jsonRegPriceAvi.price[availCounter].rpr!=''){
                      prodObject.ss="You Pay $"+jsonRegPriceAvi.price[availCounter].rpr;
              }
              delete spuONLYProductArray[partNumber];
              spuONLYProductArray[partNumber]=prodObject;
              }
            }
         
         } 
 
 
 }
 function displayRegionalSaveStoryInQV(saveStory){
  var saveStoryHTML="<div class=\"youPay bl\"> <span class=\"text\">You Pay: </span> <span class=\"pricing\"> $ "+saveStory+"</span> </div>";
   $('.overviewTab .saveStory').html(saveStoryHTML);
  }
 
 function getRegionalSSForSPUOnlyItem(partNumber){
     var prodObject=spuONLYProductArray[partNumber];
      if(prodObject!='undefined' && prodObject!=null){
    		 return prodObject.ss;
         }
        else{
        return '';
        }
 
 }
  function getRegionalAvailForSPUOnlyItem(partNumber){
 
 var prodObject=spuONLYProductArray[partNumber];
      if(prodObject!='undefined' && prodObject!=null){
    		 return prodObject.avail;
         }
        else{
        return '';
        }
 
 
 }
function genksnSpuLists(){
	//Variable to store spu only list
	spuOnlyKSNList="";

	//variable to store spu eligible list
	spuEligKSNList="";
	
	//Iterate through entire set of products
	for(i=0;i<jsonProducts.products.length;i++){
			// append the ksn to the SpuOnlyList if the default fulfillment is SPU
			if(jsonProducts.products[i].ksn!='' && jsonProducts.products[i].dff=='SPU'){
			    addSpuOnlyEntryQV(jsonProducts.products[i].no,jsonProducts.products[i].ksn,jsonProducts.products[i].ss);
				if(spuOnlyKSNList=="") {
					spuOnlyKSNList=jsonProducts.products[i].ksn;
				}else {
					spuOnlyKSNList=jsonProducts.products[i].ksn + "|" + spuOnlyKSNList;
				}	
			}
			// append the ksn to the SpuEligibleList if the default fulfillment is SPU
			else if(jsonProducts.products[i].ksn!='' && (jsonProducts.products[i].spi==true)&&(jsonProducts.products[i].dff=='VD'||jsonProducts.products[i].dff=='TW')){
				if(spuEligKSNList=="") {
					spuEligKSNList=jsonProducts.products[i].ksn;
				} else {	
					spuEligKSNList=jsonProducts.products[i].ksn + "|" + spuEligKSNList;
				}			
			}	
	}
}

//Function to make an ajax call when user changes his store
function changeStorePriceAvl(){
	//Vraiable beanType set to pb for Keyword/Subcategory pages
	
	var beanType="pb";
	var isAssociatedPrice=false;//default value
    var isGoldenStore=false;//default value
	
	//Call function to generate the ksn lists
	genksnSpuLists();
		
	if((spuOnlyKSNList.length > 0 || spuEligKSNList.length > 0) && spuOnlyKSNList!="undefined" && spuEligKSNList!="undefined" ){
		//Ajax URL for Page Refresh command
		var remoteURL="PageRefreshCmd?spuOnlyKSNList="+spuOnlyKSNList+"&spuEligKSNList="+spuEligKSNList+"&storeId=10151";
		request=$.getJSON(remoteURL,processPageRefreshJSONResponse);		
	}	
}
//Function called after the PageRefresh ajax call completes
function processPageRefreshJSONResponse(jsonResponse){
	// Function to display the availability and pricing of the products
	updateSpuPriceAvail(jsonResponse.jsonRegPriceAvi);
	availRowHiding();
} 

/* Kmart SPU ENDS HERE */

/* Common Methods for Server Side & Client Side Flow - Starts Here */
/*Debugging Trace Window*/
function trace(what) {
    var id      = "trace";
    var a_id    = "clearTrace";
    this.num    = 0;
    if (!document.getElementById(id))
    {
        var div = document.createElement('div');
            div.id = id;
            div.style.position = "fixed";
            div.style.top   = "10px";
            div.style.left  = "10px";
            div.style.opacity = ".8";
            div.style.filter = "alpha(opacity=80)";
            div.style.width = "300px";
            div.style.minHeight = "20px";
            div.style.maxHeight = "300px";
            div.style.overflow = "auto";
            div.style.backgroundColor = "#000000";
            div.style.border = "5px solid #f1f1f1";
            div.style.MozBorderRadius = "10px";
            div.style.color = "#f1f1f1";
            div.style.textAlign = "left";
            div.style.padding = "15px";
            div.style.zIndex = "1000";
            document.body.appendChild(div);
        var a = document.createElement('a');
            a.id = a_id;
            a.className = "clear";
            a.style.display = "block";
            a.style.margin = "0 0 5px";
            a.style.cursor = "pointer";
            div.appendChild(a);
    }
    // Set position of this div //
    var debugWindow = document.getElementById(id);
        debugWindow.innerHTML   += "<hr />\n";
        debugWindow.innerHTML   += "<samp>"+what+"</samp>";
    var clear = document.getElementById(a_id);
        clear.innerHTML = "close";
        clear.onclick = function(){
            document.body.removeChild(debugWindow);
        };
}

/*Returns the value of a specific query string variable*/
var getURLandSetChecked = function(){
    var qs = window.location.search.substring(1);
    if(qs != ''){
        qs = qs.split('&');
        var same;
        for( var z=0; z<qs.length; z++ ){
            var attribute = qs[z];
            if(attribute.indexOf("lastFilter") == -1){
                var pair = qs[z].split('=')[1];
                if(pair!=null && pair.length > 0){
                    pair = pair.split('^');
                    for (var a=0; a<pair.length; a++){
                        var att = pair[a].split('+')[0];
                        var sel = pair[a].split('+')[1];
                        if(att && sel){
                            sel = sel.split('|');
                            for(var b=0; b<$("."+att+" li label").length; b++){
                                for(var c=0; c<sel.length; c++){
                                    var $input = $("."+att+" li > label:eq("+b+") :checkbox");
                                    if($input.attr("name") == sel[c]){
                                        $input.attr("checked","checked")
                                        $input.parent().parent().parent().parent().addClass("selected");
                                        if($("div.left-column h4:eq(0) a").length<1){
                                            $("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
                                            $("div.left-column h4:eq(0) a").click(clearAll);
                                        }
                                        if($input.parent().parent().parent().parent().children("h5").children("a").length<1){
                                            var createClearHtml = "<a href='javaScript.html' name='"+$(this).parent().parent().attr('class')+"' title='Clear selections'>Clear</a>";
                                            $(this).parent().parent().parent().children("h5").prepend(createClearHtml);
                                            $input.parent().parent().parent().parent().children("h5").children("a").click(clearSelection);
                                        }
                                    }
                                }
                            }
                        }
                    }               
                }

            } else {
                var last = attribute.split('=')[1];
                $("."+last).prev().toggleClass("open");
                $("."+last).slideToggle("fast");
            }
        }
    }
};

/*FIND POSITION*/
function findPosExact(obj) {
    xPos = yPos = 0;
    if (obj.offsetParent) {
        xPos = obj.offsetLeft;
        yPos = obj.offsetTop;
        while (obj = obj.offsetParent) {
            xPos += obj.offsetLeft;
            yPos += obj.offsetTop;
        }
    }
    if($.browser.msie && $.browser.version.split('.')[0] <= 6) {
        yPos-=1;
    }
	// IE drop down fix
	if($.browser.msie && $.browser.version.split('.')[0] >6) {
	xPos=xPos-$('div.col_2').css('margin-left').replace("px","");
	}
    return [xPos,yPos];
}

/*Glossary layer*/
function glossaryView(me){
    var term        = $(me).parent().text();
    var definition  = $(me).attr("alt");
    var id          = "glossary";
    if (!document.getElementById(id))
    {
        var containerDiv = document.createElement('div');
        containerDiv.id = id;
        containerDiv.className = "floatingLayer";
        containerDiv.style.width = "300px";
        document.body.appendChild(containerDiv);
    }
    // Set position of this div //
    var thisDIV = document.getElementById(id);
    findPosExact(me);
    thisDIV.style.top   = yPos +"px";
    thisDIV.style.left  = xPos +20+"px";
    $(thisDIV).html(
        "<a href='#"+id+"' class='closeWindow' title='Close this layer'>Close</a>\n"+
        "<h4>"+term +"</h4>\n"+
        "<p>"+definition+"</p>"
    );
    $(thisDIV).children("a.closeWindow").click(function(){ $(this).parent().remove(); return false; });
}

/*Customize View*/
function customizeView(me){
    var id = "customize";
    if (!document.getElementById(id))
    {
        var containerDiv = document.createElement('div');
        containerDiv.id = id;
        containerDiv.className = "floatingLayer";
        containerDiv.style.width = "250px";
        document.body.appendChild(containerDiv);
    }
    // Set position of this div //
    var thisDIV = document.getElementById(id);
    findPosExact(me);
    thisDIV.style.top   = yPos - 95 +"px";
    thisDIV.style.left  = xPos - 30 +"px";
    $(thisDIV).html(
        "<a href='#"+id+"' class='closeWindow' title='Close this layer'>Close</a>\n"+
        "<h5>Select Product Details to Display</h5>\n"+
        "<ul></ul>"+
        "<p class='button'><b>UPDATE</b></p>"
    );
    var liLength = $(me.parentNode).parent().children("li").length;
    for(var li=0; li<liLength-1; li++){
        if(me.parentNode.parentNode.getElementsByTagName("li")[li].style.display == "none"){
            $("div#customize ul").append(
                "<li><input type='checkbox' id='this_"+li+"'> <label for='this_"+li+"'>"+
                $(me.parentNode).parent().children("li:eq("+li+")").html().split(":")[0]+
                "</label></li>"
            );
        } else {
            $("div#customize ul").append(
                "<li><input type='checkbox' id='this_"+li+"' checked='checked'> <label for='this_"+li+"'>"+
                $(me.parentNode).parent().children("li:eq("+li+")").html().split(":")[0]+
                "</label></li>"
            );
        }
    }
    $(thisDIV).children("a").click(function(){ $(thisDIV).remove(); return false; });
    $(thisDIV).children("p").children("b").click(function(){
        var input = this.parentNode.parentNode.getElementsByTagName("input");
        var infoLength = $("div.info").length;
        for(var x=0; x<input.length; x++){
            if(input[x].checked==true){
                for(var inf=0; inf<infoLength; inf++){
                    $("div.info:eq("+inf+") ul li:eq("+x+")").show();
                }
            } else {
                for(var inf=0; inf<infoLength; inf++){
                    $("div.info:eq("+inf+") ul li:eq("+x+")").hide();
                }
            }
        }
        $(thisDIV).remove();
        return false;
    });
}

/*Function to store all the sort options in an array*/
function getSortOptions() {
    currentSortOption=$("div.sort li a.selected").parent().text();
    selectedSortOption=$("div.sort li a.selected").attr('name');
    $('div.sort').find('li').each(function(i) {             
        $(this).find('a').each(function(j) {    
            if(sortOptionsValues == ''){    
                sortOptionsValues=$(this).parent().text();
                sortOptionsNames=$(this).attr('name');
            }else{
                sortOptionsValues=sortOptionsValues+'::'+$(this).parent().text();
                sortOptionsNames=sortOptionsNames+'::'+$(this).attr('name');                
            }   
        });
    });
}

/*js_ReplaceChar*/
function js_ReplaceChar(str,charFind,replaceWith){
    //replaceWith = "\\"+charToRemove;
    regExp = new RegExp("["+charFind+"]","g");
    return str.replace(regExp,replaceWith);
}

/*Retain the products selected  for Comparision*/
function initCompareCheckBox() {
    $("p.compare input:checkbox").each(function(i){
        for(i=0;i<partNumberValues.length;i++){
            if(partNumberValues!='' && partNumberValues!=null){
                    if($(this).attr('name')==partNumberValues[i]){
                        this.checked=true;
                        $(this.parentNode.parentNode.parentNode).addClass("selected");
                    }
            }
        }
    });
}

/*Trims and Replace all the spaces in a string with '+'*/
function stringTrim(inpText) {
    // Trim
    inpText=trim11(inpText);
    // Replacing ' ' with '+'
    while(inpText.indexOf(" ")>=0){
        inpText=inpText.replace(" ","+");
    }
    return inpText;
}

/*LTrim & RTrim*/
var trim11 = (function(){   
    var ws = {},
        chars = ' \n\r\t\v\f\u00a0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    for(var i = 0; i < chars.length;i++ )
        ws[chars.charAt(i)] = true;
    return function( str ){
        var s = -1,
            e = str.length;
        while( ws[str.charAt(--e)] );
        while( s++ !== e && ws[str.charAt(s)] );
        return str.substring( s, e+1 );
    };                         
})();

/*Creates the URL to be used for compare functionality*/
function compareUrl(){
    var fullUrl = location.href;
    if(location.href.indexOf("#") >=0){
        fullUrl=location.href.split("#")[0];
    }
    var splitString1 = null;
    var splitString2 = null;
    var newUrl="";
    if(fullUrl.search("BrowseSubCategory?")>=0) {
        
        newUrl = fullUrl.replace("BrowseSubCategory?","Compare?");  
        
    } else {
        var mainIndex = fullUrl.search("/?");
        if(mainIndex != -1){
            var splitUrlArray = fullUrl.split("?");
            if(splitUrlArray.length > 0 ){
                splitString1 = splitUrlArray[0];
                splitString2 = splitUrlArray[1];
            }
        }
        else{
            splitString1 = fullUrl;
        }
        
        var index = splitString1.search("shc/s/");
        var chunkValue = splitString1.substring(0,index+6);
        
        var seoUrl = splitString1.substring(index+6,splitString1.length);
        var splitArray   = seoUrl.split("_");
        
        var storeId = splitArray[1];
        var catalogId = splitArray[2];
        
        var newUrl = chunkValue+"Compare?";
        if(storeId && catalogId)
        {
        newUrl = newUrl+"storeId="+storeId+"&catalogId="+catalogId;
        }
    
        if(splitString2 != null){
            newUrl = newUrl+"&"+splitString2;
        }
    }
    return newUrl;
}

/*Stores or deletes the product details when selected or deselected for Comparing*/
function setCheck(box){
    //If checked
    if(box.checked==true){
         box.parentNode.parentNode.parentNode.className="product selected";
         var partNumber = box.name;
         for(i=0;i<partNumberValues.length;i++){
            if(partNumberValues[i]=='' || partNumberValues[i]==null){
                partNumberValues[i]=partNumber;
                break;
            }
         }          
         prodCountCompare++;
         if(prodCountCompare > maxCompares) {
            partNumberValues[--prodCountCompare]='';
            //do not allow to check more than max
            box.checked=false;
            box.parentNode.parentNode.parentNode.className="product";
            alert("You can compare a maximum of "+maxCompares+" items");
         }
    
    }else{
        //if unchecked
        prodCountCompare--;
        box.parentNode.parentNode.parentNode.className="product";       
        var partNumber = box.name;
        for(i=0;i<partNumberValues.length;i++){
            if(partNumberValues[i]==partNumber){
                partNumberValues[i]='';
            }
        }
    }
}

/*When the compare button is clicked*/
function compareProducts(){
    var j=0;
    if(prodCountCompare > 1 ){
    compareParam=compareUrl();
        for(i=0;i<partNumberValues.length;i++) {
            if(partNumberValues[i]!='' && partNumberValues[i]!=null ) {
                j++;
                var temp='&partNumber_'+j+'=';
                compareParam=compareParam+temp+partNumberValues[i];
            }
        }
        compareParam=compareParam+'&prodCount='+j;
        window.location.href=compareParam;
    }
    else{
        alert("You must select atleast 2 items to compare");
    }
}

/*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;
}

/*updateFilterslider*/
function updateFilterslider(){
   if(!$.browser.safari){ 
        $('div.left-column div.attributes ul').each(function(){
        		if($(this).parent().find('h5').find('div').text() != "Price"){
	                var count = 0; 
	                var li = $(this).children('li:visible'); 
	                if($(this).hasClass('Color')){ 
	                        count = $(li).children('a:visible').length;     
	                }else{ 
	                        count = $(li).length;
	                } 
	                if(count<10){ 
	                       $(this).css({height:''});   
	                }else{ 
	                       $(this).css({height:170, overflow:'auto'});     
	                } 
           	   }    
        });  
    };  		
}

/*function for show glossary*/
var glossaryIdKey=0;
var filterValues;
var id;
function showDescription(obj,glossaryId,filterValue) {
	if(!document.getElementById("glossary")) {
		id	= "glossary";
        if (!document.getElementById(id)) {
			var containerDiv = document.createElement('div');
			containerDiv.id = id;
			containerDiv.className = "floatingLayer";
			containerDiv.style.width = "300px";
			containerDiv.style.position = "absolute";
			containerDiv.style.background = "#FFFFFF none repeat scroll 0 0";
			if(jsonProperties.sid==10153)
			{
				containerDiv.style.border = "5px solid #4B93D9";
			}
			containerDiv.style.padding = "5px";
			document.body.appendChild(containerDiv);
		}
		// Set position of this div //
		var thisDIV = document.getElementById(id);
        findPosExact(obj);
		thisDIV.style.top 	= yPos +"px";
		thisDIV.style.left 	= xPos +20+"px";
		filterValues=filterValue;
	    glossaryIdKey=glossaryId;
	    var url='GlossaryDisplayView?storeId='+jsonProperties.sid+'&catalogId='+jsonProperties.cid+'&glossaryId='+glossaryId+'&langId=-1';
	    ajaxCall(url,'callBackGlossary',null,containerDiv);
	 }
}

/*callBackGlossary*/
function callBackGlossary(value,thisDIV) {
	if(!document.createElement) return false;	
	    $(thisDIV).html(
		    "<a href='#"+id+"' class='closeWindow' title='Close this layer'>Close</a>\n"+
			"<h4>"+filterValues +"</h4>\n"+
			"<p>"+value+"</p>"
		);
	$(thisDIV).children("a.closeWindow").click(function(){ $(this).parent().remove(); return false; });
}

/*Replace all characters in a string with a specific character*/
function replaceAll(strChk, strFind, strReplace) {
  var strOut = strChk;
  while (strOut.indexOf(strFind) > -1) {
    strOut = strOut.replace(strFind, strReplace);
  }
  return strOut;
}

/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * $LastChangedDate: 2007-07-21 18:45:56 -0500 (Sat, 21 Jul 2007) $ * $Rev: 2447 $*
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);

function isNumeric(strVal)
{
  for(var i=0; i<strVal.length; i++)
  {
	var key = strVal.charCodeAt(i);
			
	if((key < '48') || (key >'57'))
	{
		return 1;
	}
  }
  	return 0;
}
/*function to enable add to cart button when zip code is present*/
function afterRegiSS(){
	$("fieldset.addToCart").each(function(i){
		if($(this).attr("style").indexOf("block") < 0){
			$(this).attr("style","display: block");
		}
   }); 
   $("fieldset.selectOptions").each(function(i){
		if($(this).attr("style").indexOf("block") < 0){
			$(this).attr("style","display: block");
		}
   }); 
   autoProd=true;
}

/*unwrap element - used in lazyload */
/*
 * jQuery unwrap plugin
 * GPL (GPL-LICENSE.txt) licenses.
 * Created by: Tiziano Treccani
 *
 * $Date: 2008-1-06 12:00:00
 *
 * Version: 1.0
 */

(function($){
	$.fn.unwrap = function(elem){
		var elements;
		if (elem == null){
			elements = jQuery(this);
		}
		else if (typeof elem == "string"){
			elements = jQuery(this).find(elem);
		}
		else if (typeof elem == "object"){
			elements = elem;
		}
		else alert("unknow elem");
		elements.each(function(){
			jQuery(this).parent().replaceWith(jQuery(this));
		});
	}
})(jQuery);
/*addItemPartNo*/
function addItemPartNo(partnumber,si,spi,sri,dff,vendorId,presellDate) {
	var urlATC=""
	if(vendorId!=null && vendorId.length>0){
		var vendorTranslatedId = vendorId;
		
		//Temporary fix to translate vendor Id of ART to MV for metaverse vendor
		if(vendorId!= null && vendorId == "ART")
		{
			vendorTranslatedId = "MV";
	}
		urlATC ="ExternalOrderItemAdd?sourceIndicator="+vendorTranslatedId+"&storeId="+jsonProperties.sid+ "&catalogId="+jsonProperties.cid+"&partNumber="+partnumber;		
	}
	else {		
		var pageType;
		var itemPartNumber;
		indexOfP = partnumber.length - 1;
		if(partnumber.charAt(indexOfP)=='P')
		{
			itemPartNumber = partnumber.substring(0,indexOfP);
		}
		if(jsonProperties.kp == true) {
			pageType="keyword";
		}else if(jsonProperties.dcp == true){
			pageType="dcp";
		}else{
			pageType="subcat";		
		}	
		if(presellDate!="" && presellDate!=null){
			urlATC = "ProductOptionsOrderItemAddCmd?langId=-1&storeId="+jsonProperties.sid+ "&catalogId="+jsonProperties.cid+"&itemPartNumber="+ itemPartNumber+"&URL=OrderItemDisplay&quantity_1=1"+
				"&atc="+pageType+"&presellDate="+presellDate+"&partNumber="+partnumber;
		} else{
			// Initializing flag for Automotive products
			// For the automotive items the first three digits of part number
			// (Division Number) will be 095 or 028 or 090.
			// var pdtDivisionNumber = partnumber.substring(0,3);
			var isAutomotive = false;
			
			// This code is commented as the requirement changed to display product details button for automotive items
				//if(pdtDivisionNumber == '028' || pdtDivisionNumber == '095' || pdtDivisionNumber == '090' ) {
				//	isAutomotive = true;
				//}
			urlATC = "ProductOptionsOrderItemAddCmd?langId=-1&storeId="+jsonProperties.sid+ "&catalogId="+jsonProperties.cid+"&itemPartNumber="+ itemPartNumber+"&URL=OrderItemDisplay&quantity_1=1"+
				"&atc="+pageType+"&partNumber="+partnumber+"&variant=0";
				
			// Add 'IndicatorA=pickup' to URL based on 3 conditions
			// if STOCKind=1 & (spi=true or sri=1)
			// if (def. fulfillment = 'VD' or 'TW') and (sri = true or spi =true) and is Automotive
			// if is Automotive and def. fulfillment = 'SPU'
			if( ((((dff=="TW"||dff=="VD")&&isAutomotive)||si==1) && (spi == 'true' || sri==1)) || (isAutomotive && dff=="SPU") || (jsonProperties.sn=="Kmart" && dff=="SPU")){
			 	urlATC+="&IndicatorA=pickup";	
			}
			else if(dff=="DDC"){
				urlATC+="&IndicatorA=delivery";
			}
			if(getCookie('zipCode')!=null && getCookie('zipCode').length>0)
			{
				urlATC+="&zipCode="+getCookie('zipCode');
			}
		}
	}
	location.href = urlATC;
}

/* storepu for RA for QV*/
function fnRegionalStorePickUpQV(spupartNo){
	$('div#availability').find('a#checkAvailSpu').each(function(i){
		var spuInfo = $(this).attr('info');
		var spuInfoArray = spuInfo.split("^");

        var spuPartNo = spuInfoArray[0];
        var spuMfg = spuInfoArray[3];
        var spuCatVal = spuInfoArray[4];
        var spuPrdUrl = spuInfoArray[5];
        var spuJsid = spuInfoArray[6];
        var spuKdb = spuInfoArray[7];
        var spuSid = spuInfoArray[8];
        var spuCid = spuInfoArray[9];
        var spuStDate = spuInfoArray[10];
		var zipCode=getRegPickZip();
		var catEntryId_1 = spuCatVal;
		var URL = spuPrdUrl;
		var storeId = spuSid;	
		var catalogId = spuCid;
		
		// CODE ADD FOR KMART SPU		
		var partNumber = spupartNo;
		var presellDate = spuStDate;
		var pageType;
		var itemPartNumber;
		var indexOfP = partNumber.length - 1;
		if(partNumber.charAt(indexOfP)=='P')
		{
			itemPartNumber = partNumber.substring(0,indexOfP);
		}
		if(jsonProperties.kp == true) {
			pageType="keyword";
		}else if(jsonProperties.dcp == true){
			pageType="dcp";
		}else{
			pageType="subcat";		
		}	
		var vName=escape(jsonProperties.vName);
			vName = replaceAll(vName,"%20","+");
		var cName=escape(jsonProperties.cName);
			cName = replaceAll(cName,"%20","+");
		var sName=escape(jsonProperties.sName);
			sName = replaceAll(sName,"%20","+");
			
		/*var vName=_vert;
		vName = replaceAll(vName,"%20","+");
		var cName=_cat;
		cName = replaceAll(cName,"%20","+");
		var sName=_sbcat;
		sName = replaceAll(sName,"%20","+");*/
		
		var storeLocatorUrl = "StorePickupCommand?storeId="+storeId+"&langId=-1&catalogId="+catalogId+"&zipCode="+zipCode+
					"&catEntryId_1="+catEntryId_1+"&quantity_1=1"+"&URL="+escape(URL)+"&browseFlag=browseSearch&presellDate="+
					presellDate+"&IndicatorA=pickup&partNumber="+partNumber+"&vname="+vName+"&cname="+cName+"&sname="+
					sName+"&itemPartNumber="+itemPartNumber+"&atc="+pageType+"&variant=0";
		
		// // CODE ADD FOR KMART SPU ENDS	(URL edited)		
		if($.browser.msie && /6.0/.test(navigator.userAgent))
				setTimeout(function() {window.location = storeLocatorUrl;}, 100);
		else
		window.location = storeLocatorUrl;
	});
}
// function for subcat page
function fnRegionalStorePickUp(spupartNo){
	$('div.availability').find('li.storepu').find('a#spu_'+spupartNo).each(function(i){
		var spuInfo = $(this).attr('info');
		var spuInfoArray = spuInfo.split("^");

        var spuPartNo = spuInfoArray[0];
        var spuMfg = spuInfoArray[3];
        var spuCatVal = spuInfoArray[4];
        var spuPrdUrl = spuInfoArray[5];
        var spuJsid = spuInfoArray[6];
        var spuKdb = spuInfoArray[7];
        var spuSid = spuInfoArray[8];
        var spuCid = spuInfoArray[9];
        var spuStDate = spuInfoArray[10];
		var zipCode=getRegPickZip();
		var catEntryId_1 = spuCatVal;
		var URL = spuPrdUrl;
		var storeId = spuSid;	
		var catalogId = spuCid;
		
		// CODE ADD FOR KMART SPU		
		var partNumber = spupartNo;
		var presellDate = spuStDate;
		var pageType;
		var itemPartNumber;
		var indexOfP = partNumber.length - 1;
		if(partNumber.charAt(indexOfP)=='P')
		{
			itemPartNumber = partNumber.substring(0,indexOfP);
		}
		if(jsonProperties.kp == true) {
			pageType="keyword";
		}else if(jsonProperties.dcp == true){
			pageType="dcp";
		}else{
			pageType="subcat";		
		}	
		var vName=escape(jsonProperties.vName);
			vName = replaceAll(vName,"%20","+");
		var cName=escape(jsonProperties.cName);
			cName = replaceAll(cName,"%20","+");
		var sName=escape(jsonProperties.sName);
			sName = replaceAll(sName,"%20","+");
		var storeLocatorUrl = "StorePickupCommand?storeId="+storeId+"&langId=-1&catalogId="+catalogId+"&zipCode="+zipCode+
					"&catEntryId_1="+catEntryId_1+"&quantity_1=1"+"&URL="+escape(URL)+"&browseFlag=browseSearch&presellDate="+
					presellDate+"&IndicatorA=pickup&partNumber="+partNumber+"&vname="+vName+"&cname="+cName+"&sname="+
					sName+"&itemPartNumber="+itemPartNumber+"&atc="+pageType+"&variant=0";
		
		// // CODE ADD FOR KMART SPU ENDS	(URL edited)		
		if($.browser.msie && /6.0/.test(navigator.userAgent))
				setTimeout(function() {window.location = storeLocatorUrl;}, 100);
		else
			window.location = storeLocatorUrl;
	});
}

function fnAtcInfo(DDCPartNo){
	$('div.product').find('div.price').find('fieldset#ddcAtc_'+DDCPartNo).each(function(i){
		var ddcAtcInfo = $(this).attr('info');
		atcInfoArray = ddcAtcInfo.split("^");
		currentPartNo = atcInfoArray[0];
        dbFlagVal = atcInfoArray[1];
        pageFlag = atcInfoArray[2];
        catentryVal = atcInfoArray[3];
        });
}


/*replaceCharacters*/
function replaceCharacters(str){
	str = replaceAll(str, "&amp;", "&");	
	str = replaceAll(str, "&apos;", "'"); 	
	str = replaceAll(str, "&#039;", "'"); 	
	str = replaceAll(str, "&quot;", "\""); 	
	str = replaceAll(str, "&copy;", "");	
	str = replaceAll(str, "&reg;", "");	
	str = replaceAll(str, "&trade;", "?"); 	
	str = replaceAll(str, "&lsquo;", "?"); 	
	str = replaceAll(str, "&rsquo;", "?");  
	str = replaceAll(str, "&sbquo;", "?");	
	str = replaceAll(str, "&ldquo;", "?"); 
	str = replaceAll(str, "&rdquo;", "?"); 
	str = replaceAll(str, "&bdquo;", "?"); 
	return str;
} 

/*Function to update the user actions to omniture(s.prop4)*/
function omFilterUpdate(pav,po) {

	/*if(cs!=null){
		omFilter = omFilter + "cs="+cs+"&";
	}
	if(pav!=null && pav!="" && pav.length>0){
		omFilter = omFilter + "pav="+pav+"&";
	}
	if(po!=null && po!="" && po.length>0){
		omFilter = omFilter + "po="+po+"&";
	}
	if(jsonProperties.kp == true) {
		omFilter = omFilter + "pn=k&";
	}else if(jsonProperties.dcp == true){
		omFilter = omFilter + "pn=dcp&";
	}else{
		omFilter = omFilter + "pn=s&";	
	}
	if(ajaxTimeOut == true) {
		omFilter = omFilter + "ajaxTimeOut=1&";	
	}
	var hashIndex=location.href.indexOf("#");
	if(hashIndex>=0  && (hashIndex< location.href.length-1)){
	  var filterURL =  location.href.substring(hashIndex+1,location.href.length);
	  var filterIndex = filterURL.indexOf("lastFilter");
	  if(filterIndex>=0  && (filterIndex< filterURL.length-1)){
	  	omFilter = omFilter + filterURL.substring(0,filterIndex-1)+"&";	  	
	  }else {
	  	omFilter = omFilter + filterURL+"&";	
	  }	
	}
	omFilter=omFilter.replace("viewItems","vi").replace("pageNum","pgn").replace("sortOption","so").replace("filter","f");
	if (typeof s != 'undefined') {
		s.linkTrackVars="prop4";
		s.tl(this,'o','SubCatFilter');		
	}*/
}
/* Function to display the Ajax Error popup when the Ajax call fails - Start */
function showAjaxErrorPopup() {
	// Hiding and removing DIVs
   	$('div#body-curtain').hide();
	$('div.progress').hide();
	$("div#filterConfirm").hide();
	$("div#noresults").hide();
	// Remove the preload image if the user has used Back button to reach this page
	if(document.getElementById('backButtonPreloader')!=undefined) {
		$('div#backButtonPreloader').remove();
		document.getElementById("contentWrapper").style.display='block';
		$('div.product').height('auto');
		
	}
	// Calculate the offset where the curtain is to be displayed
	var topForRightColumn = $('div.col_1').offset().top-5;
	$('div#right-column-curtain').css("top",topForRightColumn);
	$('div#right-column-curtain').css("left",10);
	$('div#right-column-curtain').width($('div.col_1').width()+$('div.right-column').width()+12);
	if($('div.col_1').height() > $('div.right-column').height()) {
		$('div#right-column-curtain').show().height($('div.col_1').height()+5);
	} else {
		$('div#right-column-curtain').show().height($('div.right-column').height()+5);							
	}
	// Show the pop up
	// PRICE USER INPUT ENHANCEMENT
	if (typeof lastFilterOptions != 'undefined' && lastFilterOptions.useRangeForm)
		$('div#contentWrapper').prepend(ajaxPopupNullResults);
	else
	$('div#contentWrapper').prepend(ajaxPopup);
	// Show on screen
	$('div#ajaxError').css({top: topForRightColumn});
	$('div#ajaxError').css("left",$('div.col_1').width()+12);
	$('div#ajaxError').width($('div.right-column').width()-30);
	// Bind click events for the buttons	
	$('div#ajaxError').show();
	window.scrollTo(0,0);			
}
            
var dd = "";
function timeOutHide(id) {
    var remove = function(){ $("#"+id).remove() };
    dd = setTimeout(remove,500);
}

//	 SPU LocalPriceTip Pop Up Starts
function localPriceTip(){
	var text = '';
	var timer = 0;
	$('.lpMsgRow, .lpMsgGrd')
	.data('tipText','Product availability may change as you shop.  If you change your selected store or arrival method, the price of the item in your order may be adjusted to give you the best price available.')
	.hover(function(e){
		staticPopUpName="price";
		if($('#DHTMLcontent').length == 0){
			var us = $(this);
			timer = setTimeout(function(){
				text = us.data('tipText');
				var settings = { dynamicContent:false, contentname: '.localPriceTip', windowWidth: '250px', windowHeight: '80px', staticContent:text };
				dynpop.ini(e, settings, us);
			},400)
		}
	},function(){
		clearTimeout(timer);
	})	
}
//	 SPU LocalPriceTip Pop Up Ends 

// Function to hide Row Local price tip in Grid view

function availRowHiding(){
    if((jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))) && (getCookieValue("gridIndicator")=="true")){
		$('div[@id=lpMsgRow]').each(function(i){
			$(this).attr("style","display: none;");
		});
		}
	else if((jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))) && (getCookieValue("gridIndicator")=="false")){
		$('div[@id=lpMsgRow]').each(function(i){
			$(this).attr("style","display: block;");
		});					
	}
}
// End of function availRowHiding


//   SPU LearnMore Pop Up function starts

function showLearnMore(){
	$(".util .learnMore").click(function(){
		 var offset = $(".util .learnMore").offset();
		 $("#div_LearnMore").css({ left:offset.left - 485, top:offset.top - 200 }).show();
	});
	$('#div_LearnMore .fright').click(function(){
		$('#div_LearnMore').hide();
	});	
}

//   SPU LearnMore Pop Up function ends

//   Function to get 260 popup starts
function checkNearByStores(){
	//Store Selector Functionality
	$('p.spu_oos a').click(function(e){
		staticPopUpName="nearStores";
		//Retrieving the catentry_id for the product
		var catentryIdVal=$(this).find("input").val();
		var newE = { pageX: e.pageX - 100, pageY: e.pageY - 200 };
		var settings = {filename: 'CheckAvailabilityCmd?storeId='+storeId+'&catalogId='+catalogId+'&catentryId='+catentryIdVal+
                '&langId=-1'+'&storeUnitNumber='+unitNo+'&browseFlag=true',
						contentname: '#storeSelector',
						jsonFlag: false, 
						dynamicContent:true, 
						windowWidth: '320px',
						windowHeight: 'auto'};
		dynpop.ini(newE, settings);

    });	
}
//   260 pop up ends	
/* Common Methods for Server Side & Client Side Flow - Ends Here */

/* General Methods for Server Side Flow - Starts Here */

/* Unique functions for Server Side Flow Starts */
/* DOM READY CALLS for Server Side Flow - Starts Here */
function checkCellZip()	{
  var zipCodeCell= $('input#zipCodeCell').val();
  
  var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
  var passed = lv_pattern.test(zipCodeCell); 
  if (!passed || zipCodeCell=='00000' || zipCodeCell=='99999' ) {
        showErrorMsg();
    return false;
  }
  else {
	 prePaidZip=zipCodeCell;
     setCookie('zipCode',zipCodeCell);prepaidCellCookieOnPageLoad='true';
     handlePrePaidCellCheck();
     
    return true;
  }
}
function handlePrePaidCellCheck(){
ajaxImpl();
  
}
function initCompareValues(){

	compareParam='';
	prodCountCompare=0;
	partNumberValues=new Array(maxCompares);
	
}

function printZipModule(){
 
	if(prepaidCell=='true' && prePaidZip!=null && prePaidZip!=''){
		if(subCatProductCount>=1 && prePaidNoResults=='false'){	
			prePaidCellZipValidHMTL();
		}
		else{	
		prePaidCellZipNotValidHMTL();
		}
		initCompareValues();
	}
	
 
}
function searsPop(settings){
	this.dims = function(){
		return {
			v:window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
			h:window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
			vs:document.documentElement.scrollTop || document.body.scrollTop,
			hs:document.documentElement.scrollLeft || document.body.scrollLeft
		}
	}
	var dims = this.dims()
	this.content = $('<div id="'+(settings.id?settings.id:'')+'"class="'+(settings.Class?settings.Class:'')+'"/>').hide().appendTo('body')
	this.content.css({width:(settings.width?settings.width+'px':'807'), height:(settings.height?settings.height+'px':'auto')})
	if(settings.position){
		this.content.css({top:settings.position.top, left:settings.position.left})
	}else{
		this.content.css({top:dims.vs+30, left:(dims.h/2)-(this.content.width()/2)})
	}
	if(settings.modal){
		var us = this
		this.modal = $('<div id="searsPopModal"/>').css({width:dims.h, height:$('body').height()}).hide().appendTo('body').unbind().click(function(){
			us.hide()
		})
	}
	if(settings.close){
		var us = this
		this.close = $('<div class="closeBtn"><a href="#">'+settings.close+'</a></div>').appendTo(this.content).unbind().click(function(){
			us.hide()
		})
	}
	this.populated = false;
	this.populate = function(func){
		func()
		this.populated = true
	}
	this.show = function(settings){
		if(this.modal){this.modal.show()}
		if(settings && settings.position){
			this.content.css({top:settings.position.top, left:settings.position.left})
		}
		this.content.show()
	}
	this.hide = function(){
		if(this.modal){this.modal.hide()}
		this.content.hide()
	}
	this.destroy = function(){
		if(this.modal){this.modal.remove()}
		this.content.remove()
	}
}	

function clickTerms(){
 
 	    	$(".closeBtn a").hide();
		    var bub1 = new searsPop({id:'learnMore', Class:'searsPopupLearnMore', close:'close'});
			var clickTermsURL='/shc/s/BrowseStaticPageCmd?storeId='+storeId+'&catalogId='+catalogId+'&langId=-1&catalogInd=DZD&dzName=W4&vName=prepaidCoverage';
	 
			$('#bub1').click(function(e){
		 
			 	if(!bub1.populated){
					bub1.populate(function(){
   					 $.ajax({url:clickTermsURL,success:function(html){
   				 
           				 $(html).appendTo(bub1.content)
        			} //success function
   				 });//ajax
				});//bub1.populate(function(
			 	}
				bub1.show({position:{top:e.pageY, left:(e.pageX - $('#learnMore').width()) - 40 }})
			});//$('#bub1').click(function(e){

// 
	 
}
function prePaidCellZipValidHMTL(){
var zip= getCookie('zipCode');
 
$('#zipBoxSubCat').removeClass();
$('#zipBoxSubCat').addClass("zipValid");
 var HTML=	'<img src="'+jspStoreImgDir+'img/valid-zip.gif" class="notification"/>'+
        	'<div id="zipMessage">There is coverage for these phones in{'+zip+'}.</div>'+
            '<div id="zipCode">Check another ZIP Code?'+
            '<input id="zipCodeCell" type="text" value="'+zip+'" maxlength="5" size="5"/>'+
           	'<span class="btn"><a href="#"><img onclick="checkCellZip()" src="'+jspStoreImgDir+'img/btn-go-zip.gif" class="btn"/></a></span>'+
           	' </div>'+
       		'<span id="coverLimit"><a href="#" id="bub1">Learn more about coverage limitations</a></span>';       
 
$('#zipBoxSubCat').html('');
$('#zipBoxSubCat').html(HTML);
$('#zipBoxSubCat').show();  clickTerms();
}

function prePaidCellZipNotValidHMTL(){

var zip= getCookie('zipCode');
$('#zipBoxSubCat').removeClass();
$('#zipBoxSubCat').addClass("zipNotFound");
 var HTML=	'<img alt="" src="'+jspStoreImgDir+'img/no-coverage-zip.gif" class="notification"/>'+
        	'<div id="zipMessage">We do not currently have phones with coverage in   {'+zip+'} or the ZIP Code is not valid.</div>'+
            '<div id="zipCode">Check another ZIP Code?'+
            '<input id="zipCodeCell" type="text" value="'+zip+'" maxlength="5" size="5"/>'+
           	'<span class="btn"><a href="#"><img onclick="checkCellZip()" src="'+jspStoreImgDir+'img/btn-go-zip.gif" class="btn"/></a></span>'+
           	' </div>'+
       		'<span id="coverLimit"><a href="#" id="bub1">Learn more about coverage limitations</a></span>';       

$('#zipBoxSubCat').html('');
$('#zipBoxSubCat').html(HTML);
$('#zipBoxSubCat').show();  clickTerms();
}
jQuery(document).ready(function($){
if(storeId=='10153' || storeId=='10151'){
clickTerms();
    	 prepaidCell=$('input#prepaidCell').val();
 		 var cookiZip= getCookie('zipCode');
 		 if(prepaidCell=='true' && cookiZip!=null && cookiZip!='' ){	
			prepaidCellCookieOnPageLoad='true';
			if(jsonProducts.products.length >=1){	
				prePaidCellZipValidHMTL();
				}
			else{
			prePaidCellZipNotValidHMTL();
			}
	  }
	  if(prepaidCell=='true' ||(cookiZip==null && cookiZip=='') ){
		$('#zipBoxSubCat').show();
	  }
   }
	fromProductPage = false;
	/*Row Grid switcher*/
	var Switch = {
	    grid : function(){
	        $("div#results").attr("class","grid");
	        $("a.grid").addClass("selected");
	        $("a.row").removeClass("selected");
	        document.cookie="gridIndicator=" +escape("true");
	        if(jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))){
		        $("div.price").find("div.availGrd").attr("style","display: block");
		        $("div.info").find("div.availRow").attr("style","display: none");
		        availRowHiding();
	    	}
	    	// Added as part of 08_19 Softline swatch enhancement. Call function to clear off carosels
	    	if(typeof clearCarousels != 'undefined') clearCarousels();
	    },
	    row  : function(){
	        $("div#results").attr("class","row");
	        $("a.row").addClass("selected");
	        $("a.grid").removeClass("selected");
	        document.cookie="gridIndicator=" +escape("false");
			if(jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))){
				$("div.info").find("div.availRow").attr("style","display: block");
				$("div.price").find("div.availGrd").attr("style","display: none");
				availRowHiding();
			}
	    	// Added as part of 08_19 Softline swatch enhancement. Call function to clear off carosels
	    	if(typeof clearCarousels != 'undefined') clearCarousels();
	    }
	};
	
		var domBodySetup = '<div id="body-curtain" style="display:none"></div>\n';
			domBodySetup+= '<div class="progress" style="display:none">\n';
			if(storeId == 10153 || storeId == 10156){
				domBodySetup+= '<center><img src="'+jspStoreImgDir+'img/loader/animation-generic-sears.gif" alt="Loading results..." align="center"></center>\n';
			}else{
				domBodySetup+= '	<img src="'+jspStoreImgDir+'img/loader/pre-loader2.gif" alt="Loading results...">\n';
			}
			domBodySetup+= '</div>\n';
		$('body').prepend(domBodySetup);
			
		
		if(location.href.indexOf("#")>=0  && (location.href.indexOf("#") < location.href.length-1)) {
			/* Code removed */
		} else {
			$('div#backButtonPreloader').remove();
			document.getElementById("contentWrapper").style.display='block';
		}
	
	dynamicCategoryPage=jsonProperties.dcp;
	if(jsonProducts.prodCnt>=jsonProperties.pav_threshold || dynamicCategoryPage == true || jsonProperties.kp == true)
	{
		pavValue=0;
	}
	else{
		pavValue=jsonProperties.pav_threshold;
	}
	
	var fvIdxCount=0;
		
	if(dynamicCategoryPage == true ) {
		// Code for initialising the current subcategory for dynamic category page
		var fullUrl = location.href;
		if(location.href.indexOf("#") >=0){
			fullUrl=location.href.split("#")[0];
		}
		if(fullUrl.indexOf("sName=")>=0) {
			dynamicCategoryName=(fullUrl.indexOf("&",fullUrl.indexOf("sName="))>=0)?
			fullUrl.substring(fullUrl.indexOf("sName=")+1,fullUrl.indexOf("&",fullUrl.indexOf("sName="))):
			fullUrl.substring(fullUrl.indexOf("sName=")+1,fullUrl.length-1);
		} else {
			if(fullUrl.indexOf("?")>=0){
				fullUrl=fullUrl.split("?")[0];
			}
			dynamicCategoryName=fullUrl.split("_")[fullUrl.split("_").length-1];
		}
		dynamicCategoryName=cleanFilterParam(unescape(dynamicCategoryName));
	}
		
	if(document.body.id == "subcategory" || document.body.id == "keysearch")
	{		
		var vpp=jsonForm.viewItems;
		var pageNo=jsonForm.pageNum;		
		var productCount=jsonProducts.prodCnt;		
		var tempProduct= vpp*pageNo;
		var startIndex=1;
		var endIndex= vpp;	
		if(productCount < tempProduct ){
			endIndex=productCount%vpp;
		}						
		//default call to jsonDisplayProd - ddaniell
	    
			 if(jsonProperties.vName=="Automotive") {
							$("#results").html(jsonDisplayProd(jsonProducts,false,1,endIndex+1));
							}else {	
		
		lazyLoad.ini();
			}	
		
		/* To bind the click function of DDC addtocart */
		if(jsonProperties.regAvail == "true"){
			if(fnChkZipCode()){
				if((DDItemList != "") && (DDItemList != null)){
					fnOnLoadRARepaint(jsonRegionalAvailability);
				}
			}
				var imageCA ="<div id='imageCA' style='display: none;'>"
				+"<input type='image' style='display: none;'value='Check Availability' src='"+imagePath+"img/btn_check_availability.gif'/>"
				+"</div>";	
				
			$('body').append(imageCA);
		}
		//Added for Search Within Vertical Enhancement
		//ChangeVertDropdown();
		if((jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))) && ((getCookieValue("gridIndicator")=="false") || ($('div#results').attr('class') == 'row'))){
			$("div.price").find("div.availGrd").attr("style","display: none");
	    	$("div.info").find("div.availRow").attr("style","display: block");
	    }
		/*Kmart SPU STARTS HERE */
		if(location.href.indexOf("shopBy=ship")>=0){
			// Assigning ship value to shopby variable
			shopBy="ship";
			// calling shopByOption functions
			shopByOption("ship");
		}else if(location.href.indexOf("shopBy=spu")>=0){
			// Assigning spu value to shopby variable
			shopBy="spu";
			// calling shopByOption function
			shopByOption("spu");
		}
		// On page load if store is already selected we update the pricing and availability of the products
		if(jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0) &&  fnCheckCookie())){
			// function to update the price and availabilty of the products
			updateSpuPriceAvail(jsonRegPriceAvi);
			availRowHiding();
		}		
		/*Kmart SPU ENDS HERE*/
		
		if(jsonForm) {
			var totalProducts=parseInt(jsonProducts.prodCnt);
			// To hide the compare button when there is only one item
			if(totalProducts==1) {
				$('div#comparison').hide();
			}
			else {
				$('div#comparison').show();
			}
			
		
			if(jsonProperties.mse=="true") {
				multipleSelectEnabled=true;
			}
			if(jsonProperties.mse=="false") {
				multipleSelectEnabled=false;
			}
	
			/*Call this function on Page Load*/
			commonPagination();	
			
			getSortOptions();
			/*To get the browser name */
			var browser=navigator.appName;
			
			/* Display Only Ten Items Initially */
			$("div.right-column span.star a").click(function(){return false;})
			
			/* Grid/Row Switcher */
			var resultsWrapper = document.getElementById("results");
			$("a.grid").click(function(){if(!(resultsWrapper.className=="grid")){Switch.grid();}return false;});
			$("a.row").click(function(){if(!(resultsWrapper.className=="row")){Switch.row();}return false;});
			
			var resultsWrapper = document.getElementById("results");
			if(resultsWrapper.className=="grid"){$("a.grid").addClass("selected");$("a.row").removeClass("selected");};
			if(resultsWrapper.className=="row"){$("a.row").addClass("selected");$("a.grid").removeClass("selected");};
			/* start of changes for search within vertical enhancement */	
			$("div.left-column #gobtn").click(function(){searchWithinClick();});	
			$("div.left-column #search_within_box").keypress(function(e){
			      if(e.which == 13){
			      	 searchWithinClick();
			       }
		      });
			/* end of changes for search within vertical enhancement */
			/* Unchecked all checked inputs onload */
			$("div.left-column input:checked").removeAttr("checked");
		    $("div.left-column li label input:checkbox").click(selectAttribute);
		   //price slider phase II
		   $("div.left-column li#slider label").click(bindRadioButton);
		    $("div.left-column li.selection a").click(function() {
		    	$(this).find('input:checkbox').each(selectAttribute);      
		    
		    });
		    $("div.left-column div > h5").click(function(){
					var selectedNum=0;
					$(this).toggleClass("open");
					$(this.parentNode).children("ul:eq(0)").slideToggle("fast");
					$(this.parentNode).children("span.displayAll").toggle();
					if($(this.parentNode).children("ul:eq(0)").children().length<=10){ $(this.parentNode).children("span.displayAll").hide() }
					return false;
			});
			
			/* Dropdown functions */
			$("a.select").click(function(){ findPosExact(this);dropDown(this.nextSibling,this.className, this.offsetWidth); return false; });
			$("a.select").mouseover(function(){if(dd){clearTimeout(dd);};});
			$("a.select").mouseout(function(){if(document.getElementById(this.className)){timeOutHide(this.className)};});
			/* check if there is rating and turn clear on or off */
			var span = $("div.left-column").find("span");
			for(var s=0; s<span.length; s++){
				if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.className=="left-column" ){
					span[s].parentNode.parentNode.className="selected";
					var alink = span[s].getElementsByTagName("a");
					for(var i=0; i<alink.length; i++){
						var split = span[s].className.split(" ");
						if( alink[i].className.indexOf(split[0])==-1 ){
							span[s].selectedNum = alink[i].innerHTML;
						}
					}
				} else { span[s].selectedNum = "0"; }
				span[s].selectedSpan = span[s].className;
			};

			var domSetup = '<div id="right-column-curtain" style="display:none"></div>\n';
				// This is for Multiple filter Select Condition
				domSetup+= '<div id="filterConfirm" style="display:none">\n';
				domSetup+= '	<h4>Narrow my results</h4>\n';
				domSetup+= '	<p>You have chosen the following criteria to narrow your product results</p>\n';
				domSetup+= '	<div class="filtersInPlay"></div>\n';
				domSetup+= '	<br clear="all">\n';
				domSetup+= '	<input id="filterUpdate" type="image" src="'+jspStoreImgDir+'img/buttons/btn_filter.gif" value="Update my results"><input id="filterClear" type="image" src="'+jspStoreImgDir+'img/buttons/btn_clear_filter.gif" value="Clear options">\n';
				domSetup+= '	<p>You can always choose more criteria before updating your results.</p>\n';
				domSetup+= '</div>\n';
				// This is for No Results Condition
				domSetup+= '<div id="noresults" style="display:none">\n';
				if(nameOfStores.indexOf(jsonProperties.sn)<0){
					domSetup+= '    <p><b>We were unable to find a product match based on the criteria you selected.</b></p>\n';
	                domSetup+= '    <p>Try selecting different criteria or select a different combination to find a product you like</p>\n';
	                domSetup+= '    <br clear="all">\n';
	                domSetup+= '    <input id="prevResults" type="image" src="'+jspStoreImgDir+'img/buttons/btn_prev_results.gif" value="Show previous results"><input id="filterClear" type="image" src="'+jspStoreImgDir+'img/buttons/btn_clear_filter.gif" value="Clear options">\n';
				}else{
					domSetup+= '	<p><b>We\'re sorry. There are no items matching your selection. Select OK to return to your previous product view.</b></p>\n';
					domSetup+= '	<input id="prevResults" type="image" src="'+jspStoreImgDir+'img/buttons/ok_noResult.gif" value="Show previous results">\n';
				}
				domSetup+= '</div>\n';
			$('div#contentWrapper').prepend(domSetup);
			
			urlFilterParameterOnLoad="";
			// on load if for keyword page update the categories
	        var tIndex = -1;
		    var kFullUrl = location.href;
		    if(kFullUrl.indexOf("#")>=0){
		    	kFullUrl = kFullUrl.substr(0,kFullUrl.indexOf("#"));
		    }
		    var pageParam = getPaginationParam(kFullUrl);
		    if(kFullUrl.indexOf("filter=")>=0){
		   		tIndex = kFullUrl.indexOf("&",kFullUrl.indexOf("filter="));
		    	if(tIndex<0){
		    		tIndex = kFullUrl.length;
		    	}
		    	urlFilterParameterOnLoad = kFullUrl.substring(kFullUrl.indexOf("filter="),tIndex);
		    	filterParamAfterAjaxCall=urlFilterParameterOnLoad;
				}
			if(jsonProperties.dcp == false){
				if(urlFilterParameterOnLoad != null && urlFilterParameterOnLoad.length > 0){				
			    	firstTimeFlag=false;
					//ShoeFinder related fix 22267
					if (typeof gup !='undefined') {
				        var shoeFinder = gup('shoeFinder');
						if(shoeFinder !='undefined' &&  shoeFinder=='true' && parseInt(jsonForm.pageNum) == 1) {
							firstTimeFlag=true;
						}
					}
			    	lastUnselectedFlag=true;
			    	start=1;
					end=parseInt(jsonForm.viewItems);
					subCatProductCount=parseInt(jsonProducts.prodCnt);
					pageNo=parseInt(jsonForm.pageNum);	
					filterParam=urlFilterParameterOnLoad;			    	
					keywordCheck(urlFilterParameterOnLoad,"keyword");
					//Added for Search Within Search
					genExtnBreadCrumb();
				  }	
				  if(jsonProperties.kp == true){		
						updateCategoriesOnLoad(urlFilterParameterOnLoad,pageParam);
				  }
			}
			if(jsonProperties.dcp == false){
				mergeFilters(jsonFilters.filter);
				var opened = false;
				$("div.attributes").each(function() {
					if(this.style.display!="none" && (opened==false || $(this).find('h5').find('div').html()==jsonProperties.xfname)) {
						$(this).find('h5').attr('class','open');
						$(this).find('ul').show();
						// If the first filter block is 'Store', open second one also. In Keyword pages, open Store filter & Categories block alone
						if($(this).find('h5').find('div').html()!=jsonProperties.xfname) {
							opened = true;
						}
					}
				});
			}

			/* Clear Button */
			$('input[@id=filterClear]').click(function(){							
				clearInputRangeFields();
				countSelected=0;
				$("div.left-column input:checked").removeAttr("checked");
				$("div.left-column div.narrow div").removeClass("selected");
				$("div.left-column > ul li a").removeClass("selected");
				//Added For Search Within Search
				clearSearchWithin();
				var span = $("div.left-column").find("span");
				for(var s=0; s<span.length; s++){
					if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.parentNode.parentNode.className=="left-column" ){
						$(span[s].parentNode.parentNode.parentNode).removeClass("selected");
						span[s].className="no star";
						span[s].nextSibling.innerHTML="0 stars or better";
						span[s].selectedSpan = span[s].className;
						span[s].selectedNum = "0";
					};
				};
				$("div.left-column h5 a").remove();
				$("div.left-column li a").removeClass("selected");
				$('div.colorSelected').remove();
				$("div.left-column h4:eq(0) a").remove();	
				
				// Remove Sub Price Ranges
				$("li#slider div.sub_price_range").remove();
				
				/* Reset the value of Last filter to null when clear All is clicked */
				lastFilter="";				
				prefilter();								
							
				if((!firstTimeFlag) && (lastUnselectedFlag)) {
					gotoPage(1);
					ajaxImpl();
				}											
				return false;																	 
			});

			/* Star Ratings functions */
			$("li.ratings span.star a").each(function(i){

				$(this).click(function(){ 
				//Flag is set to false when ajax call happens on Go button 
				userInputPrice=false;
				/*Intialize first flag to true so that we need not add the same filter again */
				var firstFlag=true;
					$(this).parent().find('input').each(function(j){
						if(j <= i){
							$(this).attr('checked','checked');
							
							/* To append star filter to the last filter array */
							if(firstFlag==true){
							
							  /* Obtain the filter Name */
								var filterName=$(this).parent().parent().parent().parent().parent().find('h5').find('div').text();
								filterName=stringTrim(filterName);
								
								/*Append the filter name to the last Filter array*/
								lastFilter=lastFilter+","+filterName+":empty";
								firstFlag=false;
							}		
						}else{
							$(this).removeAttr('checked');
						}											 
					});
					
					$(this.parentNode.parentNode.parentNode.parentNode).addClass("selected");
					if($("div.left-column h4:eq(0) a").length<1){
						$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
						$("div.left-column h4:eq(0) a").click(clearAll);
					}
					if($(this.parentNode.parentNode.parentNode.parentNode).children("h5").children("a").length<1){
						$(this.parentNode.parentNode.parentNode.parentNode).children("h5").prepend("<a href='javaScript.html' title='Clear selections'>Clear</a>");
						$(this.parentNode.parentNode.parentNode.parentNode).children("h5").children("a").click(clearSelection);
					}
					prefilter();
					if(this.className.indexOf("selected")>=0){
									this.className=this.className.replace("selected","");
					}
					this.parentNode.selectedSpan = this.className + " star";
					this.parentNode.selectedNum = $(this).text();
					if($(this).text()=="0" || $(this).text()=="1"){
						this.parentNode.nextSibling.innerHTML = $(this).text() + " star or better";
					} else {
						this.parentNode.nextSibling.innerHTML = $(this).text() + " stars or better";
					} 
					parent.className = this.parentNode.selectedSpan;
					// Set the Offset for Update and NoResults popup
					var newTop = $(this).parent().offset();
					//newTop.top -= $('div#filterConfirm').parent().offset().top;
		            $('div#filterConfirm').css({top: newTop.top});
		            $('div#noresults').css({top: newTop.top});
					
					// Calling the Ajax implementation
					if(!multipleSelectEnabled) {
						gotoPage(1);
						ajaxImpl();
					}
					return false;
				});
			});
	
			$("li.ratings span.star a").hover(
				function(){
					if(this.className.indexOf("selected")>=0){
									this.className=this.className.replace("selected","");
					}
					this.parentNode.className = this.className + " star";
					if($(this).text()=="0" || $(this).text()=="1"){
						this.parentNode.nextSibling.innerHTML = $(this).text() + " star or better";
					} else {
						this.parentNode.nextSibling.innerHTML = $(this).text() + " stars or better";
					}
				},
				function(){
					this.parentNode.className = this.parentNode.selectedSpan;
					if(this.parentNode.selectedNum=="0" || this.parentNode.selectedNum=="1"){
						this.parentNode.nextSibling.innerHTML = this.parentNode.selectedNum + " star or better";
					} else {
						this.parentNode.nextSibling.innerHTML = this.parentNode.selectedNum + " stars or better";
					}
				}
			);
			/* glossary layer function 
			$("div.left-column div h5 img").click(function(){ glossaryView(this); return false; }); */
			/* Customize View function */
			$("li.customizeView a").click(function(){ customizeView(this); return false; });
			getURLandSetChecked();

			$('a[@id=btnPrevious]').click(prevButton);
			$('a[@id=btnNext]').click(nextButton);

			// Color Swatch Display. To process the image SRC attribute
			$('img[@id=imgColor]').each(function() {
				var imgSrc=$(this).attr('src');					
				var tempSrc=imgSrc.split("/");
				var colorName=tempSrc[tempSrc.length-1];
				while(colorName.indexOf(" ")>=0) {
					colorName=colorName.replace(" ","");
				}
				colorName=colorName.toLowerCase();
				tempSrc[tempSrc.length-1]=colorName;
				$(this).attr('src',tempSrc.join("/"));			
			});
			
			/* For Update button Click */
			$('input#filterUpdate').click(function(){
				createFilterParam();
				gotoPage(1);
				ajaxImpl();
			});
				
			$('input#prevResults').click(function(){
				previousResultsUpdate();
			});		
			$('div#leftNavWrapper div#topMenu ul#nav li a').click(function() {
				var dynamicCategoryNameInUrl=stringTrim(this.name.split("_")[this.name.split("_").length-1]);
				dynamicCategoryNameInUrl = cleanFilterParam(unescape(dynamicCategoryNameInUrl));
				if(dynamicCategoryNameInUrl!=dynamicCategoryName) {
					dynamicCategoryName = dynamicCategoryNameInUrl;
					bodyPreloader();
					gotoPage(1);								
					/*Reset values choosen for comparing items*/
					var compareParam='';
					prodCountCompare=0;
					partNumberValues=new Array(maxCompares);
					setHash();
					marketPlaceAjaxCall(ajaxUrl()+"&"+paginationParam+"&po=1");
					$('div#leftNavWrapper div#topMenu ul#nav li a').each(function(i){
						$(this).parent().attr('style','background-color:""');
					});
					$(this).parent().attr('style','background-color:#EEEEEE');
				}
				return false;
			});

		}

(function($) {
	
	//If the UI scope is not available, add it
	$.ui = $.ui || {};
	
	//Add methods that are vital for all mouse interaction stuff (plugin registering)
	$.extend($.ui, {
		plugin: {
			add: function(module, option, set) {
				var proto = $.ui[module].prototype;
				for(var i in set) {
					proto.plugins[i] = proto.plugins[i] || [];
					proto.plugins[i].push([option, set[i]]);
				}
			},
			call: function(instance, name, arguments) {
				var set = instance.plugins[name]; if(!set) return;
				for (var i = 0; i < set.length; i++) {
					if (instance.options[set[i][0]]) set[i][1].apply(instance.element, arguments);
				}
			}	
		},
		cssCache: {},
		css: function(name) {
			if ($.ui.cssCache[name]) return $.ui.cssCache[name];
			
			var tmp = $('<div class="ui-resizable-gen">').addClass(name).css(
				{position:'absolute', top:'-5000px', left:'-5000px', display:'block'}
			).appendTo('body');
			
			//Opera and Safari set width and height to 0px instead of auto
			//Safari returns rgba(0,0,0,0) when bgcolor is not set
			$.ui.cssCache[name] = !!(
				((/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
				!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
			);
			try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
			return $.ui.cssCache[name];
		},
		disableSelection: function(e) {
			if (!e) return;
			e.unselectable = "on";
			e.onselectstart = function() {	return false; };
			if (e.style) e.style.MozUserSelect = "none";
		},
		enableSelection: function(e) {
			if (!e) return;
			e.unselectable = "off";
			e.onselectstart = function() { return true; };
			if (e.style) e.style.MozUserSelect = "";
		}
	});
	
	$.fn.extend({
		mouseInteraction: function(o) {
			return this.each(function() {
				new $.ui.mouseInteraction(this, o);
			});
		},
		removeMouseInteraction: function(o) {
			return this.each(function() {
				if($.data(this, "ui-mouse"))
					$.data(this, "ui-mouse").destroy();
			});
		}
	});
	
	$.ui.mouseInteraction = function(element, options) {
	
		var self = this;
		this.element = element;
		$.data(this.element, "ui-mouse", this);
		this.options = $.extend({}, options);
		
		$(element).bind('mousedown.draggable', function() { return self.click.apply(self, arguments); });
		if($.browser.msie) $(element).attr('unselectable', 'on'); //Prevent text selection in IE
		
	};
	
	$.extend($.ui.mouseInteraction.prototype, {
		
		destroy: function() { $(this.element).unbind('mousedown.draggable'); },
		trigger: function() { return this.click.apply(this, arguments); },
		click: function(e) {
			
			if(
				   e.which != 1 //only left click starts dragging
				|| $.inArray(e.target.nodeName.toLowerCase(), this.options.dragPrevention) != -1 // Prevent execution on defined elements
				|| (this.options.condition && !this.options.condition.apply(this.options.executor || this, [e, this.element])) //Prevent execution on condition
			) return true;
			
			var self = this;
			var initialize = function() {
				self._MP = { left: e.pageX, top: e.pageY }; // Store the click mouse position
				$(document).bind('mouseup.draggable', function() { return self.stop.apply(self, arguments); });
				$(document).bind('mousemove.draggable', function() { return self.drag.apply(self, arguments); });
			};

			if(this.options.delay) {
				if(this.timer) clearInterval(this.timer);
				this.timer = setTimeout(initialize, this.options.delay);
			} else {
				initialize();
			}
			
			return false;
			
		},
		stop: function(e) {			
			
			var o = this.options;
			if(!this.initialized) return $(document).unbind('mouseup.draggable').unbind('mousemove.draggable');

			if(this.options.stop) this.options.stop.call(this.options.executor || this, e, this.element);
			$(document).unbind('mouseup.draggable').unbind('mousemove.draggable');
			this.initialized = false;
			return false;
			
		},
		drag: function(e) {

			var o = this.options;
			if ($.browser.msie && !e.button) return this.stop.apply(this, [e]); // IE mouseup check
			
			if(!this.initialized && (Math.abs(this._MP.left-e.pageX) >= o.distance || Math.abs(this._MP.top-e.pageY) >= o.distance)) {
				if(this.options.start) this.options.start.call(this.options.executor || this, e, this.element);
				this.initialized = true;
			} else {
				if(!this.initialized) return false;
			}

			if(o.drag) o.drag.call(this.options.executor || this, e, this.element);
			return false;
			
		}
	});

 })(jQuery);

(function($) {

	$.fn.extend({
		draggable: function(options) {
			var args = Array.prototype.slice.call(arguments, 1);
			
			return this.each(function() {
				if (typeof options == "string") {
					var drag = $.data(this, "ui-draggable");
					drag[options].apply(drag, args);

				} else if(!$.data(this, "ui-draggable"))
					new $.ui.draggable(this, options);
			});
		}
	});
	
	$.ui.draggable = function(element, options) {
		//Initialize needed constants
		var self = this;
		
		this.element = $(element);
		
		$.data(element, "ui-draggable", this);
		this.element.addClass("ui-draggable");
		
		//Prepare the passed options
		this.options = $.extend({}, options);
		var o = this.options;
		$.extend(o, {
			helper: o.ghosting == true ? 'clone' : (o.helper || 'original'),
			handle : o.handle ? ($(o.handle, element)[0] ? $(o.handle, element) : this.element) : this.element,
			appendTo: o.appendTo || 'parent'		
		});
		
		$(element).bind("setData.draggable", function(event, key, value){
			self.options[key] = value;
		}).bind("getData.draggable", function(event, key){
			return self.options[key];
		});
		
		//Initialize mouse events for interaction
		$(o.handle).mouseInteraction({
			executor: this,
			delay: o.delay,
			distance: o.distance || 0,
			dragPrevention: o.prevention ? o.prevention.toLowerCase().split(',') : ['input','textarea','button','select','option'],
			start: this.start,
			stop: this.stop,
			drag: this.drag,
			condition: function(e) { return !(e.target.className.indexOf("ui-resizable-handle") != -1 || this.disabled); }
		});
		
		//Position the node
		if(o.helper == 'original' && (this.element.css('position') == 'static' || this.element.css('position') == ''))
			this.element.css('position', 'relative');
		
	};
	
	$.extend($.ui.draggable.prototype, {
		plugins: {},
		ui: function(e) {
			return {
				helper: this.helper,
				position: this.position,
				absolutePosition: this.positionAbs,
				instance: this,
				options: this.options					
			};
		},
		propagate: function(n,e) {
			$.ui.plugin.call(this, n, [e, this.ui()]);
			return this.element.triggerHandler(n == "drag" ? n : "drag"+n, [e, this.ui()], this.options[n]);
		},
		destroy: function() {
			this.handle.removeMouseInteraction();
			this.element
				.removeClass("ui-draggable ui-draggable-disabled")
				.removeData("ui-draggable")
				.unbind(".draggable");
		},
		enable: function() {
			this.element.removeClass("ui-draggable-disabled");
			this.disabled = false;
		},
		disable: function() {
			this.element.addClass("ui-draggable-disabled");
			this.disabled = true;
		},
		recallOffset: function(e) {

			var elementPosition = { left: this.elementOffset.left - this.offsetParentOffset.left, top: this.elementOffset.top - this.offsetParentOffset.top };
			var r = this.helper.css('position') == 'relative';

			//Generate the original position
			this.originalPosition = {
				left: (r ? parseInt(this.helper.css('left'),10) || 0 : elementPosition.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)),
				top: (r ? parseInt(this.helper.css('top'),10) || 0 : elementPosition.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop))
			};
			
			//Generate a flexible offset that will later be subtracted from e.pageX/Y
			this.offset = {left: this._pageX - this.originalPosition.left, top: this._pageY - this.originalPosition.top };
			
		},
		start: function(e) {
			
			var o = this.options;
			if($.ui.ddmanager) $.ui.ddmanager.current = this;
			
			//Create and append the visible helper
			this.helper = typeof o.helper == 'function' ? $(o.helper.apply(this.element[0], [e])) : (o.helper == 'clone' ? this.element.clone().appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)) : this.element);
			if(this.helper[0] != this.element[0]) this.helper.css('position', 'absolute');
			if(!this.helper.parents('body').length) this.helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

			//Find out the next positioned parent
			this.offsetParent = (function(cp) {
				while(cp) {
					if(cp.style && (/(absolute|relative|fixed)/).test($.css(cp,'position'))) return $(cp);
					cp = cp.parentNode ? cp.parentNode : null;
				}; return $("body");		
			})(this.helper[0].parentNode);
			
			//Prepare variables for position generation
			this.elementOffset = this.element.offset();
			this.offsetParentOffset = this.offsetParent.offset();
			var elementPosition = { left: this.elementOffset.left - this.offsetParentOffset.left, top: this.elementOffset.top - this.offsetParentOffset.top };
			this._pageX = e.pageX; this._pageY = e.pageY;
			this.clickOffset = { left: e.pageX - this.elementOffset.left, top: e.pageY - this.elementOffset.top };
			var r = this.helper.css('position') == 'relative';

			//Generate the original position
			this.originalPosition = {
				left: (r ? parseInt(this.helper.css('left'),10) || 0 : elementPosition.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft)),
				top: (r ? parseInt(this.helper.css('top'),10) || 0 : elementPosition.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop))
			};
			
			//If we have a fixed element, we must subtract the scroll offset again
			if(this.element.css('position') == 'fixed') {
				this.originalPosition.top -= this.offsetParent[0] == document.body ? $(document).scrollTop() : this.offsetParent[0].scrollTop;
				this.originalPosition.left -= this.offsetParent[0] == document.body ? $(document).scrollLeft() : this.offsetParent[0].scrollLeft;
			}
			
			//Generate a flexible offset that will later be subtracted from e.pageX/Y
			this.offset = {left: e.pageX - this.originalPosition.left, top: e.pageY - this.originalPosition.top };
			
			//Call plugins and callbacks
			this.propagate("start", e);

			this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() };
			if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, e);
			
			//If we have something in cursorAt, we'll use it
			if(o.cursorAt) {
				if(o.cursorAt.top != undefined || o.cursorAt.bottom != undefined) {
					this.offset.top -= this.clickOffset.top - (o.cursorAt.top != undefined ? o.cursorAt.top : (this.helperProportions.height - o.cursorAt.bottom));
					this.clickOffset.top = (o.cursorAt.top != undefined ? o.cursorAt.top : (this.helperProportions.height - o.cursorAt.bottom));
				}
				if(o.cursorAt.left != undefined || o.cursorAt.right != undefined) {
					this.offset.left -= this.clickOffset.left - (o.cursorAt.left != undefined ? o.cursorAt.left : (this.helperProportions.width - o.cursorAt.right));
					this.clickOffset.left = (o.cursorAt.left != undefined ? o.cursorAt.left : (this.helperProportions.width - o.cursorAt.right));
				}
			}

			return false;

		},
		clear: function() {
			if($.ui.ddmanager) $.ui.ddmanager.current = null;
			this.helper = null;
		},
		stop: function(e) {

			//If we are using droppables, inform the manager about the drop
			if ($.ui.ddmanager && !this.options.dropBehaviour)
				$.ui.ddmanager.drop(this, e);
				
			//Call plugins and trigger callbacks
			this.propagate("stop", e);
			
			if(this.cancelHelperRemoval) return false;			
			if(this.options.helper != 'original') this.helper.remove();
			this.clear();

			return false;
		},
		drag: function(e) {

			//Compute the helpers position
			this.position = { top: e.pageY - this.offset.top, left: e.pageX - this.offset.left };
			this.positionAbs = { left: e.pageX - this.clickOffset.left, top: e.pageY - this.clickOffset.top };

			//Call plugins and callbacks			
			this.position = this.propagate("drag", e) || this.position;
			
			this.helper.css({ left: this.position.left+'px', top: this.position.top+'px' }); // Stick the helper to the cursor
			if($.ui.ddmanager) $.ui.ddmanager.drag(this, e);
			return false;
			
		}
	});

})(jQuery);

(function($) {

	$.ui.plugin.add("draggable", "cursor", {
		start: function(e,ui) {
			var t = $('body');
			if (t.css("cursor")) ui.options._cursor = t.css("cursor");
			t.css("cursor", ui.options.cursor);
		},
		stop: function(e,ui) {
			if (ui.options._cursor) $('body').css("cursor", ui.options._cursor);
		}
	});

	$.ui.plugin.add("draggable", "zIndex", {
		start: function(e,ui) {
			var t = $(ui.helper);
			if(t.css("zIndex")) ui.options._zIndex = t.css("zIndex");
			t.css('zIndex', ui.options.zIndex);
		},
		stop: function(e,ui) {
			if(ui.options._zIndex) $(ui.helper).css('zIndex', ui.options._zIndex);
		}
	});

	$.ui.plugin.add("draggable", "opacity", {
		start: function(e,ui) {
			var t = $(ui.helper);
			if(t.css("opacity")) ui.options._opacity = t.css("opacity");
			t.css('opacity', ui.options.opacity);
		},
		stop: function(e,ui) {
			if(ui.options._opacity) $(ui.helper).css('opacity', ui.options._opacity);
		}
	});


	$.ui.plugin.add("draggable", "revert", {
		stop: function(e,ui) {
			var self = ui.instance;
			self.cancelHelperRemoval = true;
			$(ui.helper).animate({ left: self.originalPosition.left, top: self.originalPosition.top }, parseInt(ui.options.revert, 10) || 500, function() {
				if(ui.options.helper != 'original') self.helper.remove();
				self.clear();
			});
		}
	});

	$.ui.plugin.add("draggable", "iframeFix", {
		start: function(e,ui) {

			var o = ui.options;
			if(ui.instance.slowMode) return; // Make clones on top of iframes (only if we are not in slowMode)
			
			if(o.iframeFix.constructor == Array) {
				for(var i=0;i<o.iframeFix.length;i++) {
					var co = $(o.iframeFix[i]).offset({ border: false });
					$('<div class="DragDropIframeFix"" style="background: #fff;"></div>').css("width", $(o.iframeFix[i])[0].offsetWidth+"px").css("height", $(o.iframeFix[i])[0].offsetHeight+"px").css("position", "absolute").css("opacity", "0.001").css("z-index", "1000").css("top", co.top+"px").css("left", co.left+"px").appendTo("body");
				}		
			} else {
				$("iframe").each(function() {					
					var co = $(this).offset({ border: false });
					$('<div class="DragDropIframeFix" style="background: #fff;"></div>').css("width", this.offsetWidth+"px").css("height", this.offsetHeight+"px").css("position", "absolute").css("opacity", "0.001").css("z-index", "1000").css("top", co.top+"px").css("left", co.left+"px").appendTo("body");
				});							
			}

		},
		stop: function(e,ui) {
			if(ui.options.iframeFix) $("div.DragDropIframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers	
		}
	});
	
	$.ui.plugin.add("draggable", "containment", {
		start: function(e,ui) {

			var o = ui.options;
			if((o.containment.left != undefined || o.containment.constructor == Array) && !o._containment) return;
			if(!o._containment) o._containment = o.containment;

			if(o._containment == 'parent') o._containment = this[0].parentNode;
			if(o._containment == 'document') {
				o.containment = [
					0,
					0,
					$(document).width(),
					($(document).height() || document.body.parentNode.scrollHeight)
				];
			} else { //I'm a node, so compute top/left/right/bottom

				var ce = $(o._containment)[0];
				var co = $(o._containment).offset();

				o.containment = [
					co.left,
					co.top,
					co.left+(ce.offsetWidth || ce.scrollWidth),
					co.top+(ce.offsetHeight || ce.scrollHeight)
				];
			}

		},
		drag: function(e,ui) {

			var o = ui.options;
			var h = ui.helper;
			var c = o.containment;
			var self = ui.instance;
			
			if(c.constructor == Array) {
				if((ui.absolutePosition.left < c[0])) self.position.left = c[0] - (self.offset.left - self.clickOffset.left);
				if((ui.absolutePosition.top < c[1])) self.position.top = c[1] - (self.offset.top - self.clickOffset.top);
				if(ui.absolutePosition.left - c[2] + self.helperProportions.width >= 0) self.position.left = c[2] - (self.offset.left - self.clickOffset.left) - self.helperProportions.width;
				if(ui.absolutePosition.top - c[3] + self.helperProportions.height >= 0) self.position.top = c[3] - (self.offset.top - self.clickOffset.top) - self.helperProportions.height;
			} else {
				if((ui.position.left < c.left)) self.position.left = c.left;
				if((ui.position.top < c.top)) self.position.top = c.top;
				if(ui.position.left - self.offsetParent.innerWidth() + self.helperProportions.width + c.right + (parseInt(self.offsetParent.css("borderLeftWidth"), 10) || 0) + (parseInt(self.offsetParent.css("borderRightWidth"), 10) || 0) >= 0) self.position.left = self.offsetParent.innerWidth() - self.helperProportions.width - c.right - (parseInt(self.offsetParent.css("borderLeftWidth"), 10) || 0) - (parseInt(self.offsetParent.css("borderRightWidth"), 10) || 0);
				if(ui.position.top - self.offsetParent.innerHeight() + self.helperProportions.height + c.bottom + (parseInt(self.offsetParent.css("borderTopWidth"), 10) || 0) + (parseInt(self.offsetParent.css("borderBottomWidth"), 10) || 0) >= 0) self.position.top = self.offsetParent.innerHeight() - self.helperProportions.height - c.bottom - (parseInt(self.offsetParent.css("borderTopWidth"), 10) || 0) - (parseInt(self.offsetParent.css("borderBottomWidth"), 10) || 0);
			}

		}
	});

	$.ui.plugin.add("draggable", "grid", {
		drag: function(e,ui) {
			var o = ui.options;
			ui.instance.position.left = ui.instance.originalPosition.left + Math.round((e.pageX - ui.instance._pageX) / o.grid[0]) * o.grid[0];
			ui.instance.position.top = ui.instance.originalPosition.top + Math.round((e.pageY - ui.instance._pageY) / o.grid[1]) * o.grid[1];
		}
	});

	$.ui.plugin.add("draggable", "axis", {
		drag: function(e,ui) {
			var o = ui.options;
			if(o.constraint) o.axis = o.constraint; //Legacy check
			o.axis == 'x' ? ui.instance.position.top = ui.instance.originalPosition.top : ui.instance.position.left = ui.instance.originalPosition.left;
		}
	});

	$.ui.plugin.add("draggable", "scroll", {
		start: function(e,ui) {
			var o = ui.options;
			o.scrollSensitivity	= o.scrollSensitivity || 20;
			o.scrollSpeed		= o.scrollSpeed || 20;

			ui.instance.overflowY = function(el) {
				do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-y'))) return el; el = el.parent(); } while (el[0].parentNode);
				return $(document);
			}(this);
			ui.instance.overflowX = function(el) {
				do { if(/auto|scroll/.test(el.css('overflow')) || (/auto|scroll/).test(el.css('overflow-x'))) return el; el = el.parent(); } while (el[0].parentNode);
				return $(document);
			}(this);
		},
		drag: function(e,ui) {
			
			var o = ui.options;
			var i = ui.instance;

			if(i.overflowY[0] != document && i.overflowY[0].tagName != 'HTML') {
				if(i.overflowY[0].offsetHeight - (ui.position.top - i.overflowY[0].scrollTop + i.clickOffset.top) < o.scrollSensitivity)
					i.overflowY[0].scrollTop = i.overflowY[0].scrollTop + o.scrollSpeed;
				if((ui.position.top - i.overflowY[0].scrollTop + i.clickOffset.top) < o.scrollSensitivity)
					i.overflowY[0].scrollTop = i.overflowY[0].scrollTop - o.scrollSpeed;				
			} else {
				//$(document.body).append('<p>'+(e.pageY - $(document).scrollTop())+'</p>');
				if(e.pageY - $(document).scrollTop() < o.scrollSensitivity)
					$(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				if($(window).height() - (e.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					$(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}
			
			if(i.overflowX[0] != document && i.overflowX[0].tagName != 'HTML') {
				if(i.overflowX[0].offsetWidth - (ui.position.left - i.overflowX[0].scrollLeft + i.clickOffset.left) < o.scrollSensitivity)
					i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft + o.scrollSpeed;
				if((ui.position.top - i.overflowX[0].scrollLeft + i.clickOffset.left) < o.scrollSensitivity)
					i.overflowX[0].scrollLeft = i.overflowX[0].scrollLeft - o.scrollSpeed;				
			} else {
				if(e.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					$(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				if($(window).width() - (e.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					$(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}
			
			ui.instance.recallOffset(e);

		}
	});
	
	$.ui.plugin.add("draggable", "snap", {
		start: function(e,ui) {
			
			ui.instance.snapElements = [];
			$(ui.options.snap === true ? '.ui-draggable' : ui.options.snap).each(function() {
				var $t = $(this); var $o = $t.offset();
				if(this != ui.instance.element[0]) ui.instance.snapElements.push({
					item: this,
					width: $t.outerWidth(),
					height: $t.outerHeight(),
					top: $o.top,
					left: $o.left
				});
			});
			
		},
		drag: function(e,ui) {

			var d = ui.options.snapTolerance || 20;
			var x1 = ui.absolutePosition.left, x2 = x1 + ui.instance.helperProportions.width,
			    y1 = ui.absolutePosition.top, y2 = y1 + ui.instance.helperProportions.height;

			for (var i = ui.instance.snapElements.length - 1; i >= 0; i--){

				var l = ui.instance.snapElements[i].left, r = l + ui.instance.snapElements[i].width, 
				    t = ui.instance.snapElements[i].top,  b = t + ui.instance.snapElements[i].height;

				//Yes, I know, this is insane ;)
				if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) continue;

				if(ui.options.snapMode != 'inner') {
					var ts = Math.abs(t - y2) <= 20;
					var bs = Math.abs(b - y1) <= 20;
					var ls = Math.abs(l - x2) <= 20;
					var rs = Math.abs(r - x1) <= 20;
					if(ts) ui.position.top = t - ui.instance.offset.top + ui.instance.clickOffset.top - ui.instance.helperProportions.height;
					if(bs) ui.position.top = b - ui.instance.offset.top + ui.instance.clickOffset.top;
					if(ls) ui.position.left = l - ui.instance.offset.left + ui.instance.clickOffset.left - ui.instance.helperProportions.width;
					if(rs) ui.position.left = r - ui.instance.offset.left + ui.instance.clickOffset.left;
				}
				
				if(ui.options.snapMode != 'outer') {
					var ts = Math.abs(t - y1) <= 20;
					var bs = Math.abs(b - y2) <= 20;
					var ls = Math.abs(l - x1) <= 20;
					var rs = Math.abs(r - x2) <= 20;
					if(ts) ui.position.top = t - ui.instance.offset.top + ui.instance.clickOffset.top;
					if(bs) ui.position.top = b - ui.instance.offset.top + ui.instance.clickOffset.top - ui.instance.helperProportions.height;
					if(ls) ui.position.left = l - ui.instance.offset.left + ui.instance.clickOffset.left;
					if(rs) ui.position.left = r - ui.instance.offset.left + ui.instance.clickOffset.left - ui.instance.helperProportions.width;
				}

			};
		}
	});

	//TODO: wrapHelper, snap

})(jQuery);
	if(jsonProperties.dcp == false && jsonFilters != undefined && jsonFilters.filter.length > 0 && jsonFilters.filter[jsonFilters.filter.length-1].fn=="Price"){
		var priceNode = jsonFilters.filter[jsonFilters.filter.length-1].fv;
		defaultMinPriceValue = priceNode[0].fvn.split("|")[0];
		defaultMaxPriceValue = priceNode[0].fvn.split("|")[1];
		if(isI18NConvReq()){
			defaultMinPriceValue = performConversion(defaultMinPriceValue);
			defaultMaxPriceValue = performConversion(defaultMaxPriceValue);
		}
		}	
		}
		
	// CAll function to resume the previous the state of the page
	resumeState();
	//Function call for checkboxes to be checked
	initCompareCheckBox();
	// Display filter items with/without scroll bar
	updateFilterslider();
	
	// PRICE USER INPUT ENHANCEMENT	-STARTS	
	$("input#range_low").keypress(function validateNumeric(event) {
		if (event.which!=46 && event.which!=8 && event.which!=0	&& (event.which<48 || event.which>57)) {
			//Accept numbers, dot and special keys like delete or the arrow keys
			event.preventDefault();
		} else {
			if (event.which==46) { //dot					
				if ($("input#range_low").val().indexOf(".")>=0) event.preventDefault();			
			}
		}
	});
	$("input#range_high").keypress(function validateNumeric(event) {
		if (event.which!=46 && event.which!=8 && event.which!=0	&& (event.which<48 || event.which>57)) {
			//Accept numbers, dot and special keys like delete or the arrow keys
			event.preventDefault();
		} else {
			if (event.which==46) { //dot					
				if ($("input#range_high").val().indexOf(".")>=0) event.preventDefault();			
			}
		}
		if(event.keyCode == 13){
			document.getElementById('rangeButton').click()
		}
	});
	//$("#rangeButton").click(priceClickRangeGo);
	$("#rangeButton").click(inputRangeButtonError);
	$("#clearFields").click(clearInputRangeFields);
	//PRICE USER INPUT ENHANCEMENT - ENDS
	
	
	//Set the lay-out based on the cookie
	var gridCookieValue = getCookieValue("gridIndicator");
	if(gridCookieValue != "" && gridCookieValue == "true" && ($('div#results').attr('class') == 'row')) {
		Switch.grid();
		
	} else if(gridCookieValue != "" && gridCookieValue == "false"  && ($('div#results').attr('class') == 'grid')) {
		Switch.row();
		
	}
});
/* DOM READY CALLS for Server Side Flow - Ends Here */

function leftColCheckBoxChecked(){
	var checkedCount = 0;
	var ieCount = 0;
	if($.browser.msie){
	    ieCount = 0;
		$('div.left-column').find('input').each(function(i){
			if($(this).parent().attr("class") == "selected"){
				ieCount++;
			}

		});
	}
	checkedCount = $('div.left-column div.attributes ul li input:checked').length + ieCount;
	//Added for User Input Price Enhancement
	//Condtion for checking whether User input text Boxes are present.
	var range_low = $("#range_low").val();
							if(isI18NConvReq()){
								range_low = performReversion($("#range_low").val());
							}
							var range_high = $("#range_high").val();
							if(isI18NConvReq()){
								range_high = performReversion($("#range_high").val());
							}	
	
	if(typeof range_low != 'undefined' && typeof range_high != 'undefined'){
		//Check whether any values are present inside the price text boxes
		if( range_low.length > 0 || range_high.length > 0){
			checkedCount =checkedCount +1;
		}	
	}
	/* Added for Search Within Search - start */
	var searchwithin = $("div.left-column #search_within_box").val();
	if(typeof searchwithin != 'undefined'){
		//Check whether any values are present inside the price text boxes
		if(searchwithin.length > 0){
			checkedCount = checkedCount + 1;
		}	
	}
	/* Added for Search Within Search - End */	
	return checkedCount;
}

//<-- ADDED BY ANDY 12-17-07--//
/* Iterates through the checkboxes and forms an array of checkboxes that are checked currently */
function prefilter(params){
      // PRICE USER INPUT ENHANCEMENT
	params=params||new Object();
	/*Reset values choosen for comparing items*/
	var compareParam='';
	prodCountCompare=0;
	partNumberValues=new Array(maxCompares);

	// Set the value of multiple select
	$('div#filterConfirm .filtersInPlay').empty();
	if(leftColCheckBoxChecked() > 0 || params.useRangeForm || params.searchWitinForm){
		var colCounter = 0;
		filters=[];
		var glob = this;
		$('div.left-column div.attributes ul').each(function(i){
			if($(this).attr("id") == "searchwithin" && $(this).find('input#search_within_box').val() != '') {
				filters.push({ 'title': 'searchwithin', 'selected': [] });
				$(this).find('input#search_within_box').val(ValidateSearchwithinTxt($(this).find('input#search_within_box').val()));
				filters[i].selected = $(this).find('input#search_within_box').val().split(",");
			} else {
			var title = $(this).parent().find('h5').find('div').text();

			filters.push({ 'title': title, 'selected': [] });
			var values = [];
			$(this).find('input:checked').each(function(){
				// For price ranges manipulate the id instead of name Price Ranges' Enhancement
				if(title=="Price") {
					values.push(this.id);}
				else{
				values.push( this.name);
				}
			});
			filters[i].selected = values;
		}
		});

		$('div#filterConfirm .filtersInPlay').append('<div class="filterColumn"></div>');
		var currCol = $('div#filterConfirm .filtersInPlay .filterColumn:eq('+colCounter+')');
		$(filters).each(function(a){
			if(this.title == "User Ratings"){
				if(this.selected.length > 1){
					this.selected = [this.selected[this.selected.length-1] + " stars or better"];
				} else if(this.selected.length > 0){
					this.selected = [this.selected[this.selected.length-1] + " star or better"];
				}
			}			
			if( this.selected.length > 0){
				$(currCol).append('<p class="fTitle"><b>'+this.title+'</b></p>');
				if($(currCol).height() > 168){
					colCounter++;
					$('div#filterConfirm .filtersInPlay').append('<div class="filterColumn"></div>');
					currCol = $('div#filterConfirm .filtersInPlay .filterColumn:eq('+colCounter+')');
				}
				if(this.selected.length > 1){
				$(this.selected).each(function(i){
					$(currCol).append('<p class="fName">&bull;'+this+'</p>');
					if($(currCol).height() > 168){
						colCounter++;
						$('div#filterConfirm .filtersInPlay').append('<div class="filterColumn"></div>');
						currCol = $('div#filterConfirm .filtersInPlay .filterColumn:eq('+colCounter+')');
					}
				});
				}else{
					$(currCol).append('<p class="fName">&bull;&nbsp;'+this.selected+'</p>');
					if($(currCol).height() > 168){
						colCounter++;
						$('div#filterConfirm .filtersInPlay').append('<div class="filterColumn"></div>');
						currCol = $('div#filterConfirm .filtersInPlay .filterColumn:eq('+colCounter+')');
					}	
				}
			}
		});

		/* If multiple selection option is enabled. Display the right curtain */
		if((multipleSelectEnabled) && (!hasNoResults)) {
			$('div#noresults').hide();
			$('div#filterConfirm .filtersInPlay').append('<br clear="all">');
			if($.browser.msie){$('div#filterConfirm .filtersInPlay').append('<br clear="all">')};
			$('div#right-column-curtain').show().height($('.right-column').height()+5);
		    $('div#filterConfirm').show();
		} else {
			// Call function to create the filter parameters
			createFilterParam(params);
		}
	}else{
		filters=[];
		filterParam="";
		$('div#right-column-curtain').hide();
		$('div#filterConfirm').hide();	
		$('div#noresults').hide();
	}
}

// Returns the pagination param if present in the given string (sets pageNum=1), otherwise returns empty string
function getPaginationParam(str){
	var paginParam = "";
	if(str != null && str.length >0){
		if((str.indexOf("viewItems=")>=0) || (str.indexOf("pageNum=")>=0) || (str.indexOf("sortOption=")>=0) || (str.indexOf("shopBy=")>=0)){
			var strArray = str.split("&");
			for(i=0;i<strArray.length;i++){
			if(strArray[i].indexOf("viewItems=")>=0){
					if(paginParam != null && paginParam.length > 0){
						paginParam = paginParam +"&"+strArray[i]+"&pageNum=1";
					}else{
						paginParam = paginParam + strArray[i]+"&pageNum=1";
					}
				}
				if(strArray[i].indexOf("sortOption=")>=0){
					if(paginParam != null && paginParam.length > 0){
						paginParam = paginParam +"&"+strArray[i];
					}else{
						paginParam = paginParam + strArray[i];
					}
				}
				if(strArray[i].indexOf("shopBy=")>=0){
					if(paginParam != null && paginParam.length > 0){
						paginParam = paginParam +"&"+strArray[i];
					}else{
						paginParam = paginParam + strArray[i];
					}
				}														
			}	
		}
	}
	return paginParam;		
}

function updateCategoriesOnLoad(filterParameter,paginParam){
	var newHref = "";	
	var tempIndex = -1;	
	var tempFilterParam = filterParameter;
	if(filterParameter.indexOf("&lastFilter=")>=0){
		tempFilterParam = filterParam.split(("&lastFilter="))[0];
	}
	//User Input Price Enhancement
	if(location.href.indexOf("&goBtn=true")>=0){
		tempFilterParam+="&goBtn=true";	
	}
	tempIndex = tempFilterParam.indexOf("filter=");
	var addFilter = "";
	if(tempIndex>=0){
		addFilter = tempFilterParam.substring(tempIndex,tempFilterParam.length);
	}
	if(addFilter != null && addFilter.length > 0 && paginParam != null && paginParam.length > 0 ){
		addFilter += "&"+paginParam;
	}
	else{
		addFilter += paginParam;
	}
	if(addFilter != null && addFilter.length > 0){
		$("div.left-column div.attributes ul.firstShown li").each(function(i){
			if($(this).find("a").attr('id') == "false"){
				newHref = $(this).find("a").attr('href');
				newHref+="&"+addFilter;
				$(this).find("a").attr('href',newHref);
			}
		});
	}
}

function clearFilters(){
	//Remove all filters
	$("div.left-column input:checked").removeAttr("checked");
	$("div.left-column div.narrow div").removeClass("selected");
	$("div.left-column > ul li a").removeClass("selected");
	
	var span = $("div.left-column").find("span");
	for(var s=0; s<span.length; s++){
		if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.parentNode.parentNode.className=="left-column" ){
			$(span[s].parentNode.parentNode.parentNode).removeClass("selected");
			span[s].className="no star";
			span[s].nextSibling.innerHTML="0 stars or better";
			span[s].selectedSpan = span[s].className;
			span[s].selectedNum = "0";
		};
    };
	$("div.left-column h5 a").remove();
	$("div.left-column li a").removeClass("selected");
	$('div.colorSelected').remove();		
}

	/*Common function */
	function commonPagination() {
				var curPage,totalProducts,productPerPage,sortOption;
			// Initialize the pagination parameters
				sortOption=jsonForm.sortOption;
				curPage=parseInt(jsonForm.pageNum);
				totalProducts=parseInt(jsonProducts.prodCnt);
				productPerPage=parseInt(jsonForm.viewItems);
				if(totalProducts!="" && totalProducts > 0 && productPerPage!="" && productPerPage > 0 && curPage!="" && curPage > 0 ) {	
					paginationParam="viewItems="+productPerPage+"&pageNum="+curPage+"&sortOption="+sortOption;
					defaultPaginationParam="viewItems="+productPerPage+"&pageNum="+curPage+"&sortOption="+sortOption;
				}
	}

	/*Function to implement Previous button*/
	function prevButton() {
		var productPerPage;
		if(firstTimeFlag==true) {
		// initialize the pagination parameters
			subCatProductCount=parseInt(jsonProducts.prodCnt);
			productPerPage=parseInt(jsonForm.viewItems);
			pageNo=parseInt(jsonForm.pageNum);
		}else {
			/*Number of products per page */
			productPerPage=(end-start)+1;
		}
		
		if(subCatProductCount!="" && subCatProductCount > 0 && productPerPage!="" && productPerPage > 0 && pageNo!="" && pageNo>0 ) {
			/*If we are in the first Page*/	
			if(pageNo==1){
				
			}else{
				var prePage=--pageNo;
			
				var tempParam=paginationParam.split("&");
				tempParam[1]="pageNum="+prePage;
				paginationParam=tempParam.join("&");	
	
				ajaxImpl();
			}
			
		}
		return false;
	}
	/*Function to implement Next button*/
	function nextButton() {
		var productPerPage;
		if(firstTimeFlag==true) {
		// initialize the pagination parameters
			subCatProductCount=parseInt(jsonProducts.prodCnt);
			productPerPage=parseInt(jsonForm.viewItems);
			pageNo=parseInt(jsonForm.pageNum);
		}else {
			/*Number of products per page */
			productPerPage=(end-start)+1;
		}		
		/* Calculate total number of pages*/
		var totPage=Math.ceil(subCatProductCount/productPerPage);
	
		if(subCatProductCount!="" && subCatProductCount > 0 && productPerPage!="" && productPerPage > 0 && pageNo!="" && pageNo>0) {
			if(pageNo>=totPage){
							
			}else{
				var nextPage=++pageNo;
				var tempParam=paginationParam.split("&");
				tempParam[1]="pageNum="+nextPage;
				paginationParam=tempParam.join("&");
				ajaxImpl();
			}
		}
		return false;
	}
	
	/* Function for Goto Page Drop Down Box 
	Appends The selected page no to the paginationParam */
	function gotoPage(pageNum) {	
		var tempParam=paginationParam.split("&");
		tempParam[1]="pageNum="+pageNum;
		paginationParam=tempParam.join("&");	
	}
	
	/* Function for View per page Drop Down Box 
	Appends The selected no of items to the paginationParam */
	function viewPerPage(itemsPerPage) {
		var tempParam=paginationParam.split("&");
		if(tempParam[0].split("=")[1]!=itemsPerPage) {
		paginationParam="viewItems="+itemsPerPage+"&pageNum=1"+"&"+tempParam[2];		
		ajaxImpl();
		}
	}
	
	/* Function for View per page Drop Down Box 
	Appends The selected no of items to the paginationParam */
	function sortOptionSelect(sortBy) {
		var tempParam=paginationParam.split("&");
		if(tempParam[2].split("=")[1]!=sortBy) {
		paginationParam=tempParam[0]+"&pageNum=1"+"&sortOption="+sortBy;
		ajaxImpl();
		}
	}
	
	function setHash(){
		if(!($.browser.safari)) {
			if(filterParam!=""){
				if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))
				{	
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam+"&shopBy="+shopBy+"&&"+undoCleanFilterParam(filterParam));
				}
				else
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam+"&&"+undoCleanFilterParam(filterParam));	
			} else if(dynamicCategoryName!="") {
				if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))
				{	
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam+"&shopBy="+shopBy+"&&sName="+undoCleanFilterParam(dynamicCategoryName));
				}
				else
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam+"&&sName="+undoCleanFilterParam(dynamicCategoryName));	
			} else {
				if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))
				{	
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam+"&shopBy="+shopBy);
				}
				else
					location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam);
			}
		}
	}

	/* Ajax MEthod */
	function ajaxImpl(){
	/*User Price Input Enhancement */
		if($('#tempWrap').val()!='undefined' && $('#tempContent').val()!='undefined'){
			$('#tempWrap').remove();
			$('#tempContent').remove();
		}

		// Call the function to set the URL.
		setHash();
		// Ajax Code
		var remoteUrl=ajaxUrl();
		remoteUrl = remoteUrl+"&"+paginationParam;
		if(filterParam!="") {
			remoteUrl=remoteUrl+"&"+filterParam;
		} 
		
		if(filterParamAfterAjaxCall==filterParam && remoteUrl.indexOf("&po=1")== -1){
			remoteUrl=remoteUrl+"&po=1";
		}
		remoteUrl=remoteUrl+"&pav="+pavValue;
		remoteUrl=remoteUrl.replace("&&","&");
		if(remoteUrl!="") { 
			if(remoteUrl!=urlAfterAjaxCall) {
				if(fromProductPage==false) {
					bodyPreloader();
				}
				marketPlaceAjaxCall(remoteUrl);	
			}
			else {
				bodyPreloader();
				$('div#body-curtain').hide();
				$('div.progress').hide();
				$('div#right-column-curtain').hide();
				$('div#noresults').hide();
				$("div#filterConfirm").hide();
			}
		}	
	};

    //	 Function for Shop By Drop Down start
	function shopByOption(shopByValue){
		if(shopByValue=="ship"){
		// replacing "All items" with "Shippable Items"
			$('div#shopByHeader').find("a.select").text(jsonProperties.sbship);
			// replacing "Shippable Items" with "All Items"
			$('div#shopByHeader').find("a.ship").text(jsonProperties.sball);
			// replacing All Items with In-store Items
			$('div#shopByHeader').find("a.spu").text(jsonProperties.sbspu);
		}else if(shopByValue=="spu"){
			// replacing All Items with In-store Items
			$('div#shopByHeader').find("a.select").text(jsonProperties.sbspu);
			// replacing Shippable Items with All Items
			$('div#shopByHeader').find("a.ship").text(jsonProperties.sball);
			// replacing In-store Items with Shippable Items
			$('div#shopByHeader').find("a.spu").text(jsonProperties.sbship);
		}else {
			// replacing Shippable Items with All Items
			$('div#shopByHeader').find("a.select").text(jsonProperties.sball);
			// replacing In-store Items with Shippable Items
			$('div#shopByHeader').find("a.ship").text(jsonProperties.sbship);
			// replacing All Items with In-store Items
			$('div#shopByHeader').find("a.spu").text(jsonProperties.sbspu);
		}		
	}
	//	Function for Shop By Drop Down Ends
	
	//Function to Update the Product URLs with Availabilty and Quantity

      function updateProductURL(ksn,avl,oriQty){
              //Iterate through all the products with same ksn number
              $('div[@id=pro_'+ksn+']').find("div.photo").find("a").each(function(i){
                    var avlProductURL=$(this).attr("href");                       

                    if(avlProductURL.indexOf("?") >= 0){
                       //append Availability status and quantity parameters

                    avlProductURL+="&avl="+avl+"&oriQty="+oriQty;
                          $(this).attr("href",avlProductURL);
                    }else{
                           //append Availability status and quantity parameters
                           avlProductURL+="?avl="+avl+"&oriQty="+oriQty;
                           $(this).attr("href",avlProductURL);
                    }

              });

              //Iterate through all the products with same ksn number
              $('div[@id=pro_'+ksn+']').find("div.info").find("p#prodUrl").find("a").each(function(i){
                    var avlProductURL=$(this).attr("href");                       

                    if(   avlProductURL.indexOf("?") >= 0){
                       //append Availability status and quantity parameters
                    avlProductURL+="&avl="+avl+"&oriQty="+oriQty;
                          $(this).attr("href",avlProductURL);
                    }else{
                           //append Availability status and quantity parameters
                           avlProductURL+="?avl="+avl+"&oriQty="+oriQty;
                           $(this).attr("href",avlProductURL);
					}              
			});   
		}

	
	// Function to Update the availability and price
	function updateSpuPriceAvail(jsonRegPriceAvi) {
      if(fnCheckCookie() && typeof jsonRegPriceAvi != 'undefined' && typeof jsonRegPriceAvi.pco != 'undefined'){
	    	var size=jsonRegPriceAvi.pco;
	    	var storedetails=storeName.titleCase()+" Store "+city.titleCase()+" "+state+" "+zipCode;
	    	for(var availCounter=0;availCounter<size;availCounter++){
	    	
	    		var avl=jsonRegPriceAvi.price[availCounter].avl;
				var ksn=jsonRegPriceAvi.price[availCounter].pId;
				var oriQty=jsonRegPriceAvi.price[availCounter].oriQty;

	    		
				var currProd = $('div[@id=pro_'+jsonRegPriceAvi.price[availCounter].pId+']');
	         	//Availabilty updation
	         	if(jsonRegPriceAvi.price[availCounter].avl=="N"){
	         		//Obtaining the catentry id for the product
	         		 var catentryValue=$('div#'+jsonRegPriceAvi.price[availCounter].pId).text();	
	         		 $(currProd).find("div p.spu_in").attr("class","spu_oos");
	         		 $(currProd).find("div p.spu_elig").attr("class","spu_oos");
	         		 $(currProd).find("div p.spu_oos").text(jsonProperties.spuOos+" "+storedetails+" - ");	         		 
	         		 $(currProd).find("div p.spu_oos").append("<a href=\"javascript:;\" id='checkOtherStores'><input type=\"hidden\" id="+jsonRegPriceAvi.price[availCounter].pId+" value="+catentryValue+">Check other stores</a>");
	         		 $(currProd).find("div.price").find("fieldset.addToCart").attr("style","display: none");
	         		 $(currProd).find('div.divAddToOrder').attr("style","display: none");
	         		 
	         	}else if(jsonRegPriceAvi.price[availCounter].avl=="Y"){
	            	 $(currProd).find("div p.spu_oos").attr("class","spu_in");	
	               	 $(currProd).find("div p.spu_elig").attr("class","spu_in");
	            	 $(currProd).find("div p.spu_in").text(jsonProperties.spuInStock+" "+storedetails);
	            	 $(currProd).find("div.price").find("fieldset.addToCart").attr("style","display: block");
	         		 $(currProd).find('div.divAddToOrder').attr("style","display: block");
	         		 
		        }else if(jsonRegPriceAvi.price[availCounter].avl=="NA"){
	            	 //Obtaining the catentry id for the product
	            	 var catentryValue=$('div#'+jsonRegPriceAvi.price[availCounter].pId).text();   
	            	 $(currProd).find("div p.spu_in").attr("class","spu_oos");
	         		 $(currProd).find("div p.spu_elig").attr("class","spu_oos");
	         		 $(currProd).find("div p.spu_oos").text(jsonProperties.spuItemNC+" "+storedetails+" - ");
	         		 $(currProd).find("div p.spu_oos").append("<a href=\"javascript:;\" id='checkOtherStores'><input type=\"hidden\" id="+jsonRegPriceAvi.price[availCounter].pId+" value="+catentryValue+">Check other stores</a>");
	         		 $(currProd).find("div.price").find('fieldset.addToCart').attr("style","display: none");
	         		 $(currProd).find('div.divAddToOrder').attr("style","display: none");	         		
 	         		
	         	}
	         	 //Function to Update the Product URLs with Availabilty and Quantity
	         	updateProductURL(ksn,avl,oriQty);
	            //Regional price updation //&& (jsonRegPriceAvi.price[availCounter].isEx!="" && jsonRegPriceAvi.price[availCounter].isEx!=null)
	            if((jsonRegPriceAvi.price[availCounter].isEx==false || jsonRegPriceAvi.price[availCounter].isEx=="") && jsonRegPriceAvi.price[availCounter].rpr.length > 0 ){ 	
	           		 $(currProd).find("div#youPay").find("span.text").text("You Pay:");
	            	 $(currProd).find("div#youPay").find("span.pricing").text("$"+jsonRegPriceAvi.price[availCounter].rpr);
	            	 $(currProd).find("div.lpMsgGrd").attr("style","display: block");
	            	 $(currProd).find("div.lpMsgGrd").text(jsonProperties.localPrice.replace(/\&amp;/g,'&'));
	            	 $(currProd).find("div.lpMsgRow").attr("style","display: none");
	         		 $(currProd).find("div.lpMsgRow").text(jsonProperties.localPrice.replace(/\&amp;/g,'&'));
					 $(currProd).find("div.saveStory").attr("style","display: block");
					 $(currProd).find('div.saveStory').find('div').attr("style","display: none");
					 $(currProd).find('div.saveStory').find('div#youPay').attr("style","display: block");
	            }else if(jsonRegPriceAvi.price[availCounter].isEx==true || jsonRegPriceAvi.price[availCounter].rpr.length==0 ){
	            	$(currProd).find("div.saveStory").attr("style","display: block");
	            	$(currProd).find('div.saveStory').find('div').attr("style","display: block");
	            	$(currProd).find('div.saveStory').find('div.youPay').attr("style","display: block");
	            	$(currProd).find('div.saveStory').find("div#youPay").attr("style","display: none");
	            } 
				
	    	} 	
	   } 
	   checkNearByStores();					
	}
/* Function to repaint the products if ZipCode is selected and DFF is DDC */
function repaintRegAvial(availValues,partNumArr){
	var ZipCodeVal=getRegDelZip();
	if(fnChkZipCode()){
		if(getCookieValue('zipCode')==null){
			cookieNameDel = 'zipCode';
			setCookieValue(cookieNameDel,ZipCodeVal);
		}
	for(var availCnt=0;availCnt<partNumArr.length;availCnt++){	    		
			if(typeof availValues.Get(partNumArr[availCnt])!='undefined'){
    		ddcMsg = availValues.Get(partNumArr[availCnt]);	
			$('div.availability').find('li#part_'+partNumArr[availCnt]).text(ddcMsg+" "+ZipCodeVal+". ");
			$('div.availability').find('li#part_'+partNumArr[availCnt]).append('<a href=\"javascript:;\" id=\"changeZip\" class=\"changeZip\" rel=\"regionalAvailability\" info="'+partNumArr[availCnt]+'^Y^CAT^ ">Change ZIP Code.</a>');
			}
		}	
	}
	if(flagCartQV=='true'){
		$('#availPopup').remove();
		flagCartQV='false';
	}
	readyOnLoad();
	ddItemPartNumArr = new Array();	
}
/* End of Repaint Logic*/
	
/* Add to cart flow for DDC items : Starts */
	
//Global variable to retain Add to cart information for DDC items in subcategory page
var DDCPartNoVal;
var DDCSiVal;
var DDCSpiVal;
var DDCSriVAl;
var DDCDffVal;
var DDCVendorVal;
var DDCStDateVal;
// This function will be called when add to cart is clicked for a DDC item in subcat page
function fnAddDdctoCart(catentryVal,DDCPartNo,DDCSi,DDCSpi,DDCSri,DDCDff,DDCVendor,DDCStDate){
	fnAtcInfo(DDCPartNo);
	var pos = $('#ddcAtc_'+DDCPartNo).offset();
	pos.left = (((pos.left - 300) < 0 ) ? (pos.left + 300) : pos.left);
	//If an Add To cart flow is not yet started then do it now
	if(fnChkZipCode()){
		if(ddcAvlCheck == 'NA'){
			//Initiate availability check for add to cart, set status to in progress
			ddcAvlCheck = 'IP';
				showCAPopUp();
				$('div#availPopup').css({top: pos.top - 100, left: pos.left - 300});
				//If the Zip Code is already present in the cookie, make an AJAX call to check availability
				fnRegDeliveryAvlAjax('cat','N',catentryVal);
		}
	}	
	else{
			showCAPopUp();
			$('#availPopup').css({display: "block"});
			$('#availPopup .standardDiv').css({display: "block"});
			$('#availPopup .errorDiv').css({display: "none"});
			$('div#availPopup').css({top: pos.top - 100, left: pos.left - 300});
	}
		DDCPartNoVal = DDCPartNo;
		DDCSiVal = DDCSi;
		DDCSpiVal = DDCSpi;
		DDCSriVAl = DDCSri;
		DDCDffVal = DDCDff;
		DDCVendorVal = DDCVendor;
		DDCStDateVal = DDCStDate;
}
	/* Function that makes the Ajax call and updates the page based on the response from the server */
	function marketPlaceAjaxCall(remoteUrl) { 
		
		/*Kmart SPU Removing the PO parameter from the ajax URL to update the Filters when  
		user clicks on the Shop By drop down*/
		if (typeof removePoParam !='undefined' && removePoParam==true){
			
			if(remoteUrl.indexOf("&po=1") >= 0 && jsonProperties.dcp == false ){
				var tempRemoteURL=remoteUrl.split("&po=1");
				remoteUrl=tempRemoteURL[0]+tempRemoteURL[1];
			}	

		}
		/* AJAX Setup */
		$.ajaxSetup( {
			error : errorFunction 
		});
   		request = $.getJSON(remoteUrl,showResponse);  
   		function errorFunction(jsonResponse){
   			// check whether the store is Kmart 
			if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0) && removePoParam == true){
				// calling the shopByOption function with prevShopByVal variable
				 shopByOption(prevShopByVal);
				 // assigning prevShopByVal value to shopBy variable
				 shopBy=prevShopByVal;
			}
			// set the flag value when user clicks on shopBy drop down
			removePoParam=false;
   			showAjaxErrorPopup();
   			// Bind click events for the buttons
			$('input#prevResultsAjaxError').click(function() {
				ajaxTimeOut = false;
				if(leftColCheckBoxChecked() > 0){
					countSelected=leftColCheckBoxChecked();
					lastUnselectedFlag=true;
				}
				// If no check box is checked currently
				else {
					lastUnselectedFlag=false;
					countSelected=0;
					filterParam="";
				}
				// Reset the previous filter param and call function to reset the filters
				previousResultsFilterParam=filterParamAfterAjaxCall;
				previousResultsUpdate();
			});
			$('input#tryAgain').click(function(){
				ajaxTimeOut = false;
				bodyPreloader();
				marketPlaceAjaxCall(remoteUrl);
			});
			
			// Call Omniture function to track the Ajax failure
			ajaxTimeOut = true;
			// Commenting out Omniture Function on request from Business team ECOM-47333 - omFilterUpdate("","");
   		}
   		function showResponse(resp){
   		 
			//Pre-Paid Cell Phone
			var taskQuery=resp['subCatJson'].taskQuery;
			 
			if(prepaidCell!=null && prepaidCell=='true' && prePaidZip!=null && prePaidZip!=''){
				prePaidNoResults='false';			
				if(taskQuery!=null && taskQuery!='' &&  (taskQuery.indexOf('Network Provider')==-1 ) && (taskQuery.indexOf('Cellular Network')  ==-1))
					prePaidNoResults='true';
				
				}
			
			
			//Pre-Paid Cell Phone	 
			    if(jsonProperties.regAvail == "true"){
			    	// Get the Regional Availablity JSON
			    	jsonRegionalAvailResponse = resp['RegAvail'].jsonRegionalAvailAjax;
			    }
			    
			    entireDynaDetails = resp['entireDynaDetails'];
			    jsonAPARNetdownDeal = {};
				jsonSHCNetdownDeal = {};
				jsonDynamicSSDetails = {};
				for(i=0; i < entireDynaDetails.length; i++) {
					if(typeof entireDynaDetails[i] != 'undefined' && entireDynaDetails[i] != '') {
						if(entireDynaDetails[i].aparND == 'true') {
							jsonAPARNetdownDeal[entireDynaDetails[i].pno] = entireDynaDetails[i].aparNetDownDeals;
						} else if(entireDynaDetails[i].shcND == 'true') {
							jsonSHCNetdownDeal[entireDynaDetails[i].pno] = entireDynaDetails[i].shcNetDownDeals;
						}		
						if(entireDynaDetails[i].dynaSS == 'true') {
							jsonDynamicSSDetails[entireDynaDetails[i].pno] = entireDynaDetails[i].dynamicSaveStory;
						}
					}
				}
			    
			    // Finally, set the original Sub cat JSON to jsonResponse
			    jsonResponse = resp['subCatJson'];

			    //If None of the Deals or RA is applicable the only JSON Object is original jsonResponse
				jsonProducts.products=jsonResponse.products;
				if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0)){
				}
							
				// Hide the preloader
				$('div#backButtonPreloader').remove();
				document.getElementById("contentWrapper").style.display='block';
				$('div#body-curtain').hide();
				$('div.progress').hide();
				
				subCatProductCount = parseInt(jsonResponse.prodCnt); 
	        	if(subCatProductCount>0){
	        		firstTimeFlag=false;
	               	var noItemsPerPage=parseInt(jsonResponse.viewItems);
	               	pageNo = parseInt(jsonResponse.pageNum);
	               	var jsonSortOption = jsonResponse.sortOption;
	               	
	               	if ( pageNo==1 ) {
						//Deriving the Start and End Value
						start = 1;
						end = noItemsPerPage;
					} else  {
						//Deriving the Start and End Value
						start = (pageNo * noItemsPerPage) - noItemsPerPage + 1;
						end = pageNo * noItemsPerPage;
					}
	               
	               	/*Variables for server side */
					var productCount=jsonResponse.prodCnt;
					var tempProduct=noItemsPerPage*pageNo;
					var startIndex=1;
					var endIndex=noItemsPerPage;
	
					if(productCount < tempProduct ){
						endIndex=productCount%noItemsPerPage;
					}	
					
					var prodIndexArrayAjax=[];	  
					 
	                for(i=startIndex;i<=endIndex;i++){
		                prodIndexArrayAjax[i-1]=i-1;
	             	
	               }
	            
	              	 if(jsonProperties.vName=="Automotive") {
		      					$("#results").html(jsonDisplayProd(jsonProducts,false,1,endIndex+1));
		      					}else {	
		      						
		      						lazyLoad.ini();
					}	
					
	               if(jsonProperties.regAvail == "true"){
   				 		if(fnChkZipCode()){
   				 			if((DDItemList != "") && (DDItemList != null)){
	   				 		fnOnLoadRARepaint(jsonRegionalAvailResponse);
   				 		}
   				 		}
   				 		readyOnLoad();
   				 	}
   				 //Availability and pricing is updated after displaying the products in the page 
   				 	if(jsonProperties.sn == "Kmart" || ((jsonProperties.enableSBL == 1) && (nameOfStores.indexOf(jsonProperties.sn)>=0))){
   				 		updateSpuPriceAvail(jsonResponse.jsonRegPriceAvi);
   				 		localPriceTip();
   				 		availRowHiding();
   						//if no store is selected 160 store locator will be called.
						$('div[@id=selectStore] a.storeSelect').click(function(){
						launchMapModal(getStoreId(),"BROWSE");
						});
   				 	}
   				 	
   				 	if((jsonProperties.sn == "Kmart" || (jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))) && ((getCookieValue("gridIndicator")=="false") || ($('div#results').attr('class') == 'row'))){
						$("div.price").find("div.availGrd").attr("style","display: none");
	    				$("div.info").find("div.availRow").attr("style","display: block");
	   				}
						if(dynamicCategoryPage == false && jsonResponse.filter != null && jsonResponse.filter.length > 0) {
							//Updating the filters							
							mergeFilters(jsonResponse.filter);						
							//Added for Search Within Search
							genExtnBreadCrumb();
							// Updating Price
							if(jsonResponse.filter[jsonResponse.filter.length-1].fn == "Price") {
								var priceNode = jsonResponse.filter[jsonResponse.filter.length-1].fv;
								defaultMinPriceValue = priceNode[0].fvn.split("|")[0];
								defaultMaxPriceValue = priceNode[0].fvn.split("|")[1];
								if(isI18NConvReq()){
									defaultMinPriceValue = performConversion(defaultMinPriceValue);
									defaultMaxPriceValue = performConversion(defaultMaxPriceValue);
								}
												}
							// Updating Price Range
							var lastSelectedFilter = "";
							lastSelectedFilter = filterParam.split(("&lastFilter="))[1];
							var filterLength = (jsonResponse.filter.length > 0 && jsonResponse.filter[jsonResponse.filter.length-1].fn=="PriceRanges")?jsonResponse.filter.length-1:-1;
							if(filterLength == -1 && jsonResponse.filter.length > 1)
								filterLength = jsonResponse.filter[jsonResponse.filter.length-2].fn=="PriceRanges"?jsonResponse.filter.length-2:-1;
							if(filterLength > 0 && jsonResponse.filter[filterLength].fv.length > 1){
								updatePriceRange(jsonResponse.filter[filterLength].fv,lastSelectedFilter,subCatProductCount);
							} else {
								updatePriceRange(null,lastSelectedFilter,subCatProductCount);
											}
										}
							
	               	if(document.getElementById("results")!=null){
						var a=document.getElementsByTagName('a');
						for (i=0;i<a.length;i++)
						{
							if (a[i].rel=='emailMe')
							{
								a[i].onclick = function (){
									mePop(this.getAttribute('info'),this.rel);
								};
							}
							if (a[i].rel=='storePickup')
							{
								a[i].onclick = function (){
									mePop(this.getAttribute('info'),this.rel);
								};
							}
							if (a[i].rel=='availPresell'){
								a[i].onclick = function (){
									var offsetValue = $(this).offset();
									$('div.seeDetailPop').show().css({ top: offsetValue.top +15, left: offsetValue.left - 8 });		
								    	presellPopup();
									};
							}
						}		                
		               	if(start > 0 && end > 0 && subCatProductCount > 0){		             
							if(subCatProductCount <= noItemsPerPage){
							   pageCount = 1;						
							}
							else if(subCatProductCount > noItemsPerPage){							
							   pageCount = Math.ceil(subCatProductCount/noItemsPerPage);
							}
							
							if(end >= subCatProductCount){ 
		                	   	end = subCatProductCount;
		                    }	
				            // To modify the pagination header according to the new products loaded									
							var addPagination = "";
							if(pageCount!=1) {
							if(pageNo>1) {
								addPagination += '<a id="btnPrevious" class="btn-pager_prev-s" href="javascript:;" title="Go to previous page"></a>';										
							}
								addPagination += '<a href="javaScript:;" class="select">Page '+pageNo+'</a>';
							addPagination += '<ul class="select">';
							for(i=1;i<=pageCount;i++) {
								if(!(i==pageNo)) {
									addPagination += '<li><a href="javaScript:;" name="'+i+'" onclick="javascript:;">Page '+i+'</a></li>';
								}
							}				
							addPagination += '</ul>';
							
								if(!(pageNo==pageCount)) {
									addPagination+='<a id="btnNext" class="btn-pager_next-s" href="javascript:;" title="Go to next page"></a>';
									
							    }
						    }								  
						   document.getElementById("pageFooter").innerHTML = addPagination;


							$('a[@id=btnPrevious]').click(prevButton);
							$('a[@id=btnNext]').click(nextButton);
							
							//Kmart Spu Regenerate Shop By Drop Down
							if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0)){
								//Regenerating Shop By Structure
								var shopByDropDown="<div class=\"util\" id=\"shopByHeader\"><div class=\"shop\"><b>Shop by: </b><a href=\"javascript:;\" class=\"select\" value=\"all\"/>"+jsonProperties.sball;
								shopByDropDown+="</a><ul class=\"select\" name=\"shopBy\"  id=\"shopBy\" title=\"Shop Product Options\">";
								shopByDropDown+="<li><a href=\"javascript:;\" value=\"ship\" class=\"ship\">"+jsonProperties.sbship;
								shopByDropDown+="</a></li><li><a href=\"javascript:;\" value=\"spu\" class=\"spu\">"+jsonProperties.sbspu+"</a></li></ul>";
								shopByDropDown+="<span class=\"store\" id=\"selectedStoreValue\"></span>";
								shopByDropDown+="<a class=\"learnMore\" href=\"javascript:;\"><u>Learn More</u></a></div></div>";														
								shopByDropDown+="<div id=\"div_LearnMore\" class=\"cont_overlay\" style=\"display:none\"><div class=\"changestore\"><a href=\"javascript:;\" title=\"Close\" class=\"fright\"> close <img src=\""+imagePath+"img/btn/btn_close.gif\"></a><h4>Learn More</h4><p>You can either select to shop items that can be shipped to your home or picked up at the store. All items may not be available if you switch to pick up at a different store.</p></div></div>";
								document.getElementById("shopByHeader").innerHTML=shopByDropDown;	
								shopByOption(shopBy);		
								displayStore();
								showLearnMore();
							}
						   
						   // To modify the view option header according the new products loaded	 
						   var addViewOptions = "";
						   
						   addViewOptions += '<a href="javaScript:;" class="select">'+noItemsPerPage+' items per page</a>';
						   addViewOptions += '<ul class="select" name="viewItems" id="viewItems">';
						   var ii=0;							   						   
						   do {	
						   		ii=ii+parseInt(jsonForm.viewIncr);
						   		if(!(noItemsPerPage==ii)){
						   			addViewOptions += '<li><a href="javaScript:;" name="'+ii+'" onclick="javascript:;">'+ii+' items per page</a></li>';
						   		}							   		
						   } while(ii < subCatProductCount && ii<=(parseInt(jsonForm.maxView)-parseInt(jsonForm.viewIncr)));
		                   addViewOptions += '</ul>';
		                  
		                   document.getElementById("viewHeader").innerHTML = addViewOptions;
						   document.getElementById("viewFooter").innerHTML = addViewOptions;			                   
		                  
				            // To modify the sort option header according the new products loaded	 
			               	var addSortOptions = "";
			               	if(subCatProductCount > 1 ) {
			               	addSortOptions += '<b>Sort by</b>';
							addSortOptions += '<a href="javaScript:;" class="select">'+currentSortOption+'</a>';
							addSortOptions += '<ul class="select" name="sortBy"  id="sortBy" title="Sort Product Options">';
							var tempSortOptionsValues=sortOptionsValues.split('::');
							var tempSortOptionsNames=sortOptionsNames.split('::');
							for(i=0;i<tempSortOptionsValues.length;i++) {
								if(tempSortOptionsValues[i]!=currentSortOption) {
					   				addSortOptions += '<li><a href="javaScript:;" name="'+tempSortOptionsNames[i]+'" onclick="javascript:;">'+tempSortOptionsValues[i]+'</a></li>';
					   			}	
	   					    }
			                addSortOptions += '</ul>';
			                }   
		                    document.getElementById("sortHeader").innerHTML = addSortOptions;
		                  	document.getElementById("itemHeader").innerHTML = "Items "+start+"-"+end+" of "+subCatProductCount;                  
		                    document.getElementById("itemFooter").innerHTML = "Items "+start+"-"+end+" of "+subCatProductCount;
		               	}               						
				       	// To modify the various display properties     						
		               	var resultsWrapper = document.getElementById("results");	
				        $("a.grid").click(function(){if(!(resultsWrapper.className=="grid")){Switch.grid();}return false;});
						$("a.row").click(function(){if(!(resultsWrapper.className=="row")){Switch.row();}return false;});
					$("a.select").click(function(){ findPosExact(this);dropDown(this.nextSibling,this.className, this.offsetWidth); return false; });
						$("a.select").mouseover(function(){if(dd){clearTimeout(dd);};});
						$("a.select").mouseout(function(){if(document.getElementById(this.className)){timeOutHide(this.className)};});							
		               	$("div#noresults").hide();
		      			$("div#right-column-curtain").hide();
		      			$("div#filterConfirm").hide(); 
						$("a.mapLink").click(function(){mapClick(this)});
						if(typeof allRegiSS !='undefined' && allRegiSS.length >0 ){
							var zippCook1 = getCookie('zipCode');
							if(zippCook1 !=''){doAjax(zippCook1,storeId);$('.localPrice a').addClass('localPSel');	}
							
							$(".localPrice").hover(function() {
								$saveStory = $(this).prev();							
								$('.morePrice').hide(0);
								offsetL = $(this).offset();
								$('.morePrice').show().css({ top: offsetL.top + 23, left: offsetL.left - 92 }); 
								$('.localPrice a').removeClass('over');	
								$(this).find('a').addClass('over');
								clearTimeout(foT);	
							}, function() {
								foT = setTimeout(function(){
									$('.morePrice').fadeOut();
									$('.localPrice a').removeClass('over');			
								},500);	
							});
						}
		      		  } else {
							setTimeout(function(){showResponse(jsonResponse)},0);
					  }
	
				  /* Available for Pre-order - dynamic pop-up */
				  if(typeof dynamicPopupPath != 'undefined' && typeof dynpop != 'undefined'){
				  	$(function(){$('div.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
				  }
					  $(function($){qvBtn();});
					  greatPricePop();
		          } else{
				        // check whether the store is Kmart
						if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0) && removePoParam == true){
						// calling the shopByOption function with prevShopByVal variable
						 	shopByOption(prevShopByVal);
						// assigning prevShopByVal value to shopBy variable
				 			shopBy=prevShopByVal;
						}
	        	  		/* Show overlay to search removing last filter */
	        	  		$("div#filterConfirm").hide();
						var topForRightColumn = $('div.left-column').offset().top-5;
						$('div#right-column-curtain').css("top",topForRightColumn);
						$('div#right-column-curtain').css("left",10);
						$('div#right-column-curtain').width($('div.left-column').width()+$('div.right-column').width()+12);
						if($('div.left-column').height() > $('div.right-column').height()) {
							$('div#right-column-curtain').show().height($('div.left-column').height()+5);
						} else {
							$('div#right-column-curtain').show().height($('div.right-column').height()+5);							
						}
						
						$('div#noresults').css("left",$('div.left-column').width()+12);
						$('div#noresults').width($('div.right-column').width()-30);
						$('div#noresults').css("top",topForRightColumn+20);
						$('div#noresults').show();						
				  }
					
				if(leftColCheckBoxChecked() > 0){
					countSelected=leftColCheckBoxChecked();
					lastUnselectedFlag=true;
				}
				else {
					lastUnselectedFlag=false;
					countSelected=0;
					filterParam="";
				}
		       
		       	if(subCatProductCount == 1){
			        $('div#comparison').hide();
				}
				else {
					$('div#comparison').show();
				}
					
				// To scroll to the top of the page or to the position of NoResults popup
				if(subCatProductCount>0){
					// Function call to check the compare check boxes
					initCompareCheckBox();
					if(jsonProperties.kp == true){
						 updateCategories(jsonResponse.categories);						
					}
					// Display filter items after ajax call
					updateFilterslider();
					window.scrollTo(0,0);
				} else {
					window.scrollTo(0,$('div#noresults').offset().top-10);
				}
			previousResultsFilterParam=filterParamAfterAjaxCall;
			// Set these values only if theere are products to be displayed
			if(subCatProductCount>0){
				filterParamAfterAjaxCall=filterParam;	
				urlAfterAjaxCall=remoteUrl;				
			}
			hasNoResults=false;
			// set the flag value when user clicks on shopBy drop down
			removePoParam=false;
			printZipModule();
			// Commenting out Omniture Function on request from Business team ECOM-47333 - omFilterUpdate(jsonResponse.pavAjax,jsonResponse.poAjax);
		};//show response						
	} 
	
	// Function for going back to previous results when no results condition occurs 
	function previousResultsUpdate() {
		//Clear the values in the USER INPUT PRICE if it was the last filter selected
		if(userInputPrice==true){
			clearInputRangeFields();
		}
		// Clear off all the filters
		clearFilters();
		//Added For Search Within Search
		clearSearchWithin();
		// Resume the previous state of the filters
		keywordCheck(previousResultsFilterParam,"prevResults");	
		// Set filter parameter
		filterParam=previousResultsFilterParam;
		setHash();
		hasNoResults=true;
		$('div#noresults').hide();
		$('div#ajaxError').remove();
		$('div#right-column-curtain').hide();	
	}	
	
	function mergeFilters(ajaxFilters) {
		var fvIdxCount=0;
		var fvIdxAjaxArray = [];
		var updatedFilterValue= [];
		var filterValue="";
		var tempIndex;
		for(i=0;i<ajaxFilters.length;i++){
			if(!(ajaxFilters[i].fn == "Price" || ajaxFilters[i].fn == "PriceRanges")) {
				var toBeDisplayedCount=0;
				var toBeDisplayed=false;
				for(j=0;j<ajaxFilters[i].fv.length;j++){	
					var thisCheckbox = document.getElementById("fvIdx"+ajaxFilters[i].fv[j].fvIdx);
					if(thisCheckbox != null) {
					if(ajaxFilters[i].fv[j].fvc == 0){
						if(thisCheckbox.checked) {
							toBeDisplayed=true;
							toBeDisplayedCount++;
							filterValue="";
						  	tempIndex=thisCheckbox.parentNode.innerHTML.lastIndexOf("(");
						  	filterValue = thisCheckbox.parentNode.innerHTML.substr(0,tempIndex);
						  	filterValue = filterValue+"(0)";
						  	var parent=$(thisCheckbox).parent();
							$(thisCheckbox).parent().html(filterValue);
							$(parent).find('input').attr('checked','checked');
						} else {
							if(thisCheckbox.parentNode.tagName == 'A'){
								thisCheckbox.parentNode.style.display = 'none';						
							} else{
								thisCheckbox.parentNode.parentNode.style.display = 'none';			
							}
						}
					} else {
						if(thisCheckbox.parentNode.tagName == 'A'){
							thisCheckbox.parentNode.style.display = 'block';
							toBeDisplayedCount++;
						} else{
						var newArrival=false;
						var searsInternational=false;
						if(ajaxFilters[i].fk=="New Arrivals" && (ajaxFilters[i].fv[j].fvn=="Yes" || ajaxFilters[i].fv[j].fvn=="New Arrivals") && ajaxFilters[i].fv[j].fvc>0){
							newArrival=true;
						}
						if(ajaxFilters[i].fk=="Sears International" && isI18NConvReq()){
							searsInternational=true;
						}
							thisCheckbox.parentNode.parentNode.style.display = 'block';
							if(newArrival==false){
							toBeDisplayedCount++;
						}
						}
						filterValue="";
					  	tempIndex=thisCheckbox.parentNode.innerHTML.lastIndexOf("(");
					  	filterValue = thisCheckbox.parentNode.innerHTML.substr(0,tempIndex);
					  	filterValue = filterValue+"("+ajaxFilters[i].fv[j].fvc+")";
						if(thisCheckbox.checked) {
							toBeDisplayed=true;
						  	var parent=$(thisCheckbox).parent();
							$(thisCheckbox).parent().html(filterValue);
							$(parent).find('input').attr('checked','checked');
						} else {
							$(thisCheckbox).parent().html(filterValue);
							}
						}
					}
				}
				var escapedFilterName = replaceCharacters(ajaxFilters[i].fn);
				$("div.left-column div.attributes").each(function() {	
					var thisFilter=$(this).find('h5').find('div').text();
					if(thisFilter == escapedFilterName) {
					
						if(toBeDisplayedCount>1 || toBeDisplayed==true) { 
							this.style.display='block';
						 if(newArrival==true){	
						 	$("div.left-column").find("div.narrow").find("li.No").attr("style","display:none");
						 }
						 } 
						else if(newArrival==true){
							this.style.display='block';	
							$("div.left-column").find("div.narrow").find("div.attributes").find("li.No").attr("style","display:none");
							$("div.left-column").find("div.narrow").find("li.No").attr("style","display:none");
							
						}else if(searsInternational==true){
							this.style.display='block';	
						} else {
							this.style.display='none';				
						}
					}
				});
			}
		}
		$("div.left-column li label input:checkbox").click(selectAttribute);
	}
	
	function updateCategories(categories){
		var newCategories = "";
		var tempIndex = -1;
		var tempFilterParam = filterParam;

		if(filterParam.indexOf("&lastFilter=")>=0){
			tempFilterParam = filterParam.split(("&lastFilter="))[0];
		}
		tempIndex = tempFilterParam.indexOf("filter=");
		if(tempIndex>=0){						
				tempFilterParam = tempFilterParam.substr(tempIndex,tempFilterParam.length);			
				//Added For User Price Input Enhancement
				//Add a Url Parameter goBtn=true if price is obtained from User Input go Button	
				var range_low = $("#range_low").val();
							if(isI18NConvReq()){
								range_low = performReversion($("#range_low").val());
							}
							var range_high = $("#range_high").val();
							if(isI18NConvReq()){
								range_high = performReversion($("#range_high").val());
							}
				if(typeof range_low != 'undefined' && typeof range_high != 'undefined'){
					if( range_low.length > 0 || range_high.length > 0){
						tempFilterParam+="&goBtn=true";	
					}
				}
				if(location.href.indexOf("&goBtn=true")>=0){
					tempFilterParam+="&goBtn=true";	
				}
		}
		
		var tempPaginationParam=paginationParam.split("&");
		var viewSort=tempPaginationParam[0]+'&pageNum=1'+'&'+tempPaginationParam[2];
		if(shopBy != null && shopBy.length > 0){
			viewSort+='&shopBy='+shopBy;
		}
		
		if(categories!=null){
			for(i=0;i<categories.length;i++){
				if(categories[i].vcf == false){
					//Generating URL for SHC categories
					if((categories[i].curl.indexOf("viewItems")>=0) || (categories[i].curl.indexOf("pageNum")>=0) || (categories[i].curl.indexOf("sortOption")>=0)){
						var tempCategories=categories[i].curl.split("&");
						for(j=0;j<tempCategories.length;j++){
							if(tempCategories[j].indexOf("viewItems=")>=0){
								tempCategories[j]=tempPaginationParam[0];
							}
							if(tempCategories[j].indexOf("sortOption=")>=0){
								tempCategories[j]=tempPaginationParam[2];
							}
							if(tempCategories[j].indexOf("pageNum=")>=0){
								tempCategories[j]='pageNum=1';
							}										
						}	
						categories[i].curl=tempCategories.join("&");		
						if(tempIndex>=0){				
							newCategories+='<li><a id='+categories[i].vcf+' href="'+categories[i].curl+'&'+tempFilterParam+'">'+categories[i].cn+'</a></li>';
						} else {
							newCategories+='<li><a id='+categories[i].vcf+' href="'+categories[i].curl+'">'+categories[i].cn+'</a></li>';
						}
					} else {
						if(tempIndex>=0){				
							newCategories+='<li><a id='+categories[i].vcf+' href="'+categories[i].curl+'&'+tempFilterParam+'&'+viewSort+'">'+categories[i].cn+'</a></li>';
						} else {
							newCategories+='<li><a id='+categories[i].vcf+' href="'+categories[i].curl+'&'+viewSort+'">'+categories[i].cn+'</a></li>';
						}
					}
				} else {
					//URL for vendor specific categories	
					newCategories+='<li><a id='+categories[i].vcf+' href="'+categories[i].curl+'">'+categories[i].cn+'</a></li>';
				}			
			}
			$("div.left-column div.attributes ul.firstShown:not(#searchwithin)").html(newCategories);
		} else {
			var newHref="";
			$("div.left-column div.attributes ul.firstShown li").each(function(i){
				if($(this).find("a").attr('id') != "true"){
					newHref = $(this).find("a").attr('href');
					
					if(newHref.indexOf("&viewItems")>=0){
						var tempHref=newHref.split("&");							
							for(i=0;i<tempHref.length;i++){
									if(tempHref[i].indexOf("viewItems=")>=0){
										tempHref[i]=tempPaginationParam[0];
									}
									if(tempHref[i].indexOf("sortOption=")>=0){
										tempHref[i]=tempPaginationParam[2];
									}
									if(tempHref[i].indexOf("pageNum=")>=0){
										tempHref[i]='pageNum=1';
									}
							}
							newHref=tempHref.join("&");
					}
					else{
						newHref+='&'+viewSort;
					}
					$(this).find("a").attr('href',newHref);
				}
			});
		}
				
	}
		
// Replaces the special characters with corresponding escape characters. 
function cleanFilterParam(inputString) {
	/*Using escape function to eliminate invalid characters */
	inputString=escape(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;
}

/* Appends the filters, pagination and products selected for compare to the hash in the URL. */
window.onbeforeunload = function () {
    var compareParam="";
    for(i=0;i<partNumberValues.length;i++){
        if(partNumberValues[i]!='' && partNumberValues[i]!=null){
            compareParam=compareParam+"&"+partNumberValues[i];
        }
    }
    if(compareParam!="") {
        compareParam="compareParam="+compareParam.replace(compareParam.charAt(0),"");
    }
    var hash;
    if($.browser.safari) {  
        if(filterParam!="" && (compareParam!="" && compareParam!=null)) {
            hash=paginationParam+"&&"+filterParam+"&&"+compareParam;
        } else if(dynamicCategoryName!="" && (compareParam!="" && compareParam!=null)){
            hash=paginationParam+"&&"+dynamicCategoryName+"&&"+compareParam;
        } else if(compareParam!="" && compareParam!=null){
            hash=paginationParam+"&&"+compareParam;
        } else if(filterParam!=""){
            hash=paginationParam+"&&"+filterParam;
        } else if(dynamicCategoryName!=""){
            hash=paginationParam+"&&"+dynamicCategoryName;
        } else if(paginationParam!=defaultPaginationParam){
            hash=paginationParam;
        } else {
            return;
        }
        if( parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Safari')+ 7)) < 412 ) {
            // the form doesn't need to be attached to the document.
            var f = document.createElement('form');
            f.action = hash;
            f.submit();
        } else {
            var evt = document.createEvent('MouseEvents');
            evt.initEvent('click', true, true);
            var anchor = document.createElement('a');
            anchor.href = location.href.substring(0,location.href.indexOf("#"))+"#"+hash;   
            anchor.dispatchEvent(evt);
        }
    } else if(compareParam!="" && compareParam!=null) { 
        if(location.href.indexOf("&&compareParam=")>=0) {
            hash=location.href.substring(0,location.href.indexOf("&&compareParam="));
            location.replace(hash+"&&"+compareParam);
        } else if(location.href.indexOf("#compareParam=")>=0) {
            hash=location.href.substring(0,location.href.indexOf("#compareParam="));
            location.replace(hash+"#"+compareParam);
        } else if(location.href.indexOf("#") < 0 ) {
            hash=location.href;
            location.replace(hash+"#"+compareParam);
        } else {
            hash=location.href;
            location.replace(hash+"&&"+compareParam);
        }
    } else if(location.href.indexOf("compareParam=")>=0) {
        var indexOfAndCmp = location.href.indexOf("&&compareParam=");
        hash = indexOfAndCmp >= 0 ?
                    location.href.replace(location.href.substring(indexOfAndCmp,location.href.length),""):
                    location.href.replace(location.href.substring(location.href.indexOf("compareParam="),location.href.length),"");
        location.replace(hash);
    }
};
/* Unique functions for Server Side Flow Ends */

/* Duplicate functions for Server Side Flow Starts */
function dropDown(me,id,width){
	// To hide the currently selected option
	$('div.sort').find('li').each(function() {
		$(this).find('a').each(function() {
			if($(this).attr('name')==selectedSortOption) {
				$(this).parent().hide();
			} else {		
				$(this).parent().show();							
			}
		});
	});
	
	var msg=$(me).html();
	// To avoid small drop down when product count less than 40 items
	if($(me).parent().attr('class')=="view" && jsonProducts.prodCnt <= jsonForm.viewItems) return false;
	if (!document.getElementById(id))
	{
		var containerDiv = document.createElement('div');
		containerDiv.id = id;
		containerDiv.style.width = width+"px";
		containerDiv.style.zIndex = '101';
		document.body.appendChild(containerDiv);
	} else { return false; }
	// Set position of this div //
	var thisDIV=document.getElementById(id);
	thisDIV.style.width = width+"px";
	thisDIV.style.top = yPos +20+"px";
	thisDIV.style.left = xPos + "px";
	thisDIV.innerHTML="<ul class=\""+id+"\">"+msg+"</ul>";
	$("div#select ul.select").show().bgiframe();
	
	thisDIV.onmouseover = function(){if(dd){clearTimeout(dd);};};	
	thisDIV.onmouseout = function(){if(id){timeOutHide(id);};};
	
	/* On Click function of the dropdown options */
	$('div#select ul.select li a').click(function() {
		// Calls the Goto page funtion
			if($(me).parent().attr('class')=="page") {
				var tempParam=paginationParam.split("&");
				if(tempParam[1].split("=")[1]!=$(this).attr('name')) { 
				gotoPage($(this).attr('name'));
				ajaxImpl();
				}
			
			// Calls the view per page function
			} else if($(me).parent().attr('class')=="view") {
				setCookieValue("viewItems", $(this).attr('name'));
				viewPerPage($(this).attr('name'));
				
			// Calls the sort by function
			} else if($(me).parent().attr('class')=="sort") {
				selectedSortOption=$(this).attr('name');
				sortOptionSelect($(this).attr('name'));	
				currentSortOption=$(this).text();
			}
			
			/* KMART SPU STARTS HERE*/
			//Shop By drop down changes
			 else if($(me).parent().attr('class')=="shop"){
                //If the selected option is "Shippable Items"
				if($(this).text()==jsonProperties.sbship){
					prevShopByVal=shopBy;
					//Set the shop by varaiable
					shopBy="ship";
					shopByOption(shopBy);
					// set the flag value when user clicks on shopBy drop down
					removePoParam=true;
					//calling ajaxImpl function
					ajaxImpl();
				}	
				//If the selected option is "In-store Items"
				else if($(this).text()==jsonProperties.sbspu){
					prevShopByVal=shopBy;
					//Set the shop by varaiable
					shopBy="spu";
					if(!fnCheckCookie()){
						shopByInstore = true;
						launchMapModal(getStoreId(),"BROWSE");
					}else{
						shopByOption(shopBy);
					
					// set the flag value when user clicks on shopBy drop down
					removePoParam=true;
					//calling ajaxImpl function
					ajaxImpl();
					}
				}
				// If the selected option is "All Items"
				else if($(this).text()==jsonProperties.sball){
					prevShopByVal=shopBy;
					//Set the shop by varaiable to ""
					shopBy="";
					shopByOption(shopBy);
					// set the flag value when user clicks on shopBy drop down
					removePoParam=true;
					//calling ajaxImpl function
					ajaxImpl();
				}
				//End of Shop by drop down		
                 // make an ajax call which should have shop by option in the URL correctly and ap=1;
            }
            /* KMART SPU ENDS HERE*/
			return false;
		//}
		
	});
}

/* Clearing functions */
var clearAll = function(){
	clearInputRangeFields();
	countSelected=0;
	$("div.left-column input:checked").removeAttr("checked");
	$("div.left-column div.narrow div").removeClass("selected");
	$("div.left-column > ul li a").removeClass("selected");
	
	var span = $("div.left-column").find("span");
	for(var s=0; s<span.length; s++){
		if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.parentNode.parentNode.className=="left-column" ){
			$(span[s].parentNode.parentNode.parentNode).removeClass("selected");
			span[s].className="no star";
			span[s].nextSibling.innerHTML="0 stars or better";
			span[s].selectedSpan = span[s].className;
			span[s].selectedNum = "0";
		};
	};
	$(this).remove();
	$("div.left-column h5 a").remove();
	$("div.left-column li a").removeClass("selected");
	$('div.colorSelected').remove();
	
	// Remove Sub Price Ranges
	$("li#slider div.sub_price_range").remove();

	/* Reset the value of Last filter to null when clear All is clicked */
	lastFilter="";				
	prefilter();								
				
	if((!firstTimeFlag) && (lastUnselectedFlag)) {
		gotoPage(1);
		ajaxImpl();
	}
								
	return false;
};

var clearSelection = function(){	

	/* Variable to store the filter name for which the clear button was clicked */
	var filterName=$(this).parent().parent().find('h5').find('div').text();
	if(filterName=="Price"){
        // Price Range Enhancement (To remove sub price ranges)
        $("li#slider div.sub_price_range").remove();
        //PRICE USER INPUT ENHANCEMENT
		clearInputRangeFields();
	}				
	var selected=this.parentNode.parentNode;
	$(selected).removeClass("selected");
	var a = selected.getElementsByTagName("a");
	for(var i=0;i<a.length;i++){if(a[i].className=="selected"){a[i].className="";}};
	var input = selected.getElementsByTagName("input");
	for(var o=0;o<input.length;o++){input[o].checked=false;};
	var span = selected.getElementsByTagName("span");
	for(var s=0; s<span.length; s++){
		if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.parentNode.parentNode.className=="left-column" ){
			$(span[s].parentNode.parentNode.parentNode).removeClass("selected");
			span[s].className="no star";
			span[s].nextSibling.innerHTML = "0 star or better";
			span[s].selectedSpan = span[s].className;
			span[s].selectedNum = "0";
		};
	};
	//var selectedNum = $("div.left-column input:checked").length;
	if(leftColCheckBoxChecked() < 1 || (leftColCheckBoxChecked() < 2 && searchWithinSearch != '')) {
		 $("div.left-column h4:eq(0) a").remove(); 
	}
	$(this).remove();
	
	if(  $(this).attr('name') == 'Color'){
		$('div.colorSelected').remove();
	}

	/* When clear button is clicked to remove this filter from the last filter array */
	var tempFilters=lastFilter.split(",");
	
	/* Reset the value of Last Filter */ 
	lastFilter="";
			
	/*Traverse through the last filter array and remove the cleared filter*/
	for(i=0;i<tempFilters.length;i++) {
		if(tempFilters[i]!="") {
			var tempGrpName=tempFilters[i].split(":");
					   			
			/* Update the last filter array */
			if(tempGrpName[0]!=stringTrim(filterName) && (filterName!="Price" || tempGrpName[0]!="SubPriceRange")){			
				lastFilter=lastFilter+","+tempFilters[i];	
			}
		}
	}
	prefilter();
	if((!multipleSelectEnabled) || (leftColCheckBoxChecked()<1 && !firstTimeFlag && lastUnselectedFlag )) {
		createFilterParam();
		gotoPage(1);
		ajaxImpl();
	}
	return false;
};

/* Check box Click*/
var selectAttribute = function(){																												
	//Flag is set to false when ajax call happens other than Click of Go button for Price
	userInputPrice=false;
	if(this.parentNode.tagName == 'A'){
	// Displaying color swatch tick mark
		if($(this).parent().parent().parent().attr('class') == 'Color'){
			if($(this).parent().find('input').attr('checked')){
				$(this).parent().find('input').removeAttr('checked');
				$(this).parent().find('div.colorSelected').remove();					
			} else{
				$(this).parent().find('input').attr('checked','checked');
				$(this).parent().prepend('<div class="colorSelected"></div>');
			}
		}	
	}
	
	var selectedNum = $(this).parent().parent().parent().children("li").children("label").children("input:checked").length;
	var a_select = $(this).parent().parent().children("a").length;
	var a_selectedNum = 0;
	if(this.parentNode.tagName == "A"){ 
		if($(this).parent().attr('class')=="selected") {
			$(this).parent().removeClass("selected"); 				
    	} else {
			$(this).parent().addClass("selected"); 
		}
	}
	for(var i=0; i<a_select; i++ ){ if(this.parentNode.parentNode.getElementsByTagName("a")[i].className == "selected"){ a_selectedNum++ } }
	
	if(selectedNum && selectedNum > 0 || a_selectedNum && a_selectedNum > 0 ){
		$(this).parent().parent().parent().parent().addClass("selected");

		if($("div.left-column h4:eq(0) a").length<1){
			$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
			$("div.left-column h4:eq(0) a").click(clearAll);
		}
	
		if($(this).parent().parent().parent().parent().children("h5").children("a").length<1){
			var createClearHtml = "<a href='javaScript.html' name='"+$(this).parent().parent().parent().attr('class')+"' title='Clear selections'>Clear</a>";
			$(this).parent().parent().parent().parent().children("h5").prepend(createClearHtml);
			$(this).parent().parent().parent().parent().children("h5").children("a").click(clearSelection);
		}
	
	} else{

		$(this).parent().parent().parent().parent().removeClass("selected");
		$(this).parent().parent().parent().parent().children("h5").children("a").remove();
		$("div.left-column h2:eq(0) a").remove();
 	}
		
	countSelected=leftColCheckBoxChecked();
	if(leftColCheckBoxChecked() < 1 || (leftColCheckBoxChecked() < 2 && searchWithinSearch != '')) {
		$("div.left-column h4:eq(0) a").remove();
	}

	/* Obtain the filter name of the selected element */
	var tempFilter=$(this).parent().parent().parent().parent().find('h5').find('div').text();				

	if(tempFilter=="" || tempFilter==null || tempFilter.length==0){					
		tempFilter=$(this).parent().parent().parent().parent().parent().find('h5').find('div').text();					
	}
									
	/* Trim extra spaces and replace spaces with '+' */
	tempFilter=stringTrim(tempFilter);							
	tempElement=this.name;								
					
	/* Remove the $ sign from the price */
	while(tempElement.indexOf('$')>=0){
		tempElement=tempElement.replace('$','');	
	}			    
    tempElement=stringTrim(tempElement); 			   

	/* If the filter element is checked then append the filter and element to the  filter array */	
	if($(this).parent().find('input').attr('checked')){
		lastFilter=lastFilter+","+tempFilter+":"+tempElement;					
	} 			
	else {
	 	lastFilter=lastFilter.replace(","+tempFilter+":"+tempElement,"");
	}				

	if(fromProductPage==false){	
		prefilter();
		// Set the Offset for Update and NoResults popup
		var newTop = $(this).parent().offset();
		$('div#filterConfirm').css({top: newTop.top});
        $('div#noresults').css({top: newTop.top});
		if((!multipleSelectEnabled) || (countSelected == 0 &&  !firstTimeFlag  && lastUnselectedFlag) ) {
			gotoPage(1);
			ajaxImpl();
		} 
	}
	if(this.parentNode.tagName == "A"){ return false; }					
}

/* Funtion to handle BAck button */ 
function resumeState() {				
	if(location.href.indexOf("#")>=0  && (location.href.indexOf("#") < location.href.length-1)){
		urlAfterAjaxCall="";
		filterParamAfterAjaxCall="";
		countSelected=0;
		clearFilters();
		prefilter();											
		gotoPage(1);
		if(jsonProperties.dcp == false ){		
			if(leftColCheckBoxChecked() < 1 || (leftColCheckBoxChecked() < 2 && searchWithinSearch != '')) {
				 $("div.left-column h4:eq(0) a").remove(); 
			}
			if(leftColCheckBoxChecked() < 1 || (leftColCheckBoxChecked() < 2 && searchWithinSearch != '')) {
				 $("div.left-column h5:eq(0) a").remove(); 
			}
		}								    			
		
		/*Set the value of filterParam  and pagination param*/
		var	removedHash=location.hash.replace("#","");
		if(removedHash.indexOf("compareParam=")>=0) {
			var selectedCompareCheckBoxes=removedHash.substring(removedHash.indexOf("=",removedHash.indexOf("compareParam"))+1,removedHash.length);
			if(selectedCompareCheckBoxes.indexOf("&")>0) {
				var partNumbers=selectedCompareCheckBoxes.split("&");
				for(var i=0;i<partNumbers.length; i++) {
					partNumberValues[i]=partNumbers[i];
				}
				prodCountCompare=partNumbers.length;
			} else {
				partNumberValues[0]=selectedCompareCheckBoxes;
				prodCountCompare=1;
			}
			removedHash=removedHash.substring(0,removedHash.indexOf("&&compareParam="));
		}
		
		if(removedHash!=defaultPaginationParam && removedHash!="" && removedHash!=null) {
			if(removedHash.indexOf("&&")>=0 && removedHash.indexOf("sName=")<0){
				var splitHash=removedHash.split("&&");
				paginationParam=splitHash[0];
				var indexOfLastFilter = splitHash[1].indexOf("&lastFilter=");
				var filterParameter=cleanFilterParam(splitHash[1].substring(0,indexOfLastFilter))+"&"+cleanFilterParam(splitHash[1].substring(indexOfLastFilter+1,splitHash[1].length));
				filterParam = filterParameter;
				if(jsonProperties.kp == true){
					updateCategoriesOnLoad(filterParameter,paginationParam);
				}						
				
				// Call function to update left nav filters
				keywordCheck(filterParameter,"backbutton");
			} else if(removedHash.indexOf("sName=")>=0){
				var pagParam=removedHash.split("&&")[0];
				dynCatNameInHash = cleanFilterParam(unescape(removedHash.split("&&")[1].split("=")[1]));
				if(dynamicCategoryName==dynCatNameInHash && (pagParam==defaultPaginationParam || pagParam[3] =="shopByTab=now")) {
					$('div#backButtonPreloader').remove();
					document.getElementById("contentWrapper").style.display='block';
					$('div.product').height('auto');
					return;
				}
				paginationParam=pagParam;
				dynamicCategoryName=dynCatNameInHash;
			} else {
				// Do not make AJAX call for when View items is present in HASH. Handled in Cookie
				defPagParam=defaultPaginationParam.split("&");
				pagParam = removedHash.split("&");
				
				if(defPagParam[1]==pagParam[1] && defPagParam[2]==pagParam[2] && (pagParam.length<=3 || pagParam[3] =="shopByTab=now")) {
					$('div#backButtonPreloader').remove();
					document.getElementById("contentWrapper").style.display='block';
					$('div.product').height('auto');
					return;
				}
				paginationParam=removedHash;
				filterParam="";
			}
			/* KMART SPU STARTS HERE*/
			//Shop by value back button implementation
			if(jsonProperties.enableSBL == 1 && (nameOfStores.indexOf(jsonProperties.sn)>=0))
			{
				if(paginationParam.indexOf("shopBy=")>=0){
					// Obtain the shop by parameter from the pagination param
					var shopBySplitter=paginationParam.split("&shopBy=");
					paginationParam=shopBySplitter[0];
					var shopBySplit=shopBySplitter[1];
					if(shopBySplit == "ship"){
						// set the shop by parameter to "ship"
						shopBy="ship";
						shopByOption(shopBy);				
					}	
					else if(shopBySplit == "spu"){
						// set the shop by parameter to "spu"
						shopBy="spu";	
						shopByOption(shopBy);																
					}	
			}	
			}		
			/* KMART SPU ENDS HERE*/	
			
			// For changing the sort option value
			var indexOfSort=paginationParam.indexOf("sortOption");
			if(indexOfSort>=0) {
				var sortOptioninUrl=paginationParam.substring(paginationParam.indexOf("=",indexOfSort)+1);
				if(sortOptioninUrl!="" && sortOptioninUrl!=selectedSortOption) {
					selectedSortOption=sortOptioninUrl;
					var tempSortOptionsValues=sortOptionsValues.split('::');
		  			var tempSortOptionsNames=sortOptionsNames.split('::');
					for(i=0;i<tempSortOptionsNames.length;i++) {
						if(tempSortOptionsNames[i]==sortOptioninUrl) {
							currentSortOption=tempSortOptionsValues[i];
						}	
					}
				}
			}
			fromProductPage=true;
			ajaxImpl();
			fromProductPage=false;
		} else {
			$('div#backButtonPreloader').remove();
			document.getElementById("contentWrapper").style.display='block';
			$('div.product').height('auto');
			
		}
	}
}

/*Function for Checking check Box (KEYWORD)*/
function keywordCheck(filterParameter,from){			
	fromProductPage=true;
	var checkedBoxList=filterParameter;
	var lastSelectedFilter = "";
	/* Added For Search Within Search - start */
	var filterSplit = splitSearchWithinFilter(filterParameter);
	if(filterSplit[0].indexOf("searchwithin") > -1){
		resumeSearchWithin(filterSplit[0]);
	}
	/* Added For Search Within Search - End */
	if(filterSplit[1].indexOf("&lastFilter=")>=0){
		var temp=filterSplit[1].split("&lastFilter=");
		checkedBoxList=temp[0];
		lastSelectedFilter = temp[1];
	}
	if(filterSplit[1].indexOf("filter=")>=0){
		checkedBoxList=undoCleanFilterParam(checkedBoxList);
		checkedBoxList=checkedBoxList+"^";
	}
	$("div.left-column div.attributes").each(function(i){
        var filterName=stringTrim($(this).find('h5').find('div').text());
        if($(this).find("input:checkbox").length > 0 && filterName !="User+Ratings") {
            var indexOfFilterName = -1;
            var endOfFilter = -1;
            indexOfFilterName = checkedBoxList.indexOf("filter="+filterName+"|") >=0 ?
                                    checkedBoxList.indexOf("filter="+filterName+"|") : (checkedBoxList.indexOf("^"+filterName+"|") >= 0 ? 
                                    checkedBoxList.indexOf("^"+filterName+"|")+1 : -1);
            if(indexOfFilterName >= 0) {
                endOfFilter = checkedBoxList.indexOf("^",indexOfFilterName);					
				$(this).find("input:checkbox").each(function(i){
					var filterValues=stringTrim(this.name);
                    var indexOfFilterValues = checkedBoxList.indexOf("|"+filterValues+"|",indexOfFilterName) >=0 ?
                                                checkedBoxList.indexOf("|"+filterValues+"|",indexOfFilterName)+1 : (checkedBoxList.indexOf("|"+filterValues+"^",indexOfFilterName) >= 0 ? 
                                                checkedBoxList.indexOf("|"+filterValues+"^",indexOfFilterName)+1 : -1);
					if(this.parentNode.tagName == 'A') {
						/*For color Swatches*/
						if(indexOfFilterValues>=0 &&
                                (endOfFilter ==-1 || (endOfFilter > indexOfFilterValues))) {
							$(this).parent().find('input').each(selectAttribute);	
							$(this).parent().parent().parent().parent().find('h5').attr('class','open');
							this.parentNode.parentNode.parentNode.style.display='block';
						}
                            } else {
						if(indexOfFilterValues>=0 &&
                                (endOfFilter ==-1 || (endOfFilter > indexOfFilterValues)) ) {
							$(this).attr('checked',true);
							$(this).parent().find('input').each(selectAttribute);
                                $(this).parent().parent().parent().parent().find('h5').attr('class','open');
                                this.parentNode.parentNode.parentNode.style.display='block';
                            }
							}
				});
							}
						}			
	});
	// Price Ranges
	if(checkedBoxList.indexOf("filter=Price") >= 0 || checkedBoxList.indexOf("%5EPrice") >= 0 || checkedBoxList.indexOf("^Price") >= 0) {
		// Parse Price from URl
		var priceStart=checkedBoxList.substring(checkedBoxList.indexOf("|",checkedBoxList.indexOf("Price"))+1,checkedBoxList.indexOf("-",checkedBoxList.indexOf("Price")));
		var priceEnd=checkedBoxList.substring(checkedBoxList.indexOf("-",checkedBoxList.indexOf("Price"))+1,checkedBoxList.indexOf("^",checkedBoxList.indexOf("Price")));
		var priceDisplayLabel = "$"+priceStart+" - $"+priceEnd;
		var priceName = priceStart+"|"+priceEnd;
		var priceHTML = $("li#slider");
		if(from != "prevResults") {
			// Keyword -> Subcat flow & Back button flow
			if((location.href.indexOf("&goBtn=true") >= 0 && from == "keyword") || (lastSelectedFilter=="Price2" && from == "backbutton")) {
				// Updating price input boxes
				$("#range_low").val(priceStart);
				$("#range_high").val(priceEnd);
						} else {
				// Adding primary price range header
				$(priceHTML).html('<label class="price_range"><input type="radio" checked name="priceRange" class="slider_priceRange_radio" id="'+priceName+'"/>'+priceDisplayLabel+' ()</label><div class="sub_price_range"></div>');
				if(from == "keyword") {
					// Generate Sub Ranges, if keyword flow
					var filterLength = (jsonFilters.filter.length > 0 && jsonFilters.filter[jsonFilters.filter.length-1].fn=="PriceRanges")?jsonFilters.filter.length-1:-1;
					if(filterLength == -1 && jsonFilters.filter.length > 1)
						filterLength = jsonFilters.filter[jsonFilters.filter.length-2].fn=="PriceRanges"?jsonFilters.filter.length-2:-1;
					if(filterLength > 0 && jsonFilters.filter[filterLength].fv.length > 1) {
						updatePriceRange(jsonFilters.filter[filterLength].fv,"keyword",jsonProducts.prodCnt);
					} else {
						updatePriceRange(null,"keyword",jsonProducts.prodCnt);
						}		
				}
			}
					} else {
			if(lastSelectedFilter=="Price2") {
				// Updating price input boxes
				$("#range_low").val(priceStart);
				$("#range_high").val(priceEnd);
						}
			if($("#range_low").val()=="" && $("#range_high").val()=="") {
				// Check the selected radio price's radio button, if from previous results flow
				$('input[@id='+priceName+']').attr("checked","checked");
					}	
			}
		// UE changes
        $(priceHTML).parent().parent().find('h5').attr('class','open');
        $(priceHTML).parent().show();
        $(priceHTML).parent().parent().addClass("selected");
		// Code for adding clear Clear ALL buttons for Price
		if($("div.left-column h4:eq(0) a").length<1){
			$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
			$("div.left-column h4:eq(0) a").click(clearAll);
		}
		if($(priceHTML).parent().parent().find("h5").children("a").length<1) {
			var createClearHtml = "<a href='javaScript.html' name='"+$(this).parent().parent().parent().attr('class')+"' title='Clear selections'>Clear</a>";
			$(priceHTML).parent().parent().find("h5").prepend(createClearHtml);
			$(priceHTML).parent().parent().find("h5").children("a").click(clearSelection);
		}
	}
	
	// Extract Star Rating value
	if(checkedBoxList.indexOf("User+Ratings|")>=0){
		var userRatingSplit=checkedBoxList.split("User+Ratings|");
		var userRatingValue=parseInt(userRatingSplit[1]);
		
		//Intialize first flag to true so that we need not add the same filter again 
		var firstFlag=true;
		
		// Star Ratings functions
		$("li.ratings span.star a").each(function(i){
				
		if(userRatingValue==$(this).text()) {
			$(this).parent().find('input').each(function(j){
				if(j <= i){
					$(this).attr('checked','checked');
					
					// To append star filter to the last filter array 
					if(firstFlag==true){
						// Obtain the filter Name 
						var filterName=$(this).parent().parent().parent().parent().parent().find('h5').find('div').text();
						filterName=stringTrim(filterName);
						
						// Append the filter name to the last Filter array
						lastFilter=lastFilter+","+filterName+":empty";
						firstFlag=false;
					}		
				}else{
					$(this).removeAttr('checked');
				}											 
			});
			
			$(this.parentNode.parentNode.parentNode.parentNode).addClass("selected");
			if($("div.left-column h4:eq(0) a").length<1){
				$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
				$("div.left-column h4:eq(0) a").click(clearAll);
			}
			if($(this.parentNode.parentNode.parentNode.parentNode).children("h5").children("a").length<1){
				$(this.parentNode.parentNode.parentNode.parentNode).children("h5").prepend("<a href='javaScript.html' title='Clear selections'>Clear</a>");
				$(this.parentNode.parentNode.parentNode.parentNode).children("h5").children("a").click(clearSelection);
			}
			
			if(this.className.indexOf("selected")>=0){
				this.className=this.className.replace("selected","");
			}
			this.parentNode.selectedSpan = this.className + " star";
			this.parentNode.selectedNum = $(this).text();
			if($(this).text()=="0" || $(this).text()=="1"){
				this.parentNode.nextSibling.innerHTML = $(this).text() + " star or better";
			} else {
				this.parentNode.nextSibling.innerHTML = $(this).text() + " stars or better";
			} 
			parent.className = this.parentNode.selectedSpan;
		}
		this.parentNode.className = this.parentNode.selectedSpan;
		$(this).parent().parent().parent().parent().find('h5').attr('class','open');
		this.parentNode.parentNode.parentNode.style.display='block';			
		});
	}
	fromProductPage=false;
}

// PRICE USER INPUT ENHANCEMENT STARTS HERE
var priceClickRangeGo=function() {
	// Uncheck Price range radio buttons
	$("li#slider input:checked").removeAttr("checked");
         //Flag is set to true when ajax call happens on Go button 
	userInputPrice=true;
	$('div#body-curtain').hide();
	$('div.progress').hide();

	
		if($("div.left-column h4:eq(0) a").length<1){
			$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
			$("div.left-column h4:eq(0) a").click(clearAll);
		}

		if($('li#slider').parent().parent().find("h5").children("a").length<1){
			var createClearHtml = "<a href='javaScript.html' name='"+$(this).parent().parent().parent().attr('class')+"' title='Clear selections'>Clear</a>";
			$('li#slider').parent().parent().find("h5").prepend(createClearHtml);
			$('li#slider').parent().parent().addClass("selected");
			$('li#slider').parent().parent().find("h5").children("a").click(clearSelection);
		}
				
		if(isI18NConvReq()){
			//Reverse convert the prices to dollars so that it can be used in mercado query
			var rangeLow = performReversion($("#range_low").val());
			var rangeHigh = performReversion($("#range_high").val());
			lastFilter=lastFilter+",Price2:"+rangeLow+"-"+rangeHigh;
		}else{
			lastFilter=lastFilter+",Price2:"+$("#range_low").val()+"-"+$("#range_high").val();
		}
		
		prefilter({useRangeForm:true});
	
		if(filterParamAfterAjaxCall!=filterParam ){
			// Set the Offset for Update and NoResults popup
			var newTop = $('li#slider').parent().offset();
			$('div#filterConfirm').css({top: newTop.top});
	        $('div#noresults').css({top: newTop.top});
			gotoPage(1);
			ajaxImpl();
		
		}
		
	return false;
};

function inputRangeButtonError(){
		/*Check for empty input boxes*/
		if ($("#range_low").val()=="" && $("#range_high").val()==""){
			return;
		}
		
		else if (parseFloat($("#range_low").val()) >= parseFloat($("#range_high").val())){
	
    		findPosExact(this);
			
		    var tempModal = '<div id="tempWrap" class="modalWrap"></div><div id="tempContent" class="modalContent"><a class="closeWin" title="Close Window" href="javascript:;" >close</a><p><strong>Please enter a maximum price that is greater than the minimum price.</p></strong></div>';
		    $('body').append(tempModal);
		    var wrap = $('#tempWrap');
		    var content = $('#tempContent');
		    $('.modalWrap').hide();
		    $('.modalContent').hide();
		    if ( $.browser.msie && /7.0/.test(navigator.userAgent)) xPos += 200;
		    $(wrap).show().css('top', (yPos - 162)).css('left', (xPos + 25));
		    $(content).show().css('top', (yPos - 157)).css('left', (xPos + 30));
		    $('.modalContent a.closeWin').click(function() {
			$(wrap).remove();
			$(content).remove();
			clearInputRangeFields();
		    });
	/*            $(this).blur(function() {
			$(wrap).remove();
			$(content).remove();
		    });*/
		}
		
		else if (parseFloat($("#range_high").val()) < defaultMinPriceValue){
		    findPosExact(this);
						
		    var tempModal = "";
		    if(isI18NConvReq()){
			    tempModal = '<div id="tempWrap" class="modalWrap"></div><div id="tempContent" class="modalContent"><a class="closeWin" title="Close Window" href="javascript:;" >close</a><p><strong>Please enter a maximum price that is greater than '+ i18nCookieData.currencyCode+ ' '+ defaultMinPriceValue +'.</p></strong></div>';
			}else{
		    	tempModal = '<div id="tempWrap" class="modalWrap"></div><div id="tempContent" class="modalContent"><a class="closeWin" title="Close Window" href="javascript:;" >close</a><p><strong>Please enter a maximum price that is greater than $'+ defaultMinPriceValue+'.</p></strong></div>';		   
		   	}
		    $('body').append(tempModal);
		    
		    var wrap = $('#tempWrap');
		    var content = $('#tempContent');
		    $('.modalWrap').hide();
		    $('.modalContent').hide();
		    if ( $.browser.msie && /7.0/.test(navigator.userAgent)) xPos += 200;
		    $(wrap).show().css('top', (yPos - 162)).css('left', (xPos + 25));
		    $(content).show().css('top', (yPos - 157)).css('left', (xPos + 30));
		    $('.modalContent a.closeWin').click(function() {
			$(wrap).remove();
			$(content).remove();
					clearInputRangeFields();
           		 });
		
		}
		
		
		else if (parseFloat($("#range_low").val()) > defaultMaxPriceValue){
				    findPosExact(this);
					var tempModal = "";
				    if(isI18NConvReq()){
				    	tempModal = '<div id="tempWrap" class="modalWrap"></div><div id="tempContent" class="modalContent"><a class="closeWin" title="Close Window" href="javascript:;" >close</a><p><strong>Please enter a minimum price that is lesser than '+ i18nCookieData.currencyCode+ ' '+ defaultMaxPriceValue+'.</p></strong></div>';
					}else{
				    	tempModal = '<div id="tempWrap" class="modalWrap"></div><div id="tempContent" class="modalContent"><a class="closeWin" title="Close Window" href="javascript:;" >close</a><p><strong>Please enter a minimum price that is lesser than $'+ defaultMaxPriceValue+'.</p></strong></div>';
				   	}				   
				    $('body').append(tempModal);
				    
				    var wrap = $('#tempWrap');
				    var content = $('#tempContent');
				    $('.modalWrap').hide();
				    $('.modalContent').hide();
				    if ( $.browser.msie && /7.0/.test(navigator.userAgent)) xPos += 200;
				    $(wrap).show().css('top', (yPos - 162)).css('left', (xPos + 25));
				    $(content).show().css('top', (yPos - 157)).css('left', (xPos + 30));
				    $('.modalContent a.closeWin').click(function() {
					$(wrap).remove();
					$(content).remove();
							clearInputRangeFields();
		           		 });
				
		}
		
		else{
			
			priceClickRangeGo();
		}
}
	
function clearInputRangeFields(){
	
	$("#range_low").val("");
	$("#range_high").val("");

}

//Method for generating DDItemList.
function generateDDItemList(prodIndexArray, appendHead, startIdx, endIdx) {
if(!endIdx){endIdx = jsonProducts.products.length}

	//Reset URL paramter DDItemList to empty
	DDItemList="";
	/*Sequential loop for iterating through the jsonProducts*/	
	for (i=startIdx;i<=(endIdx-1);i++){
		if((i-1)<jsonProducts.products.length){
			/*Variable for processing products array*/
			var j=(i-1); //For array index to start from zero
			if ((jsonProperties.regAvail == "true")&& (jsonProducts.products[j].bt == jsonProperties.sppb
					&& (jsonProducts.products[j].pbType == jsonProperties.spnv 
			 		|| jsonProducts.products[j].pbType == jsonProperties.spa)
					&& (jsonProducts.products[j].dd == true || jsonProducts.products[j].ndd == true))
					&& jsonProducts.products[j].venname == "Sears"){
					DDItemList+= jsonProducts.products[j].no+"|";
			}
			
		}
	}

}

// PRICE USER INPUT ENHANCEMENT ENDS HERE
// Function to display the products on the page
function jsonDisplayProd(prodIndexArray, appendHead, startIdx, endIdx) {
if(!endIdx){endIdx = jsonProducts.products.length}
//jslog.info('jsonDisplayProd called ');
//jslog.info('prodIndexArray for jsonDisplayProd is ' + eval(prodIndexArray));
/*Variable which is used for generating products */
	var results="";
	var swatchHTML = "";
    if (typeof jsonDisplayProd_ATO_STL !='undefined') {
      results = jsonDisplayProd_ATO_STL(prodIndexArray, appendHead);	
      return results;
    }
	var storeId=jsonProperties.sid;
	var catalogId=jsonProperties.cid;
	vName=escape(jsonProperties.vName);
		vName = replaceAll(vName,"%20","+");
	cName=escape(jsonProperties.cName);
		cName = replaceAll(cName,"%20","+");
	sName=escape(jsonProperties.sName);
		sName = replaceAll(sName,"%20","+");
	keyword = escape(jsonProperties.keyword);
		keyword = replaceAll(keyword,"%20","+");
	var size=jsonProducts.products.length;
	var regSaveStory = '';
	if(typeof allRegiSS !='undefined' && allRegiSS.length >0 ){
		allRegiSS.splice(0,allRegiSS.length);
	}
	
	// Finding position for W2 Drop zones
	//var rowCount = 0;
	//Reset URL paramter DDItemList to empty
	//DDItemList="";
	/*Sequential loop for iterating through the jsonProducts*/	
	for (i=startIdx;i<=(endIdx-1);i++){
	if((i-1)<jsonProducts.products.length){
		/*Variable for processing products array*/	
		var j=(i-1); //For array index to start from zero
		var vendorProd="";
		var partNo=jsonProducts.products[j].no;
		var partNoLength=jsonProducts.products[j].no.length;
		var truncPartNumber=jsonProducts.products[j].no.substring(0,partNoLength-1);
		var xFormatVendor = false;
		var vendorImgUrl;
		var vendorProduct = false;
		var regAvaEliProd = false;
		var finalSaveStory = jsonProducts.products[j].ss;
		var priceForNetDown = jsonProducts.products[j].price;
		// Set xFormat flag if product is xFormat vendor product. to be set only in Sears & Kmart
		if((jsonProducts.products[j].vid!=null && jsonProducts.products[j].vid.length>0) && (jsonProducts.products[j].vid == "Kmart" || jsonProducts.products[j].vid == "Sears")) {
			xFormatVendor = true;
		}
		if((jsonProducts.products[j].vid!=null && jsonProducts.products[j].vid.length>0) && !(jsonProducts.products[j].vid == "Kmart" || jsonProducts.products[j].vid == "Sears")){
			vendorProduct = true;
		}
		// Set if the product is regional availabilty eligible. Condition is it should be Sears
		if(jsonProperties.regAvail == "true" && jsonProducts.products[j].venname == "Sears" && jsonProducts.products[j].bt == jsonProperties.sppb) {
			regAvaEliProd = true;
		}
		if (regAvaEliProd && (jsonProducts.products[j].pbType == jsonProperties.spnv 
		 		|| jsonProducts.products[j].pbType == jsonProperties.spa)
				&& (jsonProducts.products[j].dd == true || jsonProducts.products[j].ndd == true)) {
				// Add the product to DD Items Array and set regional avail indicator to true.
				ddItemPartNumArr[ddItemPartNumArr.length] = jsonProducts.products[j].no;
		}
		
		//Store the vendor product url
		var productUrl="";
        productUrl+=jsonProducts.products[j].vurl;
        if(!vendorProduct) {
            productUrl="p_"+storeId+"_"+catalogId+"_"+partNo;
            productUrl=productURLGen(productUrl);
            // Omniture tracking parameter for xformat products
            if(xFormatVendor) {
            	productUrl=productUrl.indexOf("?")>=0?productUrl+"&sid=":productUrl+"?sid=";
            	if("Kmart" == jsonProducts.products[j].vid) {
            		productUrl += "K-on-Sx20k061224x0000002";
            	} else {
            		productUrl += "S-on-Kx20k061224x0000002";
            	}
            }
        }
        
        // To pass paramter "mv=shf", to populate evar 40 with "shoe finder" value in product page - omiture tracking for shoe Finder
        if (typeof gup !='undefined') {
            var shoeFinder = gup('shoeFinder');
            if(shoeFinder !='undefined' &&  shoeFinder=='true') {
            productUrl+="&mv=shf";      
            }
        }
        
        var prodDisplayName=jsonProducts.products[j].na;
        vendorImgUrl = jsonProducts.products[j].img;
        
        /*Check for Vendor products with valid Image URL to the vendor site*/
        if(vendorProduct && !vendorImgUrl.match("^(http:)")) {
        	vendorImgUrl=jsonProperties.img1+jsonProducts.products[j].img+"?"+jsonProperties.img3;
			var imageUrl='<img title=\" '+prodDisplayName+' at '+jsonProperties.sn+'.com\" class= \"\" width=\"180\" height=\"180\" border=\"0\" alt=\"';
        }
        else if(vendorProduct && vendorImgUrl.indexOf("image_not_available")==-1) {            
            if(vendorImgUrl.indexOf("w=")>=0) {
                var vendorImgWidthUrl=vendorImgUrl.split("w=")[1];          
                var vImgWidth=vendorImgWidthUrl.substring(0,vendorImgWidthUrl.indexOf("&"));
            }
            if(vendorImgUrl.indexOf("h=")>=0) {
                var vImgHeight=vendorImgUrl.split("h=")[1]; 
            }
            var width=180;
            var height=180;
            if(vImgWidth > 0 && vImgHeight > 0) {
            
                wSpace = 180;
                hSpace = 180;
                if(vImgWidth <= wSpace && vImgHeight <= hSpace) {               
                    width = vImgWidth;
                    height = vImgHeight;
                } else {        
                    var scale=1;
                    if(vImgWidth > wSpace && vImgHeight<= hSpace){
                        scale = wSpace/vImgWidth;
                        width = wSpace;                     
                        height = Math.floor(vImgHeight*scale);                      
                    }
                    else if(vImgWidth <= wSpace && vImgHeight > hSpace){
                        scale = hSpace/vImgHeight;
                        width = Math.floor(vImgWidth*scale);
                        height = hSpace;
                                                
                    }
                    else {              
                        if ((vImgWidth - wSpace) > (vImgHeight-hSpace)){
                            scale = wSpace/vImgWidth;                   
                        } 
                        else {
                            scale = hSpace/vImgHeight;
                        }
                        width = Math.floor(vImgWidth*scale);
                        height = Math.floor(vImgHeight*scale);
                    }
                }   
            }
            var marginTop=((180-height)/2);
            var marginBottom=((180-height)/2);
            var marginLeft=((180-width)/2); 
            var marginRight=((180-width)/2);
            var imageUrl='<img title=\" '+prodDisplayName+' at '+jsonProperties.sn+'.com\" style=\"margin-left:'+marginLeft+'px;margin-right:'+marginRight+'px;margin-top:'+marginTop+'px;margin-bottom:'+marginBottom+'px;\" width=\"'+width+'\" height=\"'+height+'\" border=\"0\" alt=\"';
        } else {
			var imageUrl='<img title=\" '+prodDisplayName+' at '+jsonProperties.sn+'.com\" class= \"\" alt=\"';
        }
            
        prodDisplayName=js_ReplaceChar(prodDisplayName,'"','&quot;');
        prodDisplayName=js_ReplaceChar(prodDisplayName,"'","&#39;");
        imageUrl+=prodDisplayName;
        if(!vendorProduct) {
            if(jsonProducts.products[j].img == null)
            {
                if(jsonProperties.noImage != false)
                {
                imageUrl+="\" src="+jsonProperties.jsid+jsonProperties.noImage+">";
                }
                else
                {
                imageUrl+="\" src="+jsonProperties.img1+jsonProducts.products[j].img+"?"+jsonProperties.img3+">";
                }
            }
            else
            {
            if(jsonProducts.products[j].img==""){	        		
        		if(storeId==10156){
					imageUrl+="\" src="+jspStoreImgDir+"img/icons/no_image.jpg style=\"width:180px;height:180px;\">";
				}else{
					imageUrl+="\" src="+jspStoreImgDir+"img/icons/no_image.jpg>";
				}
			}else{     		
            imageUrl+="\" src="+jsonProperties.img1+jsonProducts.products[j].img+"?"+jsonProperties.img3+">";
            }
            }
        }else {
            imageUrl+="\" src="+vendorImgUrl+">";   
        }

        /*Check for Valid Part Number*/
        if((jsonProducts.products[j].no!=null && jsonProducts.products[j].no.length != 0) 
                || vendorProduct){
            if(i==1 || (i-1)%4==0){
                    /* Code commented as part of Keyword Banner Change. Will use it at later stages if required.
                    // Displaying W2 Drop zones
                    if(rowCount == (Math.ceil(Math.ceil(prodIndexArray.length/4)/2))) {
                        if($('div#results').attr('class') == 'grid'){
                            results+='<div class="dropzone_wrap" id="dropzoneW2_grid">';
                        }
                        else{
                            results+='<div class="dropzone_wrap" id="dropzoneW2_grid" style="display: none;" >';
                        }
                        results+=$('div#dropzoneW2').html();
                        results+='</div>'
                    }
                    rowCount++;
                    Code commented out as part of Keyword Banner Change. Will use it at later stages if required. */
                    results+='<div class="searchResult">';                             
            }
            var divClass="";
            if(i%4==0) {
                divClass = "product end";
            }
            else{
                divClass ="product";             
            }
            //Check for Kmart store
            if(jsonProperties.sn =="Kmart" ){
                 var ksnNo =jsonProducts.products[j].ksn;
                 //Check whether ksn is present
                 if( ksnNo!=null && ksnNo.length > 0){
                    results+='<div class="'+divClass+'" id="pro_' + ksnNo +'">';
                    results+='<div id='+ksnNo+' style="display:none">'+jsonProducts.products[j].cat+'</div>';
                 }else{
                    results+='<div class="'+divClass+'">';
                 }
            }else{
                results+='<div class="'+divClass+'">';
            }
            // Added for 08_19 Softline Swatch Enhancment Start
            swatchHTML = "";
            if(jsonProducts.products[j].dispSw != undefined && jsonProducts.products[j].dispSw == "true") {
            	swatchHTML = '<div class="colorsContainer"><div class="colors"><a class="moreSwatches" onclick="toggleSwatchCarousel(\''+jsonProducts.products[j].cat+'\',\''+jsonProducts.products[j].bt+'\',this)" href="javascript:;">More Colors</a></div></div>';
            }
            // Added for 08_19 Softline Swatch Enhancment End            
            if(jsonProperties.sn =="Kmart" ){
                results+='<div class="photoSwatchContainer"><div class="photo"><a href="'+productUrl+'">'+imageUrl+'</a></div>'+swatchHTML+'</div><div class="info"><p id="prodUrl"><a href="'+productUrl+'" title="'+prodDisplayName+'"><b>'+prodDisplayName+'</b></a></p>';
            }else{          
                results+='<div class="photoSwatchContainer"><div class="photo"><a href="'+productUrl+'">'+imageUrl+'</a></div>'+swatchHTML+'</div><div class="info"><p><a href="'+productUrl+'" title="'+prodDisplayName+'"><b>'+prodDisplayName+'</b></a></p>';                     
            }
			// Display Sold By Text
            if((jsonProperties.sn =="Sears" || jsonProperties.sn =="Kmart") && !vendorProduct) {
            	if(jsonProducts.products[j].dff =="PS"){
            		results+='<p class="vendor">Sold by Personal Shopper</p>';
            	}else{
            		results+='<p class="vendor">Sold by '+jsonProducts.products[j].venname+'</p>';
            	}
			}    
            //Store is Kmart but SPU is disabled
            if(jsonProperties.sn !="Kmart"){
            	results+='<ul class="info">';
                if( jsonProducts.products[j].bt== jsonProperties.sppb && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa) && (jsonProducts.products[j].no.length > 0) ){
                    results+='<li>';
                        if(xFormatVendor) {
                            results+=jsonProperties.spin+truncPartNumber;
                        }
                        else if(jsonProperties.sn!="InsuranceB2B"){
                            results+=jsonProperties.sn+" "+jsonProperties.spin+truncPartNumber;
                        }
                        else{
                            results+=jsonProperties.sears+" "+jsonProperties.spin+truncPartNumber;
                        }
                    results+='</li>';
                
                    //Displaying the partNumber and sku part number
                    if(jsonProducts.products[j].mfg != null && jsonProducts.products[j].mfg.length > 0){ 
                        results+='<li>'+jsonProperties.mfr+jsonProducts.products[j].mfg+'</li>';
                    }
                }else{  
                    results+='<div class="productNumber"></div>';
                }
            }
            
            if(jsonProperties.sn =="Kmart" ){
                if(jsonProducts.products[j].rt!=null && jsonProducts.products[j].rt!= ""){ 
        
                var integRating = parseInt(jsonProducts.products[j].rt)*15; 
                    results+='<ul><li>'+jsonProperties.aru+'<span class="starrating"><a href="'+productUrl+'#reviewsWrap"><span class="stars" style=width:'+integRating+'px;"></span></a></span>';
                    
        
                    if(jsonProducts.products[j].prtu && !xFormatVendor) {  
                        results+=" "+jsonProducts.products[j].nr+" "+jsonProperties.rat;
                    } 
                    results+='</li></ul>';
                }           
            }else{              
                if(jsonProducts.products[j].rt!=null && jsonProducts.products[j].rt!= ""){ 
        
                var integRating = parseInt(jsonProducts.products[j].rt)*15; 
	                if(jsonProperties.sn =="Sears" ){
	               		 if(location.href.indexOf("?")>=0) {	
	                	    results+='<li>'+jsonProperties.aru+'<span class="starrating"><a href="'+productUrl+'&fromSub=true#reviewsWrap"><span class="stars" style=width:'+integRating+'px;"></span></a></span>';
	                	 }
	                	 else
	                	 	results+='<li>'+jsonProperties.aru+'<span class="starrating"><a href="'+productUrl+'?fromSub=true#reviewsWrap"><span class="stars" style=width:'+integRating+'px;"></span></a></span>';
	                }else {
                    results+='<li>'+jsonProperties.aru+'<span class="starrating"><span class="stars" style=width:'+integRating+'px;"></span></span>';
	                }
        
                        if(jsonProducts.products[j].prtu && !xFormatVendor) {  
                            results+=" "+jsonProducts.products[j].nr+" "+jsonProperties.rat;
                        } 
                    results+='</li>';
                } 
            }
            
            var  regss= finalSaveStory.split('<script>');
            if (regss.length >1){
                if(regss[1] != undefined){
                    regSaveStory = regSaveStory + '<script>'+regss[1];
                }
            }
            if(jsonProperties.sn !="Kmart") {
                results+='</ul>';
            }   
                
             /*KMART SPU START*/  
             if(jsonProperties.sn =="Kmart" && !(jsonProducts.products[j].vi!=null && jsonProducts.products[j].vi.length >0)){
               
                // code for displaying availabilty messages
                results+='<div class="availRow" style="display:none">';
                if(!(jsonProducts.products[j].ndd==true) && !(jsonProducts.products[j].dd==true) && (jsonProducts.products[j].dff=='TW' || jsonProducts.products[j].dff=='GC' 
                                    || jsonProducts.products[j].dff=='VD' || jsonProducts.products[j].dff=='VGC')){
                 //Shipping availability message
                 //condition for checking out of stock for shipping
                
                     if(jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1){
                      //Out of stock message
                         results+='<p class="deliv_oos" id="deliv_email">'+jsonProperties.oosShip+' ';
                        //Add the email me link if Email me is eligible.
                        if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
                            if(jsonProducts.products[j].mfg!=null) {
                                results+='<a href=\"javascript:;\" rel=\"emailMe\" info=\"'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].mfg+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ ';
                                results+=jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ \">'+jsonProperties.emailMe+'</a>';
                            }   
                        }
                        results+='</p>';
                 }else{
                   // condtion for item being shipping only
                     if(jsonProducts.products[j].spi!=true ||jsonProducts.products[j].spi==false){
                        results+='<p class="deliv_elig">'+jsonProperties.availShip+'</p>';                            
                     }else{
                         results+='<p class="deliv_in">'+jsonProperties.inShip+'</p>';
                      }
                }        
                //SPU availability message
                //condition to check item is SPU eligible
                if((jsonProducts.products[j].spi==true) && (jsonProducts.products[j].pbType != "VARIATION" && jsonProducts.products[j].bt!="BundleBean") && jsonProperties.enableSBL == 1){
                    results+='<div id="selectStore" value="selectStore"><p class="spu_elig">';
                    results+=jsonProperties.pickAtStore+' - <a href=\"javascript:;\" class="storeSelect">'+jsonProperties.selStore+'</a>';
                    results+='</p></div>';
                }
             }
                //condition for displaying spu details when item is Store pick up only
                else if((jsonProducts.products[j].dff=='SPU') && (jsonProducts.products[j].pbType != "VARIATION" && jsonProducts.products[j].bt!="BundleBean") && jsonProperties.enableSBL == 1 ){
                    //check if store is selected and display the message to select store to view price and availability
                    results+='<div id="selectStore" value="selectStore"><p class="spu_elig">';
                    results+=jsonProperties.spuOnly+' - <a href=\"javascript:;\" class="storeSelect">'+jsonProperties.sStorePrice+'</a>';
                    results+='</p></div>'; 
                }
                //End of AvailRow Div
                results+='</div>';
                  
             }//end if for Kmart store
            //Kmart SPU ENDS
            
            if(jsonProperties.sn =="Kmart" ){
                if( jsonProducts.products[j].bt== jsonProperties.sppb && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa) && (jsonProducts.products[j].no.length > 0) ){
                    results+='<ul><li>';
                        if(xFormatVendor) {
                            results+=jsonProperties.spin+truncPartNumber;
                        }
                        else if(jsonProperties.sn!="InsuranceB2B"){
                            results+=jsonProperties.sn+" "+jsonProperties.spin+truncPartNumber;
                        }
                        else{
                            results+=jsonProperties.sears+" "+jsonProperties.spin+truncPartNumber;
                        }
                    results+='</li>';
                
                    //Displaying the partNumber and sku part number
                    if(jsonProducts.products[j].mfg != null && jsonProducts.products[j].mfg.length > 0){ 
                        results+='<li>'+jsonProperties.mfr+jsonProducts.products[j].mfg+'</li></ul>';
                    }
                }else{  
                    results+='<div class="productNumber"></div>';
                }
            }           
            
            //End of Info Div
            results+='</div>';
            var streetDate = jsonProducts.products[j].psl;
            var hasPreSell = streetDate!=null && streetDate != '';
            if(jsonProperties.enableDynSS == 'true') {
            	if(typeof jsonDynamicSSDetails[jsonProducts.products[j].no] != 'undefined' 
            		&& jsonDynamicSSDetails[jsonProducts.products[j].no].ss != 'undefined'
            		&& jsonDynamicSSDetails[jsonProducts.products[j].no].ss != null 
            		&& jsonDynamicSSDetails[jsonProducts.products[j].no].ss != '') {            		
            		finalSaveStory = jsonDynamicSSDetails[jsonProducts.products[j].no].ss;
            		priceForNetDown = jsonDynamicSSDetails[jsonProducts.products[j].no].cp;
            	}
            }
            //Check the store is except Kmart OR Store is Kmart but SPU is disabled
            if(jsonProperties.sn !="Kmart"){
                results+='<div class="price"><div class="saveStory clearfix">';
                if(isI18NConvReq()){
	                results+=fnConSSfly(finalSaveStory);
	            }else{
	            	results+=finalSaveStory;
	            }
                if(jsonProperties.enableDynPricing == "true"){
                	if(jsonProducts.products[j].pi!=null && jsonProducts.products[j].pi==1){
                		//sets the rebate indicator flag after checking it in the savestory
                		var rebateInd = finalSaveStory.indexOf("<div class=\"rebates\">")>=0?true:false;
                		//var mapInd = finalSaveStory.indexOf("class=\"mapLink\"")>=0?true:false;
                		var mapInd = false;
						if(finalSaveStory.indexOf("Click to see our price")>=0 
							|| finalSaveStory.indexOf("Add to cart to see our price")>=0 
							|| finalSaveStory.indexOf("Additional savings Applied at cart")>=0){
							mapInd = true;
						}
                		//if netdown deals or rebate offers are avialable get the appropriate message of netdown deals
                		//For the products which does not fall under the DIV in Config, Add the Net Down Deals from SHC component
                		if(typeof jsonSHCNetdownDeal[jsonProducts.products[j].no] != 'undefined'){
	                		if(jsonSHCNetdownDeal[jsonProducts.products[j].no].nd != null && rebateInd != null && priceForNetDown != null){
		                		 if(isI18NConvReq()){
					                results+=fnConSSfly(fnGenNetDownMsg(priceForNetDown,jsonSHCNetdownDeal[jsonProducts.products[j].no].nd,rebateInd,mapInd));
					            }else{
					            	results+=fnGenNetDownMsg(priceForNetDown,jsonSHCNetdownDeal[jsonProducts.products[j].no].nd,rebateInd,mapInd);
					            }
		                	}
	                	}
	                	//For the products which fall under the DIV in Config,Add the Net Down Deals from APAR component
	                	else if(typeof jsonAPARNetdownDeal[jsonProducts.products[j].no] != 'undefined'){
	                		if(jsonAPARNetdownDeal[jsonProducts.products[j].no].nd != null && rebateInd != null && priceForNetDown != null){
		                		 if(isI18NConvReq()){
					                results+=fnConSSfly(fnGenNetDownMsg(priceForNetDown,jsonAPARNetdownDeal[jsonProducts.products[j].no].nd,rebateInd,mapInd));
					            }else{
					            	results+=fnGenNetDownMsg(priceForNetDown,jsonAPARNetdownDeal[jsonProducts.products[j].no].nd,rebateInd,mapInd);
					            }
		                	}
	                	}
	                }
                }
                results+='</div>';
            }else{
                //If the store is Kmart only
                
                if(jsonProducts.products[j].dff=='SPU'){
                    results+='<div class="price"><div class="saveStory" id="saveStory" style="display:none">'+finalSaveStory;
                }else {
                    results+='<div class="price"><div class="saveStory" id="saveStory" style="display:block">'+finalSaveStory;
                }
                if(jsonProperties.enableDynPricing == "true"){
                	if(jsonProducts.products[j].pi!=null && jsonProducts.products[j].pi==1){
                		//sets the rebate indicator flag after checking it in the savestory
                		var rebateInd = finalSaveStory.indexOf("<div class=\"rebates\">")>=0?true:false;
                		//var mapInd = finalSaveStory.indexOf("class=\"mapLink\"")>=0?true:false;
                		var mapInd = false;
						if(finalSaveStory.indexOf("Click to see our price")>=0 
							|| finalSaveStory.indexOf("Add to cart to see our price")>=0 
							|| finalSaveStory.indexOf("Additional savings Applied at cart")>=0){
							mapInd = true;
						}
                		//if netdown deals or rebate offers are avialable get the appropriate message of netdown deals
                		//For all Kmart products Add the Net Down Deals from SHC component
                		if(typeof jsonSHCNetdownDeal[jsonProducts.products[j].no] != 'undefined'){
	                		if(jsonSHCNetdownDeal[jsonProducts.products[j].no].nd != null && rebateInd != null && priceForNetDown != null && priceForNetDown != ''){
		                		results+=fnGenNetDownMsg(priceForNetDown,jsonSHCNetdownDeal[jsonProducts.products[j].no].nd,rebateInd,mapInd);
		                	}
	                	}
	                }
                }
                results+='<div class="youPay" id="youPay" style="display:none"><span class="text"></span><span class="pricing"></span></div></div>';
                results+='<div class="lpMsgRow" id="lpMsgRow" style="display:none"></div>';
             }      
            // Add to cart implementation on search results page
            // Initializing flag for Automotive products
            // For the automotive items the first three digits of part number
            // (Division Number) will be 095 or 028 or 090.
            var pdtDivisionNumber = jsonProducts.products[j].no.substring(0,3);
            var isAutomotive = false;
            if((pdtDivisionNumber == '028' || pdtDivisionNumber == '095' || pdtDivisionNumber == '090') && jsonProducts.products[j].venname == "Sears") {
                isAutomotive = true;
            }           
             
          // Add to cart implementation on search results page
          if(jsonProperties.enableATC == "true"){
                if(finalSaveStory!=null && finalSaveStory.length>0) {
                    var orderByPhone1 = (jsonProducts.products[j].vi==jsonProperties.sptc) || (jsonProducts.products[j].vi==jsonProperties.spgc) || (jsonProducts.products[j].vi==jsonProperties.spjc) || (jsonProducts.products[j].vi==jsonProperties.spm);
                    if(!(orderByPhone1==true || jsonProducts.products[j].vi==jsonProperties.spwh || jsonProducts.products[j].vi==jsonProperties.spao || jsonProducts.products[j].vi==jsonProperties.sppt
                            || jsonProducts.products[j].dff=="VIEW_ONLY" || jsonProducts.products[j].dff=="VGC" || jsonProducts.products[j].dff=="GC")){
                        if(vendorProduct){
                            var vendorProd = jsonProducts.products[j].vid;
                        }
                        if((vendorProd!=null && vendorProd.length>0)||(jsonProducts.products[j].si!=null && jsonProducts.products[j].si != 1) || (jsonProducts.products[j].si==1 && !hasPreSell && (jsonProducts.products[j].spi == true || jsonProducts.products[j].sri == 1 )) ){
                            if((vendorProd!=null && vendorProd.length>0) || (jsonProducts.products[j].bt== jsonProperties.sppb && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa))){
                                if( jsonProperties.sn != null &&(jsonProperties.sn == "Sears" || jsonProperties.sn =="Kmart" || jsonProperties.sn =="Kenmore" || jsonProperties.sn =="InsuranceB2B" || jsonProperties.sn =="The Great Indoors")) {

                                        // If the product is a Vendor product get the Price Range indicator. IF it EMPTY or 0, display Add to cart, else display Product Details
                                        var vendorPriceRangeInd = (jsonProducts.products[j].vprind =="1")?true:false;
                                        
                                        if(((vendorProd!=null && vendorProd.length>0) || (jsonProducts.products[j].dd == false && jsonProducts.products[j].ndd== false && isAutomotive==false))
                                             && vendorPriceRangeInd == false && vendorProd!='JCW' && vendorProd!='STL' && vendorProd !='HSV' && jsonProducts.products[j].vid!="KPX"){
                                             
                                             
											//I18N
											if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping!='YES'){
											}
											else if((prepaidCell=='true' && prepaidCellCookieOnPageLoad=='false')){
											
											  results+='<fieldset class="selectOptions"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
											}
											else{
												
                                            // Hide the ADD to CART button for regionally priced products
                                                var imageName = '';
                                                if(hasPreSell){ 
                                                    imageName = 'preOrder.gif';
                                                } else {
                                                    imageName = 'btn_addtocartbrowse.gif';
                                                }
                                            if(finalSaveStory.indexOf("regiSS")<0){
                                                if(jsonProperties.sn=="Kmart" && jsonProducts.products[j].dff=='SPU'){                                                  
                                                    results+='<fieldset class="addToCart" style="display:none"><a href="javascript:addItemPartNo(';                                                 
                                                }else {
                                                    results+='<fieldset class="addToCart" style="display:block"><a href="javascript:addItemPartNo(';
                                                }                                                       
                                            }else{                                      
                                                results+='<fieldset class="addToCart" style="display:none"><a href="javascript:addItemPartNo(';
                                            }   
                                            results+="\'"+jsonProducts.products[j].no+"\'"; 
                                            results+=",";
                                            results+="\'"+jsonProducts.products[j].si+"\'";
                                            results+=",";
                                            results+="\'"+jsonProducts.products[j].spi+"\'";
                                            results+=",";
                                            results+="\'"+jsonProducts.products[j].sri+"\'";
                                            results+=",";
                                            results+="\'"+jsonProducts.products[j].dff+"\'";
                                            results+=",";
                                            results+="\'"+vendorProd+"\'";
                                            results+=",";                                                       
                                            results+="\'"+streetDate+"\'";
                                            results+=');" class="submit"><img src="'+jspStoreImgDir+'img/buttons/'+imageName+'" /></a></fieldset>';
                                            
                                            //I18N
                                            }
                                            
                                    } else if(!regAvaEliProd && (vendorProd=="" || vendorProd==null || vendorPriceRangeInd == true ||  vendorProd=='JCW' || vendorProd=='STL' || vendorProd=='HSV'
                                                || jsonProducts.products[j].ndd== true || jsonProducts.products[j].dd== true || isAutomotive==true || jsonProducts.products[j].vid=="KPX")){                                                                                                            
                                            if(finalSaveStory.indexOf("regiSS")<0){
                                                results+='<fieldset class="selectOptions" style="display:block"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
                                            }else{      
                                                results+='<fieldset class="selectOptions" style="display:none"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';                                               
                                            }
                                        }
                                     // If the store is Sears and ndd or dd is true showing add to cart button
									else if(regAvaEliProd && (vendorProd=="" || vendorProd==null || vendorPriceRangeInd == true ||  vendorProd=='JCW'
												|| isAutomotive==true)){																											
												if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping!='YES'){
												}
												else{
												if(finalSaveStory.indexOf("regiSS")<0){
												 	//i18n change-show add to cart only when product is in stock.
												 	if(isI18NConvReq()){
													 	if(((jsonProperties.sn =="Sears") && jsonProducts.products[j].intshipping =='YES') && (jsonProducts.products[j].dd == true || jsonProducts.ndd == true) && (jsonProducts.products[j].si!=1)){
if(prepaidCell=='true' && prepaidCellCookieOnPageLoad=='false'){
															 results+='<fieldset class="selectOptions"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
														}else{
													 		var DDCATCValue="";
															var catentryVal=jsonProducts.products[j].cat;
															DDCATCValue+="\'"+jsonProducts.products[j].no+"\'";	
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].si+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].spi+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].sri+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].dff+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+vendorProd+"\'";
															DDCATCValue+=",";														
															DDCATCValue+="\'"+streetDate+"\'";
															results+='<fieldset class="addToCartDel" id=ddcAtc_'+jsonProducts.products[j].no+' style="display:block;cursor:pointer;" onClick="fnAddDdctoCart('+catentryVal+','+DDCATCValue+');" rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^N^CAT^'+jsonProducts.products[j].cat+'">';
															results+='<img src="'+jspStoreImgDir+'img/buttons/btn_addtocartbrowse.gif" /></a></fieldset>';
												 		}
}
												 		else{
														results+='<fieldset class="selectOptions" style="display:block"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
														}
													}
													
													else{
														if(jsonProducts.products[j].dd == true || jsonProducts.ndd == true){
if(prepaidCell=='true' && prepaidCellCookieOnPageLoad=='false'){
																 results+='<fieldset class="selectOptions"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
															}
															else{
															var DDCATCValue="";
															var catentryVal=jsonProducts.products[j].cat;
															DDCATCValue+="\'"+jsonProducts.products[j].no+"\'";	
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].si+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].spi+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].sri+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+jsonProducts.products[j].dff+"\'";
															DDCATCValue+=",";
															DDCATCValue+="\'"+vendorProd+"\'";
															DDCATCValue+=",";														
															DDCATCValue+="\'"+streetDate+"\'";
															results+='<fieldset class="addToCartDel" id=ddcAtc_'+jsonProducts.products[j].no+' style="display:block;cursor:pointer;" onClick="fnAddDdctoCart('+catentryVal+','+DDCATCValue+');" rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^N^CAT^'+jsonProducts.products[j].cat+'">';
															results+='<img src="'+jspStoreImgDir+'img/buttons/btn_addtocartbrowse.gif" /></a></fieldset>';
														}
}
														else{
															results+='<fieldset class="selectOptions" style="display:block"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
														}
												}}else{
													results+='<fieldset class="selectOptions" style="display:none"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';												
												}
											}
										}
                                        
                                        

                                }
                            }
                        }
                    }
                }
                if(vendorProd=="") {
                    if((jsonProducts.products[j].bt== jsonProperties.sppb && jsonProducts.products[j].pbType== "VARIATION" ) || jsonProducts.products[j].dff=="VGC" || jsonProducts.products[j].dff=="GC"){
                        if( jsonProperties.sn != null &&(jsonProperties.sn == "Sears" || jsonProperties.sn =="Kmart" || jsonProperties.sn =="Kenmore" || jsonProperties.sn =="InsuranceB2B" || jsonProperties.sn =="The Great Indoors")) {
                                results+='<fieldset class="selectOptions"> <a href="'+productUrl+'" onclick="" class="submit"><img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectOptions" alt="Select Options" id="selectOptions" /></a></fieldset>';
                        }
                    }               
                    if(jsonProducts.products[j].bt != jsonProperties.sppb ) {
                        if( jsonProperties.sn != null &&(jsonProperties.sn == "Sears" || jsonProperties.sn =="Kmart" || jsonProperties.sn =="Kenmore" || jsonProperties.sn =="InsuranceB2B" || jsonProperties.sn =="The Great Indoors")) {
                            results+='<fieldset class="selectOptions"><a href="'+productUrl+'" onclick="" class="submit"> <img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" width="129" height="20" name="selectItems" alt="Select Items" id="selectItems" /></a></fieldset>';
                        }
                    }
                }
            }
        /*KMART SPU START*/

        //Check the store is Kmart or not 
        if(jsonProperties.sn =="Kmart" && !(jsonProducts.products[j].vi!=null && jsonProducts.products[j].vi.length >0) && !hasPreSell){
       // code for displaying availabilty messages
          results+='<div class="availGrd" style="display:block">';
        
          if(!(jsonProducts.products[j].ndd==true) && !(jsonProducts.products[j].dd==true) && (jsonProducts.products[j].dff=='TW' || jsonProducts.products[j].dff=='GC' 
                                    || jsonProducts.products[j].dff=='VD' || jsonProducts.products[j].dff=='VGC')){

              //Shipping availability message
              //condition for checking out of stock for shipping
                
              if(jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1){
                    //Out of stock message
                   results+='<p class="deliv_oos" id="deliv_email">'+jsonProperties.oosShip+' ';
                    //Add the email me link if Email me is eligible.
                    if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
                        if(jsonProducts.products[j].mfg!=null) {                            
                                results+='<a href=\"javascript:;\" rel=\"emailMe\" info=\"'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].mfg+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ ';
                                results+=jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ \">'+jsonProperties.emailMe+'</a>'; 
                        }   
                    }
                    results+='</p>';
              }else{
                   // condtion for item being shipping only
                   if((jsonProducts.products[j].spi!=true ||jsonProducts.products[j].spi==false)){
                        results+='<p class="deliv_elig">'+jsonProperties.availShip+'</p>';                            
                    }else{
                         results+='<p class="deliv_in">'+jsonProperties.inShip+'</p>';
                    }
               }        
             //SPU availability message
             //condition to check item is SPU eligible
              if((jsonProducts.products[j].spi==true) && (jsonProducts.products[j].pbType != "VARIATION" && jsonProducts.products[j].bt!="BundleBean") && jsonProperties.enableSBL == 1){
                    //i18n change
                    if((jsonProperties.sn =="Sears") && (isI18NConvReq())){
					}
					else{
                    results+='<div id="selectStore" value="selectStore"><p class="spu_elig">';
                    results+=jsonProperties.pickAtStore+' - <a href=\"javascript:;\" class="storeSelect">'+jsonProperties.selStore+'</a>';
                    results+='</p></div>'; }
               }
          }
          //condition for displaying spu details when item is Store pick up only
           else if((jsonProducts.products[j].dff=='SPU') && (jsonProducts.products[j].pbType != "VARIATION" && jsonProducts.products[j].bt!="BundleBean") && jsonProperties.enableSBL == 1 ){
                //check if store is selected and display the message to select store to view price and availability
                //i18n change
                if((jsonProperties.sn == "Sears") && (isI18NConvReq())){
				}
				else{
                results+='<div id="selectStore" value="selectStore"><p class="spu_elig">';
                results+=jsonProperties.spuOnly+' - <a href=\"javascript:;\" class="storeSelect">'+jsonProperties.sStorePrice+'</a>';
                results+='</p></div>';}
           }
                //End of AvailGrd Div
                results+='<div class="lpMsgGrd" id="lpMsgGrd" style="display:none"></div>';
                results+='</div>';
        }
        //end if for Kmart store
        //Kmart SPU ENDS
        
        //Display the Click to Talk and Click to Chat links for OOS items - Only for Sears/Kmart
                if((jsonProperties.sn == "Sears" || jsonProperties.sn =="Kmart") && (jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1) && !vendorProduct) {
                    if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa) && (jsonProducts.products[j].spi != true)){
                        if(jsonProperties.sn == "Kmart") {
                            //for Kmart
                            results+='<div class="psOOS">';
                            results+='<span>Need help?</span>';
                            results+='<a class="psTalk" onclick="javascript:window.open(\'https://sales.liveperson.net/hc/37457093/?cmd=file&file=visitorWantsToTalk&site=37457093&byhref=1&SESSIONVAR!skill=kmart-personalshopper-voice-sales-english&SESSIONVAR!staticButton=voice-personalshopper-oos-english\',\'\',\'scrollbars=no,location=no,titlebar=no,resizable=no,menubar=no,width=450,height=300\');" href="javascript:;">Click to talk</a>';
                            results+='<a class="psChat" onclick="javascript:window.open(\'https://sales.liveperson.net/hc/37457093/?cmd=file&file=visitorWantsToChat&site=37457093&byhref=1&SESSIONVAR!skill=kmart-personalshopper-chat-sales-english&SESSIONVAR!staticButton=chat-personalshopper-oos-english\',\'\',\'scrollbars=no,location=no,titlebar=no,resizable=no,menubar=no,width=450,height=400\');" href="javascript:;">Click to chat</a>';
                            results+='</div>';
                        }
                        else{
                            //for sears
                            //i18n change
                            if((jsonProperties.sn =="Sears") && (isI18NConvReq())){
							}
							else{
                            results+='<div class="psOOS">';
                            results+='<span>Need Help?</span>';
                            results+='<a class="psTalk" onclick="javascript:window.open(\'https://sales.liveperson.net/hc/37457093/?cmd=file&file=visitorWantsToTalk&site=37457093&byhref=1&SESSIONVAR!skill=sears-personalshopper-voice-sales-english&SESSIONVAR!staticButton=voice-personalshopper-oos-english\',\'\',\'scrollbars=no,location=no,titlebar=no,resizable=no,menubar=no,width=450,height=300\');" href="javascript:;">Click to talk</a>';
                            results+='<a class="psChat" onclick="javascript:window.open(\'https://sales.liveperson.net/hc/37457093/?cmd=file&file=visitorWantsToChat&site=37457093&byhref=1&SESSIONVAR!skill=sears-personalshopper-chat-sales-english&SESSIONVAR!staticButton=chat-personalshopper-oos-english\',\'\',\'scrollbars=no,location=no,titlebar=no,resizable=no,menubar=no,width=450,height=400\');" href="javascript:;">Click to chat</a>';
                            results+='</div>';
                            }
                        }
                    }
                }
                //End of Price Div
                results+='</div>';
            if(jsonProperties.enableATC == "true" && hasPreSell){
                results+='<div class="infoBubble">';
                results+='<div class="preReleaseDate">Release Date: '+ streetDate +'</div>';    
                if(jsonProducts.products[j].si!= 1) {                               
                    preOrderSelectURL = '/shc/s/nb_'+jsonProperties.sid+'_'+jsonProperties.cid+'_NB_PresellDetails';                        
                    results+='<div class="preOrderSelect"><a href="javascript:;" title="Available for Pre-Order">Available for Pre-Order</a>';                              
                } else {                                
                    results+='<div class="comingSoonBtn"><a href="javascript: ;">';
                    results+='<img src="'+jspStoreImgDir+'img/buttons/comingSoon.gif" alt="Item Coming Soon" height="18" width="91"></a><br>';
                    if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
                        if(jsonProducts.products[j].mfg!=null) {                                                           
                            results+='<div class="emailMe"><a href="javascript:;" rel="emailMe" info="'+streetDate+'`'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].mfg+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ ';
                            results+=jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ "> '+jsonProperties.em+' '+jsonProperties.wa+'</a></div>';
                        } else {
                            results+='<div class="emailMe"><a href="javascript:;" rel="emailMe" info="'+streetDate+'`'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ '+jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ "> '+jsonProperties.em+' '+jsonProperties.wa+'</a></div>';                       
                        }
                    }
                }
                results+='</div></div>';                                                        
            }
            //Check the store is not Kmart OR Store is Kmart but SPU is disabled
            if(!hasPreSell){
            results+='<div class="availability"><ul class="availability">';
            if(jsonProducts.products[j].vi!=null && jsonProducts.products[j].vi.length >0 ) {
                
                
                if((jsonProducts.products[j].vi==jsonProperties.sptc) || (jsonProducts.products[j].vi==jsonProperties.spgc) || (jsonProducts.products[j].vi==jsonProperties.spjc) || (jsonProducts.products[j].vi==jsonProperties.spm) ){
                    
                    results+='<li class="noicon">'+jsonProperties.obp1+'&nbsp;<nobr>'+jsonProperties.pn1+'</nobr></a></li>';
					
                    }
                    if( jsonProducts.products[j].vi==jsonProperties.spwh){
                        results+='<li class="noicon">'+jsonProperties.obp2+'&nbsp;<nobr>'+jsonProperties.pn2+'</nobr></a></li>';
                    	
                    }                       
                    if( jsonProducts.products[j].vi==jsonProperties.spis){
                        results+='<li class="noicon">'+jsonProperties.ais+'</a></li>';
                   		
                    }
                    if( jsonProducts.products[j].vi==jsonProperties.spao){
                        results+='<li class="noicon">'+jsonProperties.sac+'</a></li>';
                    	
                    }
                   //International shipping availability
					if(jsonProperties.sn =="Sears"){
                    	//For Non US
                    	if(isI18NConvReq()){
							if(jsonProducts.products[j].intshipping =='YES'){
									results+='<li class="intShip"><a href="/shc/s/CountryChooserView?storeId=10153&catalogId=12605&intrd=1">'+jsonProperties.intelg+'</a></li>';		
                    }                           
							else{
									results+='<li class="unvIntShip">'+jsonProperties.intinelg+'</li>';								    										    										    	
							}}
						//For US
						else{
							if(jsonProducts.products[j].intshipping =='YES'){
									results+='<li class="intShip"><a href="/shc/s/CountryChooserView?storeId=10153&catalogId=12605&intrd=1">'+jsonProperties.intelg+'</a></li>';		
							}
						}
                     
                    }                           
                }else{
                	//i18n change-shipping unavailable 
                	if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping!='YES'){
					}
                    else if(jsonProperties.sn !="Kmart" && (jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1)){
                    			//i18n change-shipping available
                    			if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping=='YES'){
                    			   results+='<li class="notInStock">'+jsonProperties.osd+'</li>';
                    			}
                                else if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){                                                    
                                        if(jsonProducts.products[j].mfg!=null) {
                                            results+='<li class="emailMe"><a href="javascript:;" rel="emailMe" info="'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].mfg+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ ';
                                            results+=jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ ">'+jsonProperties.em+'</a>'+jsonProperties.wa+'</li>';
                                        }else{
                                            results+='<li class="emailMe"><a href="javascript:;" rel="emailMe" info="'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ '+jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ ">'+jsonProperties.em+'</a>'+jsonProperties.wa+'</li>';                       
                                        }
                                }else{
                                    results+='<li class="notInStock">'+jsonProperties.osd+'</li>';
                                }           
					}else{
						if(!regAvaEliProd) {
							//i18n change
							if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping =='YES'){
							}	
							else{
								if(jsonProducts.products[j].ndd==true) {
								    results+='<li class="expDeliv"><a href="'+productUrl+'">'+jsonProperties.ndd+'</a></li>';
								} else if (jsonProducts.products[j].dd==true) {										    												    	
								    results+='<li class="inStock"><a href="'+productUrl+'">'+jsonProperties.df+'</a></li>';									    										    										    	
							    } else if (jsonProperties.sn !="Kmart" &&(jsonProducts.products[j].dff=='TW' || jsonProducts.products[j].dff=='GC' 
						    			|| jsonProducts.products[j].dff=='VD' || jsonProducts.products[j].dff=='DDC')) {
									results+='<li class="inStock"><a href="'+productUrl+'">'+jsonProperties.isd+'</a></li>';
								}
							}
						} else if(regAvaEliProd) {
							//i18n change
							if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping =='YES'){
							}
							else{
							 	if(jsonProducts.products[j].ndd==true) {	
							    	results+='<li class="expDeliv" id=part_'+jsonProducts.products[j].no+'>'+jsonProperties.ndd;
									results+='<a class="checkAvail" href="javascript:;" rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^Y^CAT^'+jsonProducts.products[j].cat+'">Check Availability</a>';
									
									results+='</li>';
								} 
								else if (jsonProducts.products[j].dd==true) {
								    	results+='<li class="inStock" id=part_'+jsonProducts.products[j].no+'>'+jsonProperties.df;									    										    										    	
											results+='<a class="checkAvail" href="javascript:;" rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^Y^CAT^'+jsonProducts.products[j].cat+'">Check Availability</a>';
										
										results+='</li>';
								}
								else if (jsonProperties.sn !="Kmart" &&(jsonProducts.products[j].dff=='TW' || jsonProducts.products[j].dff=='GC' 
						    			|| jsonProducts.products[j].dff=='VD' || jsonProducts.products[j].dff=='DDC')) {
										results+='<li class="inStock"><a href="'+productUrl+'">'+jsonProperties.isd+'</a></li>';
								}
							}		
				    	}
					}
					//International shipping availability
					if(jsonProperties.sn =="Sears"){
					    //For Non-US
					  	if(isI18NConvReq()){
							if(jsonProducts.products[j].intshipping =='YES'){
									results+='<li class="intShip"><a href="/shc/s/CountryChooserView?storeId=10153&catalogId=12605&intrd=1">'+jsonProperties.intelg+'</a></li>';		
					 		}
							else{
									results+='<li class="unvIntShip">'+jsonProperties.intinelg+'</li>';								    										    										    	
							}
						}
					    //For US
					  	else{
							if(jsonProducts.products[j].intshipping =='YES'){
									results+='<li class="intShip"><a href="/shc/s/CountryChooserView?storeId=10153&catalogId=12605&intrd=1">'+jsonProperties.intelg+'</a></li>';		
				 			}
						}
					}				
					
                    //Online Store Pick up code
                    if((jsonProperties.sn !="Kmart") && (jsonProducts.products[j].spi == true || jsonProducts.products[j].sri == 1)) {
                        //Display Store Pick up Link for NONVARIATION                   
                        if((jsonProperties.sn =="Sears") && (isI18NConvReq())){
						}
                        else if(jsonProducts.products[j].bt == jsonProperties.sppb && (jsonProducts.products[j].pbType == jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
                            if(!regAvaEliProd && (jsonProducts.products[j].mfg!=null)){ 																																
								results+='<li class="storepu"><a href="javascript:;" rel="storePickup" info="'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].mfg+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ '+jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ '+streetDate+'^ ">'+jsonProperties.bo+'</a></li>';																																																																										
							}
							else if(!regAvaEliProd) {
								results+='<li class="storepu"><a href="javascript:;" rel="storePickup" info="'+prodDisplayName+'^ '+jsonProducts.products[j].no+'^ '+jsonProducts.products[j].cat+'^ '+productUrl+'^ '+jsonProperties.jsid+'^ '+jsonProperties.kbd+'^ '+jsonProperties.sid+'^ '+jsonProperties.cid+'^ '+streetDate+'^ ">'+jsonProperties.bo+'</a></li>';																																																																																																						
							}
							else if(regAvaEliProd && (jsonProducts.products[j].mfg!=null)){ 		
								results+='<li class="storepu">'+jsonProperties.bo+". ";
								results+='<a class="checkAvail" href="javascript:;" id=spu_'+jsonProducts.products[j].no+' rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^Y^CAT^'+jsonProducts.products[j].mfg+'^'+jsonProducts.products[j].cat+'^'+productUrl+'^'+jsonProperties.jsid+'^'+jsonProperties.kbd+'^'+jsonProperties.sid+'^'+jsonProperties.cid+'^'+streetDate+'^">Check Availability</a></li>';																																																																										
							}
							else if(regAvaEliProd){
								results+='<li class="storepu">'+jsonProperties.bo+". ";
								results+='<a class="checkAvail" href="javascript:;" id=spu_'+jsonProducts.products[j].no+' rel="regionalAvailability" info="'+jsonProducts.products[j].no+'^Y^CAT^'+jsonProducts.products[j].mfg+'^'+jsonProducts.products[j].cat+'^'+productUrl+'^'+jsonProperties.jsid+'^'+jsonProperties.kbd+'^'+jsonProperties.sid+'^'+jsonProperties.cid+'^'+streetDate+'^">Check Availability</a></li>';																																																																																																						
							}
                        } else if ((jsonProducts.products[j].bt == jsonProperties.sppb && jsonProducts.products[j].pbType == "VARIATION") || jsonProducts.products[j].bt == "BundleBean") {
                            //Display Store Pick up static text for VARIATION and BundleBean
                            results+='<li class="storepu">'+jsonProperties.bo+'</li>';
                        }
                    }
                    //Online Store Pick up code
                    var splOffers = '\'splOffr\'';
                    if((jsonProperties.sid !=jsonProperties.ksid)&&(jsonProperties.sid !=jsonProperties.csid)&&(jsonProperties.sid==10151||jsonProperties.sid==10153)){
                        if((jsonProperties.sn =="Sears") && (isI18NConvReq()) && jsonProducts.products[j].intshipping!='YES'){
						}
                        else if(jsonProducts.products[j].pi!=null && jsonProducts.products[j].pi==1){
                            results+='<li class="spo">';
                            results+='<a href="javascript:;" class="Offer" onClick="javascript:specialOffers(';
                            results+=splOffers;
                            results+=",";
                            results+= jsonProperties.sid;
                            results+=",";
                            results+= jsonProperties.cid;
                            results+=",";
                            results+=jsonProducts.products[j].cat;
                            results+='); return false;">';
                            results+=jsonProperties.so;
                            results+='</a>';
                            results+='</li>';
                        } else if(jsonProducts.products[j].pi!=null && jsonProducts.products[j].pi==1) {
                            results+='<li class="spo">'+jsonProperties.so+'</li>';
                        }
                    }
                }                                       
                results+='</ul></div>';
                }
                if(!vendorProduct){
                	results+='<div id="comparison" class="util">';
                    results+='<p class="compare"><input type="checkbox" name="'+jsonProducts.products[j].no+'"onclick="setCheck(this);" id="product_'+i+'"><label for="product_'+i+'">Compare</label><a href="javascript:void(compareProducts())" title="Compare this item" >compare</a></p></div>';
                    
                }
                
                results+='</div>';
            
                if(i==size || i%4==0){
                    results+='<div class="clear"></div></div>';
                     /*Code commented as part of Keyword Banner Change. Will use it at later stages if required.
                    if(size <= 4) {
                        if($('div#results').attr('class') == 'grid'){
                            results+='<div class="dropzone_wrap" id="dropzoneW2_grid">';
                        }
                        else{
                            results+='<div class="dropzone_wrap" id="dropzoneW2_grid" style="display: none;" >';
                        }
                        results+=$('div#dropzoneW2').html();
                        results+='</div>';
                    }
                     Code commented as part of Keyword Banner Change. Will use it at later stages if required. */
                    /* Added to The Mercado Banner after the 20th product */
                    if((i < 20 && i == size) || i == 20) {
                    	results+='<div id="mercadoBanner">';
                    	results+=$('div#content div.col_2 div.dropzone_wrap div#mercadoBannerHidden').html();
                    	results+='</div>';                    	
                }
                }
                        
               
                        
        }else {
                results+='<div class="noresultsWrapper">No More Results</div>';
        }
        /* Code commented out as part of Keyword Banner Change. Will use it at later stages if required.
        if(i==Math.ceil(prodIndexArray.length/2)){
            if($('div#results').attr('class') == 'row'){
                    results+='<div class="dropzone_wrap" id="dropzoneW2_row">';
            }
            else{
                    results+='<div class="dropzone_wrap" id="dropzoneW2_row" style="display: none;" >';
            }
            results+=$('div#dropzoneW2').html();
            results+='</div>'
        }
        Code commented out as part of Keyword Banner Change. Will use it at later stages if required. */
     }   
    }//end for loop
    
    //Append save story to head tag everytime
    if (appendHead) {
 	   $('head').append(regSaveStory);
    }
    return results;
}
//end lazyLoad function

// Function for displaying full body preloader
function bodyPreloader(){
	$('div#filterConfirm').hide();
	$('div#noresults').hide();
	$('div#ajaxError').remove();
	$('div#right-column-curtain').hide();
	var hpos = (($('body').width()/2)-100);
	/*if($.browser.msie){ var vpos =  document.body.scrollTop;}else{ var vpos = window.pageYOffset; }
	vpos+=200;
	$('div.progress').css({ left:hpos, top:vpos }).show();*/
	$('div.progress').centerOnScreen();
	$('div.progress').show();
	var curtainHeight=2000;
	if(document.body.scrollHeight < curtainHeight) {
		$('div#body-curtain').height(curtainHeight).show();
	} else {
		$('div#body-curtain').height(document.body.scrollHeight).show();
	}
}

function ajaxUrl(){
	var fullUrl = location.href;
	if(location.href.indexOf("#") >=0){
		fullUrl=location.href.split("#")[0];
	}
	var splitString1 = null;
	var splitString2 = null;
	var newUrl="";
	if(fullUrl.search("BrowseSubCategory?")>=0) {
		newUrl = fullUrl.substring(0,fullUrl.indexOf("?")+1).replace("BrowseSubCategory?","BrowseSubCategoryBody?");
		splitString2 = fullUrl.substring(fullUrl.indexOf("?")+1,fullUrl.length);	
	} else if(fullUrl.search("BrowseDynamicCategory?")>=0) {
		var dCategoryName=(fullUrl.indexOf("&",fullUrl.indexOf("sName="))>=0)?
					fullUrl.substring(fullUrl.indexOf("sName=")+1,fullUrl.indexOf("&",fullUrl.indexOf("sName="))):
					fullUrl.substring(fullUrl.indexOf("sName=")+1,fullUrl.length-1);
		if(dynamicCategoryName!=dCategoryName) {
			fullUrl=fullUrl.replace(dCategoryName,dynamicCategoryName);
		} 
		return fullUrl;
	} else if(fullUrl.search("KeywordSearch?")>=0){
		newUrl = fullUrl.substring(0,fullUrl.indexOf("?")+1);
		splitString2 = fullUrl.substring(fullUrl.indexOf("?")+1,fullUrl.length);
	}else {
		var mainIndex = fullUrl.search("/?");
		if(mainIndex != -1){
			var splitUrlArray = fullUrl.split("?");
			if(splitUrlArray != null && splitUrlArray.length > 0 ){
				splitString1 = splitUrlArray[0];
				splitString2 = splitUrlArray[1];
			}
		}
		else{
			splitString1 = fullUrl;
		}
		
		var index = splitString1.search("shc/s/");
		var chunkValue = splitString1.substring(0,index+6);
		
		var seoUrl = splitString1.substring(index+6,splitString1.length);
		var splitArray   = seoUrl.split("_");
		var cName;
		var sName;
		var vName;
		var storeId;
		var catalogId;
		storeId = splitArray[1];
		catalogId = splitArray[2];
		if(dynamicCategoryPage == true) {
			if(splitArray[3] != null){
				cName = splitArray[3].replace(/\&/,"%26");
			}
			if(splitArray[4] != null){
				sName = splitArray[4].replace(/\&/,"%26");
			}
			newUrl = chunkValue+"BrowseDynamicCategory?";
			if(dynamicCategoryName!=sName)
			{
				newUrl = newUrl+"storeId="+storeId+"&catalogId="+catalogId+"&cName="+cName+"&sName="+dynamicCategoryName;
			} else {
				if(jsonProperties.sn == "Kmart" && shopBy != null && shopBy.length > 0 ){
					newUrl = newUrl+"storeId="+storeId+"&catalogId="+catalogId+"&cName="+cName+"&sName="+sName+"&po=1"+"&shopBy="+shopBy;
				}else	
			
				newUrl = newUrl+"storeId="+storeId+"&catalogId="+catalogId+"&cName="+cName+"&sName="+sName; 
			}
		} else {
			if(splitArray[3] != null){
				vName = splitArray[3].replace(/\&/,"%26");
			}
			if(splitArray[4] != null){
				cName = splitArray[4].replace(/\&/,"%26");
			}
				if(splitArray[5] != null){
			sName = splitArray[5].replace(/\&/,"%26");
			}
			if(jsonProperties.kp == true){
				newUrl = chunkValue+"KeywordSearch?";
			}
			else{
				newUrl = chunkValue+"BrowseSubCategoryBody?";
			}
			if(storeId != null){
				newUrl = newUrl+"storeId="+storeId; 
			}
			if(catalogId != null){
				newUrl = newUrl+"&catalogId="+catalogId;
			}
			if(vName != null){
				newUrl = newUrl+"&vName="+vName;
			}
			if(cName != null){
				newUrl = newUrl+"&cName="+cName;
			}
			if(sName != null){
				newUrl = newUrl+"&sName="+sName;
			}
			if(shopBy != null && shopBy.length > 0){
				newUrl = newUrl+"&shopBy="+shopBy;
			}
			if(prepaidCell!=null && prepaidCell=='true' && prePaidZip!=null && prePaidZip!=''){
				newUrl = newUrl+"&prePaidZip="+prePaidZip;
			
			}
		}
	}
	if(splitString2 != null){
	  	/* If the current URl has filters already appended, they should be processed */
		/* Adding Brand to filterParams for Shop By Brand Flow */  
		if(jsonProperties.dcp == false){
			var tIndex = -1;
			tIndex=splitString2.indexOf("filter=");
			if(tIndex>=0){
				if(splitString2.indexOf("&",tIndex)>=0){
					var tempSplitString2=splitString2.substring(0,tIndex-1);
					tempSplitString2+=splitString2.substring(splitString2.indexOf("&",tIndex),splitString2.length);
					splitString2=tempSplitString2;
				} else{
					splitString2=splitString2.substr(0,tIndex-1);
				}
			}
			if(splitString2.lastIndexOf("&") == splitString2.length){
				splitString2 = splitString2.substr(0,splitString2.length-1);
			}
		}
		if((splitString2.search("pageNum=") >= 0)||(splitString2.search("viewItems=") >= 0)||
				(splitString2.search("sortOption=") >= 0)) {
			var urlParamArray;
			if(splitString2.search("&") >= 0) {
				urlParamArray=splitString2.split("&");
			} else {
				urlParamArray=new Array(1);
				urlParamArray[0]=splitString2;
			}
			
			for(i=0; i<urlParamArray.length; i++) {
				if((urlParamArray[i].search("pageNum=") >= 0)||(urlParamArray[i].search("viewItems=") >= 0)||
							(urlParamArray[i].search("sortOption=") >= 0)){
						
						splitString2=splitString2.replace(urlParamArray[i],"");
						splitString2=splitString2.replace("&&","&");
				}
			}
		}
		if(!(splitString2==null || splitString2=="" || splitString2=="&")) {		
			newUrl = (newUrl.charAt(newUrl.length-1)=="?")?newUrl+splitString2:newUrl+"&"+splitString2;
		}
	}
	return newUrl;
}

function createFilterParam(params) {
     // PRICE USER INPUT ENHANCEMENT
	params=params||new Object();
	lastFilterOptions=params;
	/* Initilaize flag to true so that we append the filter name only once for every element in Filter */
	var firstFilterFlag=true;

	/*Reset the value of filterParam*/
	filterParam="";

	/* 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 filter name is present add the filter options */
				if(getFilterName != null && getFilterName.length > 0){
					filterParam=filterParam.concat(getFilterName);
					/*PRICE RADIO ENHANCEMENT */	
					if(filters[i].title=="Price"){
						filterParam=filterParam+"|"+filters[i].selected[filters[i].selected.length-1].replace("|","-");
					} else {
					/* Specififc to User ratings */
					if(filters[i].title=="User Ratings") {
						/* Obtain only the rating value */
						var tempRating=filters[i].selected[filters[i].selected.length-1];
						tempRating=tempRating.substr(0,1);
						filterParam=filterParam+"|"+tempRating;
					} else{
						/* 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;					
                  	// PRICE USER INPUT ENHANCEMENT 
			}else{
				
				if (filters[i].title=="Price"){
							
							var range_low = $("#range_low").val();
							if(isI18NConvReq()){
								range_low = performReversion($("#range_low").val());
							}
							var range_high = $("#range_high").val();
							if(isI18NConvReq()){
								range_high = performReversion($("#range_high").val());
							}
							
							//Flag added to check whether the Input price text boxes are empty
							var rangeValuesFlag;
							if(typeof range_low == 'undefined' && typeof range_high == 'undefined')
							{
								rangeValuesFlag=true;
							}else{
								if(range_low=="" && range_high==""){
									rangeValuesFlag=true;
								}else{
									rangeValuesFlag=false;
								}
							}
							
							
							if (range_low == "")
								range_low = defaultMinPriceValue;
								
							if (range_high == "")
								range_high = defaultMaxPriceValue;
							
							range = range_low + "-" + range_high;
							
							if(rangeValuesFlag==false){
								
								// Code to Check whether any filters are already present in filterParam
								// Filter param will have default value filter=
								if(filterParam.length > 7)
									filterParam+="^"+filters[i].title+"|"+range;
								else{
									filterParam+=filters[i].title+"|"+range;
								}
							/* Set flag to false */
							firstFilterFlag=false;		
							}		
						}

			
			}
		});		
		filterParam=cleanFilterParam(filterParam);
		// Appending the lastFilter
		if(lastFilter!=""){
			var tempLastFilterArray=lastFilter.split(",");
			tempLastFilter=tempLastFilterArray[tempLastFilterArray.length-1];
			tempLastFilter=tempLastFilter.split(":");
			tempLastFilter=tempLastFilter[0];
			filterParam=filterParam+"&lastFilter="+cleanFilterParam(tempLastFilter);				
		}
	}
					}
/* Duplicate functions for Server Side Flow Ends */

/* General Methods for Server Side Flow - Ends Here */

/* Great Price Link - pop up code */
function greatPricePop(){
	$("a.greatPrice").click(function () {
		  var offset = $(this).offset();
		  if(document.getElementById("greatPrice")){
		  	 document.body.removeChild(document.getElementById("greatPrice"));
		  }
		  var defDiv = document.createElement("div");
	   	  document.body.appendChild(defDiv);
	      defDiv.id = 'greatPrice';
	      defDiv.className = 'floatWindow';
	   	  defDiv.innerHTML = "<p onclick='remove(this.parentNode);'><a href='javascript:;' class='closeWindow' title='Close Window'>Close</a></p><br clear='all'>" + "<p>" + this.getAttribute('info')+ "</p>";
	   	  defDiv.style.top = offset.top - defDiv.offsetHeight - 25 + "px";
	   	  defDiv.style.left = offset.left - defDiv.offsetWidth + 250 + "px";
    });
}

/*
* Functionality: Used for displaying special offers pop up
* Applicable : All Stores
* specialOffers.js - STARTS HERE
*/

function browseSpecialOffer(value,defdiv) {
	if(!document.createElement) return false;	
    defdiv.innerHTML = value;		
}

/* specialOffers.js - ENDS HERE */

/*
* Functionality: Used for emailMe and online store pickup functionalities
* Applicable : All Stores
* emailMe.js - STARTS HERE
*/

function storeLocatorPopup() {
	if(checkZipCode()){
		setCookie("zipCode",document.getElementById('zipCode').value);
		var zipCode=document.getElementById('zipCode').value;
		var catEntryId_1 = document.getElementById('zipCatEntryId').value;
		var URL = document.getElementById('zipProductURL').value;
		var storeId = document.getElementById('zipStoreId').value;	
		var catalogId = document.getElementById('zipCatalogId').value;
		
		// CODE ADD FOR KMART SPU		
		var partNumber = document.getElementById('zipPartNumber').value;
		var presellDate = document.getElementById('zipPreSellDate').value;
		var pageType;
		var itemPartNumber;
		var indexOfP = partNumber.length - 1;
		if(partNumber.charAt(indexOfP)=='P')
		{
			itemPartNumber = partNumber.substring(0,indexOfP);
		}
		if(jsonProperties.kp == true) {
			pageType="keyword";
		}else if(jsonProperties.dcp == true){
			pageType="dcp";
		}else{
			pageType="subcat";		
		}	
		var vName=escape(jsonProperties.vName);
			vName = replaceAll(vName,"%20","+");
		var cName=escape(jsonProperties.cName);
			cName = replaceAll(cName,"%20","+");
		var sName=escape(jsonProperties.sName);
			sName = replaceAll(sName,"%20","+");
		var storeLocatorUrl = "StorePickupCommand?storeId="+storeId+"&langId=-1&catalogId="+catalogId+"&zipCode="+zipCode+
					"&catEntryId_1="+catEntryId_1+"&quantity_1=1"+"&URL="+escape(URL)+"&browseFlag=browseSearch&presellDate="+
					presellDate+"&IndicatorA=pickup&partNumber="+partNumber+"&vname="+vName+"&cname="+cName+"&sname="+
					sName+"&itemPartNumber="+itemPartNumber+"&atc="+pageType+"&variant=0";
		
		// // CODE ADD FOR KMART SPU ENDS	(URL edited)		
		window.location = storeLocatorUrl;
		return false;
	}
	else{
		return false;
	}
}

function checkZipCode() {
	zip = document.getElementById('zipCode').value;
	var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
	var passed = lv_pattern.test(zip); 
	if (!passed) {
		alert("Please enter a valid 5-digit ZIP code (example: 60515).");
		return false;
	} else {
		return true;
	}
}

// Load events to 
$(document).ready(function() {
    if(typeof dynamicPopupPath != 'undefined' && typeof dynpop != 'undefined'){
  		$(function(){$('div.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
	}
		var a=document.getElementsByTagName('a');
		for (i=0;i<a.length;i++)
		{
			if (a[i].rel=='emailMe')
			{
				a[i].onclick = function (){
					mePop(this.getAttribute('info'),this.rel);
				};
			}
			if (a[i].rel=='storePickup')
			{
				a[i].onclick = function (){
					mePop(this.getAttribute('info'),this.rel);
				};
			}
		}
	}
);

//Moved from emailMe.js and Modified accordingly
function tempFunc(){
	var emailId1 = document.getElementById('emailMeAddress').value;
	var partnumber= document.getElementById('emailPartNumber').value; 
	var storeId = document.getElementById('emailStoreId').value;
	ajaxCall('EmailMeWhenInStockCmd?partNumber='+partnumber+'&userEmail='+emailId1+'&storeId='+storeId,'emailCallBack');	
}

//Moved from emailMe.js
function emailCallBack() {
	return;
}

//Moved from emailMeProductPage.js
function validateEmailId() {	
	var emailentered = document.getElementById('emailMeAddress').value;
	if(emailentered == '') {
	    alert("Email address is required");
	    return false;
	}
	if (!validateEmailAddress(emailentered.toLowerCase(),emailentered)) {
        return false;
    }
    return true;
}

function mePop(info,id) 
{	
	if (!document.getElementById(id))
	{
		if(!document.getElementById('grayDiv')){
			var grayDiv=document.createElement('div');
			grayDiv.id="grayDiv";
			grayDiv.className="transparent";
			grayDiv.style.zIndex = '55';
			document.body.appendChild(grayDiv);
			var gray=document.getElementById('grayDiv');
			gray.style.height=document.body.scrollHeight+200+"px";
			gray.style.width=document.body.scrollWidth+"px";
		} else if (document.getElementById('grayDiv').style.display=="none"){
			document.getElementById('grayDiv').style.height=document.body.scrollHeight+200+"px";
			document.getElementById('grayDiv').style.width=document.body.scrollWidth+"px";
			document.getElementById('grayDiv').style.display="";
		}
		
		var containerDiv=document.createElement('div');
		containerDiv.id=id;
		containerDiv.className='floatWindow';
		containerDiv.style.zIndex = '60';
		document.body.appendChild(containerDiv);

		//presell changes
		var releaseDate = '';
		var status ='delivery';
		if(info.indexOf("`") >= 0) {
			releaseDate=info.split("`")[0];
			info=info.split("`")[1];
		}
		if(releaseDate != '') {
			status = 'pre-order';
		}

		//Changes for emailMe.js and emailMeProductPage.js merging
		var infoArray=info.split("^ ");		
		var pName=infoArray[0];
		var pId=infoArray[1];
		var pMfr=infoArray[2];
		var storename='';
		var catEntryId_1 = infoArray[3];
		var URL = infoArray[4];
		var jspStoreImgDir = infoArray[5];
		var kmartButtonsDir = infoArray[6];
		var storeId = infoArray[7];
		var catalogId = infoArray[8];
	
		//This block is moved from emailMe.js and modified for product page changes.
		switch (id)
		{
		case 'emailMe':
		var container=document.getElementById('emailMe');
		container.innerHTML="<p onclick='remove(this.parentNode);hideBox(\"grayDiv\");enableSelect();'><a href='javascript:;' class='closeWindow'>Close</a></p>\n"
			+ "<br clear='all'>\n"			
			+ "<div id='sorryMsg'>"
			+ "<p>We're sorry but the <b>"+pName+"</b> is temporarily unavailable for "+status+". Please enter your e-mail address below and we will notify you when it is available.</p>\n"
			+ "\t<input type='hidden'id='emailStoreId' name='storeId' value='"+storeId+"'>\n"
			+ "\t<input type='hidden' id='emailCatEntryId' name='catEntryId' value='"+catEntryId_1+"'>\n"			
			+ "\t<input type='hidden' id='emailPartNumber' name='partNumber' value='"+pId+"'>\n"
			+ "\t<p><b>Email address:</b> <input class='text'id='emailMeAddress' type='text' name='userEmail' size='20' value='"+getCookie('userEmail')+"'>\n"
			+ "\t<a href='javascript:;' onClick='if(validateEmailId()){showBox(\"thankYou\");hideBox(\"sorryMsg\");document.getElementById(\"emailAddress\").innerHTML=document.getElementById(\"emailMeAddress\").value;setCookie(\"userEmail\",document.getElementById(\"emailMeAddress\").value);tempFunc();}'><img id='emailMeSubmitBtn' width='65' height='21' alt='submit' align='top' style='margin-top: -1px; _margin-top:1px;'></a></p><br>\n"		
			+ "</div>\n"
			+ "<div id='thankYou' style='display:none;'>"
			+ "\t<p>Thank you. You will be notified at <b id='emailAddress'></b>&nbsp;when the following item is available:</p>"
			+ "\t<p><b>"+pName+"</b><br><small>"+storename+" Item #"+pId+" Mfr. model #"+pMfr+"</small></p>"
			+ "\t<p>Pricing is subject to change.</p>"
			+ "</div>";
			setTimeout(function(){
				if(typeof jspStoreImgDir != 'undefined' && typeof kmartButtonsDir != 'undefined') {					
					document.getElementById('emailMeSubmitBtn').src=jspStoreImgDir+kmartButtonsDir+"submit_blue.gif";					
				} else if(typeof imagePath != 'undefined') {
					document.getElementById('emailMeSubmitBtn').src=imagePath+'img/buttons/submit_blue.gif';
				}
			}, 0);
			break;

		case 'storePickup':
		// CODE ADDED FOR KMART SPU		
		var pDate = infoArray[9];
		// CODE ADD FOR KMART SPU ENDS
		var container=document.getElementById('storePickup');
		container.innerHTML="<p onclick='remove(this.parentNode);hideBox(\"grayDiv\");enableSelect();'><a href='javascript:;' class='closeWindow'>Close</a></p>\n"
			+ "<br clear='all'>\n"			
			+ "\t<input type='hidden' id='zipCatEntryId' name='catEntryId_1' value='"+catEntryId_1+"'>\n"
			+ "\t<input type='hidden' id='zipProductURL' name='URL' value='"+URL+"'>\n"			
			+ "\t<input type='hidden' id='zipPartNumber' name='partNumber' value='"+pId+"'>\n"
			+ "\t<input type='hidden' id='zipStoreId' name='storeId' value='"+storeId+"'>\n"
			+ "\t<input type='hidden' id='zipCatalogId' name='catalogId' value='"+catalogId+"'>\n"
			// CODE ADD FOR KMART SPU			
			+ "\t<input type='hidden' id='zipPreSellDate' name='presellDate' value='"+pDate+"'>\n"
			// CODE ADD FOR KMART SPU ENDS	
			+ "\t<p><b>Enter Zip Code:</b> <input type='text' name='zipCode' id='zipCode' size='15' maxlength='5' class='text' value='"+getCookie('zipCode')+"' /> "
			+ "\t<a href='javascript:;' onClick='return storeLocatorPopup();'><img id='storePickupGoBtn' alt='go button' align='absmiddle'></p></a>";
			setTimeout(function(){document.getElementById('storePickupGoBtn').src=jspStoreImgDir+kmartButtonsDir+"go_blue.gif";},0);
			break;
		}

		// Set position of this div //
		$('#'+containerDiv.id).centerOnScreen();
		disableSelect();
	}
}

// Function to trim the white spaces from the right side of a string 
function rtrim (s){	
   return s.replace( /\s*$/, "" );
}

// Function to trim the white spaces from the left side of a string
function ltrim ( s ){	
  return s.replace( /^\s*/, "" );
}

/* emailMe.js - ENDS HERE */

/*
* Functionality: Used for displaying the map price pop up
* Applicable : All Stores
* mapPrice.js - STARTS HERE
*/

/* DOM READY CALLS  - Starts Here */
$(document).ready(function(){
       $("a.mapLink").click(function(){mapClick(this)});
});
/* DOM READY CALLS  - Ends Here */

/* Map Price pop up Method - Starts  Here */
function mapClick(elm){ 
        var mapCode = ''
        mapCode += '<div class="mapWrap">\n'
        mapCode += '<div class="border">\n'
        mapCode += '<a class="closeWindow">Close</a>\n'
        mapCode += '<strong>Why Don\'t We Show the Price?</strong>\n'
        mapCode += '<div class="mapSummary">\n'
        mapCode += '<span class="price">*</span>\n'
        mapCode += '<span class="regPrice">Original Price: <del></del></span>\n'
        mapCode += '<span class="savings">You save: <span></span></span>\n'
        mapCode += '<small>* Does not include tax, installation, handling or delivery charges.</small>\n'
        mapCode += '</div>\n'
        mapCode += '<p>Manufacturers sometimes ask retailers not to advertise and display a price below a certain limit.</p>\n'
        mapCode += '<p>When shopping in a store, you may have to ask a salesperson for the price. On a web site, you may have to ask for the price by clicking on "Click to see our price."</p>\n'
        mapCode += '</div>\n'
        mapCode += '</div>'

        $("body").append(mapCode);
        if(isI18NConvReq()){
			currencySymb = i18nCookieData.currencyCode;
		}else{
			currencySymb = "$"
		}
        var foo = $(elm).offset();
        var thisPar = $(elm).parent();
        var tp = thisPar.find("div.truePrice").html().split(currencySymb)[1];
        tp = parseFloat(tp).toFixed(2);
        var rp = thisPar.find("span.salePrice del").html().split(currencySymb)[1];
        rp = parseFloat(rp).toFixed(2);
        $(".mapWrap .price").text(currencySymb+tp+"*");
        $(".mapWrap .regPrice del").text(currencySymb+rp);
        $(".mapWrap .savings span").text(currencySymb+parseFloat(rp-tp).toFixed(2));
        $("div.mapWrap").show(250).css({top: foo.top + 15, left: function(){
          	return (foo.left-285)<0 ? 10 : (foo.left - 285);
        }, background: '#fff'});
        $("#overlay").click(function(){
            $("div.mapWrap").hide(250, function(){$("div.mapWrap").remove();});
            $("div#overlay").remove();
            $("iframe#overlayiframe").remove();
        });
        $("a.closeWindow").click(function(){
	        $("div.mapWrap").hide(250, function(){$("div.mapWrap").remove();});
	        $("div#overlay").remove();
	        $("iframe#overlayiframe").remove();
	        return false;
        });
        return false;
};
/* Map Price pop up Method - Ends  Here */

/* mapPrice.js - ENDS HERE */

/*
* Functionality: Used for zooming the images in Quick View pop up
* Applicable : All Stores
* imgZoom.js - STARTS HERE
*/

jQuery(function($){		   
	jQuery.fn.imgZoom = function(settings){
		settings = jQuery.extend({// Default settings...
			container:  'body',
			src:		'img/fullsize.jpg',
			hideIt:		false
		}, settings);
		return this.each(function(i){
			var set = new Array();
			if($(this).is('img')){
				set.push(this);
			}else{
				$(this).find('img').each(function(){
					set.push(this);
				});
			};
			$(set).each(function(i){
				var global = this;
				var zoomtainer = settings.container;
				var maxH, maxW, helperHalf, scaleFactor, zoomedSize, helperSize;
				var ourSize = { width:$(this).width(), height:$(this).height() };
				$(this).wrap('<div class="zzz_imgzoom"/>');
				var currentContainer = $(this).parent();
				$(currentContainer).css({
					width:		$(this).width(),
					height:		$(this).height(),
					overflow:	'hidden',
					position:	'relative'
				});
				$(zoomtainer).css({
					position:	'relative',
					overflow:	'hidden'
				});
				var shade = $('<div class="zzz_shade"/>').css({ 
					width:		$(currentContainer).width(),
					height:		$(currentContainer).height(),
					display:	'none',
					position:	'absolute',
					top:		0,
					left:		0,
					background:	'url('+jspStoreImgDir+'img/loading.gif) no-repeat center center #fff',
					opacity:	0.75,
					filter:		'alpha(opacity=75)'
				}).appendTo(currentContainer);;
				var helper = $('<div class="zzz_imghelper"/>').css({
					border:		'1px solid #fff',
					background:	'url('+$(this).attr('src')+') no-repeat -1px -1px #fff',
					display:	'none',
					position:	'absolute',
					top:		0,
					left:		0
				}).appendTo(currentContainer);;
				var zoomed = $('<div class="zzz_zoomed"/>').hide().css({
					overflow:	'hidden', 
					background:	'url('+jspStoreImgDir+'img/loading.gif) center center no-repeat #fff',
					position:	'absolute',
					height:		$(zoomtainer).height(),
					width:		$(zoomtainer).width(),
					top:		$(zoomtainer).css('padding-top'),
					left:		$(zoomtainer).css('padding-left')
				}).appendTo(zoomtainer);
				
				$(currentContainer).unbind().hover(function(){
					$(shade).fadeIn(200);
					$(helper).fadeIn(200);
					$(zoomed).fadeIn(200);
					if(settings.hideIt){
						$(zoomtainer).show()
					}
				},function(){
					$(shade).fadeOut(200);
					$(helper).fadeOut(200);
					$(zoomed).fadeOut(200);
					if(settings.hideIt){
						$(zoomtainer).hide()
					}
				});

				zoomedImg.onload = function(){
					zoomedSize = { width:zoomedImg.width, height:zoomedImg.height };
					scaleFactor = { x:(zoomedSize.width/ourSize.width), y:(zoomedSize.height/ourSize.height) };
					helperSize = {
						height: Math.round($(zoomtainer).height()/scaleFactor.y),
						width:	Math.round($(zoomtainer).width()/scaleFactor.x)
					};
					$(helper).css({width:helperSize.width+'px', height:helperSize.height+'px'});
					maxH =	$(global).height()-$(helper).height();
					maxW =	$(global).width()-$(helper).width();
					helperHalf = {width: ($(helper).width()/2), height: ($(helper).height()/2)};
					$(zoomed).css({
						background:	'url('+this.src+') no-repeat 0 0 #fff'
					});
					$(shade).css({
						backgroundImage:	'none', 
						opacity: 			0.75, 
						filter:				'alpha(opacity=75)', 
						background:			'#ccc'
					});
					var us = {width: $(global).width(), height: $(global).height(), top: $(global).offset().top, left: $(global).offset().left}
					$(currentContainer).unbind().hover(function(){
						$(shade).fadeIn(200);
						$(helper).fadeIn(200);
						$(zoomed).fadeIn(200);
						if(settings.hideIt){
							$(zoomtainer).show()
						}
					},function(){
						$(shade).fadeOut(200);
						$(helper).fadeOut(200);
						$(zoomed).fadeOut(200);
						if(settings.hideIt){
							$(zoomtainer).hide()
						}
					}).mousemove(function(e){
						var us = {width: $(global).width(), height: $(global).height(), top: $(global).offset().top, left: $(global).offset().left}
						var top =	(e.pageY - us.top) - helperHalf.height;
						var left =	(e.pageX - us.left) - helperHalf.width;
						var nleft = left > maxW ? maxW : left < 0 ? 0 : left;
						var ntop = top > maxH ? maxH : top < 0 ? 0 : top;
						$(zoomed).css({
							backgroundPosition: '-'+(nleft*scaleFactor.x)+'px -'+(ntop*scaleFactor.y)+'px'
						})
						$(helper).css({
							top:	ntop,
							left:	nleft,
							backgroundPosition: '-'+(nleft+1)+'px -'+(ntop+1)+'px'
						});
					});
				};
				zoomedImg.src = settings.src;
			});
		}); 
	};
});	
	
/* imgZoom.js - ENDS HERE */

/*
* Functionality: Used for displaying Quick View pop up
* Applicable : All Stores
* quickView.js - STARTS HERE
*/
/* QuickView - v2.7.0 - 2008.09.23 */
/* QuickView - v2.7.0 - 2008.09.23 */
(function($) {  
 
/* CENTER OBJECT ON SCREEN */    
    $.fn.centerOnScreen = function(){ 
        $this = this[0];
        windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        vertScroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        $this.style.top = ((windowHeight/2) - ($this.offsetHeight/2) + vertScroll) + "px";
        $this.style.left = ((windowWidth/2) - ($this.offsetWidth/2)) + "px";
    } 
  
/* GET COORDINATE OF OBJECT */  
    $.fn.getCoordinates = function() {    
        obj = this[0];
        x = y = 0;
        if (obj.offsetParent) {
            x = obj.offsetLeft; y = obj.offsetTop;
            while (obj = obj.offsetParent){ x += obj.offsetLeft; y += obj.offsetTop; }
        }
        return {x:x,y:y};
    }  
})($);
//var jspStoreImgDir='';
//Set default thumbnail size for quick view images
var qvImgDim = 198;
var qvThmbDim = 40;
var qvThmbDim2 = 100;
 
// Put all sears specific functions into its own namespace
SEARS = {
    /* STORE PRODUCT INFO */
    Item: {
        "info":function(data){
            var data = data;
            // Product Object
            this.product        = data.P;
            this.strId          = this.product.strId;
            this.catId          = this.product.catId;
            this.vertName       = this.product.vertName;
            this.catEntId       = this.product.cid;
            this.parCatEntId    = this.product.pid;
            this.pId            = this.product.pn;
            this.revURL         = this.product.rpn;
            this.mId            = this.product.mfrNum;
            this.pTitle         = this.product.t;
            this.type           = this.product.type;
            this.oDescription   = this.product.des;
            this.rating         = this.product.ra;
            this.numReviews     = this.product.nr;
            this.reviews        = this.product.reviews;
            this.hasSpecs       = this.product.specs;
            this.Img            = this.product.Img;
            
            this.vndId          = this.product.vndrId;
	    	this.xFrmt          = this.product.xFmt;
            this.sldBy			= this.product.soldBy;
            this.vndStrId       = this.product.vndrStrId;
            this.isVP			= this.product.isVP;
            this.VPStore		= this.product.VPStore;
            this.VPEnv			= this.product.VPEnv;
            this.VProductUrl	= this.product.VProductUrl;
            this.vpReviewUrl	= this.product.vpReviewUrl;
            this.VPCSS1			= this.product.VPCSS1;
            this.VPCSS2			= this.product.VPCSS2;

            
            //Code change for handling no image condition for a product
            var tempImgDetail= this.product.Img[0];	    
	   		 if(typeof tempImgDetail == "undefined"|| tempImgDetail == "undefined"){
		    var noImageFlag=0;
		    this.Img=[{iId:"66655555000",s7:"0",w:"198",h:"198"}]
	   		 }
	   		 if(noImageFlag==0){
		    this.mImageElig= 1;
		    this.mImageWidth= 1000;
		    this.mImageHeight= 1000;
		    this.mFimgURL1=66655555000;
	    }else{
		    this.mainImage = this.product.Img[0];
		    this.mImageElig = this.mainImage.s7;
		    this.mImageWidth= this.mainImage.w;
		    this.mImageHeight= this.mainImage.h;
		    this.mFimgURL1  = this.mainImage.iId;
    	    }           
            this.mImageAltTxt   = this.product.t;
            this.click2call     = this.product.c2t;
            this.regional       = this.product.regpr;
            // Save Story Object
            this.saveStory      = data.DD; 
            this.offline        = this.saveStory.off;
            this.ssText         = this.saveStory.SStory;
            this.inStock        = this.saveStory.stock;
            this.spo            = this.saveStory.so;
            this.storepu        = this.saveStory.sp;
            this.addToCart      = this.saveStory.dispAdd;
            this.holiday        = this.saveStory.hMsg;
			this.preOrder		= this.saveStory.rdate;
			this.doNotEmail		= this.saveStory.DEME;
			this.spuFlag		= this.saveStory.spFlag;
			this.sp_ssText		= this.saveStory.spSS;
			this.sp_storeName	= this.saveStory.storeName;
			this.dff			= this.saveStory.dff;
			this.intShip		= this.saveStory.intShip; //International Shipping
			
			//Softlines
            if(data.Softline){
                this.softData   = data.Softline;
                this.variants   = this.softData.prodVarList;
            
            this.current        = {skuList:'',attList:''};
            this.ssArray        = data.Softline.ssArray;
            this.fakeDDshow     = function(elm){
                                    var t;
                                    var global = this;
                                    $('#fakeDDcontent').remove();
                                    var dd = $('<div id="fakeDDcontent"></div>').appendTo('.quickView');
                                    $(elm).children('div').each(function(){
                                        if($(this).is('.disabled')){
                                            $('<div class="notAvail">'+$(this).html()+'</div>').appendTo(dd);   
                                        }else{
                                            $('<div>'+$(this).html()+'</div>').appendTo(dd);
                                        }
                                    });
                                    if($(dd).children().length > 10){
                                        $(dd).css({
                                            height: 175,
                                            overflow:'auto'
                                        }); 
                                    };
                                    $('#fakeDDcontent div').hover(function(){
                                        $(this).addClass('hover');                                 
                                    },function(){
                                        $(this).removeClass('hover');
                                    });
                                    $(dd).css({
                                        top:    $(elm).offset().top - $(elm).parents('.quickView').offset().top,
                                        left:   $(elm).offset().left - $(elm).parents('.quickView').offset().left
                                    }).show().mouseout(function(){
                                        t = setTimeout(function(){
                                            //$(dd).remove();                       
                                        },400); 
                                    }).mouseover(function(){
                                        clearTimeout(t) ;
                                    });
                                    $(dd).find('div').click(function(){
                                        var val = $(this).text();
                                        $(elm).children('div').each(function(){
                                            if($(this).text() == val){
                                                $(this).addClass('opt_sel').removeClass('opt_not_sel');
                                            }else{
                                                $(this).removeClass('opt_sel').addClass('opt_not_sel');
                                            };
                                            
                                        });
                                        $(dd).remove();
                                        global.attrChange(elm,true);
                                        
                                        if($(elm).is('#qvp_var')){
                                            $(SEARS.Item.softData.prodList.prodVarList).each(function(){
                                                if(this.varName == val){
                                                    SEARS.Item.current.attList = this.attList;
                                                    SEARS.Item.current.skuList = this.skuList; 
                                                };                                                         
                                            });
                                            global.changeVariant();
                                            };
                                    });
            };
            }
            var tempVal;
            this.changeVariant = function(){
        
                                    $('.softAddtoCart').hide(); 
                                    $('.selectionsTab .qvp_att_dd').add('.selectionsTab div.oos').remove();
                                    $(this.current.attList).each(function(a){
                                    	if(typeof this!='undefined' && this.name != undefined && this.values.length > 0) {
                                        var dd = $('<div class="fakeDD qvp_att_dd" id="qvp_att'+a+'"></div>').appendTo('.selectionsTab').click(function(){
                                            tempVal = $(this).find('.opt_sel').removeClass('opt_sel').addClass('opt_not_sel');
                                            $(this).find('.default').addClass('opt_sel').removeClass('opt_not_sel');
                                            SEARS.Item.attrChange(dd);
                                            SEARS.Item.fakeDDshow(this);                                                                                               
                                        });
                                        $(dd).append('<div class="opt_sel default">'+this.name+'</div>')
                                        if(this.name == 'Color' || this.name == 'Overall Color' || this.name == 'COLOR'){
                                        $(dd).addClass('qvcolor');
                                            $(this.values).each(function(b){
                                                var swURL = 'http://s.sears.com/is/image/Sears/'+this.swId+'?hei=20&wid=20&op_sharpen=1';
                                                $('<div class="opt_not_sel"><img src="'+swURL+'" alt="'+this.cName+'" align="absmiddle" height="20" width="20">'+this.cName+'</div>').appendTo(dd); 
                                            });
                                        }else{
                                            $(this.values).each(function(c){
                                                $('<div class="opt_not_sel">'+this+'</div>').appendTo(dd);                   
                                            }); 
                                        };
                                        }
                                    });
                                    $('<div class="oos">This item is not available in the combination you have selected. Please change your selections.</div>').hide().appendTo('.selectionsTab');
            };
            this.attrChange = function(changed,msg){
                var condition = '';
                var closedAttrs = [];
                var matches = [];
                var skuList = SEARS.Item.current.skuList;
                var saveStory = SEARS.Item.ssArray;
                var allAttrs = $('.qvp_att_dd');
                $(allAttrs).find('div').removeClass('enabled').removeClass('disabled');
                $('.qvp_att_dd').each(function(){
                    if(!$(this).find('div:first').is('.opt_sel')){
                        closedAttrs.push(this); 
                    }                              
                });
                
                if(closedAttrs.length > 0){
                    $(closedAttrs).each(function(a){
                        var spot = this.id.split('qvp_att')[1];
                        if(a==0){
                            condition+= 'this.aVals['+spot+'] == "'+$(this).find('.opt_sel').text()+'"';
                        }else{
                            condition+= ' && this.aVals['+spot+'] == "'+$(this).find('.opt_sel').text()+'"';
                        }
                    });
                    condition+=' && this.stk > 0';
                    $(skuList).each(function(){  
                        //International Shipping
                        if(this.intShip == 'YES' && jsonProperties.sn == "Sears" && isI18NConvReq())
                        {
                        fnConvertSaveStory();
                        if(('.QVinnerWrap .itemWidgets .intShip').style == 'display: none;')
                        {
                        $('.QVinnerWrap .itemWidgets .intShip').show();
                        }
                        $('.QVinnerWrap .itemWidgets .unvIntShip').hide();
                        //$('.QVqty').removeAttr('disabled','disabled').attr('value','1');
                        }
                        else if (this.intShip == 'NO' && jsonProperties.sn == "Sears" && isI18NConvReq())
                        {
                        fnConvertSaveStory();
                        $('.QVinnerWrap .itemWidgets .intShip').hide();
                        if(('.QVinnerWrap .itemWidgets .unvIntShip').style == 'display: none;'){
                        $('.QVinnerWrap .itemWidgets .unvIntShip').show();
                        }
                        $('.gotoBtn').hide();
                        $('.QVqty').attr('disabled','disabled').attr('value','0');
                         //message intShip unavailable
                        } 
                        else if (jsonProperties.sn == "Sears" && !isI18NConvReq())
                        {
                        $('.intShip').hide();
                        $('.unvIntShip').hide();
                        $('.gotoBtn').show();
                        }
                        if(eval(condition)){
                            matches.push(this);
                            $(this.aVals).each(function(b){
                                var m = this;
                                $('#qvp_att'+b).find('div').each(function(){
                                    if($(this).text() == m){$(this).addClass('enabled')}                                          
                                });
                            });
                        }
                    });
                    $(allAttrs).children('div').not('.default').not('.enabled').addClass('disabled');
                    if(closedAttrs.length == 1){
                        $(closedAttrs).children('div').removeClass('disabled').removeClass('enabled');
                    }
                }else{
                    $(allAttrs).children('div').removeClass('disabled').removeClass('enabled');
                };
                
                if($('.qvp_att_dd').find('.opt_sel').hasClass('disabled')){
                    $('.selectionsTab .oos').show();        
                }else{
                    $('.selectionsTab .oos').hide();
                }
                if(msg){
                    var tot = allAttrs.length
                    var check = [];
                    $(allAttrs).each(function(){
                        if ($(this).children('div.default').hasClass('opt_sel')){
                            check.push(this);   
                        };                    
                    });
                    if(matches.length == 0 && check.length != tot){
                        $('.selectionsTab .oos').show();
                    };
                };
                if(closedAttrs.length == allAttrs.length && $('.selectionsTab .oos').is(':hidden')){
                    var QVparent = $('#qv'+SEARS.Item.pId);
                    var _QV = $('.quickView');
                    var pid = matches[0].pid;
                    $('form[name="addToCart"] input[name="catEntryId_1"]').val(pid);
                    var ssIndex = matches[0].ssIdx;
                    //i18n change for attribute
                    if(isI18NConvReq()){
                    $('.quickView .saveStory').html(saveStory[ssIndex]);
                    fnConvertSaveStory();
                    }
                    else{
                    $('.quickView .saveStory').html(saveStory[ssIndex]);
                    }
                    
                    var _SSqty = $(QVparent).find('.saveStory').eq(0);
                    var _defaultST ="";  
                    //i18n change for attribute
                    if(isI18NConvReq()){
		    			currencySymb = i18nCookieData.currencyCode;
		    		}else{
		    			currencySymb = "$"
		    }
                    if($(_SSqty).find('.regPrice').length){
                         _defaultST = $(_SSqty).find('.regPrice').html().split(currencySymb)[1];
                    }else if($(_SSqty).find('.salePrice').length){
                         _defaultST = $(_SSqty).find('.salePrice').html().split(currencySymb)[1];
                    }
                    else if($(_SSqty).find('.youPay').length){
						_defaultST = $(_SSqty).find('.youPay').eq(0).find('.pricing').eq(0).html().split(currencySymb)[1]
					}
                    //$('.softAddtoCart').find('.QVsubT').html(_defaultST);
                    var _a2c = $('.softAddtoCart')
                    var _qty = $(_a2c).find('.QVqty').val();
                    var _sub = $(_a2c).find('.QVsubT');
                    $(_sub).html((_qty*_defaultST).toFixed(2));
                    $('.softAddtoCart').fadeIn(400,function(){$('.QVborder').height($(_QV).height()+25)});
                    if(isI18NConvReq()){
                    $('.QVqtyWrap strong').remove();
                    var totalP = (_qty*_defaultST).toFixed(2);    
                    $('.QVqtyWrap').append('<strong>Subtotal: '+currencySymb+'<span class="QVsubT">'+' '+totalP+'</span></strong>');
                    $('.softAddtoCart').fadeIn(400,function(){$('.QVborder').height($(_QV).height()+25)});
                    }
                //    }
                }else{
                    $('.softAddtoCart').hide(); 
                };
                if($(changed).hasClass('qvcolor')){
                    if(!$(changed).find('.opt_sel').hasClass('default')){
                        var selcolor = $(changed).find('.opt_sel').text();
                        var matchcolor;
                        $(SEARS.Item.current.attList).each(function(){
                            if(this.name == 'Color' ||  this.name == 'Overall Color'){
                                $(this.values).each(function(){
                                    if(this.cName == selcolor){
                                        matchcolor = this;
                                    };                           
                                }); 
                            };                                          
                        });  
                        if(matchcolor.mImgId != ''){
                            $('.itemWidgets .imgnotavail').remove();
                            $('.quickView .slider .zzz_imgzoom:first').add('.quickView .slider .zzz_zoomed:first').fadeOut(800).remove();
                            $('<img/>').attr({
                                alt:SEARS.Item.pTitle,
                                src:'http://s.sears.com/is/image/Sears/'+matchcolor.mImgId+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0',
                                width:qvImgDim,
                                height:qvImgDim
                            }).hide().prependTo('.quickView .slider').fadeIn(800).imgZoom({container:'.content', src:"http://s.sears.com/is/image/Sears/"+matchcolor.mImgId+"?&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0"});;
                            $('.quickView .slider2 img').removeClass('selected');
                            $('.quickView .slider2 img:first').addClass('selected').animate({opacity:1}).attr('src','http://s.sears.com/is/image/Sears/'+matchcolor.mImgId+'?hei=40&wid=40&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0')
                            clickIndx = clickIndx2 = 0;
                            $('.quickView .slider').animate({left:"-"+(clickIndx*qvImgDim)},250);
                            $('.quickView .slider2').animate({left:"-"+(clickIndx2*qvThmbDim)},250);
                        }else{
                            $('.quickView .slider .zzz_zoomed:first').remove();
                            var tempimg = $('.quickView .slider .zzz_imgzoom:first').children('img').wrap('<div class="zzz_imgzoom"></div>').parents('.zzz_imgzoom');
                            $('.quickView .slider .zzz_imgzoom:first').replaceWith(tempimg);
                            $('<div class="imgnotavail">Image not available</div>').hide().appendTo('.itemWidgets');
                            $(tempimg).animate({opacity:0.1})
                            $('.itemWidgets .imgnotavail').fadeIn(800);
                            $('.quickView .slider2 img').removeClass('selected');
                            $('.quickView .slider2 img:first').animate({opacity:0.1})
                            clickIndx = clickIndx2 = 0;
                            $('.quickView .slider').animate({left:"-"+(clickIndx*qvImgDim)},250);
                            $('.quickView .slider2').animate({left:"-"+(clickIndx2*qvThmbDim)},250);
                        }
                    };
            };
            }
        }   
    },
    /* QUICK VIEW */
    QuickView: { 
        "launch":function(){
            $('.quickViewWrap').html('');
            $('.quickViewWrap').remove();
             $('.mapWrap').html('');
            $('.mapWrap').remove();
            $('#offerDetails').html('');
            $('#offerDetails').remove();
            var strName="";  
            var _vert = omVrt.split("'").join("");
            var _cat = omCat.split("'").join("");
            var _sbcat = omSubCat.split("'").join(""); 
            
            if((SEARS.Item.strId=="10153") || (SEARS.Item.strId=="10154")){strName="Sears"}else if(SEARS.Item.strId=="10151"){strName="Kmart"}else if((SEARS.Item.strId=="10152") || (SEARS.Item.strId=="12701") || (SEARS.Item.strId=="13201") || (SEARS.Item.strId=="10701") || (SEARS.Item.strId=="11701") || (SEARS.Item.strId=="11702") || (SEARS.Item.strId=="11703")){strName="My Gofer"}else if(SEARS.Item.strId=="10154"){strName="Kenmore"};
            var revPath;
            if(strName=="Sears"){revPath='http://reviews2.sears.com/2328/'}else if(strName=="Kmart"){revPath='http://reviews2.kmart.com/2348/'};
            $('body').append('<div id="qv'+SEARS.Item.pId+'" class="quickViewWrap"></div>');
            var QVparent = $('#qv'+SEARS.Item.pId);
            var QVWrap = $('.quickViewWrap');
             $(QVWrap).append('<div class="QVborder"/>');
            $(QVWrap).append('<div class="quickView"/>');
            var _QV = $('.quickView');
            $(_QV).append('<div class="drag"><a href="#close" title="Close this window" class="closeWindow">close</a></div>');
            var _drag = $('.drag');
            //Error message for Temporary Offline Status
            if(SEARS.Item.offline){
                $(_QV).append('<p>We\'re sorry. The product you selected is no longer available, or is temporarily out of stock due to high demand. Please try again later.</p>');
            }else if(!SEARS.Item.offline){
				$(_drag).append('<ul><li><a href="#overview" onclick="s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' >'+SEARS.Item.pId+' > '+'Quick View > Overview\';s.events=\'event27\';s.product=\''+SEARS.Item.pId+'\';s.tl();" title="Click OVERVIEW tab to read product overview">Overview</a></li></ul>');
                if(SEARS.Item.type!="C" && SEARS.Item.type!="GC"){
                    if(SEARS.Item.hasSpecs){
                    $(_drag).find('ul').append('<li><a href="#specs" onclick="s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' >'+SEARS.Item.pId+' > '+'Quick View > Specs\';s.events=\'event27\';s.product=\''+SEARS.Item.pId+'\';s.tl();" title="Click SPECS tab to read product specifications">Specs</a></li>')
                    }
					// Changed for Cross format. Do not show reviews for cross format product
					if(strName!="My Gofer" && SEARS.Item.reviews && !SEARS.Item.xFrmt){
                       		$(_drag).find('ul').append('<li><a href="#reviews" onclick="s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' >'+SEARS.Item.pId+' > '+'Quick View > Reviews\';s.events=\'event27\';s.product=\''+SEARS.Item.pId+'\';s.tl();">Reviews</a></li></ul>')
			       }
                }
                $(_QV).append('<div class="QVinnerWrap"/>');
                var _QVi = $('.QVinnerWrap');
                $(_QVi).append('<div class="itemWidgets" style="width:'+parseInt(qvImgDim+2)+'px;"/>').append('<div class="scrollWsmall" style="width:'+parseInt(qvThmbDim2+2)+'px;height:'+parseInt(qvThmbDim+2)+'"/>').append('<div class="content narrow"/><div class="clear"/>');
                $(_QV).append('<div class="goToButtons"/>');
                var itmWgts = $('.itemWidgets');
                var nonZoom = $('.scrollWsmall');
                var content = $('.content');
                var goTo = $('.goToButtons'); 
                 
                //Columns for images
                //$(itmWgts).append('<div class="scrollWidget" style="width:'+qvDim+'px;"><img alt="'+SEARS.Item.pTitle+'" src="http://s.sears.com/is/image/Sears/'+SEARS.Item.mFimgURL1+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0" width="'+qvImgDim+'" height="'+qvImgDim+'"</div>');
                var np_top = parseInt((qvImgDim/2)-7);
                $(itmWgts).append('<div class="scrollWidget" style="width:'+qvImgDim+'px;height:'+qvImgDim+'px;"><div class="slider" style="width:'+SEARS.Item.Img.length*qvImgDim+'px;"></div></div>');
                var slider = $(QVparent).find('.slider');
                if(SEARS.Item.Img.length>1){
                    var np_top = parseInt((qvImgDim/2)-7);
                    $(itmWgts).append('<img alt="previous image" src="'+jspStoreImgDir+'img/pImg.gif" class="pImg" style="top:'+np_top+'px;"/><img alt="next image" src="'+jspStoreImgDir+'img/nImg.gif" class="nImg" style="top:'+np_top+'px;"/>');
                    $(itmWgts).append('<div class="thumbWidget"><div class="thmbMask"><div class="slider2" style="width:'+SEARS.Item.Img.length*(qvThmbDim+10)+'px;"></div></div></div>');
                    var thmbWdgt = $('.thumbWidget')
                    var cnp_top = parseInt(qvImgDim+($(thmbWdgt).height()/2)+5)
                    if(SEARS.Item.Img.length>3){
                    $(itmWgts).append('<img alt="Previous images" src="'+jspStoreImgDir+'img/pImg.gif" class="c_pImg" style="top:'+cnp_top+'px;"/><img alt="More images" src="'+jspStoreImgDir+'img/nImg.gif" class="c_nImg" style="top:'+cnp_top+'px;"/>');
                    };
                    var slider2 = $(QVparent).find('.slider2');
                };
				
				//Code change for handling no image condition for a product
		
		            var imgSize = SEARS.Item.Img.length;  
				 for (var i=0;i<imgSize; i++) {  
				
                if(SEARS.Item.mFimgURL1=="66655555000"){
                	$('<img/>').attr({
                        alt:SEARS.Item.pTitle,
                        src:jspStoreImgDir+'img/icons/no_image.jpg?hei='+198+'&wid='+198+'&op_sharpen=1&qlt=90,0&resMode=sharp&op_usm=0.9,0.5,0,0',
                        width:qvImgDim,
                        height:qvImgDim
                    }).appendTo(slider);
                    }else{
                    	$('<img/>').attr({
                        alt:SEARS.Item.pTitle,
				                            src:'http://s.sears.com/is/image/Sears/'+SEARS.Item.Img[i].iId+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0',
				                            width:qvImgDim,
				                            height:qvImgDim
				                        }).appendTo(slider);
				                        }
				                         $('<img/>').attr({
				                            alt:SEARS.Item.pTitle,
				                            src:'http://s.sears.com/is/image/Sears/'+SEARS.Item.Img[i].iId+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0',
				                            width:qvThmbDim,
				                            height:qvThmbDim
		                    }).appendTo(slider2);
				     
		 }  
		
                /*$.each(SEARS.Item.Img, function(i,Img){
                if(SEARS.Item.mFimgURL1=="66655555000"){
                	$('<img/>').attr({
                        alt:SEARS.Item.pTitle,
                        src:jspStoreImgDir+'img/icons/no_image.jpg?hei='+198+'&wid='+198+'&op_sharpen=1&qlt=90,0&resMode=sharp&op_usm=0.9,0.5,0,0',
                        width:qvImgDim,
                        height:qvImgDim
                    }).appendTo(slider);
                    }else{
                    	$('<img/>').attr({
                        alt:SEARS.Item.pTitle,
                        src:'http://s.sears.com/is/image/Sears/'+Img.iId+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0',
                        width:qvImgDim,
                        height:qvImgDim
                    }).appendTo(slider);
                    }
                     $('<img/>').attr({
                        alt:SEARS.Item.pTitle,
                        src:'http://s.sears.com/is/image/Sears/'+Img.iId+'?hei='+qvImgDim+'&wid='+qvImgDim+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0',
                        width:qvThmbDim,
                        height:qvThmbDim
                    }).appendTo(slider2);
                });*/
                $(slider2).find('img').eq(0).addClass('selected');
                
  				//Code change for handling no image condition for a product
                if(SEARS.Item.mFimgURL1=="66655555000"){
                	$(nonZoom).append('<img alt="'+SEARS.Item.pTitle+'" src="'+jspStoreImgDir+'img/icons/no_image.jpg?hei='+qvThmbDim2+'&wid='+qvThmbDim2+'&op_sharpen=1&qlt=90,0&resMode=sharp&op_usm=0.9,0.5,0,0" width="'+qvThmbDim2+'" height="'+qvThmbDim2+'/>').hide();
				}else{
                $(nonZoom).append('<img alt="'+SEARS.Item.pTitle+'" src="http://s.sears.com/is/image/Sears/'+SEARS.Item.mFimgURL1+'?hei='+qvThmbDim2+'&wid='+qvThmbDim2+'&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0" width="'+qvThmbDim2+'" height="'+qvThmbDim2+'"/>').hide();
                } 
                //Storing re-used elements in variables
                var mNum = SEARS.Item.mId && SEARS.Item.type=="H" ? ', Mfr. model #'+SEARS.Item.mId : '';
                if(SEARS.Item.sldBy != ""){
                	if(SEARS.Item.xFrmt) {
	                	var banner = '<h3><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" title="'+SEARS.Item.pTitle+'">'+SEARS.Item.pTitle+'</a></h3><p class="vendor">'+SEARS.Item.sldBy+'</p><small class="itmNum">Item# '+SEARS.Item.pId.split("P")[0]+mNum+'</small>';
					} else {
                var banner = '<h3><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" title="'+SEARS.Item.pTitle+'">'+SEARS.Item.pTitle+'</a></h3><p class="vendor">'+SEARS.Item.sldBy+'</p><small class="itmNum">'+strName+' item# '+SEARS.Item.pId.split("P")[0]+mNum+'</small>';
					}
				} else {
					var banner = '<h3><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" title="'+SEARS.Item.pTitle+'">'+SEARS.Item.pTitle+'</a></h3><small class="itmNum">'+strName+' item# '+SEARS.Item.pId.split("P")[0]+mNum+'</small>';
				}
				if(SEARS.Item.preOrder){
					banner += '<div class="qvPreOrder"><img border="0" alt="Item Coming Soon" src="'+jspStoreImgDir+'img/icons/comingSoon.gif"/></div>';
				}
				if(SEARS.Item.type!="C"&&strName!="My Gofer"&&SEARS.Item.type!="GC"&&SEARS.Item.reviews && SEARS.Item.isVP=='BV'){
					var reviewInfo = '<span class="reviews"><img alt="'+SEARS.Item.rating.replace('_','.')+' stars out of 5" src="'+revPath+SEARS.Item.rating+'/5/rating.gif"/>';
					// Do not show review related text for cross format products.
					if(!SEARS.Item.xFrmt) {
						reviewInfo += SEARS.Item.numReviews+' reviews';
                }
					reviewInfo += '</span>';
                }
                var ssBase;
                // Save story will not displayed if the product has regional price
                if(SEARS.Item.regional){
                    ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>';
                } else {
                if(isI18NConvReq()){//International Shipping
                       	ssBase = '<div class="saveStory">'+fnConSSfly(SEARS.Item.ssText)+'</div>';
	                }else{
	                    ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>';
	                }
                }
                
                //Build out div.content
				$(content).append('<div class="overviewTab"/>');
				if(SEARS.Item.hasSpecs){$(content).append('<div class="specsTab"/>')};
                var _ovr = $('.overviewTab'); 
                var _specs = $('.specsTab');
                if(strName!="My Gofer"){$(content).append('<div class="reviewsTab"/>');
                var _reviews = $('.reviewsTab')};
                
                //Softline Data (Selections, etc.)
                if(SEARS.Item.softData && SEARS.Item.type=="S"){
                    $('.drag > ul').prepend('<li><a href="#selections" onclick="s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' >'+SEARS.Item.pId+' > '+'Quick View > Selections\';s.events=\'event27\';s.product=\''+SEARS.Item.pId+'\';s.tl();">Selections</a></li>');
                    $(content).prepend('<div class="selectionsTab"/>');
                    var _selects = $('.selectionsTab');
                    $(_selects).append(banner);
                    if(reviewInfo){$(_selects).append(reviewInfo)};
                    $(_selects).append(ssBase);
                //SOFTLINES CODE//////////////////////////////////////////////////////////////////////////////////////////
          var attData = SEARS.Item.softData
          var fitment = attData.prodList.prodVarList;
          var currentFit;
          var skuList;
          var attList;
          if(fitment.length > 1){
          var title = $('<h3>Select:</h3>').appendTo(_selects);
          var varselect = $('<div class="fakeDD" id="qvp_var"></div>').appendTo(_selects).click(function(){
          SEARS.Item.fakeDDshow(this);
          });
          $(fitment).each(function(a){
          if(a==0){
          $('<div class="opt_sel">'+this.varName+'</div>').appendTo(varselect);
          SEARS.Item.current.attList = this.attList;
          SEARS.Item.current.skuList = this.skuList;
           }else{
           $('<div class="opt_not_sel">'+this.varName+'</div>').appendTo(varselect);
           }
           });
           }else if(typeof fitment[0]!='undefined'){
           var varselect = $('<h4 id="qvp_var">'+fitment[0].varName+'</h4>').appendTo(_selects);
           SEARS.Item.current.attList = fitment[0].attList;
           SEARS.Item.current.skuList = fitment[0].skuList;
           };
           SEARS.Item.changeVariant();
///////////////////////////////////////////////////////////////////////////////////////////END SOFTLINES//                  
}}
                
                //Populate div.content
                $(_ovr).append(banner);
                if(reviewInfo){$(_ovr).append(reviewInfo)};
                $(_ovr).append(ssBase).append('<div class="description">'+SEARS.Item.oDescription+'</div>');
                $(_specs).prepend(banner).append(ssBase).append('<div class="specsBucket"/>');
                // Changed for Cross format. Do not show reviews for cross format product
	if(SEARS.Item.reviews && !SEARS.Item.xFrmt){
                $(_reviews).prepend(banner).append(ssBase);
					if(SEARS.Item.numReviews>=1 && SEARS.Item.isVp == 'BV'){
                    $(_reviews).append('<iframe class="reviewsBucket" frameborder="0" src=""/>');
                }else if(SEARS.Item.isVp == 'BV'){
                    $(_reviews).append('<br clear="both"/><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'#reviewsWrap" title="Write a Review for This Product">Click here to write a review for this product</a>');
                }else if(SEARS.Item.isVP == 'VP'){
                	$(_reviews).append('<script type="text/javascript" src="'+SEARS.Item.vpReviewUrl+'"></script>');
                	$(_reviews).append('<link rel="stylesheet" href="'+SEARS.Item.VPCSS1+'" media="screen" type="text/css">');
                	$(_reviews).append('<link rel="stylesheet" href="'+SEARS.Item.VPCSS2+'" media="screen" type="text/css">');
                    $(_reviews).append('<div id="viewpoints_review_widget" data-product_id="'+SEARS.Item.pId+'" data-product_title="'+SEARS.Item.pTitle+'" data-product_page_url="'+SEARS.Item.VProductUrl+'p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" data-display_mode="quick" data-full_reviews_url="'+SEARS.Item.VProductUrl+'allreviews_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" data-write_reviews_url="'+SEARS.Item.VProductUrl+'writereview_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" data-env="'+SEARS.Item.VPEnv+'" data-brand="'+SEARS.Item.VPStore+'" ></div>');
                }
	};
                 var ssBase;
                // Save story will not displayed if the product has regional price
                if(SEARS.Item.regional){
                    ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>';
                } else {
                if(isI18NConvReq()){//International Shipping
                		ssBase = '<div class="saveStory">'+fnConSSfly(SEARS.Item.ssText)+'</div>';
                	}else{
                    	ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>';
                    }
                }
                //Messaging under the main thumbnail area
				if(SEARS.Item.preOrder){
                    $(itmWgts).append('<span class="releaseDate"><strong>Release Date:</strong> '+SEARS.Item.preOrder+'</span><span class="preOrderSelect"><a href="javascript: ;"  title="Available for Pre-Order">Available for Pre-Order</a></span>');
                	/* The follwing condition is added for Available for Pre-Order link*/
                	if(typeof dynamicPopupPath != 'undefined' && typeof dynpop != 'undefined'){
	                	 $(function(){$('span.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
                	}
                }
	if(!SEARS.Item.preOrder){                
	switch(SEARS.Item.inStock){
	
						case 0:
						if(!isI18NConvReq()){ //International Shipping
							if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && SEARS.Item.dff=='DDC' && jsonProperties.regAvail == "true"){
								flagQV='Y';
								if(fnChkZipCode()){
									availMsg=availValues.Get(SEARS.Item.pId);
									if(typeof availMsg == 'undefined'){
										//availMsg=$('.availability #part_'+SEARS.Item.pId).children();
										$(itmWgts).append('<span id="deliv_in" class="deliv_in">Temporarily out of stock for delivery</span>')
										$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId+'">Check Availability</a>')
									}else{
										$(itmWgts).append('<span id="deliv_in" class="deliv_in">'+availMsg+' '+getRegDelZip()+'</span>')
										$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId +'">Change ZIP Code</a>')
									}
									readyOnLoad();
								}else{
									$(itmWgts).append('<span id="deliv_in" class="deliv_in">Temporarily out of stock for delivery</span>')
									$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId+'">Check Availability</a>')
									readyOnLoad();
								}
							}else{
							$(itmWgts).append('<span class="deliv_oos">Temporarily out of stock for delivery</span>');
							}
							switch(SEARS.Item.storepu){
							 
								case 1:
									if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && jsonProperties.regAvail == "true"){
										//forming URL for store pickup
										var trimSbcat=stringTrim(_sbcat);
										var pURL='p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'?vName='+_vert+'&cName='+_cat+'&sName='+trimSbcat;
										sDate='';
											$(itmWgts).append('<span id="spu_elig" class="spu_elig">Buy Online - Pickup in Store Eligible.</span>');
											$(itmWgts).append('<a id="checkAvailSpu" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.mId+'^'+SEARS.Item.parCatEntId+'^'+pURL+'^/contentserver/StaticContent/Sears/^img/buttons/^'+SEARS.Item.strId+'^'+SEARS.Item.catId+'^'+sDate+'^">Check Availability</a>')
											readyOnLoad();
									}else{
										$(itmWgts).append('<span id="spu_elig" class="spu_elig">Item is Store Pick Up Eligible </span>');
									}
								break;
								case 2:
									if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && jsonProperties.regAvail == "true"){
									//forming URL for store pickup
										var trimSbcat=stringTrim(_sbcat);
										var pURL='p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'?vName='+_vert+'&cName='+_cat+'&sName='+trimSbcat;
										sDate='';
											$(itmWgts).append('<span id="spu_elig" class="spu_elig">Buy Online - Pickup in Store Eligible.</span>');
											$(itmWgts).append('<a id="checkAvailSpu" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.mId+'^'+SEARS.Item.parCatEntId+'^'+pURL+'^/contentserver/StaticContent/Sears/^img/buttons/^'+SEARS.Item.strId+'^'+SEARS.Item.catId+'^'+sDate+'^">Check Availability</a>')
	 										readyOnLoad();
									}else{
									if(SEARS.Item.spuFlag==1){
										$(itmWgts).append('<span class="spu_in">In Stock today at '+SEARS.Item.sp_storeName+'</span>');
										//Display DD.spSS if not null
										if(SEARS.Item.type=="S"){
											ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
										}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
											ssBase = SEARS.Item.sp_ssText;
											displayRegionalSaveStoryInQV(ssBase);
										}else{
											ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
											}
										}
									}
									break;
							case 3:
									if(SEARS.Item.spuFlag==1){
										$(itmWgts).append('<span class="spu_oos">Temporarily out of stock at '+SEARS.Item.sp_storeName+'</span>');
										//Display DD.spSS if not null
										if(SEARS.Item.type=="S"){
											ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
										}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
											ssBase = SEARS.Item.sp_ssText;
											displayRegionalSaveStoryInQV(ssBase);
										}else{
											ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
										}
									}
								break;
								case 4:
									if(SEARS.Item.spuFlag==1){
										$(itmWgts).append('<span class="spu_oos">Item not carried '+SEARS.Item.sp_storeName+'</span>');
										//Display DD.spSS if not null
										if(SEARS.Item.type=="S"){
											ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
										}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
												ssBase = SEARS.Item.sp_ssText;
											displayRegionalSaveStoryInQV(ssBase);
										}else{
											ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
										}
									}
								break;
							}
						}
						break;
						case 1:
						if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && SEARS.Item.dff=='DDC' && jsonProperties.regAvail == "true" && !isI18NConvReq()){//Intrnational Shipping
								flagQV='Y';
								if(fnChkZipCode()){
									availMsg=availValues.Get(SEARS.Item.pId);
									if(typeof availMsg == 'undefined'){
										//availMsg=$('.availability #part_'+SEARS.Item.pId).text();
										$(itmWgts).append('<span id="deliv_in" class="deliv_in">Availability for home delivery varies by location</span>')
										$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId+'">Check Availability</a>')
									}else{
										$(itmWgts).append('<span id="deliv_in" class="deliv_in">'+availMsg+' '+getRegDelZip()+'</span>')
											$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId +'">Change ZIP Code.</a>')
									}
								readyOnLoad();
								}else{
									$(itmWgts).append('<span id="deliv_in" class="deliv_in">Availability for home delivery varies by location</span>')
									$(itmWgts).append('<a id="checkAvailDel" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.catEntId+'">Check Availability</a>')
									readyOnLoad();
								}
							}else{
								if(isI18NConvReq() && SEARS.Item.intShip != "YES"){//International Shipping
								}else{
									$(itmWgts).append('<span id="deliv_in" class="deliv_in">In stock for shipping</span>');
								}
							}
							if(!isI18NConvReq()){ //International Shipping
								switch(SEARS.Item.storepu){
									 
									case 1:
										if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && jsonProperties.regAvail == "true"){
											//forming URL for store pickup
											var trimSbcat=stringTrim(_sbcat);
											var pURL='p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'?vName='+_vert+'&cName='+_cat+'&sName='+trimSbcat;
											sDate='';
												$(itmWgts).append('<span id="spu_elig" class="spu_elig">Buy Online - Pickup in Store Eligible.</span>');
												$(itmWgts).append('<a id="checkAvailSpu" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.mId+'^'+SEARS.Item.parCatEntId+'^'+pURL+'^/contentserver/StaticContent/Sears/^img/buttons/^'+SEARS.Item.strId+'^'+SEARS.Item.catId+'^'+sDate+'^">Check Availability</a>')
												readyOnLoad();
										}else{
											$(itmWgts).append('<span id="spu_elig" class="spu_elig">Item is Store Pick Up Eligible </span>');
										}
									break;
									case 2:
									
										if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && jsonProperties.regAvail == "true"){
											//forming URL for store pickup
												var trimSbcat=stringTrim(_sbcat);
										var pURL='p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'?vName='+_vert+'&cName='+_cat+'&sName='+trimSbcat;
											sDate='';
												$(itmWgts).append('<span id="spu_elig" class="spu_elig">Buy Online - Pickup in Store Eligible.</span>');
												$(itmWgts).append('<a id="checkAvailSpu" class="checkAvail" style="font-size: 12px; padding-left: 50px" href="javascript:;" rel="regionalAvailability" info="'+SEARS.Item.pId+'^Y^CAT^'+SEARS.Item.mId+'^'+SEARS.Item.parCatEntId+'^'+pURL+'^/contentserver/StaticContent/Sears/^img/buttons/^'+SEARS.Item.strId+'^'+SEARS.Item.catId+'^'+sDate+'^">Check Availability</a>')
												readyOnLoad();
										}else{
											if(SEARS.Item.spuFlag==1){
												$(itmWgts).append('<span class="spu_in">In Stock today at '+SEARS.Item.sp_storeName+'</span>');
												//Display DD.spSS if not null
												if(SEARS.Item.type=="S"){
													ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
												}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
														ssBase = SEARS.Item.sp_ssText;
													displayRegionalSaveStoryInQV(ssBase);
												}else{
													ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
												}
											}
										}
									break;
									case 3:
										if(SEARS.Item.spuFlag==1){
											$(itmWgts).append('<span class="spu_oos">Temporarily out of stock at '+SEARS.Item.sp_storeName+'</span>');
											//Display DD.spSS if not null
											if(SEARS.Item.type=="S"){
												ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
											}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
													ssBase = SEARS.Item.sp_ssText;
												displayRegionalSaveStoryInQV(ssBase);
											}else{
												ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
											}
										}
									break;
									case 4:
										if(SEARS.Item.spuFlag==1){
											$(itmWgts).append('<span class="spu_oos">Item not carried '+SEARS.Item.sp_storeName+'</span>');
											//Display DD.spSS if not null
											if(SEARS.Item.type=="S"){
												ssBase = '<div class="saveStory"><strong style="color:#f00;">Please see more product information to see your price for this item.</strong></div>'
											}else if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
													ssBase = SEARS.Item.sp_ssText;
												displayRegionalSaveStoryInQV(ssBase);
											}else{
												ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>'
											}
										}
									break;
								}
							}
						break;
						case 2:
							if(!isI18NConvReq()){ //International Shipping
								switch(SEARS.Item.storepu){
								 
									case 1:
										if(SEARS.Item.spuFlag==1){
											$(itmWgts).append('<span class="spu_elig">Only available in stores.</span>');
									 		$('.overviewTab .saveStory').html(""); 
										}
									break;
									case 2:
										if(SEARS.Item.spuFlag==1){
										 
											$(itmWgts).append('<span class="spu_in">In Stock today at '+SEARS.Item.sp_storeName+'.</span>');
											//Display DD.spSS if not null
										   if(SEARS.Item.type=="H" && SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
													ssBase = SEARS.Item.sp_ssText;
												     displayRegionalSaveStoryInQV(ssBase);
											 
											}
										}
									break;
									case 3:
										if(SEARS.Item.spuFlag==1){
											$(itmWgts).append('<span class="spu_oos">Temporarily out of stock at '+SEARS.Item.sp_storeName+'.</span>');
											//Display DD.spSS if not null
										   if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
													ssBase = SEARS.Item.sp_ssText;
												displayRegionalSaveStoryInQV(ssBase);
											}
										}
									break;
									case 4:
										if(SEARS.Item.spuFlag==1){
											$(itmWgts).append('<span class="spu_oos">Item not carried at '+SEARS.Item.sp_storeName+'.</span>');
											//Display DD.spSS if not null
											 if(SEARS.Item.sp_ssText!=null || SEARS.Item.sp_ssText!='' || SEARS.Item.sp_ssText!=' '){
												ssBase = SEARS.Item.sp_ssText;
												displayRegionalSaveStoryInQV(ssBase);
											}
										}
									break;
								}
							}
						break;
					}
		}	
		
		//International shipping availability - quickview
		if(SEARS.Item.strId==10153){
		//international ship sears 
		$('.QVinnerWrap .itemWidgets').append('<li class="intShip"><a href="/shc/s/CountryChooserView?storeId=10153&catalogId=12605&intrd=1"> International Shipping </a> </li>');
		$('.QVinnerWrap .itemWidgets').append('<li class="unvIntShip"> Not available for International Shipping </li>');							    										    										    	
		$('.QVinnerWrap .itemWidgets .intShip').hide();
		$('.QVinnerWrap .itemWidgets .unvIntShip').hide();
		    //For Non-US
		  	if(isI18NConvReq()){
				if(SEARS.Item.intShip == "YES"){
					$(itmWgts).append('<li class="intShip"> International Shipping </li>');
		 		}
				else{
					$(itmWgts).append('<li class="unvIntShip"> Not available for International Shipping </li>');							    										    										    	
				}
			}
		    //For US
		  	else{
					if(SEARS.Item.intShip == "YES"){
						$(itmWgts).append('<li class="intShip"> International Shipping </li>');
		 			}
			}
		}
	
  var splOffers = '\'splOffr\'';
                if((SEARS.Item.spo&&!SEARS.Item.preOrder)&&(SEARS.Item.strId==10151||SEARS.Item.strId==10153)){ 
                	if(isI18NConvReq() && SEARS.Item.intShip != "YES"){//International Shipping
					}else{
                    	$(itmWgts).append('<span class="spo"><a href="#" onclick="specialOffers('+splOffers+','+SEARS.Item.strId+','+SEARS.Item.catId+','+SEARS.Item.parCatEntId+');return false;">Special Offers</a></span>');
                	}
                }
                //Bottom band, with Add to Cart, etc.                
                if(SEARS.Item.type=="S"){
                    $(goTo).append('<div class="softAddtoCart"><span class="QVqtyWrap"><label for="QVqty'+SEARS.Item.pId+'">Quantity:</label><input type="text" value="1" class="QVqty" id="QVqty'+SEARS.Item.pId+'"/> <strong>Subtotal: $<span class="QVsubT"></span></strong></span></div>');
                    var _QVqtyBox = $('#QVqty'+SEARS.Item.pId);
                    $(goTo).find('.softAddtoCart').append('<a href="#" class="gotoBtn"/>');
                    $(_QVqtyBox).blur(function(){
                       var global = $(this)
                       if(global.val()>99){alert('Quantity cannot be greater than 99.\nYour quantity will be set to 99.');global.val(99)};
                        if(global.val().match(/\D/)){alert('Quantity field can contain only positive numbers.\n\nYour quantity will be set to 1.');global.val(1)};
                        if(global.val()<1||global.val()==''){global.val(1)};
                        
                        if(isI18NConvReq()){ 
                        	currencySymb = i18nCookieData.currencyCode;
                        }
                        else{
                        	currencySymb = "$"
                        }
                        
                        var _SSqty = $(QVparent).find('.saveStory').eq(0);
                       if($(_SSqty).find('.regPrice').length){
                       var _QtyAmt = $(_SSqty).find('.regPrice').html().split(currencySymb)[1];
                       }else if($(_SSqty).find('.salePrice').length){
                       var _QtyAmt = $(_SSqty).find('.salePrice').html().split(currencySymb)[1];
                      }else if($(_SSqty).find('.youPay').length){
						var _QtyAmt = $(_SSqty).find('.youPay').eq(0).find('.pricing').eq(0).html().split(currencySymb)[1]
					   }
                      $('form[name="addToCart"] input[name="quantity_1"]').val(global.val());
                      $(QVparent).find('.QVsubT').html(parseFloat(_QtyAmt*global.val()).toFixed(2));
                     }).blur();
                }else{
                    $(goTo).append('<a class="gotoBtn"/>');
                }
                
                var goToBtn = $('.gotoBtn');
                var _QVqty = $('.QVqty');
                var _QVsubT = $('.QVsubT');   
                if(SEARS.Item.preOrder && SEARS.Item.inStock){
					$(goToBtn).append('<img alt="Pre-Order Item" src="'+jspStoreImgDir+'img/buttons/preOrder.gif" onclick="submitAddToCart(SEARS.Item.mFimgURL1);s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' >'+SEARS.Item.pId+' > Quick View > Add to Cart\';s.tl();" height="34"/>');
				}else if (SEARS.Item.preOrder && !SEARS.Item.inStock){
                    $(goToBtn).append('<img alt="More Product Details" src="'+jspStoreImgDir+'img/btn_moreDetails.gif" width="150" height="20"/>');
                    $(goToBtn).attr('href','/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId);
				}else if(!SEARS.Item.addToCart && SEARS.Item.type!="S"){
				
                    $(goToBtn).append('<img alt="More Product Details" src="'+jspStoreImgDir+'img/btn_moreDetails.gif" width="150" height="20"/>');
                    $(goToBtn).attr('href','/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId);
               
               }else if(SEARS.Item.spuFlag){
                   $(goToBtn).append('<img alt="More Product Details" src="'+jspStoreImgDir+'img/btn_moreDetails.gif" width="150" height="20"/>');
                    $(goToBtn).attr('href','/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId);
               }
               
               else /*if(SEARS.Item.addToCart)*/{
               		if(isI18NConvReq() && SEARS.Item.intShip != "YES"){//International Shipping
					}else{
                   		$(goToBtn).append('<img alt="Add to Cart" src="'+jspStoreImgDir+'img/btn_addToCart.gif" onclick="submitAddToCartRA(SEARS.Item.mFimgURL1);s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' > '+SEARS.Item.pId+'>Quick View > Add to Cart\';s.tl();" width="130" height="30" />');
                	} 
                }
                $(goTo).append('<br clear="all"/>');
				if(SEARS.Item.preOrder&&!SEARS.Item.inStock&&!SEARS.Item.doNotEmail){
					$(goTo).prepend('<a href="javascript:;" class="emailMe" rel="'+SEARS.Item.preOrder+'`'+SEARS.Item.pTitle+'^ '+SEARS.Item.pId+'^ '+SEARS.Item.mId+'^ '+SEARS.Item.catEntId+'^ ^ '+jspStoreImgDir+'^ img/buttons/^ '+SEARS.Item.strId+'^ '+SEARS.Item.catId+'^">E-mail me when available</a>');
				}  
				else if(SEARS.Item.click2call){
					$(goTo).prepend('<a class="clickCall" onclick="javascript:window.open(\'https://sales.liveperson.net/hc/37457093/?cmd=file&file=visitorWantsToTalk&site=37457093&byhref=1&SESSIONVAR!skill=sears-personalshopper-voice-sales-english&SESSIONVAR!staticButton=voice-personalshopper-oos-english\',\'\',\'scrollbars=no,location=no,titlebar=no,resizable=no,menubar=no,width=450,height=300\');" href="javascript:;">Call for Product Questions</a>');
                }
                if(!SEARS.Item.inStock && SEARS.Item.storepu){
                    var IndA = "pickup"
                }else if(SEARS.Item.dff == 'DDC'){
                	var IndA = "delivery"
                }
                else{
                    var IndA = "ship"
                }
                 
                var adjHgt,adjWid;
                var variant = "0";
                
		        if(SEARS.Item.type == 'H'){
		        	variant = "0";
		        } else if(SEARS.Item.type == 'S'){
		        	variant = "1";
		        }
		        var gcUserTypeVal=$.cookie('GiftRegApp'+SEARS.Item.strId);
		        if(gcUserTypeVal==null){
		        gcUserTypeVal="";
		        }
                $(goTo).append('<form name="addToCart" action="ProductOptionsOrderItemAddCmd" method="post"><input type="hidden" name="storeId" value="'+SEARS.Item.strId+'"/><input type="hidden" name="langId" value="-1"/><input type="hidden" name="catalogId" value="'+SEARS.Item.catId+'"/><input type="hidden" name="URL" value="OrderItemDisplay"/><input type="hidden" name="IndicatorA" value="'+IndA+'"/><input type="hidden" name="vName" value=""/><input type="hidden" name="cName" value=""/><input type="hidden" name="sName" value=""/><input type="hidden" name="grIdentifier" value="false"/><input type="hidden" name="addToCartBtn" value="false"/><input type="hidden" name="catEntryId_1" value="'+SEARS.Item.catEntId+'"/><input type="hidden" name="quantity_1" value="1"/><input type="hidden" name="partNumber" value="'+SEARS.Item.pId+'"/><input type="hidden" name="atc" value="quickview"/><input type="hidden" name="grUserType" value="'+gcUserTypeVal+'"/><input type="hidden" name="variant" value="'+variant+'" /></form>');
				if(SEARS.Item.preOrder){
					$(goTo).children('form').append('<input type="hidden" name="presellDate" value="'+SEARS.Item.preOrder+'"/>');
				} 
                var scrlWgt = $('.scrollWidget');
                var clickIndx=0, clickIndx2=0;
                var curImg = SEARS.Item.Img[clickIndx];
                $(slider).children('img').each(function(i){
                     var zImgTemp = SEARS.Item.Img[i];  
                     if(zImgTemp.w>2000){zImgTemp.w=2000};
                     if(zImgTemp.h>2000){zImgTemp.h=2000};

					//Code change for handling no image condition for a product
					if((SEARS.Item.strId=="10153" || SEARS.Item.strId=="10151") && SEARS.Item.vertName=="Jewelry"){
						$(nonZoom).append('<img alt="'+SEARS.Item.pTitle+'" src="'+jspStoreImgDir+'img/icons/no_image.jpg?hei='+qvThmbDim2+'&wid='+qvThmbDim2+'&op_sharpen=1&qlt=90,0&resMode=sharp&op_usm=0.9,0.5,0,0" width="'+qvThmbDim2+'" height="'+qvThmbDim2+'/>').hide();
					}
                    else if(zImgTemp.iId!=66655555000 ){
                    $(this).imgZoom({container:'.content', src:"http://s.sears.com/is/image/Sears/"+zImgTemp.iId+"?hei="+zImgTemp.h+"&wid="+zImgTemp.w+"&op_sharpen=1&qlt=90,0&op_usm=0.9,0.5,0,0"});                                
                    }
                });
                if(!$.browser.msie){$(QVWrap).draggable({handle:$(".drag")})};
                //var sliderThumbs = $(slider2).find('img'); 
                var sliderThumbs = $(slider2).children('img');
                
                highlightThumb = function(){
                    $(sliderThumbs).each(function(){
                        $(this).removeClass('selected');
                    });
                    $(sliderThumbs[clickIndx]).addClass('selected');
				};
                $(".pImg").click(function(){
                    clickIndx--;
                    if(clickIndx < 0){clickIndx = 0; return false};
                    $(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
                    highlightThumb();
                    return false;
                });
                $(".nImg").click(function(){
                    clickIndx++;
                    if(clickIndx >= SEARS.Item.Img.length){clickIndx--; return false};
                    $(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
                    highlightThumb();  
                    return false;
                });
                $(".c_pImg").click(function(){
                    clickIndx2--;
                    if(clickIndx2 < 0){clickIndx2 = 0; return false};
                    $(slider2).animate({left:"-"+(clickIndx2*qvThmbDim)},250);
                    return false;
                });
                $(".c_nImg").click(function(){
                    clickIndx2++;
                    if(clickIndx2 >= (SEARS.Item.Img.length-2)){clickIndx2--; return false};
                    $(slider2).animate({left:"-"+(clickIndx2*qvThmbDim)},250);
                    return false;
                });
                $(sliderThumbs).each(function(i){
                    $(this).click(function(){
                        clickIndx = i;
                        $(this).siblings().removeClass('selected');
                        $(this).addClass('selected');
                        $(slider).animate({left:"-"+(clickIndx*qvImgDim)},250);
                        return false;
                    })
                });  
               
            // Availability link click event
            	
			$('a.emailMe').click(function(){
					mePop(this.rel, 'emailMe');	
					$('grayDiv').css('z-index','501');
					$('emailMe').css('z-index','502');
			});
			
			/* Available for Pre-order - dynamic pop-up */
			if(typeof dynamicPopup!='undefined'){
				$(function(){$('.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
			}
			            
            $('.quickView div[class$="Tab"]').hide();
            $('.quickView div[class$="Tab"]:first').show(function(){
                $('.drag > ul > li:first').addClass('on');$('.QVborder').height($('.quickView').height()+20);
                $(QVWrap).centerOnScreen();
            });
            if(SEARS.Item.offline) $(QVWrap).centerOnScreen();
            $(QVWrap).hide();
            $(QVWrap).fadeIn(500,function(){$('.QVborder').height($(_QV).height()+25);}).bgiframe();
            if(strName=="Sears"||strName=="Kenmore"){
	    			$(QVWrap).find('.reviewsBucket').attr('src','http://reviews2.sears.com/2328qv/'+SEARS.Item.revURL+'/reviews.htm?format=noscript&user=__USERID__');            	
            }else if(strName=="Kmart"){
					$(QVWrap).find('.reviewsBucket').attr('src','http://reviews2.kmart.com/2348qv/'+SEARS.Item.revURL+'/reviews.htm?format=noscript&user=__USERID__');
            };  
            $("a.mapLink").click(function(){ 
                mapClick(this)
            });
            $('.closeWindow').click(function(){
                  $('.quickView').html('');
		$('.quickView').remove();
                  $('.quickViewWrap').html('');
	            $('.quickViewWrap').remove();
    	         $('.mapWrap').html('');
            $('.mapWrap').remove();
            $('#offerDetails').html('');
            $('#offerDetails').remove();
                $(QVWrap).fadeOut(200,function(){$(this).remove();});
                flagQV='N'
                return false;
            });
            
                overviewQV=$('.overviewTab').html();
	    	reviewsQV=$('.reviewsTab').html();
	    	    
            $('.drag > ul > li > a').each(function(){
                    

                    $(this).unbind().click(function(){
                    $('#fakeDDcontent').remove();
                    var theTab = $(this).attr('href').split('#')[1];
		    		var swap = function(){
                    $('.content > div').hide();
                    $('.'+theTab+'Tab').show();
					};
					if(theTab=='specs'){
						if(SEARS.Item.type!="C"&&SEARS.Item.type!="GC"){
							//$(QVWrap).find('.specsBucket').load('DisplayTabCmd.html',function(){
							$(QVWrap).find('.specsBucket').load('/shc/s/DisplayTabCmd?langId=&storeId='+SEARS.Item.strId+'&catalogId='+SEARS.Item.catId+'&catentryId='+SEARS.Item.parCatEntId+'&tabName=Specs',function(){
								$('.itemWidgets').hide();
								$('.scrollWsmall').show();
								$('.content').removeClass('narrow').addClass('wide');
								$('.overviewTab').html('');
								$('.reviewsTab').html('');								
								swap();
								$('.QVborder').height($(_QV).height()+25);
							});
						};
					}else if(theTab=='reviews'){
						$('.itemWidgets').hide();
						$('.scrollWsmall').show();
						$('.content').removeClass('narrow').addClass('wide');
						
						$('.overviewTab').html('');
						$('.specsBucket').html('');
						$('.reviewsTab').html(reviewsQV);
						if(SEARS.Item.isVP == 'VP'){
							ViewpointsReviewsWidget();
                			//fnInclude(SEARS.Item.VPModifiedJs,"js");
                			//quickViewCall();
                			
                		}
						swap()
						
                    }
                    if(theTab=='selections' || theTab=='overview'){
                        $('.itemWidgets').show();
                        $('.scrollWsmall').hide();
                        $('.content').removeClass('wide').addClass('narrow')
                        
                        $('.specsBucket').html('');
                        $('.reviewsTab').html('');
                        $('.overviewTab').html(overviewQV);
						swap()
                    }
                    $('.QVborder').height($(_QV).height()+25);
                    $(this).parent().addClass('on').siblings().removeClass('on');
                    if($.browser.msie){$(this).blur()};
                    return false;
                });
            });  
           if($('.saveStory').find('.callout').length){
					//alert($('.saveStory .callout').html());
					var ss2clone = $('.quickView').find('.saveStory').find('.callout').eq(0);
					$(ss2clone).clone().appendTo('.itemWidgets');
					$(ss2clone).clone().appendTo('.scrollWsmall');
					$('.quickView').find('.saveStory').find('.callout').each(function(){
						$(this).remove()
					});
				}
	      }
     }
}

/*---- HOMEMADE JQUERY PLUGINS /END ----*/

function qvBtn(){
    var screen = '<div class="screen"/>';
	var QVbtn = '<a id="qvl" href="#quickView" title="View QuickView information for this item" class="QVbtn"><img alt="quick view button"  src="'+jspStoreImgDir+'img/btn/btn_quickView.gif" width="150px" height="30px" style="background:transparent;"></a>';
    var photoDiv = $('div#results .searchResult .product .photo');
   
   
   if((jsonProperties.sn != "Sears" && jsonProperties.sn != "Kmart") 
   || ( (jsonProperties.sn == "Sears" || jsonProperties.sn == "Kmart" )&& (jsonProperties.isKiosk == "false")))
    {
   
    $(photoDiv).hover(function(){
        var _this = $(this);
        var qvString = _this.find('a').attr('href').toString().split("?")[0].split("p_")[1];
       
        //Check if the product is SHC product - Vendor Product enhancement
        if(qvString != null && (qvString.indexOf("_") > 0)) {
		    var qvStrng = qvString.split("_");
	        var qvSID = qvStrng[0];
		    var qvCID = qvStrng[1];
		    var qvPID = qvStrng[2];
			// Omniture variables
        	var vert = omVrt.split("'").join("");
        	var cat = omCat.split("'").join("");
        	var sbcat = omSubCat.split("'").join(""); 
             
            //Check whether its a SHC's store - Vendor Product enhancement
			if(qvSID=="10153"||qvSID=="11201"||qvSID=="10151"||qvSID=="10152"||qvSID=="12701"||qvSID=="13201"||qvSID=="10701"||qvSID=="11701"||qvSID=="11702"||qvSID=="11703"||qvSID=="10154"||qvSID=="10156"){ 
                

			$(QVbtn).appendTo(_this).css({left:function(){
				    return ($(this).parent().width()/2)-($(this).width()/2)
					}}).hide();
					$('#qvl').fadeIn();
					
                $('a.QVbtn').unbind('click').click(function(){
                    s.prop26 = vert+' > '+cat+' > '+sbcat+' > '+'Quick View';
              		s.events ='event27';
              		s.product = qvPartnumber;
              		s.tl();
				    if (typeof showGoferQuickView !='undefined') {
				       showGoferQuickView(qvSID,qvCID,qvPID); 
				    }else{
				     	showNewQuickView(qvSID,qvCID,qvPID); 
				    }         
                    return false;
                });
            }
        }
    },function(){
        var _this = $(this);
        _this.removeClass("over");
        _this.find(".QVbtn").remove();
        _this.find(".screen").remove();
    });
    }
    
} 

function showQuickView(storeId, catalogId, partNumber) {
      var quickViewURL='QuickViewCmd?storeId='+storeId+'&catalogId='+catalogId+'&partNumber='+partNumber;
      updateSpuOnlyEntryQV(partNumber);
      var regSaveStrory=  getRegionalSSForSPUOnlyItem(partNumber)
      var regAvail = getRegionalAvailForSPUOnlyItem(partNumber)
      if(regAvail != ''&& regAvail != 'undefined'  ){
           quickViewURL=quickViewURL + '&ss='+regSaveStrory+'&avail='+regAvail
      }
         var options = { 
        success: displayResponse,
        url:quickViewURL,
        type:'GET'
    };                        
    request=$.ajax(options)
    options="";
}
function showNewQuickView(storeId, catalogId, partNumber) {
      var quickViewURL='QuickViewCmd?storeId='+storeId+'&catalogId='+catalogId+'&partNumber='+partNumber;
      updateSpuOnlyEntryQV(partNumber);
      var regSaveStrory=  getRegionalSSForSPUOnlyItem(partNumber)
      var regAvail = getRegionalAvailForSPUOnlyItem(partNumber)
      if(regAvail != ''&& regAvail != 'undefined'  ){
           quickViewURL=quickViewURL + '&ss='+regSaveStrory+'&avail='+regAvail
      }
         var options = { 
        success: displayQuickViewResponse,
        url:quickViewURL,
        type:'GET'
    };                        
    request=$.ajax(options)
    options="";
}

function displayQuickViewResponse(data){
	
	$(".qvPopUpLayer").remove(); //remove any previous instances of this window.
	$('body').append('<div class="qvPopUpLayer"></div>'); //add the div onto the bottom of the page
	$(".qvPopUpLayer").hide();
	$(".qvPopUpLayer").html(data);
	$(".qvPopUpLayer").fadeIn('fast');
	$('div.qvPopUpLayer').css("width", "820px");
	$('#tabs').tabs();
	var count=0;
	$('#actionsForm span').each(function(){
		count += 1;
	});
	if(count == 1){
		$('#actionsForm span').attr('style','display:none');
		if($('#actionsForm span input').val() != 'ship' && ($('#actionsForm small#pd_shippingCal_msg') != null && $('#actionsForm small#pd_shippingCal_msg')!= undefined)){
			$('#actionsForm small#pd_shippingCal_msg').attr('style','display:none');
		}
	}
	/*if(isI18NConvReq()){
			$('#actionsForm span').hide();
			$('strong#ordiv').hide();
			$('strong#pickUpText').hide();
	}*/
	$(".qvPopUpLayer").show();
	qvAlignment();	
	readyCloseQV();	
	attachImgEvents();
	initializeVar();
	onload_IntShipping();
	adjustTabHeight();
	return false;
}

function displayResponse(responseText) {  
    var data = eval('(' + responseText + ')');  
    SEARS.Item.info(data);
    SEARS.QuickView.launch();
} 

/* function for sears regional availability check add to cart */
function fnSearsAddToCart(jsonresponse){
	if(jsonresponse=='OutOfStock'){
		fnSetInfo('N');
		atcZipCode = getRegDelZip();
		$('#availPopup').css({display: "block"});
		$('#availPopup .standardDiv').css({display: "none"});
		$('#availPopup .errorDiv').css({display: "block"});
		$('.errorDiv input#checkZip').css({display: "inline"});
  		$('.standardDiv #loadGif').css({display: "none"});
  		$('.errorDiv #loadGif').css({display: "none"});
		readyOnLoad();
		catentryVal = SEARS.Item.parCatEntId;
	}else if(jsonresponse=='Failure'){
		tempZip=getRegDelZip();
		//remoteUrl = 'RegionalAvailCmd?pageInd=CAT&dbFlag=Y&catEntryId='+SEARS.Item.catEntId+'&zipCode='+tempZip;
		//request = $.post(remoteUrl,{DDItemList: qvpartnumber},fnSearsDBAddToCart,"json"); 
		var dbCall = { 
		        success: fnSearsDBAddToCart,
				url:'RegionalAvailCmd?pageInd=CAT&dbFlag=Y&catEntryId='+SEARS.Item.catEntId+'&zipCode='+tempZip+'&storeId='+regionalAvlStrId,
		        type:'POST',
		        data: {DDItemList: qvpartnumber},
		        dataType:'json',
		        error: errorFnDeliveryAvailResponse
	     	};
			request=$.ajax(dbCall);
	}else{
		$('#availPopup').remove();
      	document.addToCart.submit ();
    	document.addToCart.addToCartBtn.value = 'true';
	}
}

/* function to add to cart from QV through db call */
function fnSearsDBAddToCart(jsonResponse){
	var regavail = jsonResponse.jsonRegionalAvail; 
	var partNoLen=regavail.pco;
	if(typeof regavail != 'undefined'){
		for(var availCnt=0;availCnt<partNoLen;availCnt++){
			if(regavail.regAvailList[availCnt].pn==SEARS.Item.pId){
				if(regavail.regAvailList[availCnt].msg=="InStock" || regavail.regAvailList[availCnt].msg==""){
					$('div#availPopup').remove();
					addItemPartNo(document.addToCart.partNumber.value,SEARS.Item.inStock,SEARS.Item.storepu,jsonProducts.products[j].sri,SEARS.Item.dff,jsonProducts.products[j].vid,SEARS.Item.preOrder);
		    		document.addToCart.addToCartBtn.value = 'true';
				}
			}
		}
		fnSetInfo('N');
		$('#availPopup').css({display: "block"});
		$('#availPopup .standardDiv').css({display: "none"});
		$('#availPopup .errorDiv').css({display: "block"});
		readyOnLoad();
	}
}

/* function to set info parameters for addtocart call for RA */
function fnSetInfo(callInd){
	if(callInd=='Y' || callInd=='y'){
		pageFlag='CAT';
		dbFlagVal=callInd;
		catentryVal=SEARS.Item.catEntId;
	}
	else{
		pageFlag='CAT';
		dbFlagVal=callInd;
		catentryVal=SEARS.Item.catEntId;
	}
}

/* to check RA on addtocart*/
function submitAddToCartRA(image){
	if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && SEARS.Item.dff=='DDC'&& jsonProperties.regAvail == "true"){
		var pos = $('.gotoBtn').offset();
		pos.left = (((pos.left - 200) < 0 ) ? (pos.left + 200) : pos.left);
		$('#availPopup').remove();
		pageFlag='CAT';
		showCAPopUp();
		
		$('#availPopup .standardDiv').css({display: "none"});
		$('#availPopup .errorDiv').css({display: "none"});
		$('div#availPopup').css({top: pos.top - 100, left: pos.left - 200});
		flagCartQV='true';
	    flagQV='Y';
	}
	submitAddToCart(image);
}

/* submitaddtocart function  signature changed for smartcart */
function submitAddToCart(image) {
   qvpartnumber=document.addToCart.partNumber.value;
   if(document.addToCart.addToCartBtn.value == 'false') {
        //Add to cart button has been clicked once
        	if(SEARS.Item.vndStrId == "10153" && SEARS.Item.type=="H" && SEARS.Item.dff=='DDC' && jsonProperties.regAvail == "true"){
         		if(fnChkZipCode()){
					tempZip=getRegDelZip();
					//qvpartnumber=document.addToCart.partNumber.value;
					//hardcoded scimStoreId and quant
					var scimStoreId = "09300";
					var quant = "1";
					var deliveryStore = "09300";
					if(storeId == 10156){
						scimStoreId = "09311";
						deliveryStore = "09311";
					}
					//remoteUrl = 'RegionalAvailCmd?pageInd=CAT&dbFlag=N&storeId='+SEARS.Item.strId+'&ndd=1&zipCode='+tempZip+'&catEntryId='+SEARS.Item.parCatEntId+'&scimStoreId='+scimStoreId+'&quantity='+quant+'&deliveryStore='+deliveryStore;
					//request = $.post(remoteUrl,{DDItemList: qvpartnumber},fnSearsAddToCart); 	
					var scimCall = { 
				        success: fnSearsAddToCart,
						url:'RegionalAvailCmd?pageInd=CAT&dbFlag=N&ndd=1&zipCode='+tempZip+'&catEntryId='+SEARS.Item.parCatEntId+'&scimStoreId='+scimStoreId+'&quantity='+quant+'&deliveryStore='+deliveryStore+'&storeId='+regionalAvlStrId,
				        type:'POST',
				        data: {DDItemList: qvpartnumber},
				        error: errorFnDeliveryAvailResponse
			     	};
			     	request=$.ajax(scimCall);
				}else{
					fnSetInfo('N');
					$('#availPopup').css({display: "block"});
					$('#availPopup .standardDiv').css({display: "block"});
					$('#availPopup .errorDiv').css({display: "none"});
					currentPartNo = qvpartnumber;
					readyOnLoad();
					catentryVal = SEARS.Item.parCatEntId;
				}
        	}else{
        		//Add to cart button has been clicked once          
	        	document.addToCart.submit ();
    	    	document.addToCart.addToCartBtn.value = 'true';
    	    }
    }
}


(function($){

$.fn.bgIframe = $.fn.bgiframe = function(s) {
    // This is only for IE6
    if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
        s = $.extend({
            top     : 'auto', // auto == .currentStyle.borderTopWidth
            left    : 'auto', // auto == .currentStyle.borderLeftWidth
            width   : 'auto', // auto == offsetWidth
            height  : 'auto', // auto == offsetHeight
            opacity : true,
            src     : 'javascript:false;'
        }, s || {});
        var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
            html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
                       'style="display:block;position:absolute;z-index:-1;'+
                           (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
                           'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
                           'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
                           'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
                           'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
                    '"/>';
        return this.each(function() {
            if ( $('> iframe.bgiframe', this).length == 0 )
                this.insertBefore( document.createElement(html), this.firstChild );
        });
    }
    return this;
};

})($);
// Set up document when DOM ready //
$(function($){
    qvBtn();
});  

/*This function is to display the glossary. This function is called after the ajaxCall() in case of a glossary link.
We pass the html to be displayed in the pop-up as well as the id of the html element in this case it being a link */
function showGlossary(value,linkId){
        
    var hyperlinks = document.getElementsByTagName("a");
    for (var i=0; i<hyperlinks.length; i++) {
        if (hyperlinks[i].id == linkId){
            findPos(hyperlinks[i]);
            define(value);
        }
    }
} 

/*This function is to display the glossary. This function is called after the ajaxCall() in case of a glossary image.
We pass the html to be displayed in the pop-up as well as the id of the html element in this case it being an image */
function showImageGlossary(value,imageId){
        
    var images = document.getElementsByTagName("img");
    for (var i=0; i<images.length; i++) {
        if (images[i].id == imageId){
            findPos(images[i]);
            define(value);
        }
    }
     
}

/* quickView.js - ENDS HERE */

function productURLGen(productUrl){
	if((vName!=null && vName.length > 0) || (cName!=null && cName.length > 0 )||  (sName!=null && sName.length > 0) ||
		(keyword!=null && keyword.length > 0)){
		productUrl+="?";
	}
	if((vName!=null && vName.length > 0)){
		productUrl+="vName="+vName;
	}
	if((cName!=null && cName.length > 0) && (vName==null && vName.length==0) ){
		productUrl+="cName="+cName;
	}
	else if((cName!=null && cName.length > 0)) {
		productUrl+="&cName="+cName;
	}
	if((sName!=null && sName.length > 0) && ((vName==null && vName.length==0) && (cName==null && cName.length==0))){
		productUrl+="sName="+sName;
	}
	else if((sName!=null && sName.length > 0)){
		productUrl+="&sName="+sName;
	}
	if((keyword!=null && keyword.length > 0) && 
			((vName==null || vName.length==0) && (cName==null || cName.length==0) && (sName==null || sName.length==0))){
	    productUrl+="keyword="+keyword;
	} else if((keyword!=null && keyword.length > 0)){
	    productUrl+="&keyword="+keyword;
	}
	return productUrl;
}
/* Radio button Click*/
var selectRadio = function(childRadio){																												
	// Unbind click event for selected radio btn
	$(childRadio).parent().unbind();																								
	
	// Empty price range input box
	userInputPrice = false;
	clearInputRangeFields();
	
	// Displat Price block as selected, show clear and clear all links
	if($("div.left-column h4:eq(0) a").length<1){
		$("div.left-column h4:eq(0)").prepend("<a href='javaScript.html' title='Clear all selections'>Clear All</a>");
		$("div.left-column h4:eq(0) a").click(clearAll);
	}
	if($(childRadio).parent().parent().parent().parent().children("h5").children("a").length<1){
		var createClearHtml = "<a href='javaScript.html' name='"+$(childRadio).parent().parent().parent().attr('class')+"' title='Clear selections'>Clear</a>";
		$(childRadio).parent().parent().parent().parent().children("h5").prepend(createClearHtml);
		$(childRadio).parent().parent().parent().parent().children("h5").children("a").click(clearSelection);
	}
	
    /* Obtain the filter name of the selected element */
	var tempFilter=$(childRadio).parent().parent().parent().parent().find('h5').find('div').text();	
	var tempElement=childRadio.id;								
	
	/* If main range is selected, add 'Price to lastFilter'
	If sub range is selected, add 'SubPriceRange' to lastFilter */	
	if($(childRadio).parent().parent().attr("id")=="slider"){
		$(childRadio).parent().parent().parent().parent().addClass("selected");
		lastFilter=lastFilter+","+tempFilter+":"+tempElement;					
	} else {
	 	lastFilter=lastFilter.replace(","+tempFilter+":"+tempElement,"");
	 	lastFilter=lastFilter+",SubPriceRange:"+tempElement;
	}
	// Set the Offset for Update and NoResults popup
	var newTop = $("li#slider").parent().offset();
	$('div#filterConfirm').css({top: newTop.top});
    $('div#noresults').css({top: newTop.top});
    
	/* Make Ajax */
	prefilter();
	gotoPage(1);
	ajaxImpl();	
}
// Function to update price range block in left nav
function updatePriceRange(priceRangeFilter,lastFilter,priceHeaderProdCount) {
	// Store Price Range Json in arrays
	var priceRangeName=[];
	var priceRangeDisplayName=[];
	var priceRangeProductCount=[];
	if(priceRangeFilter != null) {
		for(var i=0;i<priceRangeFilter.length;i++){
			priceRangeName[i]=priceRangeFilter[i].fvn;
			priceRangeDisplayName[i]=priceRangeFilter[i].fvk;
			priceRangeProductCount[i]=priceRangeFilter[i].fvc;
		}
	}
	if(lastFilter=="SubPriceRange") {
		// If a sub price range was clicked, show 'Show All Prices'
		if($("li#slider div.sub_price_range").find("input:checked").length > 0) {
			var selectedRange = $("li#slider div.sub_price_range").find("input:checked").parent().html();
			//i18n change
			if(isI18NConvReq()){
			fnConSSfly(selectedRange);
			}
		} else {
			var selectedRange = $("li#slider").find("input:checked").parent().html();
		}
		updatePriceRangeHeader(selectedRange,priceHeaderProdCount);
		if($("li#slider div.sub_price_range").length == 0) {
			$("li#slider").append('<div class="sub_price_range"></div>');
		}
		$("div.sub_price_range").html('<a href="javascript:;">Show All Prices</a>');
		
		// Show all prices click event
		$(".sub_price_range a").click(function(){
			$(this).parent().parent().parent().parent().find("h5").children("a").click();
		});
	} else if(lastFilter=="Price2") {
		// If user had entered price in input box reset price ranges.
		addPrimaryRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount);
	} else if(lastFilter=="Price") {
		// If a price range was clicked, show sub price ranges
		updatePriceRangeHeader($("li#slider label.price_range").find("input:checked").parent().html(),priceHeaderProdCount);
		addSubRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount);
	} else {
		// If any other user filter action
		if($("li#slider div.sub_price_range").length > 0) {
			updatePriceRangeHeader($("li#slider label.price_range").find("input:checked").parent().html(),priceHeaderProdCount);
			addSubRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount);
		} else {
			addPrimaryRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount);
		}
	}
}
// Function to Add new sub ranges/update existing sub ranges
function addSubRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount) {
	$("li#slider div.sub_price_range").remove();
	if(priceRangeName.length > 0) {
		// Show sub price range
		var str_subPriceRange = '<div class="sub_price_range">' +
				'<p><a id="a_slider_narrowBy" href="javascript:;">Continue to narrow by:</a></p>' + 
				'<div id="sub_price_range_list">';
	
		// Create  sub ranges
		for(var n = 0; n < priceRangeName.length; n++){	
			// i18n change
			if(isI18NConvReq()){
				str_subPriceRange +=
				'<label class="price_range">' + 
				'	<input id="'+ priceRangeName[n] +'" type="radio" name="subPriceRange" />'+
				fnPriceRange(priceRangeDisplayName[n]) +' ('+priceRangeProductCount[n]+')'+
		         '</label>';
	         }
	         else{
	         	str_subPriceRange +=
				'<label class="price_range">' + 
				'	<input id="'+ priceRangeName[n] +'" type="radio" name="subPriceRange" />'+
				priceRangeDisplayName[n] +' ('+priceRangeProductCount[n]+')'+
		         '</label>';
	         }
		}		
		str_subPriceRange += '</div></div>';
				
		// Add sub price to DOM	
		$("li#slider").append(str_subPriceRange);
		
		//Add click event to "Continue to narrow by" label
		$("li#slider div.sub_price_range a#a_slider_narrowBy").click(
			function(){
				if($(this).parent().hasClass("closed")){
					$(this).parent().removeClass("closed");
					$("#slider div#sub_price_range_list").slideDown("fast");
				}else{
					$(this).parent().addClass("closed");
					$("#slider div#sub_price_range_list").slideUp("fast");
				}
			}
		);
		//Add click behaviors for sub ranges
		//price slider phase II
		$("div.left-column li#slider label").click(bindRadioButton);
	} else {
		// Add Show All Price, if Price ranges are not req.
		$("li#slider").append('<div class="sub_price_range"><a href="javascript:;">Show All Prices</a></div>');
		// Show all prices click event
		$(".sub_price_range a").click(function(){
			$(this).parent().parent().parent().parent().find("h5").children("a").click();
		});
	}
}
// Function to Add new price ranges/update existing price ranges
function addPrimaryRanges(priceRangeName,priceRangeDisplayName,priceRangeProductCount) {
	if(priceRangeName.length > 0) {
		// Show primary price range
		var str_inputDOM = '<label class="price_range"><input class="slider_priceRange_radio" name="priceRange" type="radio" id="';
		var domPrice = "";
		// Create  primary price ranges
		for(var n = 0; n < priceRangeName.length; n++) {	
			// i18n change
			if(n == priceRangeName.length - 1){		
				var priceDisplayName = priceRangeDisplayName[n];
					priceRangeDisplayName[n] = priceDisplayName.replace(priceDisplayName.substring(priceDisplayName.indexOf("-"),priceDisplayName.length),"& above");
			}
			if(isI18NConvReq()){
				domPrice += str_inputDOM + priceRangeName[n] + '">' + fnPriceRange(priceRangeDisplayName[n]) + ' (' + priceRangeProductCount[n] + ')</label>'
			}else{
			  	domPrice += str_inputDOM + priceRangeName[n] + '">' + priceRangeDisplayName[n] + ' (' + priceRangeProductCount[n] + ')</label>'
			}	
		}
		// Add primary price to DOM	
		$("li#slider").html(domPrice);
		
		// Add click behaviors for price ranges
		
		//price slider phase II
		$("div.left-column li#slider label").click(bindRadioButton);
	} else {
		// Hide Price ranges, ifnot req.
		$("li#slider").html("");
	}
}
// Function to update price range header
function updatePriceRangeHeader(selectedRange,priceHeaderProdCount) {
	var sliderObj = $("li#slider");
	$(sliderObj).children("label").remove();
	$(sliderObj).prepend('<label class="price_range"></label>');
	selectedRange = selectedRange.replace(selectedRange.substring(selectedRange.indexOf('('),selectedRange.indexOf(')')+1),'('+priceHeaderProdCount+')');
	$(sliderObj).children("label").html(selectedRange);
	$(sliderObj).children("label").children("input").attr("checked","checked");
}
//Function to Associate the click of label to the corresponding radio button - Price SLider II Enhancement
var bindRadioButton = function(){
	var childRadio = $(this).find("input:radio");
	if ($(childRadio).attr("checked")){
		$(childRadio).removeAttr("checked");
	}
	else {
		$(childRadio).attr("checked","checked");
	}
	selectRadio($(childRadio));
	return false;
}
//i18n shipping 
/* Changes For Search Within Search - Start */
function searchWithinClick() {
	var txtSearchWithin = $("div.left-column #search_within_box").val();
	txtSearchWithin = ValidateSearchwithinTxt(txtSearchWithin);
	$("div.left-column #search_within_box").val(txtSearchWithin);
	if(typeof txtSearchWithin != 'undefined' && txtSearchWithin != '' && txtSearchWithin != searchWithinSearch){
			lastFilter=lastFilter+",searchwithin:" + txtSearchWithin;
			prefilter({searchWitinForm:true});
			gotoPage(1);
			ajaxImpl();
	}
}

function splitSearchWithinFilter(filterParameter){
	var splitstring =[];
	var filterSplit =["",""];
	var strLastFilter = '';
	var iLoop = 0;
	if(typeof filterParameter != 'undefined' && filterParameter!=""){
		splitstring = undoCleanFilterParam(filterParameter);
		if(splitstring.indexOf('&lastFilter') > -1){
			strLastFilter = splitstring.substring(splitstring.indexOf('&lastFilter'));
			splitstring = splitstring.substring(0,splitstring.indexOf('&lastFilter'));
		}
		splitstring = splitstring.split('^');
		splitstring[0] = splitstring[0].replace(new RegExp("filter="),'');
		for(;iLoop<splitstring.length;iLoop++){
			if(splitstring[iLoop].indexOf("searchwithin|") > -1)
				filterSplit[0] = splitstring[iLoop];
			else
				filterSplit[1] = splitstring[iLoop] + "^";
		}
		if(filterSplit[1] != '')
			filterSplit[1] = "filter=" + filterSplit[1].substring(0,filterSplit[1].length-1)+strLastFilter;
	}
	return filterSplit;
}
function resumeSearchWithin(searchWithinVal){
	if(typeof $("div.left-column #search_within_box").val() != 'undefined'){
		$("div.left-column #search_within_box").val((searchWithinVal.substring(searchWithinVal.indexOf('|')+1).replace(/[|]/g,',')).replace(/[+]/g,' '));
	}
}
function clearSearchWithin(){
	if(typeof $("div.left-column #search_within_box").val() != 'undefined'){
		$("div.left-column #search_within_box").val("");
		//Remove BreadCrumb
		ClearExtnBreadCurmb();
	}
}
function remBreadCrumbClick(){
	clearSearchWithin();
	prefilter();
	gotoPage(1);
	ajaxImpl();
}
function ClearExtnBreadCurmb(){
if(typeof $("div.left-column #search_within_box").val() != 'undefined'){
	searchWithinSearch = "";
	var breadobj = $('div.breadcrumb');
	$(breadobj).find("span#spaceId").remove();
	$(breadobj).find("span#extndbreadcrmb").remove();
	$(breadobj).find("a#remLink").remove();
	$('div.breadcrumb').append("");
}
}

function genExtnBreadCrumb(){
if(typeof $("div.left-column #search_within_box").val() != 'undefined'){
	ClearExtnBreadCurmb();
	if($("div.left-column #search_within_box").val() != ''){
		var breadHtml = "<span id=\"spaceId\">&nbsp;</span>";
		searchWithinSearch = $("div.left-column #search_within_box").val();
		breadHtml +="<a id=\"remLink\" href=\"javascript:remBreadCrumbClick();\"><img class=\"removebtn\" src=\""+jspStoreImgDir+"img/remove_btn.gif\"></a>";
		breadHtml +="<span id=\"extndbreadcrmb\">";
		breadHtml += $("div.left-column #search_within_box").val().replace(/[,]/g,' ');
		breadHtml +="</span>";		 
		$('div.breadcrumb').append(breadHtml);
	}
}
}
function ValidateSearchwithinTxt(txtSearchWithin){
	txtSearchWithin = txtSearchWithin.replace(/[!^;{}!\\/\"<>?*#@~=+()]/g,' ').replace(/[$%&_\'\-:]{2,}/g,' ').replace(/(\s{2,})/g,'');;
	txtSearchWithin = rtrim(ltrim(txtSearchWithin));
	return txtSearchWithin;
}
/* Added for Search Within Vertical - Start */
function ChangeVertDropdown(){
	if(typeof jsonProperties.csi != 'undefined' && jsonProperties.csi != null && !jsonProperties.csi){
	if(typeof jsonProperties.vName != 'undefined' && jsonProperties.vName != null){
		var vName=escape(jsonProperties.vName);
		vName = replaceAll(vName,"%20"," ");
		vName = undoCleanFilterParam(vName);
		if(vName != 'undefined' && vName != ''){
			if(vName == 'Automotive'){
	        	vName = 'Automotive & Tires';
	        }else if(vName == 'For the Home' && jsonProperties.sid==10153){
	        	vName = 'Bed, Bath & Home';
	        }else if(vName == 'Computers & Electronics' && jsonProperties.sid==10153){
	        	vName = 'Electronics & Computers';
	        }else if(vName == 'Computers & Electronics' && jsonProperties.sid==10151){
	        	vName = 'Electronics & Office';
	        }else if(vName == 'Jewelry'){
				vName = 'Jewelry & Watches';
	        }else if(vName == 'Computers & Electronics_Office Products'){
	        	vName = 'Office Products';
	        }else if(vName == 'Outdoor Living'){
	        	vName = 'Outdoor Living & Seasonal';
	        }else if(vName == 'Entertainment'){
	        	vName = 'Video Games';
			}else if(vName == 'Baby' && jsonProperties.sid==10151){
				vName = 'Baby & Nursery';
			}else if(vName == 'Tools' && jsonProperties.sid==10151){
				vName = 'Home Improvement';	
			}else if(vName == 'Pet Supplies' && jsonProperties.sid==10151){
				vName = 'Pets';	
			}
			vName = vName.replace('&','&amp;');
			$("ul#searchBy").find('li a').each(function(i){
				if(ltrim(rtrim($(this).html())) == vName){
					$("a.selectsearch").html(vName);
					$("a.selectsearch").attr("title",vName);
					$("a.selectsearch").attr("id",$(this).attr("id"));
					return false;
				}
			});
		 }
	   }
	}
}
/* Added for Search Within Vertical - End */
/* Changes for Search within Search - End */
jQuery(function($){
$("div.left-column li#slider label").click(bindRadioButton);
$("div.left-column li#slider .sub_price_range").click(bindRadioButton);
});

/*Inline Scripts for Cookie Handling moved from subCategoryLayout.jsp and keyworkBody.jsp*/
function setCookieValue(cookieName,cookieValue){
	document.cookie = cookieName+ "=" + escape(cookieValue);
}
function getCookieValue(cookieName) {
	if (document.cookie.length > 0) {
		cookieStart=document.cookie.indexOf(cookieName + "=")
		if (cookieStart!=-1) { 
			cookieStart=cookieStart + cookieName.length+1 
			cookieEnd=document.cookie.indexOf(";",cookieStart)
			if (cookieEnd==-1) cookieEnd=document.cookie.length
			    return unescape(document.cookie.substring(cookieStart,cookieEnd))
		} 
	}
	return ""
}
