/* Variable Declaration - Starts Here */
var DDItemList = "";
//Variable for all regiSS
var allRegiSS = new Array();

//New window that will be used by Prod full Desc page
//by passing in all the properties
var httpRequestSupported = true;

// Initialize storeId with b2b storeid
var storeId=10101;
var catalogId = 10101;

/* Variable Declaration - Ends Here */
// 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';

/* Browser Functions - Starts Here */

// Browser Sniff //
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

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;
   			
   			//location.href=url;
//			window.open(url,'windowname2',
  //                      'scrollbars=1,fullscreen=yes,toolbar=1');

       	}
		
	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;
   			
   			//location.href=url;
//			window.open(url,'windowname2',
  //                      'scrollbars=1,fullscreen=yes,toolbar=1');

       	}
		
/* Universal profile - ends here */

/* General Methods - Starts Here */

function setStoreId(storeIdValue){
    storeId = storeIdValue;
}

function getStoreId(){
    return storeId;
}

function setCatalogId(catalogIdValue){
    catalogId = catalogIdValue;
}

 function openWindow(url, name, properties)
 {
   var newWin = window.open(url, name, properties);
   newWin.focus();
 }

function goGlossary(url) {
    var glossWin= window.open(url, 'glossary', 'height=500,width=300,resizeable,scrollable');
    glossWin.focus();
}
    
function goPrintable(url) {
    var printWin= window.open(url, 'print_win');
    printWin.focus();
}

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();
}


 // Email Verification and Validation (Date 07/27/2003)
 function validateEmailAddress(email){
    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: sears@sears.com.) Please check your information and try again.");
        return false;
    } else if(email.match(regex2)){
        alert(email + " is not allowed");
        return false;
    }
    return true;
}

function verifyEmailAddresses(email1, email2)
{    
    if(email1 == null || email2 == null){
        alert("Email address is required");
        return false;
    }
        if(!validateEmailAddress(email1)){
           alert("The e-mail address you entered appears incorrect. (Example of a correct address: sears@sears.com.) Please check your information and try again.");
            return false;
        email1.select(); 
        email1.focus();
    }
    
    if(!validateEmailAddress(email2)){
       alert("The Confirm Email address you entered appears incorrect. (Example of a correct address: sears@sears.com.) Please check your information and try again.");
            return false;
        email2.select(); 
        email2.focus();
    }
            
    
    var emailr = email1.replace(/\+/g, "\\+");      // SY 04/16/04 PD00018534
        var regex = new RegExp("^" + emailr + "$","i"); // in case there's '+' in the email address
    if(email2.match(regex) == null)
    {
         alert(" The e-mail addresses you entered below are not the same. Please check your address and try again.");
        return false;
        email1.select(); 
        email1.focus();
        }
    
    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);
}

//Zipcode Validation
function checkZip() {
  zip = document.forms["zipForm"].elements["zip"].value; 
  var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
  var passed = lv_pattern.test(zip); 
  if (!passed) {
    alert("The zipcode you entered is not valid.  Please re-enter zipcode.");
    return false;
  }
  else {
    return 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);
}

// 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 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: sears@sears.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: sears@sears.com.) Please check your information and try again.");
    return false;
}
return true;
}

// 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
var httpRequestSupported = true;

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 */

// TABS FUNCTIONS ///
function hideTabs (a) {
    var d = document.getElementById("tabList");
    var dLength = d.getElementsByTagName("dt").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="";
}

// this function below is for changing show and hiding
// 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;
}

function showhideBox (id) {
    var d=document.getElementById(id);
    
    if(document.getElementById){
        if (d.style.display !== "none"){
            d.style.display="none";
        } else {
            d.style.display="";
        }
    }
    
    d.style.top = "15px";
    d.style.left = "-5px";
}

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+$/,""); 
        if(v != null && v.length > 0 && !v.match(/\d+/)) {
              v = v.toLowerCase();
        }
        k.value = v;
    }
    if(v == null || v.length == 0) {
        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 == 'Automotive &amp; Tires'){
        	vNameVal = 'Automotive';
        }else if(vNameVal == 'Bed, Bath &amp; Home'){
        	vNameVal = 'For the Home';
        }else if(vNameVal == 'Electronics &amp; Computers'){
        	vNameVal = 'Computers & Electronics';	
        }else if(vNameVal == 'Jewelry &amp; Watches'){
         	vNameVal = 'Jewelry';
        }else if(vNameVal == 'Office Products'){
        	vNameVal = 'Computers & Electronics_Office Products';
        }else if(vNameVal == 'Outdoor Living &amp; Seasonal'){
        	vNameVal = 'Outdoor Living';
        }else if(vNameVal == 'Video Games'){
        	vNameVal = 'Entertainment';
		}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*/
// find position of the image calling the function and set the infobox next to it //
function whereAt (a){
    var d = document.getElementById('tabContent');
    var c = d.getElementsByTagName('img');
    var f = findPosY(document.getElementById('tabContent'));
    var e = findPosX(document.getElementById('tabContent'));
    for(var i = 0; i < c.length; i++){
        if (i == a) {
            document.getElementById('prodSpecInfo').style.top = (findPosY(c[i])- f - 5) + "px";
            document.getElementById('prodSpecInfo').style.left = (findPosX(c[i])- e + 0) + "px";
            showBox ('prodSpecInfo');
        }
    }
}

// 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";
        }
        document.getElementById('contentWrapper').style.position = "static";
        document.getElementById('footer').style.position = "static";
    }

// hide and seek 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";
    }
}

// this function below is for changing CSS class of the size buttons and populating appropriate 'selected size' label with the correct value
// set initial selected size value to default before function is called
initialvalue=6;

function selectedsize_fn(id, newClass, actualsize){
    chosensize=actualsize;
    //updates value displayed to selected size///////////////
    //firefox/////////////////////////////////////////
    document.getElementById("size").innerHTML = actualsize;
    //IE/////////////////////////////////////////////
    document.getElementById("size").innerText = actualsize;

    identity1=document.getElementById("size_1");
    identity1.className="unselectedsize";
    identity2=document.getElementById("size_2");
    identity2.className="unselectedsize";
    identity3=document.getElementById("size_3");
    identity3.className="unselectedsize";
    
    //change ul class for id that called function/////////////////
    identity=document.getElementById(id);
    identity.className=newClass;
    
    initialvalue="";
}

// 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";
        }
        //document.getElementById("tab" + i).style.display="none";
        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="";
    
    var cNodes = tabHide.childNodes;
    for (var i=0; i< cNodes.length; i++) {
        var curNode = cNodes[i];
        if (curNode.tagName == "A") {
            var tabName = curNode.innerHTML;
            if (tabName != null && tabName != 'Overview') {
                if (tabName.indexOf('Review') != -1) {
                    tabName = 'Reviews';
                }
                tabName += ' Tab';
            
                //Omniture tracking.
                if (typeof omPrefix != 'undefined') {
                    omPrefix='Product Summary > ' + tabName;
                }
                if (typeof s != 'undefined') {
                    s.t();
                }
            }
            break;
            
        }
    }
    
    selectOverview(a-1);
    
    if(a==2){
        //Ajax call for executing the specs tab
        ajaxCall(url,'displayTabContent',null,'tab2');
    }
    if(a==3 && url != null){
        //Ajax call for executing the options tab
        ajaxCall(url,'displayTabContent',null,'tab3');
    }
}

// TABS FUNCTIONS  For Keyword Page///
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 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;
      }
    }
}

// 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;
}

// 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();
}

// 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;
        }
    }
}

// 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";
    }
};

// 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;
    }
}

// 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;
}

/* Browse(Home, Browse & Search, Product Pages) Methods - Ends Here */


/* Shopping Cart and Check Out Methods - Starts Here */

function checkSKUSelection() {
    var frm = document.forms["skuForm"];
    for (var i=0; i<frm.elements.length; i++) {
        var elm = frm.elements[i];
        if (elm.type.indexOf("select") != -1) { 
            if (elm.selectedIndex <= 0) { 
                alert("Please select an option for " + elm.options[0].value + ".");
                elm.focus();
                return false;
            }
        }
    }
    return true;
}

function submitSKUForm() {
    if (checkSKUSelection() == true) {
        document.forms["skuForm"].submit();
    }
}

function openInstallationCost(url) {
  var win0 = window.open(url, 'install_cost', 'scrollbars=yes,menubar=yes,toolbar=no,status=no,width=375,height=325,screenX=300,screenY=175');
  win0.focus();
}

function openShipCalc(url) {
  var win1 = window.open(url, 'ship_calc', 'resizable=yes,directories=no,scrollbars=yes,menubar=no,toolbar=no,location=no,status=no,width=520,height=450');
  win1.focus();   
}

function openDeliveryCalc() {
    var win2 = window.open("/sears/popup_deliverycalc.html", "deliver_calc", "directories=no,scrollbars=yes,menubar=yes,toolbar=no,status=no,width=545,height=350");
    win2.focus();
}

function verifyCheckoutParameters(pwd,pwdconfirm,pwdhint)
{
    var lv_ok;
    if(pwd.value==null || pwd.value=="")
    {
        alert("Please, enter the password");
        lv_ok=-1;
        pwd.focus();
        return lv_ok;
        
    }
    else if(pwdconfirm.value==null || pwdconfirm.value=="")
    {
        alert("Re-enter password is required field");
        lv_ok=-1;
        pwdconfirm.focus();
        return lv_ok;
        
    }
    else if(pwd.value!=pwdconfirm.value)
    {
        alert("The password and the re-entered password must be the same");
        lv_ok=-1;
        pwdconfirm.focus();
        return lv_ok;
    }
    else if(hint.value ==null || hint.value =="")
    {
        alert("Password hint is required field");
        lv_ok=-1;
        hint.focus();
        return lv_ok;
    }
        return lv_ok;
}

// these 2 functions are called by product option pages to hide & show select box (IE bug) when dhtml layer (what's included P.A.)is viewed
function hideSelect(id)
{if (document.all){document.getElementById(id).style.display="hidden";}}

function unhideSelect(id)
{if (document.all){document.getElementById(id).style.visibility="visible";}}

// 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);
        }
    }
); 

// 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();
}

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;
        }
 
         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');
    }
}

// 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');
}

/* Shopping Cart and Check Out 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).css({ top: +(yScroll+((windowHeight - $this.offsetHeight)/2.7)), left: +((windowWidth/2) - ($this.offsetWidth/2)) });

}

/* 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'});
        }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);
					//$('#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);
				//$('#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)});
    //$('#shoppingcart div.giftwrap a').click(launchGWmodal);
    if (typeof dynamicPopupPath != 'undefined'){
		if($('table.personalinfo a.rewardsDetails').length >= 1)
   	 	$('table.personalinfo a.rewardsDetails').dynamicPopup({filename: dynamicPopupPath+'&vName=rewardsnote',contentname: '.gcPleaseNote',windowWidth: '300px',windowHeight: 'auto'});
    }
});

/* DOM READY CALLS  - Ends Here */


/* JQUERY COLOR  - Starts Here */

(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 */
var foT;
var offsetLL = '';
var $saveStory; 

$(function(){
if(typeof dynamicPopup!='undefined'){
    $('a.envFees').dynamicPopup({filename: dynamicPopup+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});
    $('a.disFees').dynamicPopup({filename: dynamicPopup+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});
    $('a.enviroLink').dynamicPopup({filename: dynamicPopup+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});   
}
    
        $('.saveStory').each(function(){          
            if( $(this).next().attr('class') == 'localPrice' ){
                $(this).hide(0);        
            }
        });
    
        if(typeof imagePath !='undefined' && allRegiSS !='undefined' && allRegiSS.length >0 ){
            var appCode = '<span class="morePrice">'
                appCode += '<div>'
                appCode += '<strong>ZIP Code:</strong>'
                appCode += '<input type="text" value="'+getCookie('zipCode')+'" size="5" maxlength="5" />'
                appCode += '<img width="36" height="20" alt="go" src="'+imagePath+'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>';
            $('body').append(appCode);
        }
            
        //var appFees = '<div id="warnFees">'
        //  appFees += '<div class="tab">About Environmental Fees <a href="javascript:;" class="clFees">close</a></div>'
        //  appFees += '<div class="feesMsg">The environmental fee (User Fee) is a state-mandated charge on the sale of new tires or batteries. In many states the fee provides funds for hazardous waste cleanup and pollution prevention programs administered by the state.<br /><br /><strong>Tire Disposal Fees</strong> <br /><br />Sears.com does not charge you for disposing of your used tires that will be added to your work order at the time of installation if you leave your old tires with the auto center. This fee is charged to cover a portion of the costs in the disposition of used tires. We work only with licensed disposal services to ensure that the tires are properly discarded.</div>' 
        //  appFees += '</div>';
                
//      $('body').append(appFees);
        $('.morePrice').hide(0);
        //$('.morePrice, #warnFees').hide(0);           
    

        var done = 0;
        
        $(".localPrice").unbind().hover(function() {
            $saveStory = $(this).prev();                            
            $('.morePrice').hide(0);
            offsetLL = $(this).offset();
            $('.morePrice').show().css({ top: offsetLL.top + 23, left: offsetLL.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); 
        }); 
        /*
        $('.envFees, .disFees').click(function(){
            var offsetFees = $(this).offset();                          
            $('#warnFees').show().css({ top: offsetFees.top +15, left: offsetFees.left - 160 });
            $('.clFees').click(function(){
                $('#warnFees').hide(0);                             
            });
        });
        */
        $('#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();
            var invZip = validateZip($zipVal);
            var $saveStory = $(this).prev();
            
            if((!$zipVal.match(regExp)) || invZip){ //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
                doAjax($zipVal,storeId);
                $('.centerInfo').html("<strong>Nearest Sears Auto Center<\/strong><br \/>Enter your ZIP Code to get the address and phone number.").removeClass('errZip');
                $('.morePrice').find('input').removeClass('errZip').val($zipVal);
                $('.localPrice a').addClass('localPSel');   
                if( done == 0 ){
                     if( ($("body").attr('id') != 'subcategory') ){                                                    
                         var mvHt = 42;                                                   
                         var moveHeight = $saveStory.height() + mvHt;
                         $('.morePrice').css({ top: offsetLL.top + moveHeight  });
                     
                         }
                }
                $('.saveStory').show();
                $('.saveStory, p.centerInfo').animate({ backgroundColor: "#FFFF99" }, 100).animate({ backgroundColor: "white" }, 3000);
                done = 1;
                 
            }
        });
        
        var dynamicPopupURL;
        if(null != document.productOptionsDetails){
            dynamicPopupURL = document.productOptionsDetails.dynamicPopupPath.value;
            $('a.envFees').dynamicPopup({filename: dynamicPopupURL+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});
            $('a.disFees').dynamicPopup({filename: dynamicPopupURL+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});
            $('a.enviroLink').dynamicPopup({filename: dynamicPopupURL+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#roadHazard').dynamicPopup({filename: dynamicPopupURL+'&vName=autohazard',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '240px'});
            $('img#installationServices').dynamicPopup({filename: dynamicPopupURL+'&vName=autoinstallation',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#maintenanceDetails').dynamicPopup({filename: dynamicPopupURL+'&vName=automaintenance',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#glossAlignment').dynamicPopup({filename: dynamicPopupURL+'&vName=autoalignment',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#glossOil').dynamicPopup({filename: dynamicPopupURL+'&vName=autooil',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#glossBrake').dynamicPopup({filename: dynamicPopupURL+'&vName=autobrake',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
            $('img#glossInspection').dynamicPopup({filename: dynamicPopupURL+'&vName=autoinspection',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});     
        } 
        else if (typeof dynamicPopupPath != 'undefined' && "" != dynamicPopupPath){
            dynamicPopupURL = dynamicPopupPath;
       		if($('a.enviroLink').length >= 1)
            $('a.enviroLink').dynamicPopup({filename: dynamicPopupURL+'&vName=environmentfee',contentname: '.enPleaseNote',windowWidth: '300px',windowHeight: '140px'});
        }
        
        $(".morePrice div img").prev().bind("keypress", function(event) {
             var code=event.charCode || event.keyCode;
                if((code && code == 13)) {
                    $('.morePrice div img').click();
            
                }
        });
        var closeBox = function(){
            $('#ajaxmodal img.cancelMod').click(function(){
                curtainOverlay({closing:true});
            });
        }
        
        function validateZip(tempZip){
            var invalidZip = ['00000','11111','33333','66666','77777','88888','99999'];
            var arraySize = invalidZip.length;
            for(var i=0;i<arraySize;i++){
                if(invalidZip[i] == tempZip){return true;}
            }
            return false;
        }
        if(allRegiSS.length >0 ){
            var zippCook = getCookie('zipCode');
            if(zippCook !=''){
                // Call ajax on load
                doAjax(zippCook,storeId);
                $('.localPrice a').addClass('localPSel');   
            }
        }

/* Autofitment local price module  - Ends Here */


/* Ship Vantage module  - Starts Here */

    if( ($("body").attr('id') == 'myProfile') ){        
                
    
    	if((null != document.getElementById("appVantage"))&& (null != document.getElementById("appCanVantage"))){
        $('body').append(appVantage).append(appCanVantage); 
        }
        $('#modRenewal, #modCancel').hide(0);

        $('.btnRenewal').click(function(){
        
            var offsetVan = $(this).offset();   
            $('#modRenewal').show().css({ top: offsetVan.top -60, left: offsetVan.left -5 });                                        
            $('.clModRen').click(function(){ $('#modRenewal').hide(0); });
        });
        
        $('.btnCancel').click(function(){
            var offsetCan = $(this).offset();                           
            $('#modCancel').show().css({ top: offsetCan.top -60, left: offsetCan.left -182 });                                       
            $('.clModCan').click(function(){ $('#modCancel').hide(0); });       
        }); 

        var closeBox = function(){
            $('#ajaxmodal img.cancelMod').click(function(){
                curtainOverlay({closing:true});
            }); 
        }       

        $('.billAddressMod').click(function(){
            //curtainOverlay({ajaxmodal:true, ajaxclass:'addBillingMod'});
            //$('.addBillingMod').html( addBillingVantage );
            //closeBox();   
            var storeId = document.getElementById('storeIdToBeSubmitted').value;
            var catalogId = document.getElementById('catalogIdToBeSubmitted').value;
            var urlforAjax = "/shc/s/AddAddressModal?storeId="+storeId+"&catalogId="+catalogId+"&langId=-1";
            //urlforAjax = populateSelectedAddressValues(selectdaddressId);
            curtainOverlay({ ajaxmodal:true, ajaxclass:'addPayMod'});      
                $.ajax({    
                    url: urlforAjax,    
                    cache: false, 
                    success: function(data){
                         $('#ajaxmodal').append(data);   
                        closeBox();     
                    }
                });
            $('.addPayMod').centerOnScreen();
            
        });

        $('.editAddressMod').click(function(){
            var selectdaddressId = document.getElementById('addressChosen').value;
            var urlforAjax = "";
            urlforAjax = populateSelectedAddressValues(selectdaddressId);
            curtainOverlay({ ajaxmodal:true, ajaxclass:'editBillingMod'});      
                $.ajax({    
                    url: urlforAjax,    
                    cache: false, 
                    success: function(data){
                         $('#ajaxmodal').append(data);   
                        closeBox();    
                    }
                });
             $('.editBillingMod').centerOnScreen();
                    
        });
        
        $('.addPaymentMod').click(function(){
                    var catalogId = document.getElementById('catalogId').value;
                    var urlforAjax = "/shc/s/AddPaymentMethodModal?storeId=10153&catalogId=" + catalogId + "&langId=-1";
            curtainOverlay({ ajaxmodal:true, ajaxclass:'addPayMod'});      
                $.ajax({    
                    url: urlforAjax,    
                    cache: false, 
                    success: function(data){
                         $('#ajaxmodal').append(data);   
                        closeBox();     
                    }
                });
              $('.addPayMod').centerOnScreen();
        });     
    
        $('.editPaymentMod').click(function(){
            var selectdpiId = document.getElementById('savedPayment').value;
            var urlforAjax = "";
            urlforAjax = populateSelectedCardValues(selectdpiId);
            curtainOverlay({ ajaxmodal:true, ajaxclass:'editPayMod'});      
                $.ajax({    
                    url: urlforAjax,    
                    cache: false,
                    success: function(data){
                         $('#ajaxmodal').append(data);   
                        closeBox();    
                    }
                });   
               $('.editPayMod').centerOnScreen();  
            
        }); 
    
    }
        

});

/* Ship Vantage module  - Ends Here */


/* Gift Registry Module - Starts Here */

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;
                  }
              }
     }
     
/* Gift Registry  Module - 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 */


/* 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){
            $('#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) {
                $('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: '#039',
                    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 #9e9e9e',
                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: '#039',
                    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 #9e9e9e',
                    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){
						$('#DHTMLcontent').empty().append('<a href="javascript:;" title="Close Window" class="closeWin"></a>').append(html);
						$('.closeWin').css({height:'19px',width:'19px',position:'absolute',top:'5px',right:'5px',background:'url(/img/closeWindow.gif) no-repeat'})
						$('#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{
				$('#DHTMLcontent').empty().append('<a href="javascript:;" title="Close Window" class="closeWin"></a>').append(settings.staticContent);
				/* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- START */
				if(typeof imagePath!='undefined' && imagePath!=null && imagePath!="") {
					$('.closeWin').css({height:'19px',width:'19px',position:'absolute',top:'5px',right:'5px',background:'url('+imagePath+'/img/closeWindow.gif) no-repeat', zIndex: '999999'})
				} else {
					$('.closeWin').css({height:'19px',width:'19px',position:'absolute',top:'5px',right:'5px',background:'url(../img/closeWindow.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',
        dynamicContent: 'true',
        jsonFlag: false
    },settings);
    
    return this.each(function(){
        $(this).click(function(e){
            dynpop.ini(e, settings)
        });
        //return false; <--- This was causing multiple instances to fail.
    });
}

/* 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 */


/*
* Functionality: Used for display of Savestory for Automotive Products
* Applicable : Sears Only
* regiSS methods - STARTS HERE
*/

var zipCode = '';
function doAjax(zipp,storeId){
    zipCode = zipp;
    var cmdName='CalculateRegionalSaveStoryCmd';
    //get http or https. This is to avoid security error in firefox
    var checkhttp = window.location.protocol;
    
    if(checkhttp =='http:' || checkhttp ==''){
        cmdName='CalculateRegionalSaveStoryCmdhttp';
    }
        
    var partNumberList ='';
    var saveStoryList='';
    setCookie('zipCode',zipCode);
    var url='';
    if(typeof allRegiSS != 'undefined') {
        for(var i=0;i<allRegiSS.length;i++){
            if(allRegiSS[i].regiSSInd){
                var tempNum=allRegiSS[i].pn;
                if(!allRegiSS[i].regiIBType){
                    tempNum = allRegiSS[i].pn.substring(0,11);
                }
                if(partNumberList.search(tempNum) == -1){
                    partNumberList +=tempNum+'|';
                    saveStoryList +=allRegiSS[i].ss+'|';
                }
            }
        }
    }
    var url = cmdName+'?storeId='+storeId+'&zipCode='+zipCode+'&partNumberList='+partNumberList;
	
    //do ajax using post
    //Modified for Get Local Price changes
    //request = $.post(url,{saveStoryList: saveStoryList},showResponse); 
    
    request = $.post(url,showResponse);  
    
}

// This is the return function
function showResponse(respHTML){
    //convert HTML response to json object
    var zipCode =$.cookie('zipCode');
    var _Rp = eval('('+respHTML+')');
    var fpr ='';
    if(typeof allRegiSS != 'undefined') {
        if(_Rp.errorCode == 'STORE_FOUND'){
            for(var i=0;i<allRegiSS.length;i++){
                if(allRegiSS[i].regiSSInd){
                    var partNum = allRegiSS[i].pn;
                    for(var k=0;k<_Rp.prodCount;k++){
                        if(_Rp.price[k].pId == allRegiSS[i].pn || _Rp.price[k].pId == allRegiSS[i].pn.substring(0,11)){
                            if(_Rp.price[k].isException){
                                populatePrice(_Rp.price[k].saveStory,allRegiSS[i].pn,'Price May Vary',allRegiSS[i].regiIBType);
                            }else{
                                populatePrice(_Rp.price[k].saveStory,allRegiSS[i].pn,'Price in '+zipCode,allRegiSS[i].regiIBType);
                            }
                            break;
                        }
                    }
                }else{
                    populatePrice(allRegiSS[i].ss,allRegiSS[i].pn,'Price in '+zipCode,allRegiSS[i].regiIBType);
                }
            }
        }else{
            for(var kk=0;kk<allRegiSS.length;kk++){
                if(allRegiSS[kk].regiSSInd){
                    populatePrice(allRegiSS[kk].ss,allRegiSS[kk].pn,'Price May Vary',allRegiSS[kk].regiIBType);
                }else{
                    populatePrice(allRegiSS[kk].ss,allRegiSS[kk].pn,'Price in '+zipCode,allRegiSS[kk].regiIBType);
                }
            }
        }
    }
    populateStoreInfo(_Rp);
    // only if the afterRegiSS() is defined in target page call the function
    if(window.afterRegiSS){
        afterRegiSS();
    }
    if($('body').attr('id')=='product'){
    	fixInfoHeight();
    }
}

var regionalDiv = "";
var currentPartNo = "";
var dbFlagVal = "";
var catentryVal = "";
var pageFlag = "";
var qvDiv= "";
var repaintedZipCode = "";
var atcZipCode = "";
var CAPopUpFlag = true;
// 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.indexOf("storepu") > -1 || regionalDiv.indexOf("pickup") > -1 ) {
		  		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.indexOf("storepu") > -1) {
			$('#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.indexOf('storepu') > -1 || qvDiv == 'checkAvailSpu' || regionalDiv.indexOf('pickup') > -1)){
	   	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/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/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><p class='or'><span>------------------------------------</span>Or<span>------------------------------------</span></p>"
				+"<p>Save Delivery costs and <a id='popupPickup' style='cursor:pointer'>Pick Up your item at the store</a></p>"
				+"</div>"
				+"</div>";	
					
		 if((regionalDiv.indexOf('storepu') > -1 || regionalDiv.indexOf('pickup') > -1 )&& (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 - 400))});
		  	$('#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.indexOf("storepu") > -1 || regionalDiv.indexOf("pickup") > -1)&& 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.indexOf('storepu') > -1 || regionalDiv.indexOf('pickup') > -1 )){
	   	zipOnLoad = getCookie('zipCode'+getStoreId());
	   		zipType = 'storepu';
	   	} else {
	   		zipOnLoad = getCookie('zipCode');
	   		zipType = 'delivery';
	   	}
	   	CAPopUpFlag = false;
      	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/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/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><p class='or'><span>------------------------------------</span>Or<span>------------------------------------</span></p>"
				+"<p>Save Delivery costs and <a id='popupPickup' style='cursor:pointer'>Pick Up your item at the store</a></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;
	var storeId = getStoreId();
	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>');
			//$('div#availability').find('a#checkAvailDel').text("Change ZIP Code");
		}
	}	
	$('#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);			
}

// populate store information in all class = centerInfo
function populateStoreInfo(_Rp){
    if(_Rp.errorCode == 'STORE_FOUND'){
        var tempPhone =_Rp.storePhone;
        if(tempPhone!=''){
            tempPhone = '('+_Rp.storePhone.substring(0,3)+') '+_Rp.storePhone.substring(3,6)+'-'+_Rp.storePhone.substring(6,10);
        }
        var constructStoreInfo ='<strong>Nearest Sears Auto Center<\/strong><br\/>' + _Rp.storeName + '<br\/>'+ tempPhone;
        $('p[@class=centerInfo]').html(constructStoreInfo);
    }
}

// populate the save story and 'Price in xxxxx'in all div
function populatePrice(price,partNum,txtzip,beanType){
    
    var saveStory = price.split('^');

    // first populate zip then populate save story. do not interchange the below lines
    $('div[@id=ss_'+partNum+']').find('a').text(txtzip);
    $('div[@id=ss_'+partNum+']').find('div.saveStoryText').html(saveStory[0]);
}

/*Following methods are removed from regiSS.js, as they are already present in this global.js
getCookie(cookieName)
setCookie(cookieName,cookieValue)
*/

/* regiSS methods - 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 + 200 + "px";
    });
});
/* Methods for Great Price - Ends Here */

// AjaxCallForShopCart.js

// newFunction
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;
    if(isI18NConvReq()){
    		
    		fnConvertMiniCart();
	}
}

    function specialOffers(activeTab,storeId,catalogId,catentryId) {    
        var rebateSpecialOffers= document.createElement("div");
		document.body.appendChild(rebateSpecialOffers);
		omnDeals(activeTab);
        rebateSpecialOffers.id = 'rebateSpecialOffers';     
        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');
          
        var isSaveForLater;
       	
        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }
        //var isSaveForLater =saveForLater;
        var specialOfferView;
        
        
        if($('body').attr('id')=='checkout' || ((null != isSaveForLater) &&(isSaveForLater == 'YES'))){
        		specialOfferView = 'BrowseSpecialOfferViewHttps' ; 
        } 
        else{          
                specialOfferView = 'BrowseSpecialOfferView' ; 
        }
        
        $.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();
                    if(isI18NConvReq()){
 						fnConvertPriceSpecialOffer();

 					}
                }
 					
                
        }); 
      
    }

   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;
        }
        //var isSaveForLater =saveForLater;        
        
        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();
	});
	}	
	if (typeof dynamicPopupPath != 'undefined' && "" != dynamicPopupPath){
		if($('table.membershipNumbers a.rewardsDetails').length >0)
		{	
		$('table.membershipNumbers a.rewardsDetails').dynamicPopup({filename: dynamicPopupPath+'&vName=rewardsnote',contentname: '.gcPleaseNote',windowWidth: '300px',windowHeight: 'auto'});
	}
	}
});
$(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";
    });
}
function sr_create_script(a) {
			var b = document.createElement('script');
			b.type = 'text/javascript';    
	    	b.src = a;
    		document.getElementsByTagName('head')[0].appendChild(b);
	  }

/* 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 */

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
  				{
  					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;\">"+
  							"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*/




/*** 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 intShipFlgSwitch = 'FALSE';
var intShipJspChk = 'false';
var i18nCookieData = null;

//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!='US'){
		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, quoteId){
	$.cookie("IntnlShip", countryCode+"|"+currencyCode+"|"+exgRate+"|"+quoteId, {path:'/'});
}

function fnDeleteCountryCookie(){
	$.cookie("IntnlShip", null);
}

//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"){
		 var ckArray =cokkieVal.split('|'); 
		 var cklen = ckArray.length;
			cookieData=new Object();
		 if(cklen > 1){
			cookieData.countryCode = ckArray[0];
			cookieData.currencyCode = ckArray[1];
			if(cklen>2){
				cookieData.exgRate = ckArray[2];
			}	
			if(cklen>3){	
				cookieData.quoteId = ckArray[3];
			}	
	
			i18nCookieData = cookieData;
		}
	}
	}
	return cookieData;
}
/*** Functions added for international shipping changes : Ends ***/

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');
	}
}

//International Shipping code
function fnHideI18NCompare(){
	var nam = '';
	var sQuote= "'";
	var dot= ".";
	var bracketfnt="$(";
	var bracketbck=").hide()";
	var anch= "'a.";
	var saveLater="'input.saveLater_";
	var rev="'div.info a.p_10153_12605_";
	var cart="div.info a.cart_";
	var cartSoft=".cart_";
	var part="'div.info a.part_";
	var spucom="'div.info a.spuCom_"; 
	var DDCAtcCom ="'div.info a.DDCAtcCom_";
	var msgElg = "li.intShip";
	var msgInElg = "li.unvIntShip";
	
	var iShpaddToCartButtonArr = iShpaddToCartButton.split('|');
	var intnlShippingValue = '';
	
	var cokkieVal = $.cookie("IntnlShip");
	
	if(cokkieVal !='undefined' || cokkieVal !=null )
	{	
	intnlShippingValue = cokkieVal.split('|');
	countryCode = intnlShippingValue[0];
	}
	
	if(intShipJspChk == 'false' && countryCode == 'US')
	{
		if(pnolist != 'undefined' || pnolist != "")
		{   
			var pnolistArr = pnolist.split('|');
			var intShipSoftArr = intShipSfVal.split('|');
			for(var i=0; i<= pnolistArr.length; i++){				
				if(pnolistArr[i]!="" && intShipSoftArr[i]!="" )
				{
					if(intShipSoftArr[i] == 'NO')
					{
						eval("$('"+ msgElg + pnolistArr[i] +"').hide()");					
						eval("$('"+ msgInElg + pnolistArr[i] +"').hide()");
					}
					else if(intShipSoftArr[i] == 'YES')
					{
						eval("$('"+ msgElg + pnolistArr[i] +"').show()");					
						eval("$('"+ msgInElg + pnolistArr[i] +"').hide()");
				    }
				}	
			}		
		}	
				
		var intbutlp = intShipbut.split('|');
		var intShipval=intShipVal.split('|');
		
		for(var i=0;i<intbutlp.length;i++){					
			if(intbutlp[i]!=""){
				if(intShipval[i] == 'NO')
				{
					eval("$('"+ msgElg +intbutlp[i]+"').hide()");					
					eval("$('"+ msgInElg +intbutlp[i]+"').hide()");
				}
				if(intShipval[i] == 'YES')
				{
					eval("$('"+ msgElg +intbutlp[i]+"').show()");					
					eval("$('"+ msgInElg +intbutlp[i]+"').hide()");
				}
			}
		}
	}
	
	if(intShipJspChk == 'true'){
	  fnHideForIntShipCompare(pnolist,intShipSfVal,intShipbut,iShpSaveCart,iShpSaveCartSoft,intShipVal);
	}
}
