/* Variable Declaration - Starts Here */
var DDItemList = "";
var httpRequestSupported = true;
// Initialize storeId with b2b storeid
var storeId=10151;
var catalogId = 10104;
// Kmart SPU Home Page Navigation Variables - Starts Here
var storeName;
var city;
var state;
var unitNo;
var defaulted=false;
var superK=false;
var cookieName="selectedStore";
var street;
var zipCode;
var staticPopUpName="";
var selectedStoreId="";
//Kmart SPU Shop BY Flow
var removePoParam = false;
var shopByInstore=false;
/* Variable Declaration - Ends Here */
/* Cross Format Reg Avail */
// To get the avail Message for DDC
var availValues = {
    Set : function(key,value) {this[key] = value;},
    Get : function(key) {return this[key];}
}

var regionalZip="";
var jsonResMsg="";

var DDCPartNoVal;
var DDCSiVal;
var DDCSpiVal;
var DDCSriVal;
var DDCDffVal;
var DDCVendorVal;
var DDCStDateVal;
var ATCFailureFlg= false;
//Flag to confirm QuickView (Regional Availibility) 
var flagQV='N';
var flagCartQV='false';

//Flag to confirm QuickView (Regional Availibility) 
var flagQV='N';
var flagCartQV='false';

//setting International Shipping variable to false
var intShipJspChk = 'false';

/* Browser Functions - Starts Here */

// Browser Sniff //
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
var redirectFlag = null;


/********************************************************************
	 Change Store Implementation: Starts 
*********************************************************************/
var chngStr = null;
var CALLER_PAGE_NAME='';
function fnChangeStoreInit(store,redirect){
	
	$('#dialog').jqmHide();
	
	redirectFlag = redirect;
	chngStr = store;

	// Make an AJAX call to check the availability of items already in cart in the new store
	if(typeof pageContextType != 'undefined' && pageContextType == 'http'){	
		var url = "ChangeStoreCmdHTTP?storeId="+getStoreId()+"&storeUnitNumber="+store.unitNo;
	}else if(typeof pageContextType != 'undefined' && pageContextType == 'https'){	
		var url = "ChangeStoreCmd?storeId="+getStoreId()+"&storeUnitNumber="+store.unitNo;
	}
	$.getJSON(url,fnChangeStoreCmpl);
}

function fnChangeStoreCmpl(jsonResp){
	chngStr.defaulted = jsonResp.defaultFlag;
	if(jsonResp.available){
		//Refresh the underlying page
		fnPagerefresh()
	}else{
		// Show feedback popup
		fnShowFeedbackPop(jsonResp.viewDetailsUrl);
	}
}



function fnShowFeedbackPop(itemGridUrl){
	var feedbackPopHtml = "<div id=\"spuFeedback\" style=\"width:290px;padding: 10px;line-height: 1.3; text-align:left;\">"
	feedbackPopHtml+= "    <h1 style=\"border:none; color:#840000;font-size:16px;font-weight:300;display:inline;margin:5px;\">Change Store</h1>"
	feedbackPopHtml+= "    <hr style=\"display:block;margin-left:5px\" />"
	feedbackPopHtml+= "    <p style=\"margin: 5px 15px 15px 5px;font-size:12px;\">Not all items in your shopping cart are available in this store.</p>"
	feedbackPopHtml+= "    <p style=\"margin: 15px 15px 20px 5px;font-size:12px;\">Do you want to continue with this store or "
	feedbackPopHtml+= " <a id=\"viewDetails\" href=\""+itemGridUrl+"&unitNo="+chngStr.unitNo+"\" style=\"color:#3366CC;font-size:12px;text-decoration:underline;\">view details</a> to select another store?</p>"
	feedbackPopHtml+= "    <a href=\"javascript:;\" class=\"cancel\"><img src=\""+imagePath+"img/buttons/btn_cancel.gif\" height=\"24\" width=\"75\" alt=\"Cancel\" style=\"padding: 0px 5px;\" /></a> <a href=\"javascript:;\" class=\"continue\"><img src=\""+imagePath+"img/buttons/btn_continue.gif\" height=\"26\" width=\"98\" alt=\"Continue\" /></a>"
	feedbackPopHtml+= "</div>"
	
	var newE = { pageX: 250, pageY: 250 };
	var settings = {dynamicContent:false,contentname: '#spuFeedback', windowWidth: '320px',windowHeight: 'auto',staticContent:feedbackPopHtml};
	dynpop.ini(newE, settings);
	
	$(function(){
		$('#DHTMLcontent #spuFeedback a.cancel').click(function(){
			$('#DHTMLcontent').fadeOut().remove();
			$('#DHTMLwrap').fadeOut().remove();
		});
		$('#DHTMLcontent #spuFeedback a.continue').click(function(){
			$('#DHTMLcontent').fadeOut().remove();
			$('#DHTMLwrap').fadeOut().remove();
			//Refresh the underlying page
			fnPagerefresh()
		});
		
		/*$('#DHTMLcontent #spuFeedback a#viewDetails').click(function(){
			$('#DHTMLcontent').fadeOut().remove();
			$('#DHTMLwrap').fadeOut().remove();
		});*/
	});
}
function fnCategoryList(ksnSpuOnlyList){
	ksnSpuList=ksnSpuOnlyList;
}
function fnVerticalList(ksnSpuOnlyList){
	ksnSpuList=ksnSpuOnlyList;
}
function fnPagerefresh(){
 
 
	//Update the cookie with strUnitNo
 
	selectedStore(chngStr);
	
	//Update the static link in header
	displayStore();
	
	if(typeof redirectFlag != "undefined" && redirectFlag != null && redirectFlag == true){
		window.history.go(-2);
		return;
	}
	
	if(shopByInstore==true && ($('body').attr('id')=='subcategory' || $('body').attr('id')=='keysearch')) {
		shopByInstore = false;
			shopByOption(shopBy);
			   // set the flag value when user clicks on shopBy drop down
			   removePoParam=true;
		       ajaxImpl();
	}else if($('body').attr('id')=='subcategory' || $('body').attr('id')=='keysearch') {
		changeStorePriceAvl();		
	}
	else if(($('body').attr('id')=='category')) {
	  
	}
	else if(($('body').attr('id')=='vertical')) {
		
	}else if(($('body').attr('id')=='compare')) {
		fnCompareRefresh();
	}
	else if(($('body').attr('id')=='hardline') || (CALLER_PAGE_NAME!=null && CALLER_PAGE_NAME!='' && CALLER_PAGE_NAME=='PRODUCT_PAGE')){
	 makeRTIPriceAvailabilityInq();
 
	}

    else if(($('body').attr('id')=='collection')||(CALLER_PAGE_NAME!=null && CALLER_PAGE_NAME!='' && CALLER_PAGE_NAME=='COLLECTION_PAGE')){
     
	 makeRTIPriceAvailabilityInq();
 
	}

	else if(($('body').attr('id')=='shoppingcart')) {
				
			 location.href=location.href;
	}

}

/********************************************************************
	 Change Store Implementation: Ends 
*********************************************************************/

/********************************************************************
	 Functions for Stope Pickup options in Header: Starts 
*********************************************************************/
$(function(){
	if(typeof enableShopByLink != 'undefined' && enableShopByLink == '1') {
		// Display the Static link in header
		displayStore();
	}
});
//function to show the Storename, state and city in the toplink
function displayStore() {
	if(fnCheckCookie()){
		if((city!=null&&city.length>0)&&(state!=null&&state.length>0)&&(storeName!=null&&storeName.length>0)){
			$('strong#storePickup').html('<a id="a_showItemAvailablityPopUp" href="javascript:;"/>My selected store for pickup:<span id="selectStoreDetails"><div id="storeDetails"> </div></span>');
			$('div#storeDetails').html("<a href=\"javascript:;\">"+storeName.titleCase()+", "+city.titleCase()+", "+state+"</a>");
			if($('body').attr('id')=='subcategory' || $('body').attr('id')=='keysearch'){
				$('#selectedStoreValue').html(storeName.titleCase()+", "+street.titleCase()+", "+city.titleCase()+", "+zipCode+" "+"<a href=\"javascript:;\" id='changeStore'><u>Change Store</u></a>");
				$('#changeStore').click(function(){
					$('#DHTMLcontent').fadeOut().remove();
					$('#DHTMLwrap').fadeOut().remove();
					launchMapModal(getStoreId(),"BROWSE");
				});
			}
		}
	}
	
	//if no store is selected 160 store locator will be called.
	$('strong#storePickup a').click(function(){
		if(!fnCheckCookie()){
			launchMapModal(getStoreId(),"BROWSE");
		}
	});
	
	//on mouseover of the question mark
	
	var dhtmlPop = "<style type=\"text/css\">"
	dhtmlPop += "#DHTMLcontent a.closeWin{ display:none; }"
	dhtmlPop += "</style>"
	dhtmlPop += "<div id=\"storeNotSelected\" style=\"margin:0;text-align:left;width:210px;padding:5px 15px;\">"
	dhtmlPop += "     <h5 style=\"font-size:1.2em;border-bottom:#999999 1px solid;padding-bottom:5px;width:190px;\">Need it Now?</h5>"
	dhtmlPop += "     <a id=\"mapping\" style=\"float:left;font-size:1.1em;text-decoration:underline;margin:5px 0;\" href=\"javascript:fnStaticMapLaunchModal();\">Please select a store to:</a>"
	dhtmlPop += "     <p style=\"clear:both;padding-top:5px;font-size:1.1em;\">See items avaliable for same day store.</p>"
	dhtmlPop += "</div>"

	$('strong#storePickup img').dynamicMouseOver({dynamicContent:false,contentname: '#storeNotSelected',windowWidth: '210px',windowHeight: 'auto',staticContent:dhtmlPop});

	
	
	//if store is already selected open 902 store selector module.	
	if(typeof pageContextType != 'undefined' && pageContextType == 'http'){	
		$('div#storeDetails').dynamicPopup({filename: 'storeSelectorCmdHTTP?storeId='+getStoreId(), contentname:'#storeSelect', windowWidth: '285px', windowHeight: 'auto'});
	} else if (typeof pageContextType != 'undefined' && pageContextType =='https'){
		$('div#storeDetails ').dynamicPopup({filename: 'storeSelectorCmd?storeId='+getStoreId(), contentname:'#storeSelect', windowWidth: '285px', windowHeight: 'auto'});
	}
}

function fnStaticMapLaunchModal(){
	$('#DHTMLwrap').add('#DHTMLcontent').remove();
	$('body').append(mapContent);
	launchMapModal();
}

// function to check for selectedStore cookie
function fnCheckCookie(){
	if($.cookie("selectedStore")==null){
		return false;
	}else{
		return fnParseCookie();
	}
}

//function to parse through selectedStore cookie
function fnParseCookie(){
	var selectedStoreValue=$.cookie('selectedStore');
	var tempSelectedStoreValue=selectedStoreValue.split('|');
	unitNo=tempSelectedStoreValue[0];
	storeName=tempSelectedStoreValue[1];
	defaulted=tempSelectedStoreValue[2];
	superK=tempSelectedStoreValue[3];
	state=tempSelectedStoreValue[4];
	city=tempSelectedStoreValue[5];
	street=tempSelectedStoreValue[6];
	zipCode=tempSelectedStoreValue[7];
	selectedStoreId=tempSelectedStoreValue[8];
		
	if((city!=null&&city.length>0)&&(state!=null&&state.length>0)&&(storeName!=null&&storeName.length>0))
		return true;
		
	else 
		return false;
}
// Function to update/create selectedStore cookie values
function selectedStore(store) {
	var cookieName="selectedStore";
	var cookieStoreId = '';
	cookieStoreId = (typeof store.selectedStoreId != 'undefined' && store.selectedStoreId != null) ? store.selectedStoreId : '';
    	var cookieValue=store.unitNo+"|"+store.storeName+"|"+store.defaulted+"|"+store.superK+"|"+store.state+"|"+store.city+"|"+store.street+"|"+store.zip+"|"+cookieStoreId;
	$.cookie(cookieName,cookieValue);
}

/********************************************************************
	 Functions for Stope Pickup options in Header: Ends 
*********************************************************************/			
if (checkIt('konqueror')){
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac";
	else if (checkIt('win')) OS = "Windows";
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/* Browser Functions - Ends Here */

/* Universal profile - starts here */

function fnUnivprofStarterListMG1(starterCount, mgurl, slurl, curStoreId, curCatalogId)
   		{
   			var dynamicCategoryUrl = mgurl;

       		var starterListCategory = slurl;
   			var catalogId = curCatalogId;
   			var storeId = curStoreId;
   			   		   			
   			var subCategory = document.getElementById("starterListsName1_"+starterCount).value;
   			
   			
   			var stList = subCategory.split(" ");
   			var subCat="";
   			var flag = false;
   			for(var i=0;i<stList.length;i++){
   				if(flag){
   					subCat = subCat+"+";
	   				subCat = subCat+stList[i];
	   			}
   				else{
   					subCat = subCat+stList[i];
   					flag = true;
   				}
   			}
   			var url = dynamicCategoryUrl+"/slc_"+storeId+"_"+catalogId+"_"+starterListCategory+"_"+subCat+"_true";
   			return url;
       	}
		
	function fnUnivprofStarterListMG2(starterCount, mgurl, slurl, curStoreId, curCatalogId)
   		{
   			var dynamicCategoryUrl = mgurl;

       		var starterListCategory = slurl;
   			var catalogId = curCatalogId;
   			var storeId = curStoreId;
   			   		   			
   			var subCategory = document.getElementById("starterListsName_"+starterCount).value;
   			
   			
   			var stList = subCategory.split(" ");
   			var subCat="";
   			var flag = false;
   			for(var i=0;i<stList.length;i++){
   				if(flag){
   					subCat = subCat+"+";
	   				subCat = subCat+stList[i];
	   			}
   				else{
   					subCat = subCat+stList[i];
   					flag = true;
   				}
   			}
   			var url = dynamicCategoryUrl+"/slc_"+storeId+"_"+catalogId+"_"+starterListCategory+"_"+subCat+"_true";
   			return url;   			
       	}	
		
/* Universal profile - ends here */

/* General Methods - Starts Here */

function setStoreId(storeIdValue){
	storeId = storeIdValue;
}

function getStoreId(){
	return storeId;
}

function setCatalogId(catalogIdValue){
	catalogId = catalogIdValue;
}

function getCatalogId(catalogIdValue){
	return catalogId;
}

function trim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

function trimAll(sString) 
	{
	while (sString.substring(0,1) == ' ')
	{
	sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
	sString = sString.substring(0,sString.length-1);
	}
	return sString.toLowerCase();
}

// function for validating email //
function validateEmailAddress(tempemail,displayEmail){
var email1 = rtrim(tempemail);
var email =  ltrim(email1);
if(email == '' ){
	    alert("Email address is required");
	    return false;
}
var regex1 = /^[^\s@]+@([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]\.|[A-Za-z0-9]\.)+([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]|[A-Za-z0-9])$/;
var regex2 = /^(root@|abuse@|spam@)/;
if(!email.match(regex1)){
alert("The e-mail address you entered appears incorrect. (Example of a correct address: kmart@kmart.com.) Please check your information and try again.");
    return false;
} else if(email.match(regex2)){
alert(displayEmail + " is not allowed");
return false;
}else if(!checkEmailChar(email)){
alert("The e-mail address you entered appears incorrect. (Example of a correct address: kmart@kmart.com.) Please check your information and try again.");
	return false;
}
return true;
}

// this function parses the values from URL
function gup( name )
{
  	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  	var regexS = "[\\?&]"+name+"=([^&#]*)";
  	var regex = new RegExp( regexS );
  	var results = regex.exec( window.location.href );
  	if( results == null )
  	{
    	return "";
    }
  	else
  	{
    return results[1];
    }
}

function remove(id){
	var obj=id.parentNode;
	obj.removeChild(id);
}

function removeID(id){
	var foo=document.getElementById(id);
	document.body.removeChild(foo);
}

// Set up page to do multiple loads //
function addLoadEvent(func) {

	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} 
	else 
	{
		window.onload = function() {
		  if (oldonload) {
			oldonload();
		  }
		  func();
		}
	}
	
}

// function to removespaces
function removeSpaces(string) {
var tstring = "";
string = '' + string;
splitstring = string.split(" ");
for(i = 0; i < splitstring.length; i++)
tstring += splitstring[i];
return tstring;
}

//Ajax call
function ajaxCall(url,callbackFunction,returnData,linkId) 
{ 
	var httpRequest = false; 

	// Exit if this function is not supported
	if (!httpRequestSupported) {
		return;  
	}
	
	// check if supported
	httpRequest = isHttpRequestSupported();
	
	if (!httpRequest) { 
		httpRequestSupported = false;
		return false; 
	} 
   
	// Map the response to the callback function
	httpRequest.onreadystatechange = function() { 
		if (httpRequest.readyState == 4) {  
			if (httpRequest.status == 200) {
				if (returnData) { 
					eval(callbackFunction + '(httpRequest.responseXML,linkId)'); 
				} else { 
					eval(callbackFunction + '(httpRequest.responseText,linkId)'); 
				} 
			} else { 
				// TODO:  Keep this line commented in production.  The user will have no idea what this means.
				//('The AJAX request was made to our backend server and the following error occurred: ' + httpRequest.status); 
				eval(callbackFunction + '("")'); 
			} 
		}
		else{
			if(callbackFunction == 'displayTabContent'){
				
				htmlValue = "<img src= '"+ imagePath + "img/backgrounds/loading.gif' />";
				document.getElementById(linkId).innerHTML = htmlValue;
			}
			if(callbackFunction == 'browseSpecialOffer'){	
				htmlValue = "<img src= '"+ imagePath + "img/backgrounds/loading.gif' />";
				linkId.innerHTML = htmlValue;			
			}
			if(callbackFunction == 'loadingProductOptions'){   
				htmlValue = "<h4>Options and Services</h4>"
					+ "<img src= '"+ imagePath + "img/backgrounds/loading.gif' />";
                document.getElementById(linkId).innerHTML = htmlValue;
            }
		} 
	} 
	
	httpRequest.open('GET', url, true); 
	httpRequest.send(null); 
}

function isHttpRequestSupported() {

	if (window.XMLHttpRequest) {   
		// Test if the Gecko engine is running.  Gecko supports AJAX
		httpRequest = new XMLHttpRequest(); 
		if (httpRequest.overrideMimeType) { 
			httpRequest.overrideMimeType('text/xml'); 
		}  
	} else if (window.ActiveXObject) { 
		// Test if an IE engine is running
		try {      
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try {  
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (e) {} 
		} 
	} 
	 
	if (!httpRequest) { 
		httpRequestSupported = false;
	} 
	return httpRequest;
}

// Pop Up Window //
function popUpWin(url,width,height){
	var newWin=window.open(url,'NewWindow','width='+width+',height='+height+',status=no,scrollbars=yes,resizable=yes,directories=no,menubar=no,toolbar=no,location=no');
	newWin.focus();
}

//Gets a cookie from the session based on the cookiename. if there is no cookie present an empty string is returned
function getCookie(cookieName)
{
	var cookieArray = document.cookie.split("; ");
	var searchString = cookieName+"=";
	var returnValue = '';

	for(var index = 0; index < cookieArray.length ; index++)
	{
		var cookie = cookieArray[index];
		var position = cookie.indexOf(searchString);

		if(position == 0)
		{
			var name_value = cookie.split("=");
			

			if(name_value[1] != '')
			{
					returnValue = name_value[1];
			}
			else
			{
				returnValue = '';
			}

		}
	}
	return returnValue;
}

//Sets a cookie in the session based on the cookiename and cookievalue
function setCookie(cookieName,cookieValue)
{
	document.cookie = cookieName + "=" + cookieValue + ";";
}

/* General Methods - Ends Here */


/* Browse(Home, Browse & Search, Product Pages) Methods - Starts Here */

// VERTICAL DROP DOWN FUNCTIONS //
var h = "";
function timeOutNav(id) {
    var hide = "hideBox('d"+id+"')";
    h = setTimeout(hide,500);
}

function dropNav(a,l) {
    var dLength = l; //how many drop downs
    
    for (var i = 1; i < dLength + 1; i++){
		document.getElementById("d" + i).style.display="none";
		document.getElementById("c" + i).style.position="static";
	} 
    document.getElementById("d" + a).style.display="block";
    document.getElementById("c" + a).style.position="relative";
    document.getElementById("content").style.zIndex = 10;
}

// TABS FUNCTIONS ///
function showTab (a,url) {
    var d = document.getElementById("tabList");
    var dLength = d.getElementsByTagName("dd").length;
    
    for (var i = 1; i < dLength + 1; i++){
        if (document.getElementById("tab_" + i).className == "selected"){
    		tabHide = document.getElementById("tab_" + i);
    		tabHide.className = "unselected";
    	}
    	if(document.getElementById("tab" + i)) {
			document.getElementById("tab" + i).style.display="none";
		}
	} 
    
    tabHide = document.getElementById("tab_" + a);
    tabHide.className = "selected";
    document.getElementById("tab" + a).style.display="";
	selectOverview(a-1);
	
	if(a==2){
		//Ajax call for executing the specs tab
		ajaxCall(url,'displayTabContent',null,'tab2');
	}
	if(a==3){
		//Ajax call for executing the options tab
		ajaxCall(url,'displayTabContent',null,'tab3');
	}
}

/* Universal profile - starts here */

function fnUnivprofStarterList(starterCount, mgurl, slurl, curStoreId, curCatalogId)
   		{
   			
   			var dynamicCategoryUrl = mgurl;

       		var starterListCategory = slurl;
   			var catalogId = curCatalogId;
   			var storeId = curStoreId;
   			   		   			
   			var subCategory = document.getElementById("starterListsName_"+starterCount).value;
   			
   			
   			var stList = subCategory.split(" ");
   			var subCat="";
   			var flag = false;
   			for(var i=0;i<stList.length;i++){
   				if(flag){
   					subCat = subCat+"+";
	   				subCat = subCat+stList[i];
	   			}
   				else{
   					subCat = subCat+stList[i];
   					flag = true;
   				}
   			}
   			var url = dynamicCategoryUrl+"/slc_"+storeId+"_"+catalogId+"_"+starterListCategory+"_"+subCat+"_true";   			
   			return url;
   			//location.href=url;
//			window.open(url,'windowname2',
  //                      'scrollbars=1,fullscreen=yes,toolbar=1');

       	}
		
		
		
/* Universal profile - ends here */




// TABS FUNCTIONS ///
function showSearchTab (a) {

    var d = document.getElementById("tabList");
    var dLength = d.getElementsByTagName("dd").length;

    for (var i = 1; i < dLength + 1; i++){
        if (document.getElementById("tab_" + i).className == "selected"){
    		tabHide = document.getElementById("tab_" + i);
    		tabHide.className = "unselected";
    	}
		document.getElementById("tab" + i).style.display="none";
	} 
    
    tabHide = document.getElementById("tab_" + a);
    tabHide.className = "selected";
    document.getElementById("tab" + a).style.display="";
	selectOverview(a-1);
}

function selectOverview(x){
    if (document.getElementById("overviewBox")){
        var d = document.getElementById("overviewBox");
        var li = d.getElementsByTagName("li");
        
        for (var i=0; i<li.length; i++){
            if (li[i].className == "selected"){
        		li[i].className = '';
        	}
    	} 
        
    	li[x].className = "selected";
    }
}

// HIDE AND SHOW //
function showBox (id) {
	if (document.getElementById && null != document.getElementById(id)) document.getElementById(id).style.display = "";
    return true;
}

function hideBox (id) {
	if(document.getElementById && null != document.getElementById(id)) document.getElementById(id).style.display = "none";
    return true;
}

// HIDE AND SHOW ADVANCE //
function showHideLite(id){
	var id = document.getElementById(id);
	id.style.display = (id.style.display == 'none') ? "" : "none";
}

function showHide(id){
	var d = document.getElementById(id);
	var d_edit = document.getElementById(id+"_edit");
	d.className = (d.className == 'open') ? "close" : "open";
	d_edit.style.display = (d_edit.style.display == 'none') ? "" : "none";
}

function showHideSelect(id,what) {
	if (!document.getElementsByTagName) return false;
	if (!document.getElementById) return false;
	var select = document.getElementById(id);
	var opts = select.getElementsByTagName("option");
	for (var j=0; j<opts.length; j++) {
		var option = opts[j].value;
		var optDivs = document.getElementById(option);
        if(optDivs){
            optDivs.style.display = "none";
        }
	}
	var elem = document.getElementById(what);
    if(elem){
        elem.style.display = "";
    }
}

// CHECK ALL CHECKBOX RELATED TO ID //
function checkAll(theElement, id) {
	var input = document.getElementsByTagName('input');
	for(z=0; z<input.length;z++){
	  if(input[z].type == 'checkbox' && input[z].name == id){
		input[z].checked = theElement.checked;
	  }
	}
}

// Disable select form elements //
function disableSelect()
{
	var select = document.getElementsByTagName('select');
	for(z=0; z<select.length;z++){
		select[z].disabled = true;
	}
}

function enableSelect()
{
	var select = document.getElementsByTagName('select');
	for(z=0; z<select.length;z++){
		select[z].disabled = false;
	}
}

function fn_kw_checkKeyword(){
    //Added for Search Within Search-calling fnManipulateParam method
    fnManipulateParam();
	var k = null;
	if(document.keywordForm != null){
		k = document.keywordForm.keyword;
	}
	else if(document.searchForm != null){
		k = document.searchForm.keyword;
	}
	var v = k.value;
	/* Added for 08_19 Auto Complete Related Search Enhancement Start 
    var i = 0;
	var relatedWords = '';
	var relatedWordsSize = 3;
	$('body').children('div.ac_results').find('ul').find('li').each(function() {
		if(v != this.selectValue) {
			i++;
			if(relatedWords != '') {
				relatedWords = relatedWords+'|';
			}
			relatedWords = relatedWords+this.selectValue;
			if(i == relatedWordsSize) {
				return false;
			}
		}
	});
	if(relatedWords != '') {
		$(k).parent().append("<input type='hidden' name='relatedwords' value='"+relatedWords+"'/>");
	}
	 Added for 08_19 Auto Complete Related Searches Enhancement End */
	if(v != null){
		v = v.replace(/^\s+/,"");
		v = v.replace(/\s+$/,"");
		v = v.replace(/^search/i,"");
		if(v != null && v.length > 0 ) {
			v = v.toLowerCase();
		}
		k.value = v;
	}
	if(v == null || v.length == 0){return false;}
	if(v == 'search for...'){
		k.style.backgroundColor = "#ffffb7";
		k.style.color = "#a00";
		return false;
	}
	return true;
} 

/*Added for Search within Vertical - Start*/
function fnManipulateParam(){
    var vNameVal = $("a.selectsearch").html();
    vNameVal = vNameVal.replace(/^\s+/,"");
 	vNameVal = vNameVal.replace(/\s+$/,"");
    if(typeof vNameVal != 'undefined' && vNameVal == 'All Products'){
      if(typeof $('div.searchBox input#vName').val() == 'undefined'){
          $("div.searchBox").find("input#vName").remove();
      }
    }else{
        if(typeof $('div.searchBox input#vName').val() == 'undefined'){
             $('div.searchBox').append("<input type=\"hidden\" id=\"vName\" name=\"vName\">");
        }
        if(vNameVal == 'Baby &amp; Nursery'){
         	vNameVal = 'Baby'; 
        }else if(vNameVal == 'Electronics &amp; Office'){
         	vNameVal = 'Computers & Electronics';
        }else if(vNameVal == 'Home Improvement'){
        	vNameVal = 'Tools';
        }else if(vNameVal == 'Jewelry &amp; Watches'){
         	vNameVal = 'Jewelry';
        }else if(vNameVal == 'Video Games'){
        	vNameVal = 'Entertainment';
        }else if(vNameVal == 'Outdoor Living &amp; Seasonal'){
         	vNameVal = 'Outdoor Living';
        }else if(vNameVal == 'Pets'){
        	vNameVal = 'Pet Supplies';
        }else{
	       	vNameVal = undoCleanURLParam(vNameVal);
	    }
        $('div.searchBox input#vName').val(vNameVal);
    }
}
function undoCleanURLParam(inputString) { 

    while(inputString.indexOf('&amp;')>=0){
            inputString=inputString.replace('&amp;','&');
}
    /*Using unescape function to eliminate invalid characters */
    inputString=unescape(inputString);
    return inputString;
}
/*Added for Search within Search - End*/

// Display Div over select form dropdown and switch z index //
function divFloat(id,state)
    {
        var DivRef = document.getElementById(id);
        var IfrRef = document.getElementById('iCover');
        if(state)
        {
            DivRef.style.display = "block";
            IfrRef.style.width = DivRef.offsetWidth;
            IfrRef.style.height = DivRef.offsetHeight - 2;
            IfrRef.style.top = DivRef.style.top;
            IfrRef.style.left = DivRef.style.left;
            IfrRef.style.zIndex = DivRef.style.zIndex - 1;
            IfrRef.style.display = "block";
        }
           else
        {
            DivRef.style.display = "none";
            IfrRef.style.display = "none";
        }
		
    }

// change container width for compare page //
function changeCompareWidth()
{
	var table=document.getElementById('compareTable');
	var all=document.getElementById('all');
	var allLeft=document.getElementById('allLeft');
	if (all.offsetWidth<table.offsetWidth)
	{
		all.style.width=(table.offsetWidth+50)+"px";
		if (browser=="Internet Explorer"){
			allLeft.style.padding="2em";
			return;
		}
	} else if (all.offsetWidth>=table.offsetWidth) {
		all.style.width=(780)+"px";
		if (browser=="Internet Explorer"){
			allLeft.style.padding="2em";
			return;
		}
	}
}

//Email me eligible submit //
function submitEmail()
{	
	
	var emailVal = document.emailNotify.userEmail.value;
	
	var partNumber = document.emailNotify.partNumber.value;
	var catEntryId = document.emailNotify.catEntryId.value;
	var skuDiff = document.emailNotify.skuDiff.value;
	var brandName = document.emailNotify.brandName.value;
	var productDescription = document.emailNotify.productDescription.value;
	var searsItemNumber = document.emailNotify.searsItemNumber.value;
	
	var manufacturerPartNumber = document.emailNotify.manufacturerPartNumber.value;
	
	
 	document.cookie = "userEmail1="+emailVal+";"
	
		
	if((emailVal == '')){
	    alert("Email address is required");
	    return false;
	}
	
	if(validateEmailAddress(emailVal)){
	var ajaxcallUrl = "EmailMeWhenInStockCmd?userEmail="+emailVal+"&catEntryId="+catEntryId+
	"&skuDiff="+skuDiff+"&brandName="+brandName+"&productDescription="+productDescription+
	"&searsItemNumber="+searsItemNumber+"&manufacturerPartNumber="+manufacturerPartNumber;
	
	ajaxCall(ajaxcallUrl,'showEmailMe');
	}else{
	   return false;
	}
	
	return true;
}

// This function is for recently viewed items.
function compareRecentlyViewed()
{
	var a = document.compare.prodCount.value;
	var count=0;
 	var anotherCount=0; 
 	 	
 	for (var i = 1; i <= a; i++){
 	  var object = 'document.compare.partNum'+i;
 	  var chkBox = eval(object);
	               
      if(chkBox.checked){
   	    count++;
   	  }
   	}
 if(count<2){
   alert("You must check atleast 2 items to compare.");
 }
 if(count>=2){
 	for (var j = 1; j <= a; j++){
 	var object = 'document.compare.partNum'+j;
 	var chkBox = eval(object);
    if(chkBox.checked){
   	anotherCount++;
   	//tempString = tempString + 'partNumber_'+count+'='+chkBox.value+'&';
  	currentElement = document.createElement("input");
	currentElement.setAttribute("type", "hidden");
	currentElement.setAttribute("name", "partNumber_"+anotherCount);
	currentElement.setAttribute("id", "partNumber_"+anotherCount);
	currentElement.setAttribute("value", chkBox.value);
	document.tempform.appendChild(currentElement);
 	
  }
 }
  // document.tempform.prodCount.value = count +'&'+tempString ;
  document.tempform.prodCount.value = count;
  document.tempform.submit();
  }
}

function uncheckAndSubmit(){
	var totalCount = document.compare.prodCount.value;
	for (var k = 1; k <= totalCount; k++){
	  var object = 'document.compare.partNum'+k;
	  var chkBox = eval(object);
	  if(chkBox.checked){chkBox.checked=false;}
   	}
	document.compare.submit();
}

// FIND POSITION //
function findPos(obj) {
	xPos = yPos = 0;
	if (obj.offsetParent) {
		xPos = obj.offsetLeft;
		yPos = obj.offsetTop;
		while (obj = obj.offsetParent) {
			xPos += obj.offsetLeft;
			yPos += obj.offsetTop;
		}
	}
	xPos += 20;
	yPos += 20;
	return [xPos,yPos];
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	{
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	{
		curtop += obj.y;
	}
	return curtop;
}

// SHOW HIDE TABLE CELLS  //
function showCell (b) {
    var c = document.getElementsByTagName('tr');
	for(var i = 0; i < c.length; i++)
	{
        if(c[i].getAttribute('hiding') == b){
            c[i].style.display = "";
        }
    }
}

function hideCell (b) {
    var c = document.getElementsByTagName('tr');
	for(var i = 0; i < c.length; i++)
	{
        if(c[i].getAttribute('hiding') == b){
            c[i].style.display = "none";
        }
    }
}

// SHOW HIDE DIVs //
function collapse(a,b) {
	if (document.getElementById(a).className=="hideAtt")
	{
        hideCell (b);
		tableHide=document.getElementById(a);
		tableHide.className="showAtt";
        tableHide.innerHTML="<a href=\"javascript:;\" onClick=\"collapse('"+a+"','"+b+"');\">See Details</a>";
		a = a + "_on";
	} 
	else if (a + "_on")
	{
        showCell (b);
		tableHide=document.getElementById(a);
		tableHide.className="hideAtt";
        tableHide.innerHTML="<a href=\"javascript:;\" onClick=\"collapse('"+a+"','"+b+"');\">Hide Details</a>";
		a = a + "_off";
	}
}

// CHANGE STYLESHEETS
function changeView(title,id) {
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) 
	{
		if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if (a.getAttribute("title") == title){
				a.disabled = false;
			}
		}
	}

	if (title == "row")
	{
		c=document.getElementById(id);
		c.innerHTML="<img onclick=\"changeView('grid','changeButton');\" src=\"images/icons/switch_grid.gif\" alt=\"switch to grid layout\" width=\"25\" height=\"23\" border=\"0\" align=\"absmiddle\">";
	}
	else if (title == "grid")
	{
		c=document.getElementById(id);
		c.innerHTML="<img onclick=\"changeView('row','changeButton');\" src=\"images/icons/switch_row.gif\" alt=\"switch to row layout\" width=\"25\" height=\"23\" border=\"0\" align=\"absmiddle\">";
	}  
}

// Set up Row Grid switcher //
var Switch = {
	buttons : function(which){
		var changeButton=document.getElementById('changeButton');
		changeButton.firstChild.onclick=function(){
			switch(which){
				case "row" : Switch.row();Switch.buttons('grid');this.src="img/icons/switch_grid.gif";break;
				case "grid" : Switch.grid();Switch.buttons('row');this.src="img/icons/switch_row.gif";break;
			}
		}
	},
	grid : function(){
		var contentWrapper=document.getElementById('contentWrapper');
		contentWrapper.className="grid";
	},
	row	 : function(){
		var contentWrapper=document.getElementById('contentWrapper');
		contentWrapper.className="row";
	}
};

// Check the querystring for guidElms and if they exist load the delivery_guide.js //
if (window.location.search.match( "guide" )){
	$('head').append('\n<link rel="stylesheet" href="css/delivery_guide.css">\n<script type="text/javascript" src="js/delivery_guide.js"></script>\n<script type="text/javascript" src="js/ifxscrollto.js"></script>\n');
}

/* Browse(Home, Browse & Search, Product Pages) Methods - Ends Here */


/* Shopping Cart and Check Out Methods - Starts Here */

// Set Up Links //
function prepareLinks (id, tag, clas) {
	if (document.getElementById || document.all){
		
		var li = document.getElementById(id).getElementsByTagName(tag);
		
		for (i=0; i<li.length; i++) 
		{
			if (li[i].className == clas && clas == "print"){
				li[i].onclick = function (){
					print();
				};
			}
			
			if (li[i].className == clas && clas == "shippingCal"){
				li[i].onclick = function (){
					shippingCalculator(id);
				};
			}
			
		}
		
		flyOut();
	}
	
}

window.onresize=flyOut;

function flyOut(){
	// flyout menu //
	if (document.getElementById('nav'))
	{
		if (this.innerHeight) // all except Explorer
		{
			var pageHeight = (this.innerHeight)+window.pageYOffset-250;
		}
		else if (document.body) // other Explorers
		{
			var pageHeight = (document.body.clientHeight)+document.body.scrollTop-250;
		}
		var n = document.getElementById('nav');
		for (i=0; i < n.childNodes.length; i++)  {
			node = n.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover = function() {
					this.className += " over";
					//alert(pageHeight);
					if(this.childNodes[2]!=undefined && this.childNodes[2].offsetHeight>pageHeight){
						this.childNodes[2].style.overflow='auto';
						this.childNodes[2].style.height=pageHeight+"px";
					}
				}
				node.onmouseout = function() {
					this.className = this.className.replace("over", "");
				}
			}
		}
	}
}

// LOAD EVENTS //
addLoadEvent(function() 
	{ 
		if(document.getElementById('subcategory') && document.getElementById('changeButton')){
			var contentWrapper=document.getElementById('contentWrapper');
			if(contentWrapper.className=="row"){ contentWrapper.className="grid"; Switch.row();Switch.buttons('grid');} 
			else if(contentWrapper.className=="grid"){ contentWrapper.className="row"; Switch.grid();Switch.buttons('row'); }
		}
		if (document.getElementById("crumbWrapper") && document.getElementById("crumbWrapper").getElementsByTagName("li"))
		{
			prepareLinks ("crumbWrapper", "li", "print");
			prepareLinks ("crumbWrapper", "li", "sendFriend");
		}
		if (document.getElementById("contentWrapper"))
		{
			prepareLinks ("contentWrapper", "a", "shippingCal");
		}
		if (document.getElementById("nav"))
		{
			prepareLinks ("nav", "li", "");
		}
		if (document.getElementById("scroll_widget"))
		{
			initScrollWidget();
		}
		if (document.getElementById("overviewBox"))
		{
			showTab(1);
		}
		if (document.getElementById("allLeft"))
		{
			changeCompareWidth();
		}
	}
);

// POSITION FIXED //
var verticalpos = "fromtop";

function JSFX_FloatTopDiv()
{
	var ns = (navigator.appName.indexOf("Netscape") != -1);
	var startX = 690;
	var startY = (document.all) ? 100 : 120;
	if (document.getElementById("checkout-shipping")){
		var startY = (document.all) ? 135 : 120;
	}
	var d = document;
	function ml(id)
	{
		var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
		if(d.layers)el.style=el;
		el.sP = function(x,y){this.style.left=x;this.style.top=y;};
		el.x = startX;
		if (verticalpos == "fromtop")
			el.y = startY;
		else{
			el.y = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
			el.y -= startY;
		}
		return el;
	}
	window.stayTopLeft = function()
	{
		if (verticalpos == "fromtop"){
			var pY = ns ? pageYOffset : document.body.scrollTop;
			ftlObj.y += (pY + startY - ftlObj.y)/8;
		}
		else{
			var pY = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
			ftlObj.y += (pY - startY - ftlObj.y)/8;
		}
		
		var newX = (document.body.clientWidth <= 800) ? 590 : ftlObj.x + ((document.body.clientWidth/2)-ftlObj.x)+188;
		var newY = (document.body.scrollTop < startY) ? startY : ftlObj.y - startY + 10;

		ftlObj.sP(newX, newY);
		setTimeout("stayTopLeft()", 10);
	}
	ftlObj = ml("rightColWrapper");
	d.getElementById("rightColWrapper").style.display = "block";
	stayTopLeft();
}

// Send to friend submit //
function submitFinish()
 {
 		var name = document.sendToFriendForm.visitorName.value;
 		var vEmail = document.sendToFriendForm.visitorEmail.value;
        var fEmail = document.sendToFriendForm.friendsEmail.value;
        var msg = document.sendToFriendForm.message.value;
        var locationurl = top.location.href;
        document.sendToFriendForm.url.value = locationurl;
       
        if(!nameValidation(name))
        {
        	return false;
        }
        
       function nameValidation(name){
       
           for(iLoop=0;iLoop<name.length;iLoop++){
            if(!((name.charCodeAt(iLoop)>64 && name.charCodeAt(iLoop)<91)||(name.charCodeAt(iLoop)>96 && name.charCodeAt(iLoop)<123) || (name.charCodeAt(iLoop)==32) || (name.charCodeAt(iLoop)== 46))){
             alert("The name you entered appears incorrect. Please check your information and try again.");
              return false;
              }
            }                       
          if(iLoop == name.length )
          {
            return true;
          }
       }       
		
	if((vEmail == '') || (fEmail == '')){
	    alert("Email address is required");
	    return false;
	}

	if (!validateEmailAddress(vEmail.toLowerCase(),vEmail))
        {
                
                return false;
        }

	// fEmail = removeSpaces(fEmail); 
         var vArray = fEmail.split(";");
                  
	 var count;
          for (count=0; count < vArray.length; count++)
          {
                var vElem = vArray[count];
                if (!validateEmailAddress(vElem.toLowerCase(),vElem))
                        {
                        return false;
                        }
          }

	if ((msg.length > 200))
	{
		alert("Message exceeds 200 characters");
	        return false;
        }

        var locationurl = top.location.href;
		var stringUrl = locationurl.replace(/&/g,"*");
		var visitorName  = document.sendToFriendForm.visitorName.value;
		var visitorEmail = document.sendToFriendForm.visitorEmail.value;
		var friendsEmail = document.sendToFriendForm.friendsEmail.value;
		var message      = document.sendToFriendForm.message.value;
		document.cookie = "userEmail="+visitorEmail+";"
		var storeIdValue = document.sendToFriendForm.storeValue.value;
		var ajaxurl = "SendToAFriendCmd?storeId="+storeIdValue+"&visitorName="+visitorName+"&visitorEmail="+visitorEmail+"&friendsEmail="+friendsEmail+"&message="+message+"&url="+stringUrl;
    	ajaxCall(ajaxurl,'showSendToFriend');
         
  	return true;
}
//submitfinish function ends

//This function is for calling rebate controller command
function openRebate(rebateId){
	      var rebate=rebateId.split(",");
      var   catentry=rebate[rebate.length-1];
      var isSaveForLater;       	
        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }  
      
    if($('body').attr('id')=='vertical'|| $('body').attr('id')=='category'|| $('body').attr('id')=='subcategory' || $('body').attr('id')=='keysearch'
    || $('body').attr('id')=='shopbybrand'|| $('body').attr('id')=='shopbyhome'||$('body').attr('id')=='hardline'||$('body').attr('id')=='softline' 
    || $('body').attr('id')=='dynamiccategory'  || $('body').attr('id')=='compare'|| $('body').attr('id')=='collection' 
    || $('body').attr('id')=='shoppingcart' || $('body').attr('id')=='checkout'||$('body').attr('id')=='product'){ 
      specialOffers('rebateDet',storeId,catalogId,catentry);    
    }
    else if((null != isSaveForLater) &&(isSaveForLater == 'YES')){
    	specialOffers('rebateDet',storeId,catalogId,catentry);    
    }
    else{
    var rebateDetail = 'RebateDetailsCmd?RebateId='+rebateId+'&storeId='+storeId;
    window.open(rebateDetail,'enlargedview','scrollbars=yes,titlebar=no,resizable=no,width=400,height=500');
    }

}

function popupSubmit(){
              var storeId = document.getElementById("storeId").value;
              var langId = document.getElementById("langId").value;
              var catalogId = document.getElementById("catalogId").value;
              for (i=0;i<document.GRForm.registry.length;i++) 
		  	  {
		  		if (document.GRForm.registry[i].checked) 
				{ 
				    var extId = document.GRForm.registry[i].value;
				    if (extId == 'create'){
					  var cattId = '&catEntryId_1='+catEntryIdScim+'&quantity_1=1';
					  var rew = "~";
				      cattId = cattId.replace(/&/g,rew);
				      window.location = 'WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId;
					}
					else{
				      onRegistry(extId);
					}
				}
			  }
			  
			  if (document.GRForm.registry.checked)
              {
	            if (document.getElementById("registry").value == 'create')
	              {
				     var cattId = '&catEntryId_1='+catEntryIdScim+'&quantity_1=1';
				     var rew = "~";
				     cattId = cattId.replace(/&/g,rew);
				     window.location = 'WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId;
				     
				  }
			  }
     }
     
 function popupWishlistSubmit(){
          var storeId = document.getElementById("storeId").value;
          var langId = document.getElementById("langId").value;
          var catalogId = document.getElementById("catalogId").value;
          for (i=0;i<document.GRForm.registry.length;i++) 
	  	  {
	  		if (document.GRForm.registry[i].checked) 
			{ 
			    var extId = document.GRForm.registry[i].value;
			    if (extId == 'create'){
				  var cattId = '&catEntryId_1='+catEntryIdScim+'&quantity_1=1';
				  var rew = "~";
			      cattId = cattId.replace(/&/g,rew);
			      location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId;
				}
				else{
			      onWishlist(extId);
				}
			}
		  }
		  
		  if (document.GRForm.registry.checked)
          {
            if (document.getElementById("registry").value == 'create') 
              {
			    var cattId = '&catEntryId_1='+catEntryIdScim+'&quantity_1=1';
			     var rew = "~";
				 cattId = cattId.replace(/&/g,rew);
			     location.href = "WeddingWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId;
			  }
		  }
 }

/* Shopping Cart and Check Out Methods - Ends Here */


/* Omniture Methods  - Starts Here */

//Omniture tracking
function omnitureTracking(name) { 
	//Omniture tracking.
	if (typeof omPrefix != 'undefined') {
		omPrefix='Product Summary > '+name;
	}
	if (typeof s != 'undefined') {
		s.t();
	}
}

// SEND TO A FRIEND FUNCTIONS
function sendToFriend(ajaxUrl,a) { 
    	s.pageName.Value = 'Product Summary > sendToFriend';
	omnitureTracking('sendToFriend');
	//Ajax call for executing the send to a friend
	ajaxCall(ajaxUrl,a);	
}

/* Omniture Methods  - Ends Here */


/* CENTER OBJECT ONTO SCREEN FOR MODALs - Starts Here */

$.fn.centerOnScreen = function(){
	var $this = this[0];
	var yScroll = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
	var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	var windowWidth  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	$this.style.top  = (yScroll+((windowHeight - $this.offsetHeight)/2)) + "px";
	$this.style.left = ((windowWidth/2) - ($this.offsetWidth/2)) + "px";
}

/* CENTER OBJECT ONTO SCREEN FOR MODALs - Ends Here */


/* BGIFRAME  - Starts Here */

$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

/* BGIFRAME  - Ends Here */


/* THROW UP A CURTAIN ON AN ELM  - Starts Here */

function curtainOverlay(params){
	if(!params.closing){										
		if(!params){
			var params = {};
			params.elm = 'body'; 
			params.trans = '0.8'; 
			params.color = '#333'
			params.closing = false;
			params.ajaxclass = '';
			params.ajaxmodal = false;
			params.closeonclick = true;
			params.persistmodal = false;
			params.fade = true;
		};
		if(!params.elm){params.elm = 'body'};
		if(!params.trans){params.trans = '0.8'};
		if(!params.color){params.color = '#333'};
		if(!params.ajaxclass){params.ajaxclass = ''};
		if(params.ajaxmodal != false){params.ajaxmodal = true};
		if(params.closeonclick != false){params.closeonclick = true};
		if(params.persistmodal != false){params.persistmodal = true};
		if(params.fade != false){params.fade = true}
	};
	if(params.fade){
		$.fn.inmode = $.fn.fadeIn;
		$.fn.outmode = $.fn.fadeOut;
		var duration = 1000;
	}else{
		$.fn.inmode = $.fn.show;
		$.fn.outmode = $.fn.hide;
		var duration = 0;
	}
	$('#curtain').remove();
	if(params.persistmodal){
		$('#ajaxmodal').hide();
	}else{
		$('#ajaxmodal').remove();
	}
	if(params.closing){
		if($.browser.msie){
			$('body').css({overflow:'auto'});
			//$('select').css({visibility:''});
		}else{
			$('html').css({overflow:''})
		}
	}
	var w = 0; var h = 0; var s = 0;
	if(!params.closing){
		if ($(params.elm).is('body')){
			if($.browser.msie){
				$('body').css({overflow:'hidden'});
				if($.boxmodel){
					w = document.documentElement.clientWidth;
					h = document.documentElement.clientHeight;
					s = document.documentElement.scrollTop;
				}else{
					w = document.body.clientWidth;
					h = document.body.clientHeight;
					s = document.body.scrollTop;
				}
			}else{
				$('html').css({overflow:'hidden'});
				w = window.innerWidth;
				h = window.innerHeight;
				s = window.pageYOffset;
			}
		}else{
			w = $(params.elm).width();
			h = $(params.elm).height();
			s = $(params.elm).offset().top
		}
		var curtain = $('<div id="curtain"/>').css({
			position:	'absolute',
			display:	'none',
			zIndex:		500,
			top:		s,
			left:		$(params.elm).offset().left,
			width:		w,
			height:		h,
			background:	params.color,
			opacity:	params.trans
		}).appendTo('body');
		
		if($.browser.msie){ 
				//curtain.bgiframe()
				curtain.css({ filter:'alpha(opacity='+(params.trans * 100)+')'}).show();
		}else{
			curtain.show();
		}
		if(params.ajaxmodal){
			if(params.persistmodal){
				if($('#ajaxmodal').length > 0){
					$('#ajaxmodal').fadeIn(1000);	
				}else{
					$('#ajaxmodal').remove();
					$('<div id="ajaxmodal" class="'+params.ajaxclass+'"/>').css({display:'none', position:'absolute', zIndex:'1000', backgroundColor:'#FFF', padding:'10px'}).insertAfter('#curtain').inmode(duration);
					//$('<div id="ajaxmodal" class="'+params.ajaxclass+'"/>').css({display:'none'}).insertAfter('#curtain').inmode(duration);
					//$('#ajaxmodal').show().centerOnScreen();
				}	
			}else{
				$('#ajaxmodal').remove();
				$('<div id="ajaxmodal" class="'+params.ajaxclass+'"/>').css({display:'none', position:'absolute', zIndex:'1000', backgroundColor:'#FFF', padding:'10px'}).insertAfter('#curtain').outmode(duration);
				//$('<div id="ajaxmodal" class="'+params.ajaxclass+'"/>').css({display:'none'}).insertAfter('#curtain').outmode(duration);
				//$('#ajaxmodal').centerOnScreen();
			}
		}		
		if(params.closeonclick){
			curtain.unbind().click(function(){
				curtainOverlay({closing:true});
			});
		};
	};
};


/* THROW UP A CURTAIN ON AN ELM  - Ends Here */


/* SHIPPING METHOD CHECKBOX FUNCTION  - Starts Here */

function changeShipMeth(elm){
	$(elm).parents('.shipMethod').find('label').removeClass('current');
	$(elm).parent('label').addClass('current');
}

/* SHIPPING METHOD CHECKBOX FUNCTION  - Ends Here */


/* GIFT WRAP MODAL LAUNCH FUNCTION  - Starts Here */
/*
launchGWmodal = function(orderId, orderItemId, storeId, catalogId, selectedGWCatId, comments, productName, productPartNumber, cmdStoreId) {
	var productNameDecode = unescape(productName);
	var urlforAjax = "";
	var emptyString = "";
	if(selectedGWCatId != ""){
		urlforAjax = "/shc/s/GiftWrapModalWindowView?storeId="+storeId
						+"&orderId="+orderId+"&catalogId="+catalogId
						+"&gwParOrderItemId="+orderItemId+"&selGiftWrapCatId="+selectedGWCatId
						+"&comments="+comments+"&productName="+productNameDecode
						+"&productPartNumber="+productPartNumber+"&cmdStoreId="+cmdStoreId;
	} else{
		urlforAjax = "/shc/s/GiftWrapModalWindowView?storeId="+storeId
						+"&orderId="+orderId+"&catalogId="+catalogId
						+"&gwParOrderItemId="+orderItemId+"&selGiftWrapCatId="+emptyString
						+"&comments="+emptyString+"&productName="+productNameDecode
						+"&productPartNumber="+productPartNumber+"&cmdStoreId="+cmdStoreId;
	}
	curtainOverlay({ ajaxmodal:true, ajaxclass:'giftwrapModal', closeonclick:false, color:'#335597', trans:0.3 });
	$.ajax({
	
		url: urlforAjax,    
	  
		cache: false,   
		success: function(data){
			$('#ajaxmodal').append(data).centerOnScreen();
			giftWrapFunctionality();
		}
	});
	//return false;
}*/

/* GIFT WRAP MODAL LAUNCH FUNCTION  - Ends Here */


/* DOM READY CALLS  - Starts Here */

$(function(){
	$('.shipMethod').find('input:radio').click(function(){changeShipMeth(this)});
	if(typeof dynamicPopupPath != 'undefined'){
		if($('table.personalinfo a.rewardsDetails').length >0){	
		$('table.personalinfo a.rewardsDetails').dynamicPopup({filename: dynamicPopupPath+'&vName=rewardsnote',contentname: '.gcPleaseNote',windowWidth: '300px',windowHeight: 'auto'});
	}
	}
	//$('#shoppingcart div.giftwrap a').click(launchGWmodal);
});

/* DOM READY CALLS  - Ends Here */


/* JQUERY COLOR  - Starts Here */

// jquery.color plugin
(function(D){D.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(F,E){D.fx.step[E]=function(G){if(G.state==0){G.start=C(G.elem,E);G.end=B(G.end)}G.elem.style[E]="rgb("+[Math.max(Math.min(parseInt((G.pos*(G.end[0]-G.start[0]))+G.start[0]),255),0),Math.max(Math.min(parseInt((G.pos*(G.end[1]-G.start[1]))+G.start[1]),255),0),Math.max(Math.min(parseInt((G.pos*(G.end[2]-G.start[2]))+G.start[2]),255),0)].join(",")+")"}});function B(F){var E;if(F&&F.constructor==Array&&F.length==3){return F}if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return[parseInt(E[1]),parseInt(E[2]),parseInt(E[3])]}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return[parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55]}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return[parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16)]}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return[parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16)]}return A[D.trim(F).toLowerCase()]}function C(G,E){var F;do{F=D.curCSS(G,E);if(F!=""&&F!="transparent"||D.nodeName(G,"body")){break}E="backgroundColor"}while(G=G.parentNode);return B(F)}var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);

/* JQUERY COLOR  - Ends Here */


/* Autofitment local price module  - Starts Here */

$(function(){

	if( ($("body").hasClass('fitment')) ){	

		$('.saveStory').each(function(){		  
			if( $(this).next().attr('class') == 'localPrice' ){
				$(this).hide(0);		
			}
		});
	
		var appCode = '<span class="morePrice">'
			appCode += '<div>'
			appCode += '<strong>Zip Code:</strong>'
			appCode += '<input type="text" value="" size="5" maxlength="5" />'
			appCode += '<img width="36" height="20" alt="go" src="img/buttons/auto_price_go.gif" />'
			appCode += '<p class="centerInfo">'
			appCode += '<strong>Nearest Sears Auto Center</strong>'
			appCode += '<br />'
			appCode += 'Enter your Zip Code to get the address and phone number.'
			appCode += '</p>'
			appCode += '</div>'
			appCode += '</span>';
			
	
		var appWarn = '<div id="warnLocal">'
			appWarn += '<div class="tab">Add to Cart</div>'
			appWarn += '<div class="priceMsg">Please Get Local Price by entering your Zip Code.</div>'
			appWarn += '<img src="img/buttons/okay_btn.gif" alt="okay" class="okayButton" />'		
			appWarn += '</div>';
			
		var foT;
		var done = 0;
		var offsetL;
		var $saveStory;
	
		$('body').append(appCode).append(appWarn);
		$('.morePrice, #warnLocal').hide();
		
		$(".localPrice").unbind().hover(function() {
			$saveStory = $(this).prev();							
			$('.morePrice').hide(0);
			offsetL = $(this).offset();
			$('.morePrice').show().css({ top: offsetL.top + 23, left: offsetL.left - 92 }); 
			$('.localPrice a').removeClass('over');	
			$(this).find('a').addClass('over');
			clearTimeout(foT);	
		}, function() {
			foT = setTimeout(function(){
				$('.morePrice').fadeOut();
				$('.localPrice a').removeClass('over');			
			},500);	
		});
		
		$(".morePrice").hover(function(){						   
			clearTimeout(foT);	
		}, function(){
			foT = setTimeout(function(){
				$('.morePrice').fadeOut();
				$('.localPrice a').removeClass('over');
			},500);	
		});	
		
		$('#cartButtons a:first').click(function(){
			if( ($("body").attr('id') == 'hardline') && (done != 1) ){	
				var offsetCart = $('#cartButtons').offset();
				$('#warnLocal').show().css({ top: offsetCart.top -350, left: offsetCart.left - 145 }); 
				$('.localPrice a').addClass('err');
				$('#warnLocal .okayButton').click(function(){
					$('#warnLocal').hide(0);
					$('.localPrice a').removeClass('err');				
				});
			}
		});
	
		$(".morePrice div img").click(function(){
			var regExp = /^\d{5}([\-]\d{4})?$/;		
			var $zipInput = $(this).prev();
			var $zipVal = $(this).prev().val();
			var $zipMsg = $(this).next();
			
			if( !$zipVal.match(regExp) ){ //error
				if( $zipVal == '' || $zipVal == '0' ){
					$zipMsg.html("The Zip Code was blank. Please enter a Zip Code to Get Local Price.").addClass('errZip');
				}else{
					$zipMsg.html("Please enter a 5-digit U.S. Zip Code.").addClass('errZip');
				}
				$zipInput.addClass('errZip');
			}else{ //success
				$('.centerInfo').html("<strong>Nearest Sears Auto Center<\/strong><br \/>4411 W Broad St<br \/>(614) 275-2195").removeClass('errZip');
				$('.localPrice a').html('Price in '+$zipVal);	
				//$('.localPrice a').html('Price May Vary'); // this is for the national price option
				$('.morePrice').find('input').removeClass('errZip').val($zipVal);
				$('.localPrice a').addClass('localPSel');	
				if( done == 0 ){
					var mvHt = 42;
					if( $saveStory.parent().parent().parent().parent().hasClass('grid') ){
						mvHt -= 10;	
					}
					var moveHeight = $saveStory.height() + mvHt;
					$('.morePrice').css({ top: offsetL.top + moveHeight  });
				}
				$('.saveStory').show();
				$('.saveStory, p.centerInfo').animate({ backgroundColor: "#FFFF99" }, 100).animate({ backgroundColor: "white" }, 3000);
				done = 1;
				 
			}
		});
	}
});

/* Autofitment local price module  - Ends Here */


/* xBrowser page dims(returns width height and scrolltop) - Starts Here */

function pageDims(){
	var dims = {};
	if($.browser.msie){
		if($.boxmodel){
			dims.w = document.documentElement.clientWidth;
			dims.h = document.documentElement.clientHeight;
			dims.s = document.documentElement.scrollTop;
		}else{
			dims.w = document.body.clientWidth;
			dims.h = document.body.clientHeight;
			dims.s = document.body.scrollTop;
		}
	}else{
		dims.w = window.innerWidth;
		dims.h = window.innerHeight;
		dims.s = window.pageYOffset;
	}
	return dims;
}

/* xBrowser page dims(returns width height and scrolltop) - Ends Here */


/* DHTML POP-UP PLUG-IN  - Starts Here */

var dynpop = { ini: 
	function(e, settings, caller){
			$('#DHTMLwrap').add('#DHTMLcontent').remove();
			var w;
			var h;
			var dhtmlContent = '<div id="DHTMLwrap"></div><div id="DHTMLcontent"></div>';
			var dhtmlHeight = Number(settings.windowHeight.split('px')[0]);
			var dhtmlWidth = Number(settings.windowWidth.split('px')[0]);
			var pagesize = pageDims();
			var w = pagesize.w+20;
			var h = pagesize.h;
			var s = pagesize.s;
			if ($.browser.msie) {
				if(settings.contentname == '#storeSelect'){
					$('body').append(dhtmlContent);
					$('#DHTMLwrap').bgiframe();
					$('#DHTMLwrap').css({
						position: 'absolute',
						top: 50,
						left: 300,
						zIndex: '1000001',
						backgroundColor: '#999999',
						opacity: '0.3',
						filter: 'alpha(opacity=30)',
						display: 'none'
					});
					$('#DHTMLcontent').css({
						position: 'absolute',				
						top: 55,
						left: 305,
						backgroundColor: '#fff',
						border: '1px solid #cccccc',
						zIndex: '1000002',
						display: 'none'
					});
				}
				else {
					$('body').append(dhtmlContent);
					$('#DHTMLwrap').bgiframe();
					$('#DHTMLwrap').css({
						position: 'absolute',
						top: (e.pageY+dhtmlHeight > (h+s)) ? (e.pageY - (((e.pageY+dhtmlHeight)-(h+s)))*1.3) : e.pageY,
						left: e.pageX+dhtmlWidth>(w-55) ? e.pageX - ((e.pageX+dhtmlWidth)-w) - 55 : e.pageX,
						zIndex: '1000001',
						backgroundColor: '#999999',
						opacity: '0.3',
						filter: 'alpha(opacity=30)',
						display: 'none'
					});
					$('#DHTMLcontent').css({
						position: 'absolute',				
						top: (e.pageY+dhtmlHeight > (h+s)) ? (e.pageY - ((((e.pageY+dhtmlHeight)-(h+s)))*1.3)+5) : e.pageY+5,
						left: (e.pageX+dhtmlWidth>(w-50)) ? e.pageX - ((e.pageX+dhtmlWidth)-w) - 50 : e.pageX + 5,
						backgroundColor: '#fff',
						border: '1px solid #cccccc',
						zIndex: '1000002',
						display: 'none'
					});				
				}
			}
			else {
				if(settings.contentname == '#storeSelect'){
					$('body').append(dhtmlContent);
					$('#DHTMLwrap').css({
						position: 'absolute',
						top: 39,
						left: 301,
						zIndex: '1000001',
						MozBorderRadius: '8px',
					  	WebkitBorderRadius: '8px',
						backgroundColor: '#999999',
						opacity: '0.3',
						filter: 'alpha(opacity=30)',
						display: 'none'
					});
					$('#DHTMLcontent').css({
						position: 'absolute',				
						top: 43,
						left: 306,
						backgroundColor: '#fff',
						border: '1px solid #cccccc',
						MozBorderRadius: '8px',
					  	WebkitBorderRadius: '8px',
						zIndex: '1000002',
						display: 'none'
					});
				}
				else{
					$('body').append(dhtmlContent);
					$('#DHTMLwrap').css({
						position: 'absolute',
						top: (e.pageY+dhtmlHeight > (h+s)) ? (e.pageY - (((e.pageY+dhtmlHeight)-(h+s)))*1.3) : e.pageY,
					left: e.pageX+dhtmlWidth>(w-75) ? (e.pageX - ((e.pageX + dhtmlWidth)-w)) - 75 : e.pageX,
						zIndex: '1000001',
						MozBorderRadius: '8px',
					  	WebkitBorderRadius: '8px',
						backgroundColor: '#999999',
						opacity: '0.3',
						filter: 'alpha(opacity=30)',
						display: 'none'
					});
					$('#DHTMLcontent').css({
						position: 'absolute',				
						top: (e.pageY+dhtmlHeight > (h+s)) ? (e.pageY - ((((e.pageY+dhtmlHeight)-(h+s)))*1.3)+5) : e.pageY+5,
					left: e.pageX+dhtmlWidth>(w-70) ? (e.pageX - ((e.pageX + dhtmlWidth)-w)) - 70 : e.pageX +5,
						backgroundColor: '#fff',
						border: '1px solid #cccccc',
						MozBorderRadius: '8px',
					  	WebkitBorderRadius: '8px',
						zIndex: '1000002',
						display: 'none'
					});
				}
			}
			if(settings.dynamicContent){
				if(settings.jsonFlag){
					$.getSearsCode = $.getJSON;
				}else{
					$.getSearsCode = $.ajax;
				}
				$.getSearsCode({
					url: settings.filename,
					cache: false,
					success: function(html){
						if(staticPopUpName=="nearStores"){
							$('#DHTMLcontent').empty().append('<a href="javascript:;" title="Close Window" class="closeWin"></a>').append(html);
						 	staticPopUpName="checkStores";
						}
						else {
							$('#DHTMLcontent').empty().append('<a href="javascript:;" title="Close Window" class="closeWin"></a>').append(html);
						}
						/* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- START */
						if(typeof imagePath!='undefined' && imagePath!=null && imagePath!="") {
							if(staticPopUpName=="checkStores"){
								$('.closeWin').css({height:'20px',width:'48px',position:'absolute',cursor:'pointer',top:'5px',right:'10px',background:'url('+imagePath+'img/btn/btn_closemap.gif) no-repeat', zIndex: '999999'});
							}else {
								$('.closeWin').css({height:'12px',width:'48px',position:'absolute',top:'5px',right:'5px',background:'url('+imagePath+'img/close-pref.gif) no-repeat', zIndex: '999999'});
							}
						
						} else {
							if(staticPopUpName=="checkStores"){
								$('.closeWin').css({height:'20px',width:'48px',position:'absolute',cursor:'pointer',top:'5px',right:'10px',background:'url(../img/btn_closemap.gif) no-repeat', zIndex: '999999'});
							}
							else{
								$('.closeWin').css({height:'12px',width:'48px',position:'absolute',top:'5px',right:'5px',background:'url(../img/close-pref.gif) no-repeat', zIndex: '999999'});
							}
						}
						/* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- END */

						$('#DHTMLcontent').find(settings.contentname).width(settings.windowWidth);
						$('#DHTMLcontent').find(settings.contentname).height(settings.windowHeight);
						if(!$.browser.msie){
							$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
						}
						else{
						$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
						}
						if(!$.browser.msie){
							$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
						}
						else{
						$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
						}		
						$('#DHTMLwrap').add('#DHTMLcontent').show('fast');
						$('.closeWin').click(function(){
							$('#DHTMLwrap').add('#DHTMLcontent').fadeOut('fast',function(){
								$(this).remove();
							});
						});
					}
				});
			}else{
				if(staticPopUpName=="price"){
					$('#DHTMLcontent').empty().append('<div class="cont_overlay" id="div_LocalPrice"><div class="changestore"><a href="javascript:;" title="Close" class="closeWin"> close <img src="'+imagePath+'img/btn/btn_close.gif"></a><br><p>'+settings.staticContent+'</p></div></div>');
				}
				else{
					$('#DHTMLcontent').empty().append('<div class="cont_overlay" id="div_feedback"><div class="changestore"><a href="javascript:;" title="Close" class="closeWin"> close <img src="'+imagePath+'img/btn/btn_close.gif"></a><br><p>'+settings.staticContent+'</p></div></div>');
				}	
				/* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- START */
				if(typeof imagePath!='undefined' && imagePath!=null && imagePath!="") {
					$('.closeWin').css({height:'12px',width:'48px',position:'absolute',top:'5px',right:'5px',background:'url('+imagePath+'img/close-pref.gif) no-repeat', zIndex: '999999'});
				} else {
					$('.closeWin').css({height:'12px',width:'48px',position:'absolute',top:'5px',right:'5px',background:'url(../img/close-pref.gif) no-repeat', zIndex: '999999'});
				}
				/* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- END */
						
				
				$('#DHTMLcontent').find(settings.contentname).width(settings.windowWidth);
				$('#DHTMLcontent').find(settings.contentname).height(settings.windowHeight);
				if(!$.browser.msie){
					$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
				}
				else{
				$('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
				}
				if(!$.browser.msie){
					$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
				}
				else{
				$('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
				}		
				$('#DHTMLwrap').add('#DHTMLcontent').show('fast');
				$('.closeWin').click(function(){
					$('#DHTMLwrap').add('#DHTMLcontent').fadeOut('fast',function(){
						$(this).remove();
					});
				});
			}
	}
}
$.fn.dynamicPopup = function(settings) {
	var settings = $.extend({
		filename: 'default.html',
		contentname: '#popup',
		windowWidth: '300px',
		windowHeight: '100px',
		jsonFlag: false,
		dynamicContent:true,
		staticContent:''
	},settings);
	
	return this.each(function(){
		$(this).click(function(e){
			dynpop.ini(e, settings)
		});
		//return false; <--- This was causing multiple instances to fail.
	});
}


$.fn.dynamicMouseOver = function(settings) {
	var settings = $.extend({
		filename: 'default.html',
		contentname: '#popup',
		windowWidth: '300px',
		windowHeight: '100px',
		jsonFlag: false,
		dynamicContent:true,
		staticContent:''
	},settings);
	
	return this.each(function(){
		$(this).mouseover(function(e){					   
			var newE = { pageX: e.pageX + 5, pageY: e.pageY + 5 }
			dynpop.ini(newE, settings);
		}).mouseout(function(){
			var t = setTimeout("$('#DHTMLwrap').add('#DHTMLcontent').fadeOut('fast',function(){$(this).remove();});", 1500);
			$(this).mouseover(function(){ clearTimeout(t); });
			$('#DHTMLcontent').hover(function(){ clearTimeout(t); },
									function() { $('#DHTMLwrap').add('#DHTMLcontent').fadeOut('fast',function(){$(this).remove();}); 			
		});
	});
	});
}
/* DHTML POP-UP PLUG-IN  - Ends Here */
if (typeof dynamicPopupPath != 'undefined' && "" != dynamicPopupPath){
	if($('div.preOrderSelect a').length >0){
	$(function(){$('div.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
	}
	if($('a.preOrderLink').length >0){	
	$(function(){$('a.preOrderLink').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
}
}

/*
* Functionality: Used for display of review in product page
* Applicable : Sears, Kmart, Kenmore
* Method - STARTS HERE
*/

//Moved from shared/js/reviews.js
function rObj(name) {
 var obj = document.getElementById(name);
 return obj;
}

function disObjBlk (objBlk,show){
	if(typeof objBlk == "object"){
		if(show) objBlk.style.display="block";
		         
		else	objBlk.style.display="none";
	}
}

function searsAjax( url, opt) 
{ 
     
      var req = null; 
      var onSuccess = opt.onSuccess;
      var onFailure = opt.onFailure;

      if (window.XMLHttpRequest) 
      {
                  req = new XMLHttpRequest();
            if (req)
            {
                  
                        req.onreadystatechange = processReqChange;
                        req.open(opt.method, url, opt.asynchronous);
                        req.send(null);
            }
     }
      else if (window.ActiveXObject) 
      {
                  req = new ActiveXObject("Microsoft.XMLHTTP");
                  if (req) 
            {
                  
                        req.onreadystatechange = processReqChange;
                        req.open(opt.method, url, opt.asynchronous);
                        req.send();
            }
      } 
      if (!req) return;

      function processReqChange() {
            if (req.readyState == 4) {
                  if (req.status == 200) {
                        
                              onSuccess(req);
                  } 
                  else {
                        
                        onFailure(req);
                  }
            }
      };
}

/* Method - ENDS HERE */


/*
* Functionality: Used for Email Check of AskNAnswer 
* Applicable : Sears, Kmart, Kenmore
* Method - STARTS HERE
*/

//Moved from shared/js/askNAnswer.js
function checkEmailChar(temail) {
var length = temail.length;

	for(iLoop=0;iLoop<length;iLoop++){
		if((temail.charCodeAt(iLoop)>= 33 && temail.charCodeAt(iLoop)<= 41) || ( temail.charCodeAt(iLoop)>= 58 && temail.charCodeAt(iLoop)<= 63) ){
			
			return false;
		}
	}
return true;
}

/* Method - ENDS HERE */


/*
* Functionality: Used for display of review in product page
* Applicable : Sears, Kmart, Kenmore
* Method - STARTS HERE
*/

//Moved from shared/js/productpage/ProductPage.js
function BVcheckLoadStateRdNew(){
    if(!BVisLoaded){
        rObj('BVFrame').src="";
        var page = rObj('BVFrame').src;
        rObj('BVFrame').src=rvInfo;
        rObj('BVReviewsContainer').innerHTML = "Product Reviews Currently Unavailable";
    }
}

/* Method - ENDS HERE */


/* Methods for Great Price - Starts Here 

function greatPrice(def) {
    if(!document.createElement) return false;
    var defDiv = document.createElement("div");
    document.body.appendChild(defDiv);
    defDiv.id = 'greatPrice';
    defDiv.className = 'floatWindow';
    defDiv.innerHTML = "<p onclick='remove(this.parentNode);'><a href='javascript:;' class='closeWindow'>Close</a></p><br clear='all'>" + "<p>" + def + "</p>";
    defDiv.style.top = yPos - defDiv.offsetHeight - 25 + "px";
    defDiv.style.left = xPos - defDiv.offsetWidth + 135 + "px";
}

function prepareGreatPrice() {
    if(!document.getElementsByTagName) return false;
    var links = document.getElementsByTagName("a");
    for (var i=0; i<links.length; i++) {
        if (links[i].className == "greatPrice"){
            links[i].onclick = function() {
                if(!document.getElementById("greatPrice")) {
                    findPos(this);
                    greatPrice(this.getAttribute("info"));
                } else {
                    var details = document.getElementById("greatPrice")
                    document.body.removeChild(details);
                    findPos(this);
                    greatPrice(this.getAttribute("info"));
                }
            }
        }
    }
}
addLoadEvent(prepareGreatPrice);*/

$(document).ready(function($){
 $("a.greatPrice").click(function () {
	  var offset = $(this).offset();
	  if(document.getElementById("greatPrice")){
	  	 document.body.removeChild(document.getElementById("greatPrice"));
	  }
	  var defDiv = document.createElement("div");
   	  document.body.appendChild(defDiv);
      defDiv.id = 'greatPrice';
      defDiv.className = 'floatWindow';
   	  defDiv.innerHTML = "<p onclick='remove(this.parentNode);'><a href='javascript:;' class='closeWindow'>Close</a></p><br clear='all'>" + "<p>" + this.getAttribute('info')+ "</p>";
   	  defDiv.style.top = offset.top - defDiv.offsetHeight - 25 + "px";
   	  defDiv.style.left = offset.left - defDiv.offsetWidth + 250 + "px";
    });
});

/* Methods for Great Price - Ends Here */

function ajaxCallForShopCart(catEntryId,orderItemId,zipCode) {
	
	var catalogId = document.ShopCartForm.catalogId.value;
	var storeId = document.ShopCartForm.ajaxStoreId.value;
	
	var prodOptionZipOpt = {
    method: 'GET',
  	asynchronous: true,
  	postBody: '',
 	//Handle successful response
   	onSuccess: function(t) {
   		var response = t.responseXML.documentElement;
        var paEntries = response.getElementsByTagName('PAPrices');
        //alert("Length of PAEntries"+paEntries.length);
        for (var i = 0; i < paEntries.length; i++) {
            var paId = paEntries[i].getElementsByTagName('PACatEntryId')[0].childNodes[0].nodeValue;
            var paPrice = paEntries[i].getElementsByTagName('Price')[0].firstChild.data;
            var paPriceDivElm = 'pa_price_'+paId+'_'+orderItemId;
            var paPriceDiv = document.getElementById(paPriceDivElm);
            paPriceDiv.innerHTML = "$"+formatCurrency(paPrice);
        }
        //document.getElementById("item_"+orderItemId+"_protectionAgreements_table").style.display='block';
    },
        // Handle other errors
	    onFailure: function(t) {
        showBox('errorBox');
        var err1 = document.getElementById("error1");
        err1.innerHTML="Error processing your request, please try again later.";
    	}
	};  // end of global var prodOptionZipOpt

    	var url = "GetProductOptionPrices?storeId="+storeId+"&catalogId="+catalogId+"&zipCode="+zipCode+"&parentCatId="+catEntryId;
    	new searsAjax(url, prodOptionZipOpt);	
    	
    	
	
}

// Function to update Mini Cart Display when items deleted from cart through Ajax call.
function updateMiniCartDisplay(totalQuantity,totalPrice){
	totalPrice= formatCurrencyCheck(totalPrice);
	document.getElementById("items").innerHTML = totalQuantity;
	document.getElementById("miniCartTotal").innerHTML = "$"+totalPrice;
}

// Function to update Mini Cart Display and Link when items added to cart through Ajax call. Link is updated to handle changes for empty cart.
function updateMiniCartDisplayLink(totalQuantity,totalPrice){
	updateMiniCartDisplay(totalQuantity,totalPrice);
	document.getElementById("miniCartLink").href = document.getElementById("miniCartURL").value;
}

   function specialOffers(activeTab,storeId,catalogId,catentryId) {    
        var rebateSpecialOffers= document.createElement("div");
		document.body.appendChild(rebateSpecialOffers);
		omnDeals(activeTab);
        rebateSpecialOffers.id = 'rebateSpecialOffers'; 
        var isSaveForLater;
        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }        
        var specialOfferView;
        
        
        if($('body').attr('id')=='checkout'||((null != isSaveForLater) &&(isSaveForLater == 'YES'))){
        		specialOfferView = 'BrowseSpecialOfferViewHttps' ; 
        } 
        else{          
                specialOfferView = 'BrowseSpecialOfferView' ; 
        }
        
        curtainOverlay({trans:'0.0',ajaxmodal:true,fade:false,closeonclick:true,ajaxclass:'rebateSpecialOffers',persistmodal:true});
        var rebateSpecialOffers = $('.rebateSpecialOffers');  
        var rebateMessageCSS = '<link rel="stylesheet" type="text/css" media="all" href="'+imagePath+'css/rebateMessage.css">';
        var printCSS = '<link rel="stylesheet" type="text/css" media="print" href="'+imagePath+'css/rebates_print.css">';
        $(rebateMessageCSS).appendTo('head');
        $(printCSS).appendTo('head');      
        $.ajax({
                url: ''+specialOfferView+'?storeId='+storeId+'&activeTab='+activeTab+'&catalogId='+catalogId+'&catentryId='+catentryId,
                
                success: function(data){                    
                    $(rebateSpecialOffers).html(data);
                    $('#ajaxmodal').bgiframe().centerOnScreen();
                    
                    $(rebateSpecialOffers).show();
                    $('#curtain').add('#closeWinDeals').unbind().click(function(){
                    	$('head link[@href *= "rebates_print.css"]').remove();	
                        curtainOverlay({closing:true});
                        $('div#rebateSpecialOffers').remove();
                    });
                    
                    rebates_tabs(); 
                    rebateTabDisp();
                    splFinTabDisp();            
                    scrollSize();
                    detailView();
                    expandOffers();
                }
        }); 
    }

    function omnDeals(activeTab){
   	
		if(activeTab == 'splOffr'){
			omPrefix = 'Special Offer > Deals Popup';
		}
		if(activeTab == 'splFin'){
			omPrefix = 'Special Financing > Deals Popup';
		}
		if(activeTab == 'rebateDet'){
			omPrefix = 'Rebate > Deals Popup';
		}
		if(activeTab == 'siteWide'){
			omPrefix = 'Site Wide > Deals Popup';
		}
		s.tl();
		
    }
    
  function rebateTabDisp(){
    var tabStatus = $('#intTab3_content').attr('class');
    if (tabStatus == 'visible'){
        mailInRebateAjax();
    }
  }
  
  function splFinTabDisp(){
    var tabStatus = $('div#intTab2_content').attr('class');
    if (tabStatus == 'visible'){
        splFinanceAjax('splFinanceTab');
    }
  }
    
  function mailInRebateAjax(){
     if ( $('input#mailInRebPres').attr('value') == 'mailInRebatePresent'){
        var rebateIds = $('input#rebateContent').attr('value');
        var frmDealsPopUp = 'frmDealsPopUp';
        var isSaveForLater;
        var rebateDetailsView;
        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }
        
        if($('body').attr('id')=='checkout'||((null != isSaveForLater) &&(isSaveForLater == 'YES'))){
        		rebateDetailsView = 'RebateDetailsCmdSecure' ; 
        }
        else{
        		rebateDetailsView = 'RebateDetailsCmd';
        }
        
        $.ajax({
                url: ''+rebateDetailsView+'?storeId='+storeId+'&RebateId='+rebateIds+'&dealsPopUp='+frmDealsPopUp,
                type:'GET',
                success: function(data){                    
                    $('#pForm').html(data);
                    $('#pForm').show();                 
                }
        }); 
            
    }       
  }
  
    function splFinanceAjax(tabSelected){
    
	 if ( $('input#splFinPres').attr('value') == 'splFinPresent'){
     
	 $('input#splFinPres').attr('value','splFinLoaded') ;
        var storeIdFin  = $('input#splFinStoreId').attr('value');
        var catalogIdFin = $('input#splFinCatalogId').attr('value');
        var langIdFin = $('input#splFinLangId').attr('value');
        var catalogIndFin = $('input#splFinCatalogInd').attr('value');
        var vNameFin = $('input#splFinVName').attr('value');
        var dzName = $('input#dzName').attr('value');
        var isSaveForLater;
        var browseStaticView;
        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }
        
        if($('body').attr('id')=='checkout'||((null != isSaveForLater) &&(isSaveForLater == 'YES'))){
        		browseStaticView = 'BrowseStaticPageCmdSecure' ; 
        }
        else {
        		browseStaticView = 'BrowseStaticPageCmd' ; 
        }
        
        
        $.ajax({
                url: ''+browseStaticView+'?storeId='+storeIdFin+'&catalogId='+catalogIdFin+'&langId='+langIdFin+'&catalogInd='+catalogIndFin+'&vName='+vNameFin+'&dzName='+dzName,
                type:'GET',
                success: function(data){    
				$('#splFinDet').html(data);
				$('#splFinDetails').append(data);
				$('#splFinDetails').show();
					if(tabSelected == 'splOfferTab'){				
						$('#splFinDet').show();		
					}
					$('#splFinDetails').css({height:307});				
                }
        }); 
            
    }   
        
  }
  
  function rebates_tabs(){
    
    var tabLink = $('#dTabs li a');
    $(tabLink).unbind().click(
        function(){
        //the tabs 
            var tab_li_id_string = $(this).parent().attr('id');
            var tab_li_id = '#' + tab_li_id_string;
            var tab_li_siblings = $(tab_li_id).siblings();
        //The content wrappers
            var div_id = tab_li_id + '_content';
            var div_siblings = $(div_id).siblings();
        
        //Turning the tabs Active & Inactive
            $(tab_li_siblings).removeClass('active');
            $(tab_li_id).addClass('active');
            
        //If you clicked on a tab make the correct content area visible
            if ($(tab_li_id)) {
                $(div_siblings).removeClass('visible').addClass('notVisible');
                $(div_id).removeClass('notVisible').addClass('visible');
            }
        }
    );
}

function scrollSize (){
    if ($('#intTab1_content img.adImg').length == 0){
        $('#intTab1_content div.offerScroll').css({height:307});
    };
}



function detailView(){
    $('.detailHd').addClass('closed');
    $('a.showDetails').click(function(){
        if($(this).parent().hasClass('closed')){
            $(this).parent('.detailHd').removeClass('closed').addClass('open');
            $(this).text('Hide Details');
            $(this).parent().next('.details').fadeIn('fast');
        }
        else {
            $(this).parent('.detailHd').removeClass('open').addClass('closed');
            $(this).text('See Details');
            $(this).parent().next('.details').fadeOut('fast');
        }
        
    });
}

function rebateDisp(){
    mailInRebateAjax();
    $('#intTab1_content').removeClass('visible').addClass('notVisible');
    $('#intTab1').removeClass('active');
    $('#intTab3_content').removeClass('notVisible').addClass('visible');
    $('#intTab3').addClass('active');
}


$(function(){
	if($('div#dealData div.offerScroll p').length > 0){
	var	rebateDetailsTabTurn = $('div#dealData div.offerScroll p a[@title = "Rebate Details"]');
	rebateDetailsTabTurn.click(function(){
		$('ul#tabs li a[@title = "Rebate Details"]').click();
	});
	}	
});

$(function(){
//IE6 Browser Caching issue.
      try {
            document.execCommand("BackgroundImageCache", false, true);
      }catch(err) {}
});

function LTrim( value ) {
	 
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1"); 
 
	
}

function RTrim( value ) {
 	 
	var re = /((\s*\S+)*)\s*/;
	 return value.replace(re, "$1"); 
 
	
}

function trimStr( value ) {
	
	return LTrim(RTrim(value));
	
}

if (typeof  Sears == 'undefined'){
	var Sears = {
		showHideRecentlyView: function(e){
			if(e)
				$("#recentlyView").fadeIn("slow");
			else 
				$("#recentlyView").fadeOut("slow");
		}	
	};
}

function bindEventsForRR(){
	//Binding Map price and Great price events to RR products
	$("a.mapLink").click(function(){mapClick(this)});
	$("a.greatPrice").click(function () {
	      var offset = $(this).offset();
	      if(document.getElementById("greatPrice")){
	         document.body.removeChild(document.getElementById("greatPrice"));
	      }
	      var defDiv = document.createElement("div");
	      document.body.appendChild(defDiv);
	      defDiv.id = 'greatPrice';
	      defDiv.className = 'floatWindow';
	      defDiv.innerHTML = "<p onclick='remove(this.parentNode);'><a href='javascript:;' class='closeWindow'>Close</a></p><br clear='all'>" + "<p>" + this.getAttribute('info')+ "</p>";
	      defDiv.style.top = offset.top - defDiv.offsetHeight - 25 + "px";
	      defDiv.style.left = offset.left - defDiv.offsetWidth + 200 + "px";
    });

}

/* Cross Format Regional Avail Functions */
var regionalDiv = "";
var currentPartNo = "";
var dbFlagVal = "";
var catentryVal = "";
var pageFlag = "";
var qvDiv= "";
var repaintedZipCode = "";
var atcZipCode = "";
var CAPopUpFlag = true;
// Function to check whether zipcode cookie is present or not
function fnChkZipCode(){
	if($.cookie("zipCode")==null && $.cookie("zipCode"+getStoreId())==null){
		return false;
	}
	else {
		return true;
	}
}

function getRegDelZip(){
	var zipCode = '';
	if($.cookie('zipCode')!=null){
		zipCode = $.cookie('zipCode');
	}
	else if($.cookie('zipCode'+getStoreId())!=null){
		zipCode = $.cookie('zipCode'+getStoreId());
	}
	return zipCode;
}

function getRegPickZip(){
	var zipCode = '';
	if($.cookie('zipCode'+getStoreId())!=null){
		zipCode = $.cookie('zipCode'+getStoreId());
}
	else if($.cookie('zipCode')!=null){
		zipCode = $.cookie('zipCode');
	}
	return zipCode;
}

function setRegZip(zipCode,zipType){
	var cookieName = '';
	if(zipType=='storepu'){
		cookieName = 'zipCode'+getStoreId();
		if($.cookie('zipCode')==null){
			cookieNameDel = 'zipCode';
			$.cookie(cookieNameDel,zipCode);
		}
	} else {
		cookieName = 'zipCode';
		if($.cookie('zipCode'+getStoreId())==null){
			cookieNameSPU = 'zipCode'+getStoreId();
			$.cookie(cookieNameSPU,zipCode);
		}
	}
	$.cookie(cookieName,zipCode);
}

// Function to check whether the entered zipcode is correct or not
function checkRegionalZip()	{
  regionalZip = $('#availPopup div:visible #zipCode').val();
  var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
  var passed = lv_pattern.test(regionalZip); 
  if (!passed) {
        showErrorMsg();
    return false;
  }
  else {
    return true;
  }
}


function showErrorMsg()
{
		var validatePopup = "<div id='validatePopup' class='validatePopup'>"
							+"<h3>Enter Zip Code</h3>\n"
							+"<h2>Please enter a valid 5-digit ZIP code (example: 60515).</h2>"
							+"\n\n<input type='submit' name='ok' value='OK' onclick='remove(this.parentNode);' style='margin-bottom:10px'>\n";
		$('body').append(validatePopup);
		$('#validatePopup').centerOnScreen();
}

//inserted code ends
// variable for getting zip code on page load
var zipOnLoad = '';
function regionalAvlMain(pageFlag,dbFlagVal,catentryVal)	{

	// for loading image		
	$('.standardDiv input#checkZip').css({display: "none"});
	$('.errorDiv input#checkZip').css({display: "none"});
	$('.standardDiv #loadGif').css({display: "inline"});
	$('.errorDiv #loadGif').css({display: "inline"});
	var qvCheck=false;
	
	if($("input#qvPickUpFlag")){
		var qvPickupFlag= $("input#qvPickUpFlag").attr("value");
		if(qvPickupFlag =='1'){
			qvCheck=true;
		}
	}
	/* perform actions for product page */	
  	if(pageFlag == "PRD" )	{
  		
  		/* perform actions on click of pick up link */
	  	if(regionalDiv == "storepu" ) {
		  		storeLocator();
	  	}
  		/* perform actions on click of delivery link */	  	
	  	else {
	  		
			if(zipOnLoad == '')	{
				// ajax call for add to cart + delivery
				if(atcDelFlag)	{
		  			makeRegionalDeliveryCall(pageFlag, dbFlagVal, catentryVal, "");
		  		}
		  		// ajax call for on click of delivery
		  		else	{
		  			makeRegionalDeliveryCall(pageFlag, dbFlagVal, catentryVal, "");		  		
					// Make RTI call if pick up enabled
		  			if(pickUpVar == '1') {
					makeRegionalRTICall();
				}
			}
			}
			else	{
				makeRegionalDeliveryCall(pageFlag, dbFlagVal, catentryVal, "");				
			}
	  	}
	}
	/* perform actions for subcat page */	
  	else {
  		if((qvDiv == "checkAvailSpu" || qvCheck) && qvDiv != "checkAvailDel"){
			$('#availPopup').remove();
			if(qvDiv == "checkAvailSpu"){
				fnRegionalStorePickUpQV(currentPartNo);
			}else if(qvCheck){
		  		storeLocator();
		  	}
		}else if(regionalDiv == "storepu") {
			$('#availPopup').remove();
	  		fnRegionalStorePickUp(currentPartNo);
		} else	{
  			fnRegDeliveryAvlAjax(pageFlag,dbFlagVal,catentryVal);
		}
  	}
}
$(document).ready(function() {
  readyOnLoad();
});

function readyOnLoad(){
		$('a.checkAvail, a.changeZip').click(function(e){
		$('#availPopup').remove();
		ATCFailureFlg= false;
		CAPopUpFlag= true;
		var showFlag = true;
		var regionalInfoArray = "";
		zipType = "";
		regionalDiv = $(this).parent().attr("class");
		qvDiv = $(this).attr("id");
	    var regionalInfo = this.getAttribute('info');
	    regionalInfoArray = regionalInfo.split("^");
	    if(typeof regionalDiv != 'undefined'){
		    currentPartNo = regionalInfoArray[0];
		    dbFlagVal = regionalInfoArray[1];
		    pageFlag = regionalInfoArray[2];
		    catentryVal = regionalInfoArray[3];
		}
		if((pageFlag == 'PRD' || pageFlag == 'CAT' || pageFlag == 'COM') && (regionalDiv == 'storepu' || qvDiv == 'checkAvailSpu')){
	   	zipOnLoad = getCookie('zipCode'+getStoreId());
	   		zipType = 'storepu';
	   	} else {
	   		zipOnLoad = getCookie('zipCode');
	   		zipType = 'delivery';
	   	}
	  	var div ="<div id='availPopup' class='availPopup'><div class='standardDiv'><h2>Check Availability</h2><a href='javascript:;\' class='closeAvail'>Close</a>"
				+"<p><span>See What\'s in Stock</span>We need a little more info to check this item\'s local availability.<br/>"
				+"Enter your zip.</p><p><label for='zipCode'>Enter ZIP Code: </label><input type='text' id='zipCode' value='"+fnSpuZip()+"' maxlength='5' size='5'/>"
				+"<input type='image' value='Check Availability' id='checkZip' src='"+imagePath+"img/buttons/btn_check_availability.gif' onClick='if(checkRegionalZip()){setRegZip(regionalZip,zipType);regionalAvlMain(pageFlag,dbFlagVal,catentryVal);}'/>"
				+"<img height='16' width='16' alt='loading...' src='"+imagePath+"img/loadingSmall.gif' id='loadGif' style='display: none;'/></p>"
				+"</div>"
				+"<div style='display: none;' class='errorDiv'><h2>Check Availability</h2><a href='javascript:;' class='closeAvail'>Close</a>"
				+"<p class='error'>This product doesn\'t seem to be available for Delivery in the ZIP Code you\'ve entered.</p><p>Some product availability is based on region, so this product may not be available in your area.</p>"
				+"<p><label for='zipCode'>Check another ZIP Code for Delivery: </label><input type='text' id='zipCode' maxlength='5' size='5'/>"
				+"<input type='image' value='Check Availability' id='checkZip' src='"+imagePath+"img/buttons/btn_check_availability.gif' onClick='if(checkRegionalZip()){setRegZip(regionalZip,zipType);regionalAvlMain(pageFlag,dbFlagVal,catentryVal);}'/>"
				+"<img height='16' width='16' alt='loading...' src='"+imagePath+"img/loadingSmall.gif' id='loadGif' style='display: none;'/>"
				+"</p>"
				+"</div>"
				+"</div>";	
					
		 if((regionalDiv == 'storepu') && (pageFlag == 'PRD')){
		 	var pickAvl = $(this).attr("class");
		    if(pickAvl != 'checkAvail'){
			  		//	when user lands on the page with zip code entered don't display CA POP Directly go to STORE GRID page
					storeLocator();
					showFlag = false;
			  		$('#availPopup').remove();
		  	}
		  }
	  	if(showFlag == true){
			$('body').append(div);
		  	$('#tip').remove();
		  	$('#availPopup').css({top: e.pageY -100, left: (((e.pageX - 320) < 0 ) ? 0 :(e.pageX - 320))});
		  	$('#availPopup .closeAvail').click(function(){
		  	$('#availPopup').remove();
		  	});
		 }
		 $('a#popupPickup').click(function(e){
		 	$.cookie('zipCode'+getStoreId(),getRegDelZip());
	 	 	if(pageFlag == 'PRD')	{
	 	 		storeLocator();
	 	 	}
	 	 	else if(pageFlag == 'CAT' && qvDiv == 'checkAvailSpu'){
	  	 		fnRegionalStorePickUpQV(currentPartNo);
	  		}else{
	 	 		fnRegionalStorePickUp(currentPartNo);
	 		}
	  });
	  });
	  $('a.changeZip').hover(function(e){
	  	var tip = '<div id="tip">Change your ZIP Code by clicking this link.</div>';
	  	$('body').append(tip);
	  	$('#tip').css({top: e.pageY + 10, left: e.pageX - 80});
	  },function(){
	  	$('#tip').remove();
	  });
}
// Function to return a zipcode when check availabilty link of Spu item is clicked
function fnSpuZip(){
	var zipValue = "";
	if((pageFlag == "CAT" || pageFlag == "COM") && fnChkZipCode()){
		if((regionalDiv == "storepu") || (qvDiv == 'checkAvailSpu')){
			zipValue=getRegPickZip();
		}
		else {
			zipValue=getRegDelZip();
	}
		}
	else if( pageFlag == "PRD"){
		if(regionalDiv == "storepu" && fnChkZipCode()){
			
			zipValue=getRegPickZip();
			
		} else if(fnChkZipCode()){
		
			zipValue=getRegDelZip();
	  }
		}
	
	return zipValue;		
}
var atcDelFlag = false;
// Function call on click of addtocart button in subcat page
var showCAPopUp = function(){
		$('#availPopup').remove();
	   		fnPopUp();
}
function fnPopUp(){
		zipType = '';
		if((pageFlag == 'PRD' || pageFlag == 'CAT' || pageFlag == 'COM') && regionalDiv == 'storepu'){
	   	zipOnLoad = getCookie('zipCode'+getStoreId());
	   		zipType = 'storepu';
	   	} else {
	   		zipOnLoad = getCookie('zipCode');
	   		zipType = 'delivery';
	   	}
	   	CAPopUpFlag = false;
	   	// Removed the pick up message from Error pop up, for Kmart.
      	var div ="<div id='availPopup' class='availPopup' style='display: none;'><div style='display: none;' class='standardDiv'><h2>Check Availability</h2><a href='javascript:;\' class='closeAvail'>Close</a>"
	 			+"<p><span>See What\'s in Stock</span>We need a little more info to check this item\'s local availability.<br/>"
				+"Enter your zip.</p><p><label for='zipCode'>Enter ZIP Code: </label><input type='text' id='zipCode' value='"+fnSpuZip()+"' maxlength='5' size='5'/>"
				+"<input type='image' value='Check Availability' id='checkZip' src='"+imagePath+"img/buttons/btn_check_availability.gif' onClick='if(checkRegionalZip()){setRegZip(regionalZip,zipType);regionalAvlMain(pageFlag,dbFlagVal,catentryVal);}'/>"
				+"<img height='16' width='16' alt='loading...' src='"+imagePath+"img/loadingSmall.gif' id='loadGif' style='display: none;'/></p>"
				+"</div>"
				+"<div style='display: none;' class='errorDiv'><h2>Check Availability</h2><a href='javascript:;' class='closeAvail' id='closeAvail'>Close</a>"
				+"<p class='error'>This product doesn\'t seem to be available for Delivery in the ZIP Code you\'ve entered.</p><p>Some product availability is based on region, so this product may not be available in your area.</p>"
				+"<p><label for='zipCode'>Check another ZIP Code for Delivery: </label><input type='text' id='zipCode' maxlength='5' size='5'/>"
				+"<input type='image' value='Check Availability' id='checkZip' src='"+imagePath+"img/buttons/btn_check_availability.gif' onClick='if(checkRegionalZip()){setRegZip(regionalZip,zipType);regionalAvlMain(pageFlag,dbFlagVal,catentryVal);}'/>"
				+"<img height='16' width='16' alt='loading...' src='"+imagePath+"img/loadingSmall.gif' id='loadGif' style='display: none;'/>"
				+"</p>"
				+"</div>"
				+"</div>";
	  	$('body').append(div);
	  	
	  	// On click of close button of error popup repainting the entire subcat page
		if((pageFlag == 'CAT') || (pageFlag == 'COM'))	{
	  	$('#availPopup #closeAvail').click(function(){
	  		ATCFailureFlg= false;
	  		if(atcZipCode != repaintedZipCode){
			fnRegDeliveryAvlAjax(pageFlag,'Y',catentryVal);
			}
	  		$('#availPopup').remove();
	  	});
		 }
	  	
	  	$('#availPopup .closeAvail').click(function(){
	  		if(pageFlag == 'PRD')	{
	  			// initializing back to false on close of CA Pop up
	  			atcDelFlag = false;
	  		}
	  		$('#availPopup').remove();
	  	});
	  	$('a#popupPickup').click(function(e){
	  		$.cookie('zipCode'+getStoreId(),getRegDelZip());
	 	 	if(pageFlag == 'PRD')	{
	 	 		storeLocator();
	 	 	}
	 	 	else if(pageFlag == 'CAT' && qvDiv == 'checkAvailSpu'){
	  	 		fnRegionalStorePickUpQV(currentPartNo);
	  		}else{
	 	 		fnRegionalStorePickUp(currentPartNo);
	 		}
	  	});
}
// Global variable to maintain 'availability check' progress info for add to cart in subcat page.
// 'NA':: Not started,
// 'IP': In Progress ,
// 'CPIN': Completed and Instock, 
// 'CPOUT': Completed and Out of stock
var ddcAvlCheck = "NA";


/* Ajax call function for regional availability of delivery products. 
* Apart from the input variables, this function uses a global variable DDItemList, 
* which is | separated list of item level Partnumbers.
* 
* pageInd = "cat" or "prd" based on call made from subcat page or product page.
* dbFlag = Y or N indicating DB call or SCIM Call
* catentryId = parent catentry Id, Needed only if its a SCIM call
*/
function fnRegDeliveryAvlAjax(pageInd,dbFlag,catentryId){
	var zipCode = getRegDelZip();
	var catentryIdVal=catentryId;
	//Getting the sears storeId from the javascript variable, initialized in SubcategoryDynaHeader.jsp & CompareBody.jsp.
	var storeId = regionalAvlStrId;
	if(DDItemList != null && DDItemList != ""){
		if (dbFlag == "Y"){
			var dbInput = DDItemList;
			if(ATCFailureFlg){
				dbInput = currentPartNo;
			}
			//remoteUrl = 'RegionalAvailCmd?pageInd='+pageInd+'&dbFlag='+dbFlag+'&catEntryId='+catentryId+'&zipCode='+zipCode+'&storeId='+storeId;
			//request = $.post(remoteUrl,{DDItemList: dbInput},fnDeliveryAvailResponse,"json");  
		        var dbCall = { 
		        success: fnDeliveryAvailResponse,
				url:'RegionalAvailCmd?pageInd='+pageInd+'&dbFlag='+dbFlag+'&catEntryId='+catentryId+'&zipCode='+zipCode+'&storeId='+storeId,
		        type:'POST',
		        data: {DDItemList: dbInput},
		        dataType:'json',
		        error: errorFnDeliveryAvailResponse
	     	};
			request=$.ajax(dbCall);
		        
		        
		}else if (dbFlag == "N"){
			
			var ndd = "1";
			var scimStoreId = "09300";
			var quant = "1";
			var deliveryStore = "09300";
			//remoteUrl = 'RegionalAvailCmd?pageInd='+pageInd+'&dbFlag='+dbFlag+'&storeId='+strId+'&ndd='+ndd+'&zipCode='+zipCode+'&catEntryId='+catentryIdVal+'&scimStoreId='+scimStoreId+'&deliveryStore='+deliveryStore+'&quantity='+quant+'&storeId='+storeId;
			//request = $.post(remoteUrl,{DDItemList: currentPartNo},fnDeliveryAddToCartResponse); 
			
			var scimCall = { 
		        success: fnDeliveryAddToCartResponse,
				url:'RegionalAvailCmd?pageInd='+pageInd+'&dbFlag='+dbFlag+'&storeId='+storeId+'&ndd='+ndd+'&zipCode='+zipCode+'&catEntryId='+catentryIdVal+'&scimStoreId='+scimStoreId+'&deliveryStore='+deliveryStore+'&quantity='+quant,
		        type:'POST',
		        data: {DDItemList: currentPartNo},
		        error: errorFnDeliveryAvailResponse
	     	};
			request=$.ajax(scimCall);
		}
	}
}
function errorFnDeliveryAvailResponse(){
	$('div#availPopup').remove();
	ddcAvlCheck = 'NA';
	}

// This function is called when the DB ajax call is completed
function fnDeliveryAvailResponse(jsonResponse){
    var regavail = jsonResponse.jsonRegionalAvail;   
    var partNoLen=regavail.pco;
    var inStockMsg=regavail.ddcInstk;
    var outStockMsg=regavail.ddcOutstk;
	var partNumArr = new Array(); 
	var avlMsg = "";
    if(fnChkZipCode() && typeof regavail != 'undefined'){
    	for(var availCnt=0;availCnt<partNoLen;availCnt++){
    		var partNum=regavail.regAvailList[availCnt].pn;
			var availMsg =regavail.regAvailList[availCnt].msg;
			if(availMsg == "InStock"){
				avlMsg = inStockMsg;
			}
			else if(availMsg == ""){
				avlMsg = inStockMsg;
					if(ATCFailureFlg){
						availMsg = "InStock";
					}
			}
			else{
				avlMsg=outStockMsg;
			}
			availValues.Set(partNum, avlMsg);
			partNumArr[partNumArr.length] = partNum;
			if(currentPartNo == partNum){
				// If the current item is in stock then close the pop up
				if(availMsg=="InStock"){
					$('div#availPopup').remove();
					if(ATCFailureFlg){
						if(pageFlag == 'CAT'){
							addItemPartNo(DDCPartNoVal,DDCSiVal,DDCSpiVal,DDCSriVAl,DDCDffVal,DDCVendorVal,DDCStDateVal);
						}
						else if(pageFlag == 'COM'){
							var compareATCUrl;
							$('div.col_1').find('a#DDCAtcCom_'+currentPartNo).each(function(i){
							var ddcAtcInfo = $(this).attr('info');
							var atcInfoArray = ddcAtcInfo.split("^");
							compareATCUrl = atcInfoArray[4];
							});
							submitCart(compareATCUrl);
						}
					}
				}
				// If the clicked item is out of stock then showing the error popup
				else if(availMsg == ""){
					$('div#availPopup').remove();
				}
				else{	
					//$('#availPopup div:visible #zipCode').val() = "";
					//'#loadGif').remove();
					$('#availPopup').css({display: "block"});
					$('#availPopup .standardDiv').css({display: "none"});
					$('#availPopup .errorDiv').css({display: "block"});
					$('.errorDiv input#checkZip').css({display: "inline"});
  					$('.standardDiv #loadGif').css({display: "none"});
  					$('.errorDiv #loadGif').css({display: "none"});
					if(ATCFailureFlg){
						if((pageFlag == 'CAT') || (pageFlag == 'COM')){
							atcZipCode = getRegDelZip();
						}
						return false;
					}
				}
			}
		}	
		//Repainting QuickView is function call is from QuickView
		if(flagQV == 'Y'){
			availMsg=availValues.Get(qvPartnumber);
			if(availMsg == regavail.ddcInstk){
				$('div#availPopup').remove();
			}
			else{
				$('#availPopup').css({display: "block"});
				$('#availPopup .standardDiv').css({display: "none"});
				$('#availPopup .errorDiv').css({display: "block"});
			}
			
			$('div#availability').find('span.delivery').html(availMsg+' '+getRegDelZip()+'<a id="checkAvailDel" class="checkAvail" href="javascript:;" rel="regionalAvailability" info='+partnumber+'^Y^'+pageFlag+'^'+itemCatentryVal+'>Change ZIP Code</a>');
		}
	}	
	$('#availPopup .standardDiv').css({display: "none"});
	// Repainting the entire page 
	repaintedZipCode = getRegDelZip();
	repaintRegAvial(availValues,partNumArr);
} 

// This function is called after SCIM ajax call is completed	
function fnDeliveryAddToCartResponse(viewName){
	ATCFailureFlg=false;
		if(typeof viewName != 'undefined'){
	if(flagCartQV=='true'){
		fnSearsAddToCart(viewName);
	}else{
	// If the item is out of stock we will show the error popup
	if(viewName == 'OutOfStock'){
		
		ddcAvlCheck = 'CPOUT';
		atcZipCode = getRegDelZip();
		$('#availPopup').css({display: "block"});
		$('#availPopup .standardDiv').css({display: "none"});
		$('#availPopup .errorDiv').css({display: "block"});
		$('.errorDiv input#checkZip').css({display: "inline"});
  		$('.standardDiv #loadGif').css({display: "none"});
  		$('.errorDiv #loadGif').css({display: "none"});
		ddcAvlCheck = 'NA';
	}
	// If the ajax call fails then close the popups and repaint the entire page
	else if(viewName == 'Failure'){
		ddcAvlCheck = 'NA';
			ATCFailureFlg=true;
		fnRegDeliveryAvlAjax(pageFlag,'Y',catentryVal);
	}
	// If the Item is in stock removing the popup and calling addItemPartNo function which takes to shopping cart page
	else { //TODO:: Check the actual value
		ddcAvlCheck = 'CPIN';
		//Completed and instock
		$('#availPopup').remove();
		if(pageFlag != 'COM'){
			
			addItemPartNo(DDCPartNoVal,DDCSiVal,DDCSpiVal,DDCSriVAl,DDCDffVal,DDCVendorVal,DDCStDateVal);
		}else{
			
		var compareATCUrl;
			$('div.col_1').find('a#DDCAtcCom_'+currentPartNo).each(function(i){
					var ddcAtcInfo = $(this).attr('info');
						var atcInfoArray = ddcAtcInfo.split("^");
					compareATCUrl = atcInfoArray[4];
					compareATCUrl = compareATCUrl+"&IndicatorA=delivery";
			});
			submitCart(compareATCUrl);
			}
			ddcAvlCheck = 'NA';
		}
	}
	}
}
// function for RA on page load repainting 
function fnOnLoadRARepaint(jsonResponse)	{
    var regavail = jsonResponse;   
    var partNoLen=regavail.pco;
    var inStockMsg=regavail.ddcInstk;
    var outStockMsg=regavail.ddcOutstk;
	var partNumArr = new Array(); 
	var avlMsg = "";
    if(fnChkZipCode() && typeof regavail != 'undefined'){
    	for(var availCnt=0;availCnt<partNoLen;availCnt++){
    		var partNum=regavail.regAvailList[availCnt].pn;
			var availMsg =regavail.regAvailList[availCnt].msg;
			if(availMsg == "InStock"){
				avlMsg = inStockMsg;
			}
			else if(availMsg == ""){
				avlMsg = inStockMsg;
			}
			else{
				avlMsg=outStockMsg;
			}
			availValues.Set(partNum, avlMsg);
			partNumArr[partNumArr.length] = partNum;

		}	
	}	
	// Repainting the entire page 
	repaintedZipCode = getRegDelZip();
	repaintRegAvial(availValues,partNumArr);			
}
//Fix for jira ECOM-35170
function openWindow(url, name, properties){ 
	var newWin = window.open(url, name, properties); 
	newWin.focus(); 
} 

/* Added for 08_19 Auto Complete Related Searches Enhancement Start 
jQuery(document).ready(function($) {
 	var relatedWords = unescape(gup("relatedwords"));
	var actualWord = '';
    if(relatedWords != undefined && relatedWords != null && relatedWords != '') {
    	var searchSuggestionsDiv = $("div#content div.searchSuggestions");
    	if($(searchSuggestionsDiv).length > 0) {
	       	var keywordArray = relatedWords.split("|");
	       	var domKeywords = "";
	       	domKeywords = "<strong>Related searches: </strong>";
			for(var i = 0; i < keywordArray.length; i++) {
				if(i > 0) {
					domKeywords += ',\n';
				}
				actualWord = keywordArray[i].replace(/\+/g," ");
	 			domKeywords += '<a title="'+actualWord+'" href="search_'+getStoreId()+'_'+catalogId+'?keyword='+keywordArray[i]+'">'+actualWord+'</a>';
	   		}
			$(searchSuggestionsDiv).html(domKeywords).show();
		}
   	}
});
Added for 08_19 Auto Complete Related Searches Enhancement End */
/*** Functions added for international shipping changes : Starts ***/

// Gloabl variable to hold domestic county code and currency, this can be set in global config and updated through dyna headers
var DEFAULT_COUNTRY_CODE = "US";
var DEFAULT_CURRENCY_SYMBOL = "USD";
var i18nCookieData = null;
var intShipFlgSwitch = 'FALSE';

//This function will return a boolean true, if International Shipping is activated
//through global config and (the selected country is not US)/(Selected currency is not Dollar)
//This will be used as a check in all the places for I18N changes in javascript
// IMP: This function should be present in global js of all the stores and should return false for them
function isI18NConvReq(){
	var flag = false;
	var prodPgBoolean = false;
	var pageId = $('body').attr('id');
		      if(intShipFlgSwitch == 'TRUE'){
	var cookieData = fnParseCountryCookie();

		            if(cookieData != null && cookieData.countryCode!=DEFAULT_COUNTRY_CODE){
		flag = true;
	}
		      }

	
	return flag;
}

/// for creating a cookie to store currently selected country
//this function will be called whenever user will change selected country in the drop down list.
function fnCreateCountryCookie(countryCode, currencyCode, exgRate){
	if(countryCode!=DEFAULT_COUNTRY_CODE && currencyCode!=DEFAULT_CURRENCY_SYMBOL)
	{
	$.cookie("IntnlShip", countryCode+"|"+currencyCode+"|"+exgRate);
	}
}

//This function can be used to fetch the currently selected country by the //user and the exchange rates for the country. This function will parse the //cookie and store the values in global variables.
function fnParseCountryCookie(){
	var cookieData = null;
	if(i18nCookieData != null){
		cookieData = i18nCookieData;
	}else{
		var cokkieVal = $.cookie("IntnlShip");
		if( cokkieVal != null && typeof cokkieVal != "undefined" && cokkieVal.split('|').length == 4){
		var intnlShippingValue = cokkieVal.split('|');
		countryCode = intnlShippingValue[0];
		currencyCode = intnlShippingValue[1];
		exgRate = intnlShippingValue[2];
			quoteId = intnlShippingValue[3];

		cookieData=new Object();
		cookieData.countryCode =countryCode;
		cookieData.currencyCode =currencyCode;
		cookieData.exgRate =exgRate;
			cookieData.quoteId =quoteId;

		i18nCookieData = cookieData;
	}
	}
	return cookieData;
}
/*** Functions added for international shipping changes : Ends ***/
jQuery(document).ready(function($) {
		var keywordFrmUrl = '';
		var vName	='';
		var cName	='';
		var sName	='';
		var keywordFrmUrl = unescape(gup("keyword"));
	    if(window.jsonProperties && jsonProperties != null && jsonProperties != '') {
	    	vName	=	jsonProperties.vName;
	    	cName	=	jsonProperties.cName;
	    	sName	=	jsonProperties.sName;
	    }
		actualWord = keywordFrmUrl.replace(/\+/g," ");
		if(actualWord != '' && null!=actualWord && vName=='' && cName=='' && sName==''){
			var relatedWords = retrieveRelatedWords(actualWord);
		}
	});  	

/*Dynamic Pricing and Net DownDeals -Start*/
 // gets the appropriate messages for the products with the netdown deals offers
 function fnGenNetDownMsg(curSalePrice,minPrice,rebateInd,mapInd){
              var netDownMsg = "";
              //to check if the minPrice is coming from SHC component like (NO#-1.00##)
              if(minPrice.indexOf("#")>-1){
                   netDownMsg=fnGenDealMsg(curSalePrice,minPrice,rebateInd,mapInd);
                   return netDownMsg;
              }
              curSalePrice = removeCurrencyFormat(curSalePrice);
              minPrice = removeCurrencyFormat(minPrice);
              var dealPrice = addCurrencyFormat(curSalePrice-minPrice);
              //checks for if min price or final payment should not be zero 
              if(eval(curSalePrice) > eval(minPrice) && removeCurrencyFormat(minPrice) != 0){
              	//If map price is false
                 if(!mapInd){
                 	if(!rebateInd){
                 		netDownMsg = "<div class=\"addl savings\" style=\"position:relative;padding-left:10px;padding-right:10px;padding-bottom:20px;\">"+
                                 "<span class=\"text\" style=\"font-weight:bold;color:#FA7238;float:left;font-size:11px;height:1.3em;width:170px;position:absolute;\">"+
                                 "Additional Savings: "+dealPrice+"</span><br/>"+
                                 "<span class=\"dealPrice\" style=\"position:relative;float:left;right:0;color:#8DA351;font-size:12px;font-weight:bold;height: 29px; width: 135px; \">"+
                                 " You Pay: "+addCurrencyFormat(minPrice)+"</span>"+
                                 "</div>";
                         }else{
                                 netDownMsg = "<div class=\"addl savings\" style=\"position:relative;padding-left:10px;padding-right:10px;padding-bottom:20px;\">"+
                                 "<span class=\"text\" style=\"font-weight:bold;color:#FA7238;float:left;font-size:11px;height:1.3em;position:absolute;\">"+
                                 "Plus, save an additional "+dealPrice+" when you add to cart</span>"+
                                 "</div>";
                         }
                  }
                 else
                 {
                 	netDownMsg = "<div class=\"addl savings\" style=\"position:relative;padding-left:10px;padding-right:10px;padding-bottom:20px;\">"+
                                "<span class=\"text\" style=\"font-weight:bold;color:#FA7238;float:left;font-size:11px;height:1.3em;position:absolute;\">"+
                                "additional savings may apply in cart</span>"+
                                "</div>";
                 }
   
              }else{
   	           netDownMsg = "";          
              }
   	return netDownMsg;
   }
   
   function fnGenDealMsg(curSalePrice,value,rebateInd,mapInd){
              var dealMsg = "";
              var priceDisplayed = "" ;
              var tempFlag = value.split("#")[0];
              var tempValue = value.split("#")[1];
              var tempPriceValue = tempValue;
              var tempRebateValue ="";
              if(rebateInd || !mapInd){
   	           tempRebateValue = addCurrencyFormat(curSalePrice - tempPriceValue);
              }
              var notAllSimple = value.split("#")[2];
              if(tempFlag =="YES"  || notAllSimple!= ""){
   		   priceDisplayed = "YES" ;
              }
              if (tempValue!= null && tempValue!= "" && priceDisplayed!="YES"){
                          if(tempValue == "-1.00") {
   				dealMsg ="<span style=\"color: red;font-size:15px;font-weight:bold !important;\"></span>";
   
                          } else {
   				if(!mapInd){
   					if(!rebateInd){
   						dealMsg = "<span style=\"color: red;font-size:15px;font-weight:bold !important;\">$"
   							+tempValue +
   						"</span> after deducting applicable additional savings ";
   					}else{
   						dealMsg = "<div class=\"addl savings\" style=\"position:relative;padding-left:10px;padding-right:10px;padding-bottom:20px;\">"+
   							"<span class=\"text\" style=\"font-weight:bold;color:#FA7238;float:left;font-size:11px;height:1.3em;position:absolute;\">"+
   							"Plus, save an additional "+tempRebateValue+" when you add to cart</span>"+
   							"</div>";
   					}                                   
   				}
                 else
                 {
                 	netDownMsg = "<div class=\"addl savings\" style=\"position:relative;padding-left:10px;padding-right:10px;padding-bottom:20px;\">"+
                                "<span class=\"text\" style=\"font-weight:bold;color:#FA7238;float:left;font-size:11px;height:1.3em;position:absolute;\">"+
                                "additional savings may apply in cart</span>"+
                                "</div>";
                 }
   				
                          }
              }
              return dealMsg;
  }
 function removeCurrencyFormat(num){
 	num = num.toString().replace(/\$|\,/g,'');
 	if(isNaN(num)) num = "0";
 	return num;
 }
 
 function addCurrencyFormat(num) {
 	num = num.toString().replace(/\$|\,/g,'');
 	if(isNaN(num)) num = "0";
 	sign = (num == (num = Math.abs(num)));
 	num = Math.floor(num*100+0.50000000001);
 	cents = num%100;
 	num = Math.floor(num/100).toString();
 	if(cents<10) cents = "0" + cents;
 	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
 	num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
 	return "$"+(num + '.' + cents);
 }
/*Dynamic Pricing and Net DownDeals -End*/


function expandOffers(){

	var checkPrdPage=$('body').attr("id");
	var expOffers=$("input#expOffers").attr('value');
	if(checkPrdPage=='product'){
		if(typeof expOffers !='undefined' && expOffers=='true'){
			$("div#intTab1_content .offerScroll .details").each(function(i){
				$(this).show();	
			});	
		
			$("div#intTab1_content .offerScroll .detailHd").each(function(i){
				var ancHref = $(this).find("a").attr('href');
				if(ancHref=='javascript:;'){
					$(this).attr("class","detailHd open");	
					$(this).find("a").text("Hide Details")
				}
			});
		}
		$("input#expOffers").attr('value','false');
	}
}

