/* Variable Declaration - Starts Here */
var dynamicCategoryName="";

/* Declare variable to hold filter options in URL */
var filterParam="";
 
/* Declare variable to hold pagination URL attributes */
var paginationParam="";
var defaultPaginationParam="";
/* For DCP page */
var dynamicCategoryPage;
/* Declaring the filter Map */
var filters = [];

/* Declare variable lastFilter and initialize it to null string */
var lastFilter="";

// 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 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 urlAfterAjaxCall='';
var filterParamAfterAjaxCall='';
var fromProductPage=false;
var jsonProducts;
var urlFilterParameterOnLoad="";
var userSelectedPrice="";
var previousResultsFilterParam="";
var omFilter="";
var remoteUrl;
var viewItems;	
var pageNumber = 1;
var ajaxTimeOut = false;

/* AJAX Setup */
$.ajaxSetup( {
	timeout : 20000
});

// Ajax error pop up
var ajaxPopup= '<div id="ajaxError" class="lightbox" style="display:none">\n';
    /* Dk modification: using our layout */
	ajaxPopup+= '	<div class="lightboxBody ajaxError">\n';
	ajaxPopup+= '	<div class="lb_content">\n';
    /* --end Dk modification */
	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>';
    /* Dk modification: using our layout */
	//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+= '	<li>RealPlayer Browser Record Plugin</li>';
	ajaxPopup+= '	<li>Talkback Plugin</li>';
    /* --end Dk modification */
	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';
    /* Dk modification: using our layout */
	//ajaxPopup+= '	<input id="tryAgain" type="image" src="'+jspStoreImgDir+'img/buttons/btn_continueanyway_red.gif" value="Try Again" width="135" height="27"><input id="prevResultsAjaxError" type="image" src="'+jspStoreImgDir+'img/buttons/btn_prev_results.gif" value="Show previous results">\n';
	ajaxPopup+= '	<a id="tryAgain" class="button-continueAnyway" href="javascript:;">Try Again</a><a id="prevResultsAjaxError" class="button-previousResults" href="javascript:;">Show previous results"</a>\n';
    /* Dk modification: using our layout */
	ajaxPopup+= '	<div class="clear"><!--zero height IE6--></div>\n'; //close .lb_content
	ajaxPopup+= '	</div>\n'; //close .lb_content
	ajaxPopup+= '	</div>\n'; //close .lightboxbody
    /* --end Dk modification */
	ajaxPopup+= '</div>\n';	

/* Variable Declaration - Ends 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);
        };
}

/*FIND POSITION*/
function findPosExact(obj) {
    xPos = yPos = 0;
    if (obj.offsetParent) {
        //console.log("have nearest positioned ancestor as '%o', HTML as \n'%s'",obj.offsetParent,$(obj.offsetParent).html());
        xPos = obj.offsetLeft;
        yPos = obj.offsetTop;
        while (obj = obj.offsetParent) {
            //console.log('looping while obj = obj.offsetParent; obj %o (tagName "%s", className "%s", id "%s")',obj,obj.tagName,obj.className,obj.id);
            if (obj.offsetParent) {
            //console.log('\nobj.offsetParent %o (tagName "%s", className "%s", id "%s")',obj.offsetParent,obj.offsetParent.tagName,obj.offsetParent.className,obj.offsetParent.id);
            }
            xPos += obj.offsetLeft;
            yPos += obj.offsetTop;
            //console.log('\n new xPos as "%s", yPos as "%s"',xPos,yPos);
        }
    }
    return [xPos,yPos];
}

/*Function to store all the sort options in an array*/
function getSortOptions() {
    currentSortOption=$("div#sortByGroup li a.selected").parent().text();
    selectedSortOption=$("div#sortByGroup li a.selected").attr('name');
    $('div#sortByGroup').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() {
    $("div.compareBar 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=ltrim(rtrim(inpText));
    // Replacing ' ' with '+'
    while(inpText.indexOf(" ")>=0){
        inpText=inpText.replace(" ","+");
    }
    return inpText;
}

/*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){
    	if(jsonProperties.enableATO_STL == true){
            $(box).parent().parent().parent().addClass('selected');
        }
        else{
        	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;
                        
            //also remove the css
            if(jsonProperties.enableATO_STL == true){
            	$(box).parent().parent().parent().removeClass('selected');
           	}
           	else{
            box.parentNode.parentNode.parentNode.className="product";
           	}
            alert("You can compare a maximum of "+maxCompares+" items");
         }
    
    }else{
        //if unchecked
        prodCountCompare--;
        if(jsonProperties.enableATO_STL == true){
        	$(box).parent().parent().parent().removeClass('selected');
       	}
       	else{
        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;
}

/*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;
}

/*addItemPartNo*/
function fnAddToCartOverlay(partnumber,si,spi,sri,dff,presellDate,productURL,catEntryId) {
	var urlATC=""	
	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";		
	}	
	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+"&variant=0";
		window.location.href=urlATC;
	} else {
		if(!(spi == 'true' || sri==1) && si!=null && si!=1) {
			urlATC = "ProductOptionsOrderItemAddCmd?langId=-1&storeId="+jsonProperties.sid+ "&catalogId="+jsonProperties.cid+"&itemPartNumber="+ itemPartNumber+"&URL=OrderItemDisplay&quantity_1=1"+
				"&atc="+pageType+"&partNumber="+partnumber+"&variant=0";
			window.location.href=urlATC;
		}
		else if(dff == "SPU" || ((spi == 'true' || sri==1) && si==1)) {
			var overlayToShow = '#lb_zipfinder';
        	var overlayID = 'lb_zipfinder';
	        if ($(overlayToShow).length) {
	            //console.log('found overlay in DOM, removing it before recreating and appending...')
	            $(overlayToShow).remove();
	        }
			var container = $('body').append('<div id="'+overlayID+'" class="lightbox"><div class="lightboxBody zipfinder"></div></div>');
	        var alertBox = $(overlayToShow+' .lightboxBody');
	        $(alertBox).append('<div class="lb_header">'+
	                          '<span>Available for In-Store Pickup</span>'+
	                          '<a class="close" href="javascript:void(0)" onclick="hidebox(\''+overlayToShow+'\')">Close</a>'+
	                          '<div class="clear"></div>'+
	                          '</div>'+
	                          '<div class="lb_content"></div>');
	        var alertContent = $(overlayToShow+' .lb_content');
	        var newContent = "<p>This Craftsman product is available for in-store pickup when you buy it online.</p>"+
	                         "<div class='clear'></div>"+
	                         "<div class='lb_inputs'>"+
	                            "<p>Enter your ZIP code to find this item at a store near you.</p>"+
	                            "<input type='text' name='zipCode' id='zipCode' size='15' maxlength='5' class='text' value='"+getCookie('zipCode')+"'/><a class='ok' onClick='return storeLocatorPopup();' href='javascript:;'>Ok</a>"+
	                         "</div>"+
	                         "<div class='clear'></div>"+
	                         "\t<input type='hidden' id='zipCatEntryId' name='catEntryId_1' value='"+catEntryId+"'>\n"+
							 "\t<input type='hidden' id='zipProductURL' name='URL' value='"+productURL+"'>\n"+			
							 "\t<input type='hidden' id='zipPartNumber' name='partNumber' value='"+partnumber+"'>\n"+
							 "\t<input type='hidden' id='zipStoreId' name='storeId' value='"+jsonProperties.sid+"'>\n"+
							 "\t<input type='hidden' id='zipCatalogId' name='catalogId' value='"+jsonProperties.cid+"'>\n"+
							 "\t<input type='hidden' id='zipPreSellDate' name='presellDate' value=''>\n";	
	        $(alertContent).append(newContent);
	        showbox(overlayToShow);
		} else {
			if(!document.getElementById('lb_addtocart')){
			     var containerDiv=document.createElement('div');
			     containerDiv.id='lb_addtocart';
			     containerDiv.className='lightbox';
			     document.body.appendChild(containerDiv);
			}
		    var container=document.getElementById('lb_addtocart');
		    var results='<a class="ship" href="ProductOptionsOrderItemAddCmd?langId=-1&storeId='+jsonProperties.sid+'&catalogId='+jsonProperties.cid+'&itemPartNumber='+ itemPartNumber+'&URL=OrderItemDisplay&quantity_1=1'+
					'&atc='+pageType+'&partNumber='+partnumber+'&variant=0"></a>' 
		    var pickup ='<a onclick="showpickup(\'#zipFinder\');" class="pickup" href="javascript:;">Pick up at store </a>';
		    container.innerHTML="<div class='lightboxBody addtocart'>"
								+ " <div class='lb_header'>"
								+ " <span>Add to Cart</span>"
								+ " <a class='close' href='javascript:;' onclick='hidebox(\"#lb_addtocart\");'>Close</a>"
								+ " <div class='clear'></div></div>"
								+ " <div class='lb_content'>"
								+ " <p>Would you like this item shipped or will you pick it up from the store?</p>"
								+ " <div class='buttons'>"
								+ results
								+ pickup
								+ " </div><div class='clear'></div>"
								+ " <div id='zipFinder' class='lb_inputs'>"
								+ " <p>Enter your ZIP Code to find this item at a store near you.</p>"
								+ " <form name='zipCodeForm' onsubmit='return false;'>"
									+ " <input type='hidden' id='zipStoreId' value='"+jsonProperties.sid+"' /> "
								    + " <input type='hidden' id='zipCatalogId' value='"+jsonProperties.cid+"' /> "
								    + " <input type='hidden' id='zipCatEntryId' value='"+catEntryId+"' /> "
								    + " <input type='hidden' id='zipPartNumber' value='"+partnumber+"' /> "
								    + " <input type='hidden' id='zipProductURL' value='"+productURL+"' /> "
								    + " <input type='hidden' id='zipPreSellDate' name='presellDate' value=''> "	
								    + " <input type='text' id='zipCode' maxlength='5' value='"+getCookie('zipCode')+"'/> <a class='ok' id='zipCodeEnter' onClick='return storeLocatorPopup();'>Ok</a>"
								+ " </form>"
								+ " </div><div class='clear'></div></div></div></div>";
		    showbox('#lb_addtocart');
		}
	}
}

/*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) {
	omFilter = omFilter + "cs=0&";
	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();
    /* Dk modification: using our layout */
	//$("div#noresults").hide();
	hidebox("#lb_noresults");
    /* --end Dk modification */
	// 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("content").style.display='block';
		init_FilterSlider();
		$('div.product').height('auto');
		heightAdjust();
	}
	// Calculate the offset where the curtain is to be displayed
    /* Dk modification: safely operate on div.left-column, don't assume 
       it exists */
	//var topForRightColumn = $('div.left-column').offset().top-5;
    var leftCol = $('div.categories');
    var topForRightColumn;
    if (leftCol.length) {
	    topForRightColumn = $('div.categories').offset().top-5;
    }
    /* --end Dk modification */
	$('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);							
	}
	// Show the pop up
    /* Dk modification: using our layout */
	//$('div#contentWrapper').prepend(ajaxPopup);
	$('body').prepend(ajaxPopup);
    showbox("div#ajaxError");
    /* --end Dk modification */
}
/* Function to adjust the height of the product blocks when row/grid switch happens */
var heightAdjust = function(){ // { Readjust heights to act like table cells };
	var newheight = '';
	if($.browser.msie){newheight = '1%'}
		$('div.searchResult div.product').height(newheight);
};

var dd = "";
function timeOutHide(id) {
    var remove = function(){ $("#"+id).remove() };
    dd = setTimeout(remove,500);
}

/* DOM READY CALLS - Starts Here */
jQuery(document).ready(function($) {
	var domBodySetup = '<div id="body-curtain" style="display:none"></div>\n';
		domBodySetup+= '<div class="progress">\n';
		domBodySetup+= '	<img src="'+jspStoreImgDir+'images/img/loader/pre-loader2.gif" alt="Loading results...">\n';
		domBodySetup+= '</div>\n';
	$('body').prepend(domBodySetup);
	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" || document.body.id == "searchResults" || document.body.id == "product")
	{		
		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;
		}						
		var prodIndexArray=[];	              
	    
	    for(i=startIndex;i<=endIndex;i++){
		        prodIndexArray[i-1]=i-1;
      	
	    }
        /* Dk modification: show pre-load while building product display
            for use on static templates */
        bodyPreloader();
        /* --end Dk modification */
        /* Dk modification: safely write into #results, make sure it exists */
        //document.getElementById("results").innerHTML=jsonDisplayProd(prodIndexArray, true);
        var myResults = jsonDisplayProd(prodIndexArray);
        var resultsObj = document.getElementById("results");
		if (resultsObj){
            resultsObj.innerHTML=myResults;
        }
        /* --end Dk modification */
        /* Dk modification: show #lb_noresults if no products returned in JSON data set,
           otherwise remove the curtain after appending results */
        if (myResults.length < 1) {
            $(window).load(function(){
                removeCurtain();
                var waitABit = setTimeout('showbox("#lb_noresults")',500);
            });
        } else {
            var waitABit = setTimeout(removeCurtain,0);
        }
        /* --end Dk modification */
		if(jsonForm) {
            //console.log('subcat.js: jsonForm is true');
			var totalProducts=parseInt(jsonProducts.prodCnt);
			// To hide the compare button when there is only one item
			if(totalProducts==1) {
				$('div.compareBar').hide();
			}
			else {
				$('div.compareBar').show();
			}
			
			/* adjust height on product containers */
			heightAdjust();

			/*Call this function on Page Load*/
			commonPagination();	
			
			getSortOptions();
			/*To get the browser name */
			var browser=navigator.appName;
				
			/* Unchecked all checked inputs onload */
			$("div.categories input:checked").removeAttr("checked");
		    $("div.categories ul li.open div.filters ul li ul li input:checkbox").click(selectAttribute);
		    $("div.categories ul li.open div.filters ul li.filterColor ul li").click(function() {
		    	$(this).find('input:checkbox').each(selectAttribute);
		    });
			
			/* Dropdown functions */
			$("a.select").click(function(){ findPosExact(this); /*console.log('findPosExact sets xPos "%s", yPos "%s"',xPos,yPos);*/dropDown($(this).next(), this.className, $(this).width()); 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 */
            /* Dk modification: using our layout */
			//var span = $("div.left-column").find("span");
			var span = $(".filters .ratings span");
            /* --end Dk modification */
			for(var s=0; s<span.length; s++){
                /* Dk modification: change of selector above makes check for left column as ancestor unnecessary */
				//if(span[s].className.indexOf("no")==-1 && span[s].parentNode.parentNode.parentNode.className=="left-column" ){
				if(span[s].className.indexOf("no")==-1){
                /* --end Dk modification */
                    /* Dk modification: safely add class, don't clobber existing classNames */
					//span[s].parentNode.parentNode.className="selected";
                    $(span[s]).parent().parent().addClass("selected");
                    /* --end Dk modification */
					var alink = span[s].getElementsByTagName("a");
					for(var i=0; i<alink.length; i++){
						var split = span[s].className.split(" ");
                        /* Dk modification: fix bug, identify the correctly selected star rating */
						//if( alink[i].className.indexOf(split[0])==-1 ){
						if( !(alink[i].className.indexOf(split[0])==-1) ){
                        /* --end Dk modification */
                            /* Dk modification: fix parsing bug where "<input..." HTML was being included
                               in the selectedNum property assignment */
							//span[s].selectedNum = alink[i].innerHTML;
                            var thisSelected = alink[i].innerHTML;
                            var chopFromHere = thisSelected.indexOf("<input");
                            var thisSelectedNum = thisSelected.substring(0,chopFromHere);
                            span[s].selectedNum = thisSelectedNum;
						}
					}
				} else { span[s].selectedNum = "0"; }
				span[s].selectedSpan = span[s].className;
			};

            //console.log('subcat JS: doing DOM setup,line 1299...');
            var domSetup = '<div id="right-column-curtain" style="display:none"></div>\n';
                // This is for No Results Condition
                /* Dk modification: using our layout */
				//domSetup+= '<div id="noresults" style="display:none">\n';
				domSetup+= '<div id="lb_noresults" class="lightbox" style="display:none">\n';
				domSetup+= '    <div class="lightboxBody noresults">\n';
				domSetup+= '        <div class="lb_content">\n';
                /* --end Dk modification */
				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';
                /* Dk modification: using our layout */
				//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';
				domSetup+= '	        <a id="prevResults" class="button-previousResults" href="javascript:;">Show previous results</a>';
                domSetup+= '            <a id="filterClear" class="button-clear" href="javascript:;">Clear</a>\n';
				domSetup+= '	        <div class="clear"><!--zero height IE6--></div>\n';
				domSetup+= '        </div>\n';
                /* --end Dk modification */
				domSetup+= '</div>\n';
            /* Dk modification: using our layout */
			//$('div#contentWrapper').prepend(domSetup);
            if ($('#wrapper').length) {
			    $('#wrapper').before(domSetup);
            } else {
			    $('body').prepend(domSetup);
            }
            /* --end Dk modification */
			
			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;
			    	start=1;
					end=parseInt(jsonForm.viewItems);
					subCatProductCount=parseInt(jsonProducts.prodCnt);
					pageNo=parseInt(jsonForm.pageNum);	
					filterParam=urlFilterParameterOnLoad;			    	
					keywordCheck(urlFilterParameterOnLoad,false);			    	
				  }	
				  if(jsonProperties.kp == true){		
						updateCategoriesOnLoad(urlFilterParameterOnLoad,pageParam);
				  }
			}
			if(jsonProperties.dcp == false){
				mergeFilters(jsonFilters.filter);
				var opened = false;
				$('div#leftCol li.open li a').each(function(node) {
					if($(this).next('ul') && this.parentNode.style.display!="none" && opened==false) {
						$(this.parentNode).addClass('first open');
						opened = true;
					}
				});
			}

			/* Clear Button */
			$('#filterClear').click(function() {
				$("div.categories input:checked").removeAttr("checked");
				// For price clear all option
				$("div.filters div.ui-slider").each(function(){
			        if($(this).slider("getMax") != $(this).find("input[type='hidden']").val()) {
			            $(this).removeClass("selected");
			            FilterSlider.slider('reset');
			        }
			    });
				var span = $("div.ratings").find("span");
				for(var s=0; s<span.length; s++){
					if(span[s].className.indexOf("no")==-1 && span[s].parentNode.className=="ratings" ){
						$(span[s].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.categories div.filters a.clearAll").remove();
				$("div.categories div.filters ul li a.clear").remove();
				$('div.colorSelected').remove();
				
				/* Reset the value of Last filter to null when clear All is clicked */
				lastFilter="";				
				userSelectedPrice="";
				prefilter();
				gotoPage(1);
				ajaxImpl();						
				return false;															 
			});

			/* Star Ratings functions */
			$("div.ratings span.star a").each(function(i) {
				$(this).click(function() {
					/*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().find('div.hidden').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).addClass("selected");
					if($("div.categories ul:eq(0) a.clearAll").length<1) {
						$(this).parent().parent().parent().parent().prepend("<a class='clearAll' href='javaScript:;'>Clear All</a>");
						$("div.categories ul:eq(0) a.clearAll").click(clearAll);
					}
					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();
					$('div#noresults').css({top: newTop.top});
				
					// Calling the Ajax implementation
					gotoPage(1);
					ajaxImpl();
					return false;
				});
			});
	
			$("div.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";
					}
				}
			);
			$('div#leftCol div.categories ul#nav li a').click(function(){
					$('div#leftCol div.categories ul#nav li a.on').attr('class','');
						$(this).attr('class','on');
					});
			$('a[@id=btnPrevious]').click(prevButton);
			$('a[@id=btnNext]').click(nextButton);			
			$('#prevResults').click(function(){
				previousResultsUpdate();
			});	
			$('div#leftCol div.categories 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");
					
					/*$(this).parent().css({
							'background-color': '#ad151d',
							'background-image': 'none',
							'color': '#fff'
					});*/
		}
				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);
   	
	}

	// CAll function to resume the previous the state of the page
	resumeState();
	//Function call for checkboxes to be checked
	initCompareCheckBox();
	$("div#itemShown ul li a.off").click(function() {
		viewPerPage($(this).attr('name'));
	});
	
	$("div.prodListingPagination div ul li a").click(function(){
		if(($(this).attr('id')!="btnNext") && ($(this).attr('id')!="btnPrevious") && (!($(this).parent().is(".active")))) {
			var pageShown=$("div#pagin ul li").attr('id');
			var tempParam=paginationParam.split("&");
			if(tempParam[1].split("=")[1]!=$(this).attr('name')) { 
				gotoPage($(this).attr('name'));
				ajaxImpl();
			}	
		}	
	});	
});
/* DOM READY CALLS for Server Side Flow - Ends Here */

function leftColCheckBoxChecked(){
    //console.log('leftColCheckBoxChecked()...');
	var checkedCount = 0;
	var ieCount = 0;
	if($.browser.msie){
	    ieCount = 0;
        /* Dk modification: using our layout */
		//$('div.left-column').find('input').each(function(i){
		$('.filters ul ul input').each(function(i){
        /* --end Dk modification */
			if($(this).parent().attr("class") == "selected"){
				ieCount++;
			}

		});
	}
    /* Dk modification: using our layout */
	//checkedCount = $('div.left-column div.attributes ul li input:checked').length + ieCount;
	checkedCount = $('.filters ul ul input:checked').length + ieCount;
    /* Dk modification: Rating and Price filter have different layout,
       consider them separately */
    $(".filters .ratings > span").each(function(){
        var extractedClass = this.className.replace(/star/,"");
        extractedClass = extractedClass.replace(/\s+/,"");
        if ((extractedClass != "") && (extractedClass != "no")) {
            //console.log('adding checkedCount for Ratings'); 
            checkedCount++;
        }
    });
    $(".filters .ui-slider").each(function(){
        if(userSelectedPrice!="") {
            checkedCount++;
        }
    });
    /* --end Dk modification */
	return checkedCount;
}

//<-- ADDED BY ANDY 12-17-07--//
/* Iterates through the checkboxes and forms an array of checkboxes that are checked currently */
function prefilter() {

	/*Reset values choosen for comparing items*/
	var compareParam='';
	prodCountCompare=0;
	partNumberValues=new Array(maxCompares);

	if(leftColCheckBoxChecked() > 0){
        //console.log('prefilter(): have leftColCheckBoxChecked() return > 0');
		var colCounter = 0;
		filters=[];
		$('div.categories ul li.open div.filters ul li ul,div.categories ul li.open div.filters div.ui-slider,div.categories ul li.open div.filters div.ratings').each(function(i){
			var title = $(this).parent().find('div.hidden').text();
			filters.push({ 'title': title, 'selected': [] });
			var values = [];
			if("Price"==title) {
				if(userSelectedPrice!="") {
		            values.push(userSelectedPrice);
		        }
			} else {
				$(this).find('input:checked').each(function(){
					values.push(this.name);
				});
			}
			if("User Ratings"==title) {
				if(values.length > 1){
					values = [values[values.length-1] + " stars or better"];
				} else if(values.length > 0){
					values = [values[values.length-1] + " star or better"];
				}
			}
			filters[i].selected = values;
		});

        //console.log("calling createFilterParam()...");
		// Call function to create the filter parameters
		createFilterParam();
	} else {
        //console.log('prefilter(): leftColCheckBoxChecked() returns < 1');
		filters=[];
		filterParam="";
	}
	$('div#right-column-curtain').hide(); 
    /* Dk modification: using our layout */
	//$('div#noresults').hide();
	$('#lb_noresults').hide();
    /* --end Dk modification */
}

// 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)){
			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];
					}
				}													
			}	
		}
	}
	return paginParam;		
}

function updateCategoriesOnLoad(filterParameter,paginParam){
	var newHref = "";	
	var tempIndex = -1;	
	var tempFilterParam = filterParameter;
	if(filterParameter.indexOf("&lastFilter=")>=0){
		tempFilterParam = filterParam.split(("&lastFilter="))[0];
	}
	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.categories ul li div.filters ul li ul 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() {
	$("div.categories input:checked").removeAttr("checked");
	// For price clear all option
	$("div.filters div.ui-slider").each(function(){
        if(typeof FilterSlider != 'undefined' && $(this).slider("getMax") != $(this).find("input[type='hidden']").val()) {
            $(this).removeClass("selected");
            FilterSlider.slider('reset');
        }
    });
	var span = $("div.ratings").find("span");
	for(var s=0; s<span.length; s++){
		if(span[s].className.indexOf("no")==-1 && span[s].parentNode.className=="ratings" ){
			$(span[s].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.categories div.filters ul li a.clear").remove();
	$('div.colorSelected').remove();
	
	/* Reset the value of Last filter to null when clear All is clicked */
	lastFilter="";		
}

	/*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 pageStart=(((Math.floor(pageNo/jsonForm.pageRange))*jsonForm.pageRange)+1)-jsonForm.pageRange;
				var prePage=pageStart;
				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 pageStart=((Math.ceil(pageNo/jsonForm.pageRange))*jsonForm.pageRange)+1;
				var nextPage=pageStart;
				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) {
			setCookieValue("viewItems", 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!=""){
				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 {
				location.replace(location.href.substring(0,location.href.indexOf("#"))+"#"+paginationParam);
			}
		}
	}

	/* Ajax MEthod */
	function ajaxImpl() {
		// 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=remoteUrl+"&po=1";
		}
		remoteUrl=remoteUrl+"&pav=0";
		remoteUrl=remoteUrl.replace("&&","&");
		if(remoteUrl!="") { 
			if(remoteUrl!=urlAfterAjaxCall) {
				if(fromProductPage==false) {
					bodyPreloader();
				}
				marketPlaceAjaxCall(remoteUrl);	
			}
			else {
                //console.log('ajaxImpl(): remoteUrl === "", hiding all overlays');
				bodyPreloader();
				$('div#body-curtain').hide();
				$('div.progress').hide();
				$('div#right-column-curtain').hide();
                /* Dk modification: using our layout */
				//$('div#noresults').hide(); 
				hidebox('#lb_noresults');
			}
		}	
	};

	/* Function that makes the Ajax call and updates the page based on the response from the server */
	function marketPlaceAjaxCall(remoteUrl) { 
		/* AJAX Setup */
		$.ajaxSetup( {
			error : errorFunction 
		});
   		request = $.getJSON(remoteUrl,showResponse);  
   		function errorFunction(jsonResponse){
            //console.log('running marketPlaceAjaxCall() error function');
   			showAjaxErrorPopup();
   			// Bind click events for the buttons
            /* Dk modification: using our layout */
			//$('input#prevResultsAjaxError').click(function() {
			$('a#prevResultsAjaxError').click(function() {
            /* --end Dk modification */
                //console.log('a#prevResultsAjaxError.click()...');
				ajaxTimeOut = false;
                var checkCount = leftColCheckBoxChecked();
				if(checkCount == 0) {
					filterParam="";
				}
				// Reset the previous filter param and call function to reset the filters
				previousResultsFilterParam=filterParamAfterAjaxCall;
                //console.log('prev results click: have filterParamAfterAjaxCall as "%s"',filterParamAfterAjaxCall);
				previousResultsUpdate();
			});
            /* Dk modification: using our layout */
			//$('input#tryAgain').click(function(){
			$('a#tryAgain').click(function(){
            /* --end Dk modification */
				ajaxTimeOut = false;
				bodyPreloader();
				marketPlaceAjaxCall(remoteUrl);
			});
			
			// Call Omniture function to track the Ajax failure
			ajaxTimeOut = true;
			omFilterUpdate("","");
   		}
   		function showResponse(jsonResponse){
                //console.log('showResponse()...');
				jsonProducts.products=jsonResponse.products;
							
				// Hide the back button preloader & initiate price slider
				if($('div#backButtonPreloader').length > 0) {
					$('div#backButtonPreloader').remove(); // Dk note: note in our layout 
	                /* Dk modification: not in our layout, safely operate 
	                   on this element to prevent error */
					//document.getElementById("contentWrapper").style.display='block';
					$("div#content").css({ "display": "block" });
					init_FilterSlider();
				}
                /* --end Dk modification */
				$('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;
	             	
	               }
	               
	              var y=jsonDisplayProd(prodIndexArrayAjax, false);

				 $('div#results').html(y);
   				  y="";				  							
						if(dynamicCategoryPage == false && jsonResponse.filter != null){
							//Updating the filters							
							mergeFilters(jsonResponse.filter);
							for(i=0;i<jsonResponse.filter.length;i++){
								if(jsonResponse.filter[i].fn == "Price"){
                                    if(jsonResponse.filter[i].fv[0].fvn != null){
										var sliderStart=jsonResponse.filter[i].fv[0].fvn.replace("$","").split("|")[1];
										if(sliderStart%10 !=0 || sliderStart == 0){
											sliderStart = sliderStart - sliderStart%10 + 10;
										}
										if(sliderStart != $("div.filters div.ui-slider").slider("getMax") || userSelectedPrice!="") {
											if(userSelectedPrice == ""){
												FilterSlider.slider("reset",sliderStart);
											} else if(parseInt(userSelectedPrice) >= sliderStart) {
												FilterSlider.slider("reset",userSelectedPrice);
											} else if(parseInt(userSelectedPrice) < sliderStart) {
												FilterSlider.slider("reset",sliderStart);
												FilterSlider.slider("moveToValue",userSelectedPrice);
											}
										}
									}
								}
							}
						}
							
	               	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=='preOrder')
							{
								a[i].onclick = function (){
									mePop(this.getAttribute('info'),this.rel);
								};
							}
						}		                
		               	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) {
								addPagination +='<ul>';
								addPagination += '<li><span>Page:</span></li>';
								
							if(pageNo>jsonForm.pageRange) {
								addPagination += '<li><a href="javaScript:;" title="View the previous set of pages" id="btnPrevious">previous</a></li>';										
							}
								var pageStart=(((Math.ceil(pageNo/jsonForm.pageRange))*jsonForm.pageRange)-6);	
								var pageEnd=((Math.ceil(pageNo/jsonForm.pageRange))*jsonForm.pageRange);	
								
							for(i=pageStart;i<=pageEnd;i++) {
								if(i<=pageCount) {
									if(pageNo==i)
									{
										addPagination += '<li class="active"><a href="javaScript:;" name="'+i+'" >'+i+'</a></li>';
									}else {										
									addPagination += '<li><a href="javaScript:;" name="'+i+'" >'+i+'</a></li>';
									}
								}
							}				
													
								if((pageCount-pageStart)>jsonForm.pageRange) {
									addPagination+='<li><a href="javascript:;" title="View the next set of pages" onclick="javascript:;" id="btnNext">next</a></li>';
									
							    }
							    addPagination += '</ul>';
						    }								  
						   $('div.pagination').html(addPagination);
						   //document.getElementById("pageFooter").innerHTML = addPagination;
						   heightAdjust();

							$('a[@id=btnPrevious]').click(prevButton);
							$('a[@id=btnNext]').click(nextButton);
						   
						   // To modify the view option header according the new products loaded	 
						   var addViewOptions = "";
						   addViewOptions='<label>Items Shown:</label>';
						   addViewOptions += '<ul>';
						   var ii=0;							   						   
						   do {	
						   		ii=ii+parseInt(jsonForm.viewIncr);
			   					if(ii==noItemsPerPage) {
			   						addViewOptions += '<li><a href="javaScript:;" name="'+ii+'" onclick="javascript:;" class="on">'+ii+'</a></li>';
			   					}else {						   					
			   		  				addViewOptions += '<li><a href="javaScript:;" name="'+ii+'" onclick="javascript:;" class="off">'+ii+'</a></li>';
			   		  			}
						   } while(ii < subCatProductCount && ii<=(parseInt(jsonForm.maxView)-parseInt(jsonForm.viewIncr)));
		                   addViewOptions += '</ul>';
		                   document.getElementById("itemShown").innerHTML = addViewOptions;
		                   if($('div#itemShown ul li').length == 1) {
								$('div#itemShown ul li a').attr("class","on");
		                   }
						   //document.getElementById("viewFooter").innerHTML = addViewOptions;			                   
		                  
				            // To modify the sort option header according the new products loaded	 
			               	var addSortOptions = "";
			               	if(subCatProductCount > 1 ) {
			               	document.getElementById("sortByGroup").style.display="block";
			               	addSortOptions += '<strong>Sort by:</strong>';
							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("sortByGroup").innerHTML = addSortOptions;
			                }else{
			                	document.getElementById("sortByGroup").style.display="none";
			                }	
			                
		                  	//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");	
	               		$("div#itemShown a.off").click(function() {
	               			viewPerPage($(this).attr('name'));
						});
	
		               	$("div.prodListingPagination div ul li a").click(function(){
		               		if(($(this).attr('id')!="btnNext") && ($(this).attr('id')!="btnPrevious")&& (!($(this).parent().is(".active")))) {
			               		var tempParam=paginationParam.split("&");
			               		if(tempParam[1].split("=")[1]!=$(this).attr('name')) { 
									gotoPage($(this).attr('name'));
									ajaxImpl();
								}	
							}
						});
						$("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)};});							
                        //console.log("showResponse(): hiding #noresults");
                        /* Dk modification: using our layout */
		               	//$("div#noresults").hide();
		               	hidebox("#lb_noresults");
                        /* --end Dk modification */
		      			$("div#right-column-curtain").hide();
                        /* Dk modification: using our layout */
                        /* --end Dk modification */
						bindEventsForRR();
		      		  } else {
							setTimeout(function(){showResponse(jsonResponse)},0);
					  }
	
					  $(function($){qvBtn();});
		          } else{
                        /* Dk modification: using our layout */
						showbox('#lb_noresults');						
                        /* --end Dk modification */
				  }
					
				if(leftColCheckBoxChecked() == 0){
					filterParam="";
				}
		       
		       	if(subCatProductCount == 1){
			        $('div.compareBar').hide();
				}
				else {
					$('div.compareBar').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);						
					}
					window.scrollTo(0,0);
				} else {
                    /* Dk modification: using our layout */
					//window.scrollTo(0,$('#noresults').offset().top-10);
                    /* --end Dk modification */
				}
			previousResultsFilterParam=filterParamAfterAjaxCall;
			// Set these values only if theere are products to be displayed
			if(subCatProductCount>0){
				filterParamAfterAjaxCall=filterParam;	
				urlAfterAjaxCall=remoteUrl;				
			}
	
			omFilterUpdate(jsonResponse.pavAjax,jsonResponse.poAjax);
		};//show response						
		$('div#leftCol div.categories ul#nav li a').click(function(){
						$('div#leftCol div.categories ul#nav li a.on').attr('class','');
						$(this).attr('class','on');
					});					
	} 
	
	// Function for going back to previous results when no results condition occurs 
	function previousResultsUpdate() {
        //console.log('previousResultsUpdate()...');
		clearFilters();
		keywordCheck(previousResultsFilterParam,false);

		filterParam=previousResultsFilterParam;
		setHash();

		//$('div#noresults').hide();
		hidebox('#lb_noresults');
        /* Dk modification using our layout / showbox() JS */
		//$('div#ajaxError').remove();
        hidebox('div#ajaxError');
        /* --end Dk modification */
		$('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")){
				var toBeDisplayedCount=0;
				var toBeDisplayed=false;
                /* Dk modification -----*/
				//for(j=0;j<ajaxFilters[i].fv.length;j++){	
				for(j=0;j<ajaxFilters[i].fv.length;j++){	
                /* ----end Dk modification */
					var thisCheckbox = document.getElementById("fvIdx"+ajaxFilters[i].fv[j].fvIdx);
					if(ajaxFilters[i].fv[j].fvc == 0){
						if(thisCheckbox.checked) {
							toBeDisplayed=true;
							toBeDisplayedCount++;
							$(thisCheckbox).next('label').children('span').html("(0)");;
						} else {
							thisCheckbox.parentNode.style.display = 'none';
						}
					} else {
						var newArrival=false;
						if((ajaxFilters[i].fk=="What&#039;s New" || ajaxFilters[i].fk=="What's New" || 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;
						}
						thisCheckbox.parentNode.style.display = 'block';
						toBeDisplayedCount++;
					  	$(thisCheckbox).next('label').children('span').html("("+ajaxFilters[i].fv[j].fvc+")");
						if(thisCheckbox.checked) {
							toBeDisplayed=true;
						}
					}
				}
				var escapedFilterName = replaceCharacters(ajaxFilters[i].fn);
				$("div.categories div.filters").children("ul").children("li").each(function() {	
					var thisFilter=$(this).find('div.hidden').text();
					if(thisFilter == escapedFilterName) {
						if(toBeDisplayedCount>1 || toBeDisplayed==true) { 
							this.style.display='block';
							if(newArrival==true){	
						 		$("div#leftCol").find("div.categories").find("div.filters").find("li.No").attr("style","display:none");
							}
							// Setting the height of each filter block
					        $(this).find("ul").each(function(){
				                var count = 0; 
				                var li = $(this).children('li:visible'); 
				                count = $(li).length;
				                if(count <= 10){ 
				                       $(this).css({height:'',"overflow-y" : "hidden", "overflow-x" : "hidden"});   
						} else {
				                       $(this).css({height:200,"overflow-y" : "auto", "overflow-x" : "hidden"});     
				                }    
					        });
						} else {
							this.style.display='none';				
						}
					}
				});
			}
		}
	}
	
	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);			
		}
		
		var tempPaginationParam=paginationParam.split("&");
		var viewSort=tempPaginationParam[0]+'&pageNum=1'+'&'+tempPaginationParam[2];
		
		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.categories div.filters ul li.first ul").html(newCategories);
            } else {
                  var newHref="";
                  $("div.categories div.filters ul li.first ul 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){
    //console.log('running dropDown("%o","%s","%s")',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();
	if (!document.getElementById(id))
	{
        //console.log('can\'t find object id "%s"',id);
		var containerDiv = document.createElement('div');
		containerDiv.id = id;
		var newWidth = width + "px";
		containerDiv.style.zIndex = '101';
		document.body.appendChild(containerDiv);
    /* Dk modification: if element exists, use it instead of just exiting early */
	//} 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";
    //console.log("Setting dropdown position x '%s'; y '%s'",xPos,yPos);
	thisDIV.innerHTML="<ul class=\""+id+"\">"+msg+"</ul>";
    /* Dk modification: using our layout, select via dynamic reference */
	//$("div#select ul.select").show().bgiframe();
	$(thisDIV).show().bgiframe();
    /* --end Dk modification */
	
	thisDIV.onmouseover = function(){if(dd){clearTimeout(dd);};};	
	thisDIV.onmouseout = function(){if(id){timeOutHide(id);};};
	
	/* On Click function of the dropdown options */
    /* Dk modification: using our layout */
	$('div#select ul.select li a').click(function() {
    /* --end Dk modification */
        //console.log('dropDown item receives click');
		 if($(me).parent().attr('id')=="sortByGroup") {
				selectedSortOption=$(this).attr('name');
				sortOptionSelect($(this).attr('name'));	
				currentSortOption=$(this).text();
			}
			return false;
		//}
		
	});
}

/* Clearing functions */
var clearAll = function() {
	$("div.categories input:checked").removeAttr("checked");
	// For price clear all option
	$("div.filters div.ui-slider").each(function(){
        if($(this).slider("getMax") != $(this).find("input[type='hidden']").val()) {
            $(this).removeClass("selected");
            FilterSlider.slider('reset');
        }
    });
	var span = $("div.ratings").find("span");
	for(var s=0; s<span.length; s++){
		if(span[s].className.indexOf("no")==-1 && span[s].parentNode.className=="ratings" ){
			$(span[s].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.categories div.filters ul li a.clear").remove();
	$('div.colorSelected').remove();
	
	/* Reset the value of Last filter to null when clear All is clicked */
	lastFilter="";				
	userSelectedPrice="";
	prefilter();
	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().find('div.hidden').text();			
	var selected=$(this).parent().find('ul');
	var input = $(selected).find("input");
	
	for(var o=0;o<input.length;o++){input[o].checked=false;};
	if($(this).parent().hasClass('filterColor')){
		$('div.colorSelected').remove();
	}
	$(this).remove();
	if(leftColCheckBoxChecked() < 1) {
		$("div.categories ul:eq(0) a.clearAll").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)){			
				lastFilter=lastFilter+","+tempFilters[i];	
			}
		}
	}
	prefilter();
	createFilterParam();
	gotoPage(1);
	ajaxImpl();
	return false;
};

/* Check box Click*/
var selectAttribute = function() {
	// Displaying color swatch tick mark
	if($(this).parent().parent().parent().hasClass('filterColor')){
		if($(this).attr('checked')){
			$(this).removeAttr('checked');
			$(this).parent().find('div.colorSelected').remove();					
		} else{
			$(this).attr('checked','checked');
			$(this).parent().prepend('<div class="colorSelected"></div>');
		}
	}
	
	var selectedNum = $(this).parent().parent().children("li").children("input:checked").length;	
	if(selectedNum && selectedNum > 0){
		if($("div.categories ul:eq(0) a.clearAll").length<1) {
			$(this).parent().parent().parent().parent().parent().prepend("<a class='clearAll' href='javaScript:;'>Clear All</a>");
			$("div.categories ul:eq(0) a.clearAll").click(clearAll);
		}
		if($(this).parent().parent().parent().children("a.clear").length<1){
			var createClearHtml = "<a class='clear' href='javaScript:;' name='"+$(this).parent().parent().parent().attr('class')+"'>Clear</a>";
			$(this).parent().parent().parent().prepend(createClearHtml);
			$(this).parent().parent().parent().parent().children("li").children("a.clear").click(clearSelection);
		}
	} else {
		$(this).parent().parent().parent().children("a.clear").remove();
 	}
	if(leftColCheckBoxChecked() < 1) {
		$("div.categories ul:eq(0) a.clearAll").remove(); 
	}

	/* Obtain the filter name of the selected element */
	var tempFilter=$(this).parent().parent().parent().find('div.hidden').text();							
	/* Trim extra spaces and replace spaces with '+' */
	tempFilter=stringTrim(tempFilter);							
	tempElement=stringTrim(this.name); 			   

	/* If the filter element is checked then append the filter and element to the  filter array */	
	if($(this).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#noresults').css({top: newTop.top});
		gotoPage(1);
		ajaxImpl();
	}	
}

/* Funtion to handle BAck button */ 
function resumeState() {				
	if(location.href.indexOf("#")>=0  && (location.href.indexOf("#") < location.href.length-1)){
		urlAfterAjaxCall="";
		filterParamAfterAjaxCall="";
		clearFilters();
		prefilter();											
		gotoPage(1);
		if(jsonProperties.dcp == false ){		
			userSelectedPrice="";
		}								    			
		
		/*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!=null && removedHash!="" &&  
						(removedHash.indexOf("filter=")>=0 || removedHash.indexOf("viewItems=")>=0)) {
			if(removedHash.indexOf("&&")>=0 && removedHash.indexOf("sName=")<0){
				var splitHash=removedHash.split("&&");
				paginationParam=splitHash[0];
				var indexOfLastFilter = splitHash[1].indexOf("&lastFilter=");
				var filterParameter=cleanFilterParam(unescape(splitHash[1].substring(0,indexOfLastFilter)))+"&"+cleanFilterParam(unescape(splitHash[1].substring(indexOfLastFilter+1,splitHash[1].length)));
				filterParam = filterParameter;
				if(jsonProperties.kp == true){
					updateCategoriesOnLoad(filterParameter,paginationParam);
				}
				keywordCheck(filterParameter,true);
			} 
			else if(removedHash.indexOf("sName=")>=0){
				var pagParam=removedHash.split("&&")[0];
				dynCatNameInHash = cleanFilterParam(unescape(removedHash.split("&&")[1].split("=")[1]));
				$('div#leftCol div.categories ul#nav li a.on').attr('class','');
				$('div#leftCol div.categories ul#nav li#'+dynCatNameInHash+' a').attr('class','on');
				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 {
				paginationParam=removedHash;
				filterParam="";
			}
			// 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 {
        	/*  Dk modification: avoid Sears-specific layout adjustments  */
        	// Hide back button preloader & initiate price
			$('div#backButtonPreloader').remove();
			document.getElementById("content").style.display='block';
			// IE6 Sort Options misaligned fix
			document.getElementById("sortByGroup").style.display='block';
			init_FilterSlider();
			$('div.product').height('auto');
			heightAdjust();
		}
	}
}
/*Function for Checking check Box (KEYWORD)*/
function keywordCheck(filterParameter,backButtonFlow){
    //console.log('keywordCheck()....');
	fromProductPage = true;
	var checkedBoxList=filterParameter;
	var checkboxstatus = false;
	if(filterParameter.indexOf("&lastFilter")>=0){
		var temp=filterParameter.split("&lastFilter");
		checkedBoxList=temp[0];
	}
	if(filterParameter.indexOf("filter=")>=0) {
	
	checkedBoxList=undoCleanFilterParam(checkedBoxList);
	checkedBoxList=checkedBoxList+"^";
	$('div.categories ul li.open div.filters ul li ul').each(function(i) {
		var filterName = stringTrim($(this).parent().find('div.hidden').text());
		if($(this).find('li').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('li').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).parent().parent().parent().hasClass('filterColor')) {
						/*For color Swatches*/
						if(indexOfFilterValues>=0 && (endOfFilter ==-1 || (endOfFilter > indexOfFilterValues))) {
							$(this).each(selectAttribute);
							checkboxstatus=true;
						}
					}  
					else {
						if(indexOfFilterValues>=0 && (endOfFilter ==-1 || (endOfFilter > indexOfFilterValues))) {
							$(this).attr('checked',true);
							$(this).each(selectAttribute);
						    checkboxstatus =true;
						}
					}	
				});
				if(checkboxstatus == true){
					$(this.parentNode).addClass('open');
					checkboxstatus =false;
				}
			}
		}
	});
	// Extract Star Rating value
	if((checkedBoxList.indexOf("filter=Price|") >= 0 || checkedBoxList.indexOf("^Price|") >= 0) && !backButtonFlow) {
	    /* Dk modification: handle price separately */
	    $('.filters .box3d .ui-slider').each(function() {
	    	/* Dk modification: using our layout */
	        var maxPrice = $(this).slider("getMax");
	        /* --end Dk modification */
			var priceInUrl = parseInt(checkedBoxList.substring(checkedBoxList.indexOf("-",checkedBoxList.indexOf("Price"))+1,checkedBoxList.indexOf("^",checkedBoxList.indexOf("Price"))));
			userSelectedPrice = priceInUrl;
			if(parseInt(priceInUrl) >= parseInt(maxPrice)) {
				FilterSlider.slider("reset",userSelectedPrice);
				$(this).removeClass('selected');
			} else if(parseInt(priceInUrl) < parseInt(maxPrice)) {
				FilterSlider.slider("moveToValue",priceInUrl);
				$(this).addClass('selected');
			}
			if($("div.categories ul:eq(0) a.clearAll").length<1) {
				$(this).parent().parent().prepend("<a class='clearAll' href='javaScript:;'>Clear All</a>");
				$("div.categories ul:eq(0) a.clearAll").click(clearAll);
			}	
	    });
	    /* --end Dk modification: handle price separately */
	} else if(checkedBoxList.indexOf("filter=Price|") >= 0 || checkedBoxList.indexOf("^Price|") >= 0) {
		userSelectedPrice = checkedBoxList.substring(checkedBoxList.indexOf("-",checkedBoxList.indexOf("Price"))+1,checkedBoxList.indexOf("^",checkedBoxList.indexOf("Price")));
	} else {
		userSelectedPrice = "";
	}
	// 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
        /* Dk modification: using our layout */
		$(".filters .box3d .ratings span a").each(function(i){
	        /* --end Dk modification */		
	        //console.log('iterating over ratings stars with %o, comparing userRatingValue "%s" to rating text "%s"',this,userRatingValue,$(this).text());
			if(userRatingValue==$(this).text()) {
	            //console.log('this star is the user setting');
				$(this).parent().find('input').each(function(j){
	                //console.log('found ratings stars input for check');
					if(j <= i){
	                    //console.log('...selecting');
						$(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().find('div.hidden').text();
							filterName=stringTrim(filterName);
							/*Append the filter name to the last Filter array*/
							lastFilter=lastFilter+","+filterName+":empty";
							firstFlag=false;
						}		
					}else{
	                    //console.log('...un-selecting');
						$(this).removeAttr('checked');
					}											 
				});
	            $(this.parentNode.parentNode.parentNode).addClass("selected");
				if($("div.categories ul:eq(0) a.clearAll").length<1) {
					$(this).parent().parent().parent().parent().prepend("<a class='clearAll' href='javaScript:;'>Clear All</a>");
					$("div.categories ul:eq(0) a.clearAll").click(clearAll);
				}
	            /* --end Dk modification */
	            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";
				} 
				$(this).parent().attr("class",this.parentNode.selectedSpan);
			}
		});
	}
	}
    //console.log('keyword check, done with all filters');
	fromProductPage = false;
}

// Function to display the products on the page
function jsonDisplayProd(prodIndexArray) { 
 //console.log('jsonDisplayProd()....');
/*Variable which is used for generating products */
	var results="";
	var storeId=jsonProperties.sid;
	var catalogId=jsonProperties.cid;
	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 keyword = escape(jsonProperties.keyword);
		keyword = replaceAll(keyword,"%20","+");
	var size=jsonProducts.products.length;
	/*Sequential loop for iterating through the jsonProducts*/	
	for (i=1;i<=prodIndexArray.length;i++){	
		/*Variable for processing products array*/	
		if((i-1)<jsonProducts.products.length){
		var j=prodIndexArray[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);

		//Store the vendor product url
		var productUrl="";
		productUrl+=jsonProducts.products[j].vurl;
		if(!(jsonProducts.products[j].vid != null && jsonProducts.products[j].vid.length > 0)) {
	
			productUrl="p_"+storeId+"_"+catalogId+"_"+partNo;//vname="+vName+"&cname="+cName+"&sname="+sName;
	
			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;
		}
		}
        
        var prodDisplayName=jsonProducts.products[j].na;
        var vendorImgUrl = jsonProducts.products[j].img;        
		var imageUrl='<img title=\" '+prodDisplayName+' at '+jsonProperties.sn+'.com\" class= \"\" width=\"180\" height=\"180\" border=\"0\" alt=\"';
		prodDisplayName=js_ReplaceChar(prodDisplayName,'"','&quot;');
		prodDisplayName=js_ReplaceChar(prodDisplayName,"'","&#39;");
		imageUrl+=prodDisplayName;
		
		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
        {
		imageUrl+="\" src="+jsonProperties.img1+jsonProducts.products[j].img+"?"+jsonProperties.img3+">";
        }
		
        //console.log('working with imageUrl "%s"',imageUrl);

		/*Check for Valid Part Number*/
		if((jsonProducts.products[j].no!=null && jsonProducts.products[j].no.length != 0)){
            results+='<div class="product">';
            /* --end Dk modification */
												
            /* Dk modification: move pricing above other product content, using our layout */
			var streetDate = jsonProducts.products[j].psl;
			var hasPreSell = streetDate!=null && streetDate != '';	
			
			/* This is a variable for ATW & TIO Overlay */
			var overlay = jsonProperties.sid+","+jsonProperties.cid+","+jsonProducts.products[j].cat+",\'"
                		   							+"\',\'"+prodDisplayName+"\',\'"+jsonProperties.img1+jsonProducts.products[j].img+"?hei=100&wid=110\',\'\',\'"
                		   							+jsonProducts.products[j].no+"\',\'\',\'false\'";
                                    
					
			results+='<div class="price"><div class="saveStory">'+jsonProducts.products[j].ss+'</div>';
			
			// Add to cart implementation on search results page
            /* Dk modification: move string variable declarations outside conditionals
               to ensure re-set while looping over products */
            var imageButtonClass = '';
            var actionText = '';
            var addOptionsText = '';
            /* --end Dk modification */
            var myDebugText = '\n ** Product "'+jsonProducts.products[j].na+'", building Save Story content';
			if(jsonProperties.enableATC == "true"){
                myDebugText += '\n - attribute "enableATC" = "'+jsonProperties.enableATC+'"';
           //console.log('attribute "enableATC" = "%s"',jsonProperties.enableATC);
				if(jsonProducts.products[j].ss!=null && jsonProducts.products[j].ss.length>0) {
            //console.log('attribute "ss" = "%s"',jsonProducts.products[j].ss);
                myDebugText += '\n - attribute "ss.length" = "'+jsonProducts.products[j].ss.length+'"';
					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")){
                        myDebugText += '\n - meeting multiple conditions related to "view only" and order by phone';
						
						if((jsonProducts.products[j].si!=null && jsonProducts.products[j].si != 1) || (!hasPreSell && (jsonProducts.products[j].spi == true || jsonProducts.products[j].sri == 1 )) || jsonProducts.products[j].dff == "SPU") { 
							if(jsonProducts.products[j].bt== jsonProperties.sppb && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)) {
								// 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
								
								if((jsonProducts.products[j].dd == false && jsonProducts.products[j].ndd== false)) {
									if(hasPreSell){
                                        actionText = 'Pre Order';
                                        /* Dk modification: using our layout */
                                        imageButtonClass = 'button-cartActions button-preOrder';
                                        addOptionsText = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                                    '<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
                                        myDebugText += '\naddOptions group 1: Set addOptionsText disabled';
                                        /* --end Dk modification */
									} else {
                                        actionText = 'Add to Cart';
                                        /* Dk modification: using our layout */
                                        imageButtonClass = 'button-cartActions';
                                        addOptionsText = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                                    	'<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
                                        myDebugText += '\naddOptions group 1: Set addOptionsText enabled';
                                        /* --end Dk modification */
									}
										
									results+='<fieldset class="addToCart" style="display:block"><a href="javascript:fnAddToCartOverlay(';
									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+="\'"+streetDate+"\'";
									results+=",";														
									results+="\'"+productUrl+"\'";
									results+=",";														
									results+="\'"+jsonProducts.products[j].cat+"\'";
									results+=');" class="submit '+imageButtonClass+'">'+actionText+'</a></fieldset>';
								} else if(jsonProducts.products[j].ndd== true || jsonProducts.products[j].dd== true){																											
                                    /* Dk modification: using our layout */
                                               
                                    addOptionsText = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                                        '<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
                                    myDebugText += '\naddOptions group 2: Set addOptionsText disabled';
                                    /* --end Dk modification */
                                    /* Dk modification: using our layout */
									//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>';
									results+='<fieldset class="selectOptions" style="display:block"> <a href="'+productUrl+'" onclick="" class="submit button-cartActions button-details">Product Details</a></fieldset>';
								}
							}
						} else {
							addOptionsText = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                                    	'<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
						}
                    /* Dk modification: debugging */
                    //}
					} else {
                        /* Dk modification: using our layout */
                        addOptionsText ='<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                        	'<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
                        myDebugText += '\naddOptions group 2: Set addOptionsText enabled';
                        /* --end Dk modification */
                    }
                    /* --end Dk modification */
				}else {
						addOptionsText = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a>'+
                                                        '<a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
				}
				if(hasPreSell && jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1) {
					results+='<div class="availability"><div class="comingSoon">Item Coming Soon</div>';
					if((jsonProducts.products[j].nemi!=null && jsonProducts.products[j].nemi.length==0) && (jsonProducts.products[j].pbType==jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
						results+='<div class="preOrderSelect">'; 
						if(jsonProducts.products[j].mfg!=null) {                                                           
	                        results+='<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>';
	                    } else {
                        	results+='<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>';
                        }
                        results+='</div>'; 
                    }
					results+='</div>'; 
				}				
				if((jsonProducts.products[j].bt== jsonProperties.sppb && jsonProducts.products[j].pbType== "VARIATION" ) || jsonProducts.products[j].dff=="VGC" || jsonProducts.products[j].dff=="GC" || jsonProducts.products[j].bt != jsonProperties.sppb ) {
                    /* Dk modification: using our layout */
                    actionText = 'Product Details';
                    imageButtonClass = 'button-cartActions button-details';
                    addOptionsText = '<span class="wishlist">Add To Wishlist</span>'+
                                     '<span class="ownThis">I Own This</span>';
                    myDebugText += '\naddOptions group 4: Set addOptionsText disabled';
					//results+='<fieldset class="selectOptions"><a href="'+productUrl+'" onclick="" class="submit"> <img src="'+jspStoreImgDir+'img/buttons/btn_prod_details.gif" name="selectItems" alt="Select Items" id="selectItems" /></a></fieldset>';
					results+='<fieldset class="selectOptions"><a href="'+productUrl+'" onclick="" class="submit '+imageButtonClass+'">'+actionText+'</a></fieldset>';
                    /* --end Dk modification */
				}
			} //close 
			
			results+='</div>';
            results += '<div class="prodInfo">';
			results+='<div class="photo"><a href="'+productUrl+'">'+imageUrl+'</a></div><div class="info"><div class="productName"><a href="'+productUrl+'" title="'+prodDisplayName+'">'+prodDisplayName+'</a></div><p>';						

			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) ){
                /* Dk modification: using our layout */
				//results+='<li>';
                /* --end Dk modification */
				results+=jsonProperties.sears+" "+jsonProperties.spin+truncPartNumber;
					
                /* Dk modification: using our layout */
				//results+='</li>';
				results+='<br />';
                /* --end Dk modification */
				
				//Displaying the partNumber and sku part number
				if(jsonProducts.products[j].mfg != null && jsonProducts.products[j].mfg.length > 0){ 
                    /* Dk modification: using our layout */
					//results+='<li>'+jsonProperties.mfr+jsonProducts.products[j].mfg+'</li>';
					results+=jsonProperties.mfr+jsonProducts.products[j].mfg+'<br />';
                    /* --end Dk modification */
				}
			}else{	
				results+='<div class="productNumber"></div>';
			}				
			if(jsonProducts.products[j].rt!=null && jsonProducts.products[j].rt!= ""){ 
				results+=jsonProperties.aru+'<img src="'+jsonProducts.products[j].prtu+'" style="vertical-align:middle;position:relative;top:-2px">';
				if(jsonProducts.products[j].prtu) {  
					results+=" "+jsonProducts.products[j].nr+" "+jsonProperties.rat;
				} 
			} 
            /* Dk modification: using our layout */
		    results+='</p>';
            /* --end Dk modification */
			
			results+='</div>';
			if(jsonProperties.enableATC == "true" && hasPreSell) {
				results+='<div class="availability"><div class="comingSoon">Item Coming Soon</div>';
				results+='<div class="preReleaseDate">Release Date: '+ streetDate +'</div>';	
				if(jsonProducts.products[j].si!= 1) {
					results+='<div class="preOrderSelect"><a href="javascript:;" rel="preOrder" title="Available for Pre-Order" >Available for Pre-Order</a></div>';								
				}
				results+='</div>';														
			} else {
			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>';
					}							
				}else{
					if(jsonProducts.products[j].si!=null && jsonProducts.products[j].si==1 ){
								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="email"><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+' '+jsonProperties.wa+'</a></li>';
										}else{
											results+='<li class="email"><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+' '+jsonProperties.wa+'</a></li>';						
										}
								}else{
									results+='<li class="notInStock">'+jsonProperties.osd+'</li>';
								}			
					}else{
					  	if(jsonProducts.products[j].ndd==true) {																		    	
					    	results+='<li class="inStock"><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 (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>';
						}
					}
					//Online Store Pick up code
					if(jsonProducts.products[j].spi == true || jsonProducts.products[j].sri == 1) {
						//Display Store Pick up Link for NONVARIATION    
                        if(jsonProducts.products[j].bt == jsonProperties.sppb && (jsonProducts.products[j].pbType == jsonProperties.spnv || jsonProducts.products[j].pbType==jsonProperties.spa)){
							if(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 {
								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 ((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(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+= cmdStoreId;
						results+=",";
						results+= cmdCatalog;
						results+=",";
						results+=jsonProducts.products[j].cat;
						results+='); return false;">';
						results+=jsonProperties.so;
						results+='</a>';
						results+='</li>';
					}
				} 										
				results+='</ul></div>';
				}
				results+='</div>';

                /* Dk modification: using our layout order */
				results+='<div id="comparison" class="selectBar">';
                /* Dk modification: using our layout */
				//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 class="compareBar"><input type="checkbox" name="'+jsonProducts.products[j].no+'"onclick="setCheck(this);" id="product_'+i+'" class="chkCompare"><label for="product_'+i+'" class="lblCompare">Compare</label><a href="javascript:void(compareProducts())" title="Compare this item" >Compare Now</a></div>';
                /* --end Dk modification */

                /* Dk modification: Add to My Toolbox functions */
                results += '<div class="addOptions">';
                results += addOptionsText;
                results += '</div>';
                /* --end Dk modification */
                /* Dk modification: using our layout, close #comparison.selectBar */
				results+='</div>';
                /* --end Dk modification */
                /* Dk modification: using our layout, close .prodInfo */
				results+='</div>';
                /* --end Dk modification */						
		}else {
				results+='<div class="noresultsWrapper">No More Results</div>';
		}
		}
	}//end for loop
	return results;
}

// Function for displaying full body preloader
function bodyPreloader(){
    //console.log('bodyPreloader()...');
    /* Dk modification: using our layout */
	//$('div#noresults').hide();
	hidebox('#lb_noresults');
    /* --end Dk modification */
	$('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;
    /* Dk modification: using our layout and showbox() via utility.js */
	//$('div.progress').css({ left:hpos, top:vpos }).show();
    showbox("div.progress");
    /* --end Dk modification */
	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(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() {
    //console.log('createFilterParam()....');
	/* 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);
					
					if(filters[i].title=="Price"){
						filterParam=filterParam+"|"+"0-"+filters[i].selected[filters[i].selected.length-1];								
					}
					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;					
			}
		});		
		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);				
		}
	}			
}
function removeCurtain() {
	// Remove the curtain
	$('div.progress').hide();
	$('div#body-curtain').hide();
    /* Dk modification: using our layout */
	//$("div#noresults").hide();
	hidebox("#lb_noresults");
    /* --end Dk modification */
	$("div#right-column-curtain").hide();
    /* Dk modification: using our layout */
    /* --end Dk modification */
}
/* Duplicate functions for Server Side Flow Ends */

/* General Methods for Server Side Flow - 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() {
		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=='preOrder')
			{
				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,returnToQuickView) 
{
		if(info!=null && info!="") {
		
		//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':
        /* Dk modification: using our layout */
	    var overlayToShow = '#lb_sendalert';
        var overlayID = 'lb_sendalert';
        if ($(overlayToShow).length) {
            $(overlayToShow).remove();
        }
		var container = $('body').append('<div id="'+overlayID+'" class="lightbox"><div class="lightboxBody sendalert"></div></div>');
        var alertBox = $('#lb_sendalert .lightboxBody');
        $(alertBox).append('<div class="lb_header">'+
                          '<span>Send Me an Alert</span>'+
                          '<a class="close" href="javascript:void(0)" onclick="hidebox(\'#lb_sendalert\')">Close</a>'+
                          '<div class="clear"></div>'+
                          '</div>'+
                          '<div class="lb_content" id="sorryMsg"></div>'+
                          '<div id="thankYou" class="lb_content" 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>'
                          );
        var alertContent = $('#lb_sendalert #sorryMsg');
        var newContent = "<p>Enter your email address if you would like us to send you an alert"+
                         " when this item is back in stock and available for purchase.</p>"+
                         "<div class='clear'></div>"+
                         "\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"+
                         "<div class='lb_inputs'>"+
                       	 "<input type='text' id='emailMeAddress' type='text' name='userEmail' size='20' value='"+getCookie('userEmail')+"'/><a class='ok'  onClick='if(validateEmailId()){$(\"div#thankYou\").show();$(\"div#sorryMsg\").hide();document.getElementById(\"emailAddress\").innerHTML=document.getElementById(\"emailMeAddress\").value;setCookie(\"userEmail\",document.getElementById(\"emailMeAddress\").value);tempFunc();}' href='javascript:;'>Ok</a>"+
                         "</div>"+
                         "<div class='clear'></div>";
                         
			
        $(alertContent).append(newContent);
        document.getElementById('lb_sendalert').style.display="block";
		break;

		case 'storePickup':
        var pDate = infoArray[9];
        var overlayToShow = '#lb_zipfinder';
        var overlayID = 'lb_zipfinder';
        if ($(overlayToShow).length) {
            //console.log('found overlay in DOM, removing it before recreating and appending...')
            $(overlayToShow).remove();
        }
		var container = $('body').append('<div id="'+overlayID+'" class="lightbox"><div class="lightboxBody zipfinder"></div></div>');
        var alertBox = $(overlayToShow+' .lightboxBody');
        $(alertBox).append('<div class="lb_header">'+
                          '<span>Available for In-Store Pickup</span>'+
                          '<a class="close" href="javascript:void(0)" onclick="hidebox(\''+overlayToShow+'\')">Close</a>'+
                          '<div class="clear"></div>'+
                          '</div>'+
                          '<div class="lb_content"></div>');
        var alertContent = $(overlayToShow+' .lb_content');
        var newContent = "<p>This Craftsman product is available for in-store pickup when you buy it online.</p>"+
                         "<div class='clear'></div>"+
                         
                         "<div class='lb_inputs'>"+
                            "<p>Enter your ZIP code to find this item at a store near you.</p>"+
                            "<input type='text' name='zipCode' id='zipCode' size='15' maxlength='5' class='text' value='"+getCookie('zipCode')+"'/><a class='ok' onClick='return storeLocatorPopup();' href='javascript:;'>Ok</a>"+
                         "</div>"+
                         "<div class='clear'></div>"+
                         "\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"+
						 "\t<input type='hidden' id='zipPreSellDate' name='presellDate' value='"+pDate+"'>\n";	
        $(alertContent).append(newContent);
        document.getElementById('lb_zipfinder').style.display="block";
		break;
		
		case 'preOrder':
		var overlayToShow = '#lb_preOrder';
		var overlayID = 'lb_preOrder';
		if ($(overlayToShow).length) {
            //console.log('found overlay in DOM, removing it before recreating and appending...')
            $(overlayToShow).remove();
        }
		var container = $('body').append('<div id="'+overlayID+'" class="lightbox preOrder"></div>');
		function preCallBack(response) {
			document.getElementById('lb_preOrder').innerHTML="<div class='lightboxBody'><div class='lb_header'><span>Pre-Order Details</span><a class='close' onclick='hidebox(\"#lb_preOrder\");' href='javascript:void(0)'>Close</a>"
			+"<div class='clear'></div></div>"
			+"<div class='lb_content'>"+response;
			+"</div></div></div>";
			document.getElementById('lb_preOrder').style.display="block";
			if (returnToQuickView) {
	            SEARS.QuickView.close();
	            showbox(overlayToShow,true);
	        } else {
	            showbox(overlayToShow);
	        }
	        
		}
		
		function presellFailure() {
			return;
		}		
		var options = { 
		        success: preCallBack,
		        url:dynamicPopupPath+'&vName=PresellDetails',
		        type:'GET',
		        failure:presellFailure
		};
		$.ajax(options);
		break;
		
		}
		/* Dk modification: showing overlay via utility.js showbox() */
		if(id != "preOrder") {
	        if (returnToQuickView) {
	            SEARS.QuickView.close();
	            showbox(overlayToShow,true);
	        } else {
	            showbox(overlayToShow);
	        }
	        
        }
}

// 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 */

//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.brandName 		= this.product.brandName;
            this.strId          = this.product.strId;
            this.catId          = this.product.catId;
            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.preReviewUrl   = this.product.prurl;
            this.postReviewUrl  = this.product.pourl;
            this.reviews        = this.product.reviews;
            this.hasSpecs       = this.product.specs;
            this.Img            = this.product.Img;
            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;
			
			//reviews transition
			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;
			//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(){
        
                                    //console.log('changeVariant(), disabling toolbox buttons...');
                                    /* Dk modification: disable My Toolbox buttons */
                                    var toolBoxButtons = [$('.tools a.wishlist'),$('.tools a.ownThis')];
                                    $(toolBoxButtons).each(function(){
                                        $(this).replaceWith("<span class=\""+$(this).attr('class')+"\">"+$(this).text()+"</span>");
                                    });
                                    /* --end Dk modification */

                                    $('.softAddtoCart').hide(); 
                                    /* Dk modification: using our layout */
                                    //$('.selectionsTab .qvp_att_dd').add('.selectionsTab div.oos').remove();
                                    $('.softLineSelections .qvp_att_dd').add('.softLineSelections div.oos').remove();
                                    /* --end Dk modification */
                                    $(this.current.attList).each(function(a){
                                        /* Dk modification: using our layout */
                                        //var dd = $('<div class="fakeDD qvp_att_dd" id="qvp_att'+a+'"></div>').appendTo('.selectionsTab').click(function(){
                                        var dd = $('<div class="fakeDD qvp_att_dd" id="qvp_att'+a+'"></div>').appendTo('.softLineSelections').click(function(){
                                        /* --end Dk modification */
                                            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'){
                                        $(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);                   
                                            }); 
                                        };
                                    });
                                    /* Dk modification: using our layout */
                                    //$('<div class="oos">This item is not available in the combination you have selected. Please change your selections.</div>').hide().appendTo('.selectionsTab');
                                    $('<div class="oos">This item is not available in the combination you have selected. Please change your selections.</div>').hide().appendTo('.softLineSelections');
                                    /* --end Dk modification */
            };
            this.attrChange = function(changed,msg){
                //console.log('attrChange()...');
                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(){  
                        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')){
                    /* Dk modification: using our layout */
                    //$('.selectionsTab.oos').show();        
                    $('.softLineSelections .oos').show();        
                    /* --end Dk modification */
                }else{
                    /* Dk modification: using our layout */
                    //$('.selectionsTab.oos').hide();
                    $('.softLineSelections .oos').hide();
                    /* --end Dk modification */
                }
                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){
                        /* Dk modification: using our layout */
                        //$('.selectionsTab .oos').show();
                        $('.softLineSelections .oos').show();
                        /* --end Dk modification */
                    };
                };
                /* Dk modification: using our layout */
                //if(closedAttrs.length == allAttrs.length && $('.selectionsTab .oos').is(':hidden')){
                if(closedAttrs.length == allAttrs.length && $('.softLineSelections .oos').is(':hidden')){
                /* --end Dk modification */
                    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;
                    $('.quickView .saveStory').html(saveStory[ssIndex]);
                    var _SSqty = $(QVparent).find('.saveStory').eq(0);
                    var _defaultST ="";  
                    if($(_SSqty).find('.regPrice').length){
                         _defaultST = $(_SSqty).find('.regPrice').html().split("$")[1];
                    }else if($(_SSqty).find('.salePrice').length){
                         _defaultST = $(_SSqty).find('.salePrice').html().split("$")[1];
                    }
                    else if($(_SSqty).find('.youPay').length){
						_defaultST = $(_SSqty).find('.youPay').eq(0).find('.pricing').eq(0).html().split("$")[1]
					}
                    //$('.softAddtoCart').find('.QVsubT').html(_defaultST);
                    if(_defaultST != "") {
						//Calculate the total price only if we have got the price of each item from the save story
						_defaultST = _defaultST.split(' ')[0];
	                    var _a2c = $('.softAddtoCart')
	                    var _qty = $(_a2c).find('.QVqty').val();
	                    var _sub = $(_a2c).find('.QVsubT');
						$(_sub).html((_qty*_defaultST).toFixed(2));
					}
                    
                    
                    /* Logic for ATW/TIO */
					function js_ReplaceChar(str,charFind,replaceWith){
				        regExp = new RegExp("["+charFind+"]","g");
				    	return str.replace(regExp,replaceWith);
					}
              	
	              	var name=js_ReplaceChar(SEARS.Item.pTitle,'"','&quot;');
					name=js_ReplaceChar(name,"'","&#39;");
					
				             	
					var overlay = jsonProperties.sid+","+jsonProperties.cid+","+SEARS.Item.parCatEntId+",\'"
	                		   +"\',\'"+name+"\',\'"+jsonProperties.img1+SEARS.Item.mainImage.iId+"?hei=100&wid=110\',\'\',\'"+SEARS.Item.pId+"\',\'\',\'false\'";	                    
	                    
                    /* Dk modification: enable My Toolbox buttons */
                    //var toolBoxDisabled = [$(".tools")];
                    var toolBoxEnabled = [".tools a.wishlist",".tools a.ownThis"];
                    var lightBoxIDs = ["lb_addwishlist","lb_addtoolbox"];
                    $("div.itemWidgets div.tools").each(function(i){
                        var newHTML = '<a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a><a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a>';
                        $(this).html(newHTML);

                        $(toolBoxEnabled[i]).click(function(){
                            // close Quick View
                            SEARS.QuickView.close();
                            $('#lb_addwishlist').remove();
                            $('#lb_addtoolbox').remove();
 
                            if (typeof showbox === "function"){//external 
                                showbox('#'+lightBoxIDs[i]);
                            }
                        });
                    });
                    /* --end Dk modification */

                    /* Dk modification, .QVborder does not exist on Dk layout */
                    //$('.softAddtoCart').fadeIn(400,function(){$('.QVborder').height($(_QV).height()+25)});
                    $('.softAddtoCart').show();
                    /* --end Dk modification */
                }else{
                    /* Dk modification: disable My Toolbox buttons */
                    var toolBoxButtons = [$('.tools a.wishlist'),$('.tools a.ownThis')];
                    $(toolBoxButtons).each(function(){
                        $(this).replaceWith("<span class=\""+$(this).attr('class')+"\">"+$(this).text()+"</span>");
                    });
                    /* --end Dk modification */
                    $('.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 != ''){
                            $('.quickView .imageLarge').children().remove();
                            $('<img>').attr({
                                alt:SEARS.Item.pTitle,
                                src:'http://s.sears.com/is/image/Sears/'+matchcolor.mImgId+'?hei=400&wid=400&op_sharpen=1&qlt=75', 
                                width:400,
                                height:400
                            }).hide().prependTo('.quickView .imageLarge').fadeIn(800);
                        }else{
                        	$('.quickView .imageLarge').children().remove();
                            $('<img>').attr({
                                alt:'Image Not Available for this item',
                                src:jspStoreImgDir+'images/FPO/ProductDetail_noImage_available.jpg', 
                                width:400,
                                height:400
                            }).hide().prependTo('.quickView .imageLarge').fadeIn(800);
                        }
                    };
            };
            }
        }   
    },
    /* QUICK VIEW */
    QuickView: { 
        /* Dk modification: provide a close method for the Quick View
           for purposes of re-use */
        "close":function(){
            var QVWrap = $('.quickViewWrap');
            /* IE6 does not respond to fadout() well, some of QVWrap descendants would 
               remain on screen after others had already disappeared, so just remove the element */
            if(($.browser.msie) && ($.browser.version < 7)){
                $(QVWrap).remove();
            } else {
                $(QVWrap).fadeOut(200,function(){$(this).remove();});
            }
            return false;
        },
        /* ---end Dk modification */
        "launch":function(){
            $('.quickViewWrap').remove();
            $('.mapWrap').remove();
            $('#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")|| (SEARS.Item.strId=="10155")){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='sears.com/2328c/'}else if(strName=="Kmart"){revPath='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="quickView"/>');
            var _QV = $('.quickView');
            /* Dk modification */
            $(_QV).append('<div class="drag dragLeft"/>');
            $(_QV).append('<div class="drag dragRight"/>');
            $(_QV).append('<div class="drag dragBottom"/>');
            $(_QV).append('<div class="drag dragTop"/>');
           
            $(_QV).append('<a href="#close" title="Close this window" class="closeWindow">close</a>');
            /* --end Dk modification */
            var _drag = $('.drag');
            //Error message for Temporary Offline Status
            if(SEARS.Item.offline){
                $(_QV).append('<p class="unavailMsg">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>');
                $(QVWrap).centerOnScreen();
	            $(QVWrap).show().bgiframe();
	            $('.closeWindow').click(function(){
	                SEARS.QuickView.close();
	                return false;
	            });
            }else if(!SEARS.Item.offline){
                /* Dk Modification */
				
				$(_QV).append('<ul class="tabs"><li class="first"><a href="#quicklook" onclick="s.prop26=\''+_vert+' > '+_cat+' > '+_sbcat+' > '+SEARS.Item.pId+' > '+'Quick View > Quick Look\';s.events=\'event27\';s.product=\''+SEARS.Item.pId+'\';s.tl();" title="Click QUICK LOOK tab to view the product">Quick Look</a></li></ul>');
				$(_QV).find('ul').append('<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>');
                /* --end Dk modification */
                if(SEARS.Item.type!="C" && SEARS.Item.type!="GC"){
                    if(SEARS.Item.hasSpecs){
                    /* Dk Modification */
                   
                    $(_QV).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">Specifications</a></li>')
                    /* --end Dk modification */
                    }
					if(strName!="My Gofer"&&SEARS.Item.reviews){
                            /* Dk Modification */
                       		
                       		$(_QV).find('ul').append('<li class="last reviewsTabC"><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>')
                            /* --end Dk modification */
			       }
                }
                $(_QV).append('<div class="QVinnerWrap"/>');
                /* Dk modification */
               
                var _QViW = $('.QVinnerWrap');
                $(_QViW).append('<div class="QVinner"/>');
                var _QVi = $('.QVinner');
               
                $(_QVi).append('<div class="itemWidgets"/>').append('<div class="content narrow"/><div class="clear"/>');
                /* --end Dk modification */
                $(_QViW).append('<div class="goToButtons"/>');
                var itmWgts = $('.itemWidgets');
                
                var content = $('.content');
                var goTo = $('.goToButtons'); 
                //Storing re-used elements in variables
                var mNum = SEARS.Item.mId && SEARS.Item.type=="H" ? 'Mfr. model #<span>'+SEARS.Item.mId+'</span>' : '';
                /* Dk modification: assign itemNum like mNum var for reuse */
                
                var pidLength = SEARS.Item.pId.length;
                
                var itemNum = SEARS.Item.pId ? ('item# <span>'+SEARS.Item.pId.substring(0,pidLength-1)+'</span>') : '';
                /* ---end Dk modification */
           
				if(SEARS.Item.brandName == "Craftsman"){
				var brandLogo = '<img src="'+jspStoreImgDir+'images/logos/craftsman-small.png" alt="images-logo" />';
                }
                else if(SEARS.Item.brandName == "Craftsman Professional"){
				var brandLogo = '<img src="'+jspStoreImgDir+'images/logos/craftsman.professional.png" alt="images-logo" />';
                }
                else if(SEARS.Item.brandName == "Evolv"){
				var brandLogo = '<img src="'+jspStoreImgDir+'images/logos/evolv.png" alt="images-logo" />';
                }
                else{
				var brandLogo = '<img src="" alt="" />';
                }
                
                /* Dk modification: using our layout for banner items */
              
                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>';
                /* ---end Dk modification */
				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){
                /* Dk modification, using our layout for stars images */ 
					
                    var rating = parseFloat(SEARS.Item.rating.replace('_','.'));
                    /* placeholder */
					var starsHTML = '<span class="reviews"><img alt="'+SEARS.Item.rating.replace('_','.')+' stars out of 5" src="'+SEARS.Item.preReviewUrl+SEARS.Item.rating+SEARS.Item.postReviewUrl+'"/></span>';
					var reviewInfo = '<ul class="reviews"><li><ul class="stars">'+starsHTML+'</ul> </li> <li><a class="numberReviews" href="javascript:;">'+SEARS.Item.numReviews+' Reviews</a></li> <li class="last"><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'">Add a review</a></li> </ul>';
                /* -----end Dk modification */
                }
                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(SEARS.Item.ssText==0)
                    {
                    SEARS.Item.ssText="";
                    }
                    ssBase = '<div class="saveStory">'+SEARS.Item.ssText+'</div>';
                                   
                }
                
                //Build out div.content
				$(content).append('<div class="quicklookTab"/>');
				$(content).append('<div class="overviewTab"/>');
				if(SEARS.Item.hasSpecs){$(content).append('<div class="specsTab"/>')};
                var _qlook = $('.quicklookTab'); 
                var _ovr = $('.overviewTab'); 
                var _specs = $('.specsTab');
                if(strName!="My Gofer"){$(content).append('<div class="reviewsTab"/>');
                var _reviews = $('.reviewsTab')};
                
                 $(_qlook).append(banner);
                /* Dk modification: add behavior to review text */
                   if (reviewInfo) {
                    $(_qlook).append(reviewInfo);
                    $('.reviews a.numberReviews').click(function(){
                        $('.content > div').hide();
                        $('.reviewsTab').show();
                        $('.tabs > li').removeClass('active');
                        $('.tabs > li.reviewsTabC').addClass('active');
                        /* Dk modification --- layout support for IE6  */
                        if(($.browser.msie) && ($.browser.version < 7)){
                            var newHeight = $('.quickView').height() - 1;
                            $('.quickView .dragLeft').height(newHeight);
                            $('.quickView .dragRight').height(newHeight);
                            /* IE6 does not re-paint all elements for new box height. forcing redraw 
                            thus... interestingly, the classname removed does not need to exist */
                            $('.quickView .dragBottom').removeClass('redraw_me_foo');
                        }
                    });
                }
                if ((SEARS.Item.mainImage) && (imgID = SEARS.Item.mainImage.iId)) {
                    var imgURL = "http://s.sears.com/is/image/Sears/"+imgID+"?wid=400&hei=400&op_sharpen=1&qlt=75";
                } else {
                    /* placeholder, if we have one */
                    var imgURL = "../images/FPO/fpo.prodDetail.zoom.jpg";
                }
                var mainImage = '<div class="imageLarge"><img alt="pic" src="'+imgURL+'"/></div>';
                $(_qlook).append(mainImage);
                /* ---end modification, new Quick Look tab */

                $(_ovr).append(banner);
                $(_ovr).append('<ul class="modelItem"><li>'+brandLogo+'</li><li>'+itemNum+'</li><li>'+mNum+'</li></ul>');

                 /* Dk modification, right bar content */
               
                $(_ovr).append('<div class="description">'+SEARS.Item.oDescription+'</div>');
                /* ---end Dk modification */
                /* Dk modification: saveStory has moved to right column */
            
                $(_specs).prepend(banner).append('<div class="specsBucket"/>');
                /* ---end Dk modification */
				if(SEARS.Item.reviews){
              
					if(SEARS.Item.numReviews>=1 && SEARS.Item.isVp == 'BV'){
                    $(_reviews).append('<iframe class="reviewsBucket" width="437" height="500" frameborder="0" src=""/>');
                }else if(SEARS.Item.isVp == 'BV'){
                    /* Dk modification: using our layout */ 
                    $(_reviews).append('<p class="addReview"><a href="/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId+'" title="Write a Review for This Product">Click here to write a review for this product</a></p>');
                }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  width="437" height="500" 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-env="'+SEARS.Item.VPEnv+'" data-brand="'+SEARS.Item.VPStore+'" data-inventory="sears" ></div>');
                }
	};
              
              /*js_ReplaceChar*/
				function js_ReplaceChar(str,charFind,replaceWith){
				    //replaceWith = "\\"+charToRemove;
				    regExp = new RegExp("["+charFind+"]","g");
				    return str.replace(regExp,replaceWith);
				}
              	
              	var name=js_ReplaceChar(SEARS.Item.pTitle,'"','&quot;');
				name=js_ReplaceChar(name,"'","&#39;");
				
				             	
				var overlay = jsonProperties.sid+","+jsonProperties.cid+","+SEARS.Item.parCatEntId+",\'"
                		   +"\',\'"+name+"\',\'"+jsonProperties.img1+SEARS.Item.mainImage.iId+"?hei=100&wid=110\',\'\',\'"+SEARS.Item.pId+"\',\'\',\'false\'";
                  
                /* Dk modification, right bar content */
                if(SEARS.Item.type == "C") {
                    $(itmWgts).append('<div class="tools"><span class="wishlist">Add To Wishlist</span><span class="ownThis">I Own This</span></div>');
				} else {
					$(itmWgts).append('<div class="tools"><a href="javascript:showOverlay(\'MyWishlist\','+ overlay + ');" class="wishlist">Add To Wishlist</a><a href="javascript:showOverlay(\'ToolsIOwn\','+ overlay + ');" class="ownThis">I Own This</a></div>');
				}
                    $(itmWgts).append(ssBase);
                /* ---end Dk modification */

                    var toolBoxButtons = [".tools a.wishlist",".tools a.ownThis"];
                    var lightBoxIDs = ["lb_addwishlist","lb_addtoolbox"];
                    $(toolBoxButtons).each(function(i){

                        $(toolBoxButtons[i]).click(function(){
                            // close Quick View
                            SEARS.QuickView.close();
                            $('#lb_addwishlist').remove();
                            $('#lb_addtoolbox').remove();
 
                            if (typeof showbox === "function"){//external 
                                showbox('#'+lightBoxIDs[i]);
                            }
                        });
                    });

                if(SEARS.Item.softData && SEARS.Item.type=="S"){
                    /* Dk modification: using our layout */
                   
                    $('.itemWidgets').append('<div class="softLineSelections"/>');
                    /* --end Dk modification */
                    /* Dk modification: using our layout */
                   
                    var _selects = $('.softLineSelections');
                      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 = $('<h3 id="qvp_var">'+fitment[0].varName+'</h3>').appendTo(_selects);
           SEARS.Item.current.attList = fitment[0].attList;
           SEARS.Item.current.skuList = fitment[0].skuList;
           };
           SEARS.Item.changeVariant();
                 
}
            /* --end Dk modification: Softlines output below Cart Actions */
                
                if(SEARS.Item.type=="S"){
                    /* Dk modification: We are placing Cart actions just below Save Story content */
                    $(itmWgts).append('<div class="softAddtoCart" style="display:none"><span class="QVqtyWrap"><label for="QVqty'+SEARS.Item.pId+'">Quantity:</label><input type="text" value="1" class="QVqty" id="QVqty'+SEARS.Item.pId+'"/> <strong>= $<span class="QVsubT"></span></strong></span></div>');
                    
                    /* ---end Dk modification */
                    var _QVqtyBox = $('#QVqty'+SEARS.Item.pId);
                    /* Dk modification: We are placing Cart actions just below Save Story content */
                    $(itmWgts).find('.softAddtoCart').append('<a href="#" class="button-cartActions"/>');
                    
                    /* ---end Dk modification */
                    $(_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)};
                        var _SSqty = $(QVparent).find('.saveStory').eq(0);
                       if($(_SSqty).find('.regPrice').length){
                       var _QtyAmt = $(_SSqty).find('.regPrice').html().split("$")[1];
                       }else if($(_SSqty).find('.salePrice').length){
                       var _QtyAmt = $(_SSqty).find('.salePrice').html().split("$")[1];
                      }else if($(_SSqty).find('.youPay').length){
				var _QtyAmt = $(_SSqty).find('.youPay').eq(0).find('.pricing').eq(0).html().split("$")[1]
					   }
					  if(_QtyAmt) _QtyAmt = _QtyAmt.split(' ')[0];
                      $('form[name="addToCart"] input[name="quantity_1"]').val(global.val());
                      $(QVparent).find('.QVsubT').html(parseFloat(_QtyAmt*global.val()).toFixed(2));
                     }).blur();
                }else{
                    /* Dk modification: We are placing Cart actions just below Save Story content */
                    $(itmWgts).append('<a href="#" class="button-cartActions"/>');
                   
                    /* ---end Dk modification */
                }
                /* Dk modification: using more descriptive CSS classname */
               
                var goToBtn = $('.quickView .button-cartActions');
                /* ---end Dk modification */
                var _QVqty = $('.QVqty');
                var _QVsubT = $('.QVsubT');   
                
                if(SEARS.Item.preOrder&&SEARS.Item.inStock){
                    
                    /* Dk modification: using CSS image-replaced buttons */
					
					$(goToBtn).click(function(){
                        submitAddToCart(SEARS.Item.mFimgURL1);
                        s.prop26='\''+_vert+' > '+_cat+' > '+_sbcat+' > '+SEARS.Item.pId+' > '+'Quick View > Add to Cart\'';
                        s.tl();
                    });
                    $(goToBtn).addClass('button-preOrder');
                /* ---end Dk modification */
				}else if (SEARS.Item.preOrder&&!SEARS.Item.inStock){
                   
                    /* Dk modification: using CSS image-replaced buttons */
					
                    $(goToBtn).addClass('button-details');
                    /* ---end Dk modification */
                    $(goToBtn).attr('href','/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId);
				}else if(!SEARS.Item.addToCart&&SEARS.Item.type!="S"){
                   
                    /* Dk modification: using CSS image-replaced buttons */
                    
                    $(goToBtn).addClass('button-details');
                    /* ---end Dk modification */
                    $(goToBtn).attr('href','/shc/s/p_'+SEARS.Item.strId+'_'+SEARS.Item.catId+'_'+SEARS.Item.pId);
               }else /*if(SEARS.Item.addToCart)*/{
                   
                   /* Dk modification: filepath */
                  
                    /* ---end Dk modification */
                   $(goToBtn).click(function(){
                        submitAddToCart(SEARS.Item.mFimgURL1);
                        s.prop26='\''+_vert+' > '+_cat+' > '+_sbcat+' > '+SEARS.Item.pId+' > '+'Quick View > Add to Cart\'';
                        s.tl();
                    });

                } 
                /* Dk modification: using our layout */
                //$(goTo).append('<br clear="all"/>');
                /* ---end DK modification */
				if(SEARS.Item.preOrder&&!SEARS.Item.inStock&&!SEARS.Item.doNotEmail){
                    /* Dk modification: We are placing Cart actions just below Save Story content */
					//$(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>');
					$(itmWgts).append('<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>');
                    /* ---end DK modification */
					//$(goTo).prepend('<a href="javascript:;" class="emailMe" rel="emailMe" info="'+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){
                    /* Dk modification: We are placing Cart actions just below Save Story content */
					//$(goTo).prepend('<script type="text/javascript" src="http://as00.estara.com/as/InitiateCall2.php?accountid=200106282552&Template=58359"></script><a class="clickCall" href="javascript:webVoicePop (\'Template=58359\');">Call for Product Questions</a>');
					$(itmWgts).append('<script type="text/javascript" src="http://as00.estara.com/as/InitiateCall2.php?accountid=200106282552&Template=58359"></script><a class="clickCall" href="javascript:webVoicePop (\'Template=58359\');">Call for Product Questions</a>');
                    /* ---end Dk modification */
                }
                /* Dk modification: moved various item info block for output below 
                   Cart Actions content */

                /* Dk modification: using our layout elements for item availability */
                $(itmWgts).append('<div class="availability"><ul></ul></div>');
                var itmAvail = $(itmWgts).find('.availability ul');
                /* --end Dk modification */
                if(SEARS.Item.preOrder){
                    /* Dk modification: using our layout elements for item availability */
                  
                    $(itmAvail).append('<li class="releaseDate">Available for Pre-Order <p>Release Date: '+SEARS.Item.preOrder+'</p>');
                    /* --end Dk modification */
                	/* 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'});});
                	}
                }
		        else if(SEARS.Item.inStock){
                    /* Dk modification: using our layout elements for item availability */
                    
                    $(itmAvail).append('<li class="inStock"> In stock for delivery </li>');
                    /* --end Dk modification */
                }else if(!SEARS.Item.inStock){
                    /* Dk modification: using our layout elements for item availability */
                    
                    $(itmAvail).append('<li class="notInStock"> Temporarily out of stock for delivery</li>');
                    /* --end Dk modification */
                }
                /* Dk modification: move special offers after availability */
               
                if(SEARS.Item.storepu&&!SEARS.Item.preOrder){
                    /* Dk modification: using our layout elements for item availability */
                   
                    $(itmAvail).append('<li class="storepu">Buy Online - Pickup in Store Eligible</li>');
                    /* --end Dk modification */
                    /* Dk modification: add click behavior to Store Pickup link */
                    $(itmAvail).find('li.storepu a').click(function(){
                        mePop(this.rel,'storePickup',true);
                    });
                }
               if(SEARS.Item.holiday&&!SEARS.Item.preOrder){
                    /* Dk modification: using our layout elements for item availability */
                    //$(itmWgts).append('<span class="noIcon">'+SEARS.Item.holiday+'</span>');
                    $(itmAvail).append('<li class="noIcon">'+SEARS.Item.holiday+'</li>');
                    /* --end Dk modification */
                }   
                /* Dk modification: move special offers after availability */
                var splOffers = '\'splOffr\'';
                /* Dk modification: use hardcoded 'business logic' for templates display */

                 if(SEARS.Item.spo && !SEARS.Item.preOrder){  
                   /* Dk mod: temporarily disable special offers until CSS is complete */
                   
                  $(itmWgts).append('<div class="promotions"><a class="button-specialOffers" href="javascript:;" onclick="specialOffers('+splOffers+','+cmdStoreId+','+cmdCatalog+','+SEARS.Item.parCatEntId+');return false;">Special Offers</a></div>');
                   
                /* ---end Dk special offers modification */
              } 
                /* ---end Dk various item info modification */
                if(!SEARS.Item.inStock && SEARS.Item.storepu){
                    var IndA = "pickup"
                }else{
                    var IndA = "ship"
                }

                /* Dk modification: include static Craftsman Club content */
                $(itmWgts).append('<div class="craftsmanClub"> Upgrade your purchase <span>CLUB MEMBERS<br/> SAVE UP TO 10%</span> <a onclick="window.open(\'nb_10155_12602_NB_CraftsmanClub\')" href="javascript:;">Learn More</a> </div>');
                /* ---end Dk modification */

                /* Dk modification: include button link to Item Detail page */
               
                
                var storeId=jsonProperties.sid;
                var catalogId=jsonProperties.cid;
                var partnumber=SEARS.Item.pId;
				var prodUrl="p_"+storeId+"_"+catalogId+"_"+partnumber;
			 $(goTo).append('<a class="button-seeFullDetails" href="'+prodUrl+'">See full Details</a>');
              /* ---end Dk modification */
                 
                var adjHgt,adjWid;
                var variant = "0";
                
		        if(SEARS.Item.type == 'H'){
		        	variant = "0";
		        } else if(SEARS.Item.type == 'S'){
		        	variant = "1";
		        }
                /* Dk modification: We are placing Cart actions just below Save Story content */
               	var gcUserTypeVal=getCookie('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>');
                $(goTo).append('<div class="clear"/>'); 
                /* ---end Dk modification */
				if(SEARS.Item.preOrder){
                    /* Dk modification: We are placing Cart actions just below Save Story content */
				
					$(itmWgts).children('form').append('<input type="hidden" name="presellDate" value="'+SEARS.Item.preOrder+'"/>');
                    /* ---end Dk modification */
				} 
                var scrlWgt = $('.scrollWidget');
                var clickIndx=0, clickIndx2=0;
                var curImg = SEARS.Item.Img[clickIndx];
               
                if(!$.browser.msie){$(QVWrap).draggable({handle:$(".drag")})};
               
                
                highlightThumb = function(){
               };
                $(".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;
                });
               
            // Availability link click event
            	
			$('a.emailMe').click(function(){
                    //console.log('emailMe click');
                    /* Dk modification: close Quick View for the mePop overlay if is currently
                       open. we re-open it when mePop content is closed */
                    var reOpenQuickView = false;
                    if (SEARS && SEARS.QuickView) {
                        var parents = $(this).parents();
                        //console.log('parents as %o',parents);
                        $(parents).each(function(){
                            if (($(this).hasClass('quickView')) && (SEARS.QuickView.currentStatus === "open")) {
                                reOpenQuickView = true;
                            }
                        });
                    }
                    if (reOpenQuickView) {
                        SEARS.QuickView.close();
					    mePop(this.rel, 'emailMe',true);	
                    } else {
					mePop(this.rel, 'emailMe');	
                    }
                    /* Dk modification: using our layout */
					//$('grayDiv').css('z-index','501');
					//$('emailMe').css('z-index','502');
                    /* --end Dk modification */
			});
			
			/* 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();
          
            var firstTab = $('.quickView div[class$="Tab"]:first');
          
            $(firstTab).show("fast",function(){
           
                /* Dk modification: adjust border height for IE6 since
                   it cannot calculate CSS height:100% */
                if(($.browser.msie) && ($.browser.version < 7)){
                    var newHeight = $('.quickView').height() - 1;
                    $('.quickView .dragLeft').height(newHeight);
                    $('.quickView .dragRight').height(newHeight);
                }
                /* ---end Dk modification */
                $(QVWrap).centerOnScreen();
            });
            $(QVWrap).hide();
            /* Dk modification: using our layout */
             $(QVWrap).show().bgiframe();
            /* ---end Dk modification */
           
            if(strName=="Sears"){
            $(QVWrap).find('.reviewsBucket').attr('src',SEARS.Item.preReviewUrl+SEARS.Item.revURL+'/reviews.htm?format=noscript&user=__USERID__');
            }
             
            $("a.mapLink").click(function(){ 
                mapClick(this)
            });
            $('.closeWindow').click(function(){
                /* Dk modification: use Quick View close method */ 
              
                SEARS.QuickView.close();
                /* ---end Dk modification */
                return false;
            });
            /* Dk modification -- using different layout elements for tab labels */
          
            $('ul.tabs > li > a').each(function(){
            /* ---end Dk modification */
                    /* Dk modification -- mouseover/out states */
                    $(this).mouseover(function(){
                        $(this).parent().addClass('hover');
                    });
                    $(this).mouseout(function(){
                        $(this).parent().removeClass('hover');
                    });
                    /* ---end Dk modification */
                    /* Dk modification -- mouseover/out states */
                    $(this).click(function(){
                    /* Dk modification --- not using this placeholder in our layout */
                 
                    /* ---end Dk modification */
                    var theTab = $(this).attr('href').split('#')[1];
		    		var swap = function(){
                        $('.content > div').hide();
                        $('.'+theTab+'Tab').show();
                        /* Dk modification --- layout support for IE6  */
                        if(($.browser.msie) && ($.browser.version < 7)){
                            var newHeight = $('.quickView').height() - 1;
                            $('.quickView .dragLeft').height(newHeight);
                            $('.quickView .dragRight').height(newHeight);
                            /* IE6 does not re-paint all elements for new box height. forcing redraw 
                               thus... interestingly, the classname removed does not need to exist */
                            $('.quickView .dragBottom').removeClass('redraw_me_foo');
                        }
                        /* ---end Dk modification */
					};
					if(theTab=='specs'){
						if(SEARS.Item.type!="C"&&SEARS.Item.type!="GC"){
                        /* Dk modification----*/
							$(QVWrap).find('.specsBucket').load('/shc/s/DisplayTabCmd?langId=-1&commandStoreId=10153&storeId='+SEARS.Item.strId+'&partNumber='+SEARS.Item.pId+'&catalogId='+SEARS.Item.catId+'&catentryId='+SEARS.Item.parCatEntId+'&tabName=specs',function(){
							
                            /* ----end Dk modification */
                                /* Dk modification, different layout ----*/
								/* Dk modification, spec Design needs 100% table width,
                                   override inline style hardcoded in JSON data ----*/
                                var specsTable = $('table.product_spec_tab');
                                $(specsTable).css({'width': '100%'});
                                /* --end Dk modification */
                                /* Dk modification, spec Design needs span in <th> elements ----*/
                                var tableHeaders = $('.product_spec_tab th');
                                $(tableHeaders).each(function(){
                                    var inner = $(this).html();
                                    $(this).replaceWith('<th colspan="2">'+inner+'</th>');
                                });
                                /* --end Dk modification */
								swap();
                                /* Dk modification, different layout ----*/
								
                                /* --end Dk modification */
							});
						};
					}else if(theTab=='reviews'){
                 	swap();
                 	ViewpointsReviewsWidget();
						
                    }
                    /* Dk modification, added `Quick Look` Tab ----*/
                   
                    if(theTab==='selections' || theTab==='overview' || theTab==='quicklook'){
                    /* --end Dk modification */
                      
						swap()
                    }
                 
                    /* Dk modification, different class names ----*/
                   
                    $(this).parent().addClass('active').siblings().removeClass('active');
                    /* --end Dk modification */
                    if($.browser.msie){$(this).blur()};
                    return false;
                });
            });  
            /* Dk modification, set default active tab control ----*/
            $('.tabs li:first-child').addClass('active').siblings().removeClass('active');
            /* --end Dk modification */
           if($('.saveStory').find('.callout').length){
					
					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"/>';
    /* Dk modification -- Filepath */
   
    var QVbtn = '<a href="#quickView" title="View QuickView information for this item" class="QVbtn"><img alt="quick view button"  src="'+jspStoreImgDir+'images/buttons/btn_quickView.png" width="108" height="29" style="background:transparent;"></a>';
    /* ---end Dk modification */
    /* Dk modification -- using our layout */
   
    var photoDiv = $('.product .photo');
    /* ---end Dk modification */
    $(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=="10155" || qvSID=="10153"||qvSID=="11201"||qvSID=="10151"||qvSID=="10152"||qvSID=="12701"||qvSID=="13201"||qvSID=="10701"||qvSID=="11701"||qvSID=="11702"||qvSID=="11703"||qvSID=="10154"){ 
                _this.addClass("over");
                _this.append($(screen));
               
                $(QVbtn).appendTo(_this).attr('onclick','s.prop26=\''+vert+' > '+cat+' > '+sbcat+' > '+qvPID+' > '+'Quick View \';s.events=\'event27\';s.product=\''+qvPID+'\';s.tl();').hide();
                /* ---end Dk modification */
                /* Dk modification: using larger CSS height for div.screen */
              
                _this.find(".screen").animate({height:90},200,function(){
                /* --end Dk modification */
                    $(this).parent().find(".QVbtn").fadeIn(300);
                });
               $('a[@href*=#quickView]').click(function(){
                    /*$.getJSON("js/product.json",function(data){
                        SEARS.Item.info(data);
                        SEARS.QuickView.launch();
                    })*/
				    if (typeof showGoferQuickView !='undefined') {
				       showGoferQuickView(qvSID,qvCID,qvPID); 
				    }else{
				    	showQuickView(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 options = { 
        success: displayResponse,
       url:'QuickViewCmd?storeId='+storeId+'&catalogId='+catalogId+'&partNumber='+partNumber, /*general*/
     type:'GET'
    };                        
   
    request=$.ajax(options)
}
function displayResponse(responseText) {  
    //console.log('displayResponse()....');
    var data = eval('(' + responseText + ')');  
    SEARS.Item.info(data);
    SEARS.QuickView.launch();
} 
/* submitaddtocart function  signature changed for smartcart*/
function submitAddToCart(image) {
   if(document.addToCart.addToCartBtn.value == 'false') {
        //Add to cart button has been clicked once
          /* Added for Smart Cart AddToCartAJAX --Start */
         if((jsonProperties.enableATC == "true")&&(jsonProperties.enableSC == "true")){
        var qsMode = "OtherMode";
	        var isSmartCartFlag = "smartCartSingle";
        var quantity = 1;
        var img = "http://s.sears.com/is/image/Sears/"
        img += image;
	        var displayValue=isSmartCartFlag+"^"+img+"^"+qsMode;
        var sid = document.addToCart.storeId.value;
        var lid = document.addToCart.langId.value;
        var cid = document.addToCart.catalogId.value;
        var indicatorA = document.addToCart.IndicatorA.value;
        var vName = document.addToCart.vName.value;
        var cName = document.addToCart.cName.value;
        var sName = document.addToCart.sName.value;
        var grIdentifier = document.addToCart.grIdentifier.value;
        var addToCartBtn = document.addToCart.addToCartBtn.value;
        var catEntryId = document.addToCart.catEntryId_1.value;
        var quantity = document.addToCart.quantity_1.value;
        var partNumber = document.addToCart.partNumber.value;
        var grUserType = document.addToCart.grUserType.value;
        var atc = document.addToCart.atc.value;
        var presellDate = document.addToCart.presellDate.value;
	     var variant = "0";
        if(SEARS.Item.type == 'H'){
        	variant = "0";
        } else if(SEARS.Item.type == 'S'){
        	variant = "1";
        }   
        var url = "ProductOptionsOrderItemAddCmd?storeId=" + sid + "&langId="+lid+ "&catalogId="+cid+"&indicatorA="+indicatorA+"&vName="+vName+"&cName="+cName+"&sName="+sName+"&grIdentifier="+grIdentifier+"&URL=SmartCartUpdateView&quantity_1="+quantity+"&catEntryId_1="+catEntryId+"&partNumber="+partNumber+"&addToCartBtn="+addToCartBtn+"&url=SmartCartUpdateView";
        ajaxCall(url,'addToCartAjax',null,displayValue);
        }
        /* Added for Smart Cart AddToCartAJAX --End */
        else{
            document.addToCart.submit ();
        document.addToCart.addToCartBtn.value = 'true';
        }
    }
}

// Set up document when DOM ready //
//$(function(){
$(function($){
    qvBtn();
});  
/* quickView.js - ENDS HERE */
