/* Variable Declaration - Starts Here */

//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;

//setting International Shipping variable to false
var intShipJspChk = 'false';

// Initialize storeId with b2b storeid
var storeId=10101;
var catalogId = 10101;26
var cmdStoreId=10153;
var cmdCatalog=12605;
/* Variable Declaration - Ends Here */


/* 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 */


/* 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();
}


/* Universal profile - starts here */

function fnUnivprofStarterList(starterCount, mgurl, slurl, curStoreId, curCatalogId)
   		{

   			var dynamicCategoryUrl = mgurl;

       		var starterListCategory = slurl;
   			var catalogId = curCatalogId;
   			var storeId = curStoreId;

   			var subCategory = document.getElementById("starterListsName_"+starterCount).value;


   			var stList = subCategory.split(" ");
   			var subCat="";
   			var flag = false;
   			for(var i=0;i<stList.length;i++){
   				if(flag){
   					subCat = subCat+"+";
	   				subCat = subCat+stList[i];
	   			}
   				else{
   					subCat = subCat+stList[i];
   					flag = true;
   				}
   			}
   			var url = dynamicCategoryUrl+"/slc_"+storeId+"_"+catalogId+"_"+starterListCategory+"_"+subCat+"_true";
   			return url;
   			//location.href=url;
//			window.open(url,'windowname2',
  //                      'scrollbars=1,fullscreen=yes,toolbar=1');

       	}



/* Universal profile - ends here */



 // 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;
  }
}

// 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);
    bindEventsForRR();
}

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 */

/* Map Price pop up Method - Starts  Here */
function mapClick(elm){
		var overlayToShow = '#lb_mapPrice';
        if ($(overlayToShow).length) {
            $(overlayToShow).remove();
        }
        var mapCode = ''
        mapCode += '<div id="lb_mapPrice" class="lightbox mapPrice" style="display:block">'
        mapCode += '<div class="lightboxBody">'
        mapCode += '<div class="lb_header"><span>Why Don\'t We Show the Price?</span>'
        mapCode += '<a class="close" onclick="hidebox(\'#lb_mapPrice\');" href="javascript:void(0)">Close</a><div class="clear"></div></div>\n'
        mapCode += '<div class="lb_content"><div class="leftCol">\n'
        mapCode += '<p>Manufacturers sometimes ask retailers not to advertise and display a price below a certain limit.</p>\n'
		mapCode += '<p>When shopping in a store, you may have to ask a salesperson for the price. On a web stie, you may have to ask for the price by clicking on "Click to see our price."</p></div>\n'
        mapCode += '<div class="rightCol"><div class="saveStory">\n'
        mapCode += '<div class="youPay"><span class="pricing"></span></div>\n'
        mapCode += '<div class="origPrice"><span class="text">Original Price</span><span class="pricing"><del>*</del></span></div>\n'
        mapCode += '<div class="savings"><span class="text">You save</span><span class="pricing"></span></div>\n'
        mapCode += '<div class="callout"><p>* Does not include tax, installation, handling or delivery charges</p></div>\n'
        mapCode += '</div></div>\n'
        mapCode += '<div class="clear"></div>'
        mapCode += '</div></div></div>'
        $("body").append(mapCode);
        var foo = $(elm).offset();
        var thisPar = $(elm).parent();
        var tp = thisPar.find("div.truePrice").html().split("$")[1];
        tp = parseFloat(tp).toFixed(2);
        var rp = thisPar.find("span.salePrice del").html().split("$")[1];
        rp = parseFloat(rp).toFixed(2);
        $(".lightbox .youPay .pricing").text("$"+tp+"*");
        $(".lightbox .origPrice del").text("$"+rp);
        $(".lightbox .savings .pricing").text("$"+parseFloat(rp-tp).toFixed(2));
        showbox(overlayToShow);
        return false;
};
/* Map Price pop up Method - Ends  Here */

/* mapPrice.js - 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) document.getElementById(id).style.display = "";
    return true;
}

function hideBox (id) {
    if(document.getElementById) 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()
{
    var k = null;
    if(document.keywordForm != null) {
        k = document.keywordForm.keyword;
    }
    else if(document.searchForm != null) {
        k = document.searchForm.keyword;
    }
    var v = k.value;
    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;
}

// 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){
      //console.log('openRebate() running...');
      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')=='product'||$('body').attr('id')=='softline'
    || $('body').attr('id')=='dynamiccategory'  || $('body').attr('id')=='compare' || $('body').attr('id')=='collection' || $('body').attr('id')=='product'){
      specialOffers('rebateDet',storeId,cmdCatalog,catentry);
    }
    else if((null != isSaveForLater) &&(isSaveForLater == 'YES')){
    	specialOffers('rebateDet',storeId,cmdCatalog,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:''});
        }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:     1000000,
            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'}).insertAfter('#curtain').inmode(duration);
					//$('#ajaxmodal').show().centerOnScreen();
				}
			}else{
            $('#ajaxmodal').remove();
				$('<div id="ajaxmodal" class="'+params.ajaxclass+'"/>').css({display:'none'}).insertAfter('#curtain').outmode(duration);
				//$('#ajaxmodal').centerOnScreen();
        }
		}
		if(params.closeonclick){
			curtain.unbind().click(function(){
                curtainOverlay({closing:true});
            });
        };
    };
};

/* THROW UP A CURTAIN ON AN ELM  - Ends Here */


/* SHIPPING METHOD CHECKBOX FUNCTION  - Starts Here */

function changeShipMeth(elm){
    $(elm).parents('.shipMethod').find('label').removeClass('current');
    $(elm).parent('label').addClass('current');
}

/* SHIPPING METHOD CHECKBOX FUNCTION  - Ends Here */


/* GIFT WRAP MODAL LAUNCH FUNCTION  - Starts Here */
/*
launchGWmodal = function(orderId, orderItemId, storeId, catalogId, selectedGWCatId, comments, productName, productPartNumber, cmdStoreId) {
    var productNameDecode = unescape(productName);
    var urlforAjax = "";
    var emptyString = "";
    if(selectedGWCatId != ""){
        urlforAjax = "/shc/s/GiftWrapModalWindowView?storeId="+storeId
                        +"&orderId="+orderId+"&catalogId="+catalogId
                        +"&gwParOrderItemId="+orderItemId+"&selGiftWrapCatId="+selectedGWCatId
                        +"&comments="+comments+"&productName="+productNameDecode
                        +"&productPartNumber="+productPartNumber+"&cmdStoreId="+cmdStoreId;
    } else{
        urlforAjax = "/shc/s/GiftWrapModalWindowView?storeId="+storeId
                        +"&orderId="+orderId+"&catalogId="+catalogId
                        +"&gwParOrderItemId="+orderItemId+"&selGiftWrapCatId="+emptyString
                        +"&comments="+emptyString+"&productName="+productNameDecode+
                        "&productPartNumber="+productPartNumber+"&cmdStoreId="+cmdStoreId;
    }
    curtainOverlay({ ajaxmodal:true, ajaxclass:'giftwrapModal', closeonclick:false, color:'#335597', trans:0.3 });
    $.ajax({
        url: urlforAjax,

        cache: false,
        success: function(data){
            $('#ajaxmodal').append(data).centerOnScreen();
            giftWrapFunctionality();
        }
    });
    //return false;
}*/
/*  GIFT WRAP MODAL LAUNCH FUNCTION  - Ends Here */


/* DOM READY CALLS  - Starts Here */

$(function(){
    $('.shipMethod').find('input:radio').click(function(){changeShipMeth(this)});
    //$('#shoppingcart div.giftwrap a').click(launchGWmodal);
});

/* 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").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') == 'product') && (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) {

    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.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);

                    /* 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'})
                    } else {
                        $('.closeWin').css({height:'19px',width:'19px',position:'absolute',top:'5px',right:'5px',background:'url(../img/closeWindow.gif) no-repeat'});
                    }
                    /* CODE CUSTOMISED TO CORRECT IMAGE PATH. PLEASE RETATIN THIS CHANGE- END */

                    $('#DHTMLcontent').find(settings.contentname).width(settings.windowWidth);
                    $('#DHTMLcontent').find(settings.contentname).height(settings.windowHeight);
                    if(!$.browser.msie){
                    $('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
                    }
                    else{
                    $('#DHTMLwrap').width($('#DHTMLcontent').width()+12);
                    }
                    if(!$.browser.msie){
                    $('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
                    }
                    else{
                    $('#DHTMLwrap').height($('#DHTMLcontent').height()+12);
                    }
                    $('#DHTMLwrap').add('#DHTMLcontent').show('fast');
                    $('.closeWin').click(function(){
                        $('#DHTMLwrap').add('#DHTMLcontent').fadeOut('fast',function(){
                            $(this).remove();
                        });
                    });
                }
            });
    }
}

$.fn.dynamicPopup = function(settings) {
    var settings = $.extend({
        filename: 'default.html',
        contentname: '#popup',
        windowWidth: '300px',
        windowHeight: '100px',
        jsonFlag: false
    },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;
   //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 _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();
    }
    fixInfoHeight();
}

// 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);*/

/* 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;
}

/*Special Offers: Start */

function specialOffers(activeTab,storeId,catalogId,catentryId) {
        /* Dk modification: if Quick View is open, close it before showing
           Special Offers. We will re-show it after Special Offers is closed */
        var quickViewStatus = false;
		if($('div.quickView').text() != "" && $('div.quickView').text()!= undefined)
        {
        	SEARS.QuickView.close();
        	quickViewStatus = true;
        }
        /* --end Dk modification */
        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">';
        /* Dk modification: not handling CSS here, but rather allow inheritance
           via global framework
        $(rebateMessageCSS).appendTo('head');
        $(printCSS).appendTo('head');
        -- end Dk modification */

        var isSaveForLater;

        if(null != document.getElementById("saveForLater") ){
        	isSaveForLater =document.getElementById("saveForLater").value;
        }
        //var isSaveForLater =saveForLater;
        var specialOfferView;


        if((null != isSaveForLater) &&(isSaveForLater == 'YES')){
        		specialOfferView = 'BrowseSpecialOfferViewHttps' ;
        }
        else{
                specialOfferView = 'BrowseSpecialOfferView' ;
        }

        $.ajax({
                /* Dk modification: using sample data file for templates*/
                url: ''+specialOfferView+'?storeId='+storeId+'&activeTab='+activeTab+'&catalogId='+catalogId+'&catentryId='+catentryId,
                //url: ''+specialOfferView+'?storeId='+storeId+'&activeTab=splOffr&catalogId='+catalogId+'&catentryId='+catentryId,
                //url: 'data/BrowseSpecialOfferView.txt',
                /* --end Dk modification */


                success: function(data){
                    $(rebateSpecialOffers).html(data);
                    /* Dk modification: insert window controls */
                    var winControlHTML = '<div class="drag dragLeft"/><div class="drag dragRight"/><div class="drag dragBottom"/><div class="drag dragTop"/>';
                    $(rebateSpecialOffers).prepend(winControlHTML);
                    /* --end Dk modification */
                    $('#ajaxmodal').bgiframe().centerOnScreen();

                    $(rebateSpecialOffers).show();
                    $('#curtain').add('#closeWinDeals').unbind().click(function(){
                        /* Dk modification: not handling CSS here, but rather allow inheritance
                        via global framework
                    	$('head link[@href *= "rebates_print.css"]').remove();	*/
                        curtainOverlay({closing:true});
                    	$('div#rebateSpecialOffers').remove();
                        /* Dk modificaiton: Reopen Quick View if it was closed in order to
                           show Special Offers content */
                        if(quickViewStatus){
                        	if (SEARS.QuickView.temporarilyClosed == true || SEARS.QuickView.temporarilyClosed!='' || SEARS.QuickView.temporarilyClosed!=undefined) {
                          	  SEARS.QuickView.launch();
                        	}
                        }
                        /* ---end Dk modification */
                    });

                    /* Dk modification: add drag handles to our UI */
                    if(!$.browser.msie){$(rebateSpecialOffers).draggable({handle:$(".drag")})};
                    /* --end Dk modification */
                    /* Dk modification: hide detail content */
                    $('#dealData .details').hide();
                    /* --end Dk modification */
                    rebates_tabs();
                    rebateTabDisp();
                    splFinTabDisp();
                    scrollSize();
                    detailView();

                }
        });
    }

   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((null != isSaveForLater) &&(isSaveForLater == 'YES')){
        		rebateDetailsView = 'RebateDetailsCmdSecure' ;
        }
        else{
        		rebateDetailsView = 'RebateDetailsCmd';
        }


        $.ajax({
                /* Dk modification: using sample data file for templates*/
                url: ''+rebateDetailsView+'?storeId='+storeId+'&RebateId='+rebateIds+'&dealsPopUp='+frmDealsPopUp,
                //url: 'data/RebateDetailsCmd.txt',
                /* --end Dk modification */
                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((null != isSaveForLater) &&(isSaveForLater == 'YES')){
        		browseStaticView = 'BrowseStaticPageCmdSecure' ;
        }
        else {
        		browseStaticView = 'BrowseStaticPageCmd' ;
        }



        $.ajax({
                /* Dk modification: using sample data file for templates*/
                url: ''+browseStaticView+'?storeId='+storeIdFin+'&catalogId='+catalogIdFin+'&langId='+langIdFin+'&catalogInd='+catalogIndFin+'&vName='+vNameFin+'&dzName='+dzName,
                //url: 'data/BrowseStaticPageCmd.txt',
                /* --end Dk modification */
                type:'GET',
                success: function(data){
                /* Dk modification: Finance data has CSS as <link /> hardcoded. Using Dk templates we
                   do not want this stylesheet as it's not possible to disable CSS that is not linked
                   to the <head> element. Regex is not ideal but seems the only way without changing DB */
                var data = data.replace(/<link.*?>/,'');
                /* --end Dk modification */
				$('#splFinDet').html(data);
                /* --end Dk modification */
				$('#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');
            }
        }
    );
    /* Dk modification: add hover states to tab controls */
    $(tabLink).mouseover(function(){
        $(this).parent().addClass('hover');
    });
    $(tabLink).mouseout(function(){
        $(this).parent().removeClass('hover');
    });
    /* --end Dk modification */
}

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();
	});
	}
});

/*Special Offers: End */

$(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 removeItems() {
			var maxcount = document.WishListForm.maxcount.value;
			document.WishListForm.itemCatentryId.value="";
			document.WishListForm.itemSequence.value ="";
			var checkedCount = 0;
			for(var i=1;i<=maxcount;i++){
				var checkVal =  eval("document.WishListForm.check"+i);
				var selItemCatentryId =  eval("document.WishListForm.catentryId"+i);
				var selItemSequence ="";
				if(document.getElementById("sequence"+i) != null){
					selItemSequence = eval("document.WishListForm.sequence"+i);
				}
				if(checkVal){
					if(checkVal.checked){
							checkedCount++;
							document.WishListForm.itemCatentryId.value+=selItemCatentryId.value+"/";
							if(selItemSequence != ""){
							document.WishListForm.itemSequence.value+=selItemSequence.value+"/";
							}
					}
				}
			}
			if(checkedCount != 0) {
			    itemCount = checkedCount;
				var itemCatentryId = document.WishListForm.itemCatentryId.value;
				var itemSequence = document.WishListForm.itemSequence.value;
				var url = "DeleteItemFromListCmd?storeId="+document.WishListForm.storeId.value+"&catalogId="+document.WishListForm.catalogId.value+"&langId="+document.WishListForm.langId.value+"&cmdStoreId="+document.WishListForm.cmdStoreId.value+"&listId="+document.WishListForm.listId.value+"&pageFlag="+document.WishListForm.pageFlag.value+"&itemCatentryId="+itemCatentryId+"&itemSequence="+itemSequence;
				window.location.href=url;
				//ajaxCallForCM(url);
			}
			else{
				err = document.getElementById("errorMsg");
				errString = "Please select atleast one item.";
				err.style.display="";
				err.className="errorbox";
		  		err.innerHTML = "<strong>"+errString+"</strong>";
		  		return false;
			}
      }

function removeToolItems() {
			var maxcount = document.ToolForm.maxcount.value;
			document.ToolForm.itemCatentryId.value="";
			document.ToolForm.itemSequence.value ="";
			var checkedCount = 0;
			for(var i=1;i<=maxcount;i++){
				var checkVal =  eval("document.ToolForm.check"+i);
				var selItemCatentryId =  eval("document.ToolForm.catentryId"+i);
				var selItemSequence ="";
				if(document.getElementById("sequence"+i) != null){
					selItemSequence = eval("document.ToolForm.sequence"+i);
				}
				if(checkVal){
					if(checkVal.checked){
							checkedCount++;
							document.ToolForm.itemCatentryId.value+=selItemCatentryId.value+"/";
							if(selItemSequence != ""){
							document.ToolForm.itemSequence.value+=selItemSequence.value+"/";
							}
					}
				}
			}
			if(checkedCount != 0) {
			    itemCount = checkedCount;
				var itemCatentryId = document.ToolForm.itemCatentryId.value;
				var itemSequence = document.ToolForm.itemSequence.value;
				var url = "DeleteItemFromListCmd?storeId="+document.ToolForm.storeId.value+"&catalogId="+document.ToolForm.catalogId.value+"&langId="+document.ToolForm.langId.value+"&cmdStoreId="+document.ToolForm.cmdStoreId.value+"&listId="+document.ToolForm.listId.value+"&pageFlag="+document.ToolForm.pageFlag.value+"&itemCatentryId="+itemCatentryId+"&itemSequence="+itemSequence+"&UPListView=true";
				window.location.href=url;
				//ajaxCallForCM(url);
			}
			else{
				err = document.getElementById("errorMsg");
				errString = "Please select atleast one item.";
				err.style.display="";
				err.className="errorbox";
		  		err.innerHTML = "<strong>"+errString+"</strong>";
		  		return;
			}
      }


function removeWishlistItems() {
			var maxcount = document.WishListForm.maxcount.value;
			document.WishListForm.itemCatentryId.value="";
			document.WishListForm.itemSequence.value ="";
			var checkedCount = 0;
			for(var i=1;i<=maxcount;i++){
				var checkVal =  eval("document.WishListForm.check"+i);
				var selItemCatentryId =  eval("document.WishListForm.catentryId"+i);
				var selItemSequence ="";
				//if(document.getElementById("sequence"+i) != null){
				//	selItemSequence = eval("document.WishListForm.sequence"+i);
				//}
				if(checkVal){
					if(checkVal.checked){
							checkedCount++;
							document.WishListForm.itemCatentryId.value+=selItemCatentryId.value+"/";
							if(selItemSequence != ""){
							document.WishListForm.itemSequence.value+=selItemSequence.value+"/";
							}
					}
				}
			}
			if(checkedCount != 0) {
			    itemCount = checkedCount;
				var itemCatentryId = document.WishListForm.itemCatentryId.value;
				var itemSequence = document.WishListForm.itemSequence.value;
				var url = "DeleteItemFromListCmd?storeId="+document.WishListForm.storeId.value+"&catalogId="+document.WishListForm.catalogId.value+"&langId="+document.WishListForm.langId.value+"&cmdStoreId="+document.WishListForm.cmdStoreId.value+"&listId="+document.WishListForm.listId.value+"&pageFlag="+document.WishListForm.pageFlag.value+"&itemCatentryId="+itemCatentryId+"&itemSequence="+itemSequence+"&UPListView=true";
				window.location.href=url;
				//ajaxCallForCM(url);
			}
			else{
				err = document.getElementById("errorMsg");
				errString = "Please select atleast one item.";
				err.style.display="";
				err.className="errorbox";
		  		err.innerHTML = "<strong>"+errString+"</strong>";
		  		return;
			}
      }


function ajaxCallForCM(urlForDelete) {

    var catalogId = document.WishListForm.catalogId.value;

    var deleteItem = {
    method: 'GET',
    asynchronous: true,
    postBody: '',
    //Handle successful response
    onSuccess: function(t) {

    },
        // Handle other errors
        onFailure: function(t) {

        }
    };  // end of global var prodOptionZipOpt

        var url = urlForDelete;
        new searsAjax(url, deleteItem);

}

 //function for submitting the form form for Clubsearch
 function submitform(){

	//Getting the parameters
	var phno = document.MemberInfo.phno.value;
	var fname = document.MemberInfo.fname.value;
	var lname = document.MemberInfo.lname.value;

	if(phno == ""){
		document.getElementById('popuperrormsg').style.display="block";
       	document.getElementById('errormsg').innerHTML= "Please enter a Phone No.";
 	return false;
	}
	else{
		phno=reformat(phno);
		var tel = fnValidatePhone(phoneTrim(phno));

		if(!tel){
			document.getElementById('popuperrormsg').style.display="block";
        	document.getElementById('errormsg').innerHTML="Please enter a valid 10 digit Phone No.";
			return false;
 		}
 		else{

 		var areacode = phno.substring(0,3);
 		var phno = phno.substring(3,10);;

 		var url = "SearchMemCmd?&storeId=10153&PhNo="+phno+"&FName="+fname+"&LName="+lname+"&Areacode="+areacode;
 		ajaxCallForCMSearch(url);
 		}
 	}
}

 //Ajax method for Clubsearch

	function ajaxCallForCMSearch(urlForSearch) {

    	var searchmem = {
   	 	method: 'GET',
    	asynchronous: true,
    	postBody: '',
    	//Handle successful response
    	onSuccess: function(t) {

      		var response = eval("(" +t.responseText+ ")");
      		if (response.success == 'true') {

       			var optionValue=response.MemberNo;
       			var error=response.error;
       			if(error!=""){
      				document.getElementById('popuperrormsg').style.display="block";
       				document.getElementById('errormsg').innerHTML=error;
       			}else if(optionValue=='NoRec'){
       				document.getElementById('custcaremessage').style.display="none";
       				document.getElementById('popuperrormsg').style.display="none";
       				document.getElementById('tabular').style.display="none";
       				document.getElementById('results').style.display="block";
       				document.getElementById('resultmsg').innerHTML="No results Found";
       			}
       			else if(optionValue=='more'){
       				document.getElementById('popuperrormsg').style.display="none";
       				document.getElementById('tabular').style.display="none";
       				document.getElementById('results').style.display="block";
       				document.getElementById('custcaremessage').style.display="block";
      				document.getElementById('resultmsg').innerHTML="Your search pulled multiple results";
       				document.getElementById('custcaremsg').innerHTML="Contact Sears Customer Care at xxx-xxx-xxxx and someone will assist you in retrieving your club number.";
       			}
       			else{
       				document.getElementById('custcaremessage').style.display="none";
       				document.getElementById('popuperrormsg').style.display="none";
       				document.getElementById('tabular').style.display="none";
       				document.getElementById('results').style.display="block";
       				document.getElementById('resultmsg').innerHTML="Here is your customer number"+optionValue;
      			}
      	}
      	else {
       		document.getElementById('popuperrormsg').style.display="none";
       		document.getElementById('tabular').style.display="none";
       		document.getElementById('results').style.display="block";
       		document.getElementById('custcaremessage').style.display="block";
       		document.getElementById('resultmsg').innerHTML="Unable to process your Search";
       		document.getElementById('custcaremsg').innerHTML="Contact Sears Customer Care at xxx-xxx-xxxx and someone will assist you in retrieving your club number.";
      }

    },
    // Handle other errors
    	onFailure: function(t) {
       	document.getElementById('popuperrormsg').style.display="none";
       	document.getElementById('tabular').style.display="none";
       	document.getElementById('results').style.display="block";
       	document.getElementById('custcaremessage').style.display="block";
       	document.getElementById('resultmsg').innerHTML="Unable to process your Search";
       	document.getElementById('custcaremsg').innerHTML="Contact Sears Customer Care at xxx-xxx-xxxx and someone will assist you in retrieving your club number.";
      }
    };
    var url = urlForSearch;
    new searsAjax(url, searchmem);
   }

  //Validation for Phone No
	function fnValidatePhone(phoneNumber) {
		var temp = "";
		temp = phoneNumber;
		var firstDigit= temp.substring(0,1);
    	var numeric = fnIsNumeric(temp);
		if (!numeric){
    	return false;
		}
		else  if(temp.length >= 12 || temp.length < 10) {
  		return false;
    	}

  		else if (temp.length == 10 )
  		{
   			if((firstDigit == 0 || firstDigit == 1))
     		{
     		return false;;
    		}
      	return true;
  		}
 		else if (temp.length == 11  )
  		{
  			if((firstDigit == 0 || firstDigit == 1))
      		{
  			var ch = temp.charAt(1);
  				if(ch == 0 || ch == 1)
   				{
    	  			return false;
  				}
 			}
 		return true;
 		}
	}


 //Function for triming the phone no
   function phoneTrim(sString)
	{
		sString = trimLeft(sString);
		sString =trimRight(sString);
		return sString;
	}

//Function for trimming left
	function trimLeft(sString)
	{
	while (sString.substring(0,1) == ' ')
		{
		sString = sString.substring(1,sString.length);
		}
	return sString;
	}

//Function for trimming right
	function trimRight(sString)
	{
		while (sString.substring(sString.length-1,sString.length) == ' ')
		{
			sString = sString.substring(0,sString.length-1);
		}
		return sString;
	}


//Function for Reformatting the phone no
  	function reformat(value) {
	// remove special characters like "\/-(). " and ","
		re = /\$| |\(|\)|\+|\[|\-|\_|\]|\[|\}|\{|\\|\/|\$|\./g;
		var value = value.replace(re, "");
		return value;
	}

 //Function for checking whether the phone no value is numeric
 	function fnIsNumeric(value){
		var regEx = /^[0-9]+$/;
		if (!regEx.test(value)){
		return false;
		}
		return true;
	}

function bindEventsForRR(){
	//Binding Map price and Great price events to RR products
	$("a.mapLink").unbind().click(function(){mapClick(this)});
	 $("a.greatPrice").unbind().click(function () {
 	  var overlayToShow = '#lb_greatPrice';
        if ($(overlayToShow).length) {
            $(overlayToShow).remove();
        }
       var defDiv = '<div id="lb_greatPrice" class="lightbox greatPrice" style="display:block"><div class="lightboxBody"><div class="lb_header"><span>Great Price</span><a class="close" onclick="hidebox(\'#lb_greatPrice\');" href="javascript:void(0)">Close</a>'
						 +'<div class="clear"></div></div><div class="lb_content"><p>'+ this.getAttribute("info")+ '</p><div class="clear"></div></div></div></div>';
 	  $("body").append(defDiv);
 	  showbox(overlayToShow);
      return false;
    });
}
addLoadEvent(bindEventsForRR);

	//Method for share wishList functionality in Craftsman

	function dispCMIFrameWishlist(paramLangId,paramStoreId,paramCatalogId,paramListId,paramSender)
	{

		var langId = paramLangId;
		var storeId = paramStoreId;
		var catalogId = paramCatalogId;
		var listId = paramListId;
		var sender = paramSender;

		document.getElementById("shareModalAbsoluteWrap").style.display="block";
		document.getElementById("sender_name").value=sender;
		document.getElementById("sender_email").value=sender;
		//document.getElementById("sftIframe").style.height="405px";
		//document.getElementById("sftIframe").style.top="322px";
		url="EmailWishListCMView?langId="+langId+"&storeId="+storeId+"&catalogId="+catalogId+"&listId="+listId+"&sender="+sender;
	 	//document.getElementById("sftIframe").src=url;
	 	document.getElementById("stfWrapper").style.display="block";
	 	/*showBox('stfWrapper');*/
	}

	//For Craftsman
	function hideBox () {

	if(document.getElementById("shareModalAbsoluteWrap")){
	document.getElementById("shareModalAbsoluteWrap").style.display="none";
    return true;
    }
}


	function checkEmailForm(form)
	{


	 //var name = document.sendToFriendForm.visitorName.value;
       // var vEmail = document.sendToFriendForm.visitorEmail.value;
       // var fEmail = document.sendToFriendForm.friendsEmail.value;

		message = new String(document.emailToFriend.wishlist_message.value);
		form.sender_name.value = form.sender_name.value.replace(/^\s+/g, "");
		form.recipient.value = form.recipient.value.replace(/^\s+/g, "");
		form.sender_email.value = form.sender_email.value.replace(/^\s+/g, "");
		sender_name = new String(document.emailToFriend.sender_name.value);
		sender_email = new String(document.emailToFriend.sender_email.value);
		friend_email = new String(document.emailToFriend.recipient.value);
        var vArray = friend_email.split(";");
		var count;

		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@)/;

		error = 0;
		format = 0;

	/*	if (sender_name == ''){
			alert("Please enter your name");
			error=1;
		}
		else */
		if (friend_email == ''){
			alert("Please enter Your mail address");
			error=1;
		}
		else if (sender_email == ''){
			alert("Please enter Your Friend's mail address");
			error=1;
		}
	    else if(!sender_email.match(regex1)){
	    	alert(" The e-mail address you entered appears incorrect.  (Example of a correct address: kmart@kmart.com)  Please check your information and try again. ");
			format = 1;
	    }
	    else if(sender_email.match(regex2)){
	        alert(sender_email + " is not allowed");
	        format = 1;
	    }
	    else{
	    	for (count=0; count < vArray.length; count++){
           		var vElem = vArray[count];
           		if(!vElem.match(regex1)){
	       		alert(" The e-mail address you entered appears incorrect.  (Example of a correct address: kmart@kmart.com)  Please check your information and try again. ");
				format = 1;
        		}
        		else if(vElem.match(regex2)){
	        	alert(vElem + " is not allowed");
	        	format = 1;
	        	}
	        }
	    }
	    if(message.length>200){
	    	alert("Message exceeds 200 characters");
	    	error = 1;
	    }
		if(error !=1 && format !=1){

			form.submit();
			var temp ='<div class="emailModalTop" style="top: 92px; left: 835px;"></div>'+'<h2>'+
'                <a id="closeButton" title="Close" href="javascript:;"></a>'+
'                E-mail sent'+
'            </h2>'+
'            <p class="emailConfirmedMessage">'+
'            	Thank you for sharing this link with your friend(s).'+
'            </p>';
document.getElementById('modalWrapper').innerHTML=temp;

//document.getElementById('sendFriend12')..style.display="block";
			}
			else{
			return false;
			}
	}

	function hidemsgBox() {

	if(document.getElementById("sendFriend12")){
	document.getElementById("sendFriend12").style.display="none";
    return true;
    }
}


/*** Functions added for international shipping changes : Starts ***/

// Gloabl variable to hold domestic county code and currency, this can be set in global config and updated through dyna headers
var DEFAULT_COUNTRY_CODE = "US";
var DEFAULT_CURRENCY_SYMBOL = "USD";
var i18nCookieData = null;

//This function will return a boolean true, if International Shipping is activated
//through global config and (the selected country is not US)/(Selected currency is not Dollar)
//This will be used as a check in all the places for I18N changes in javascript
// IMP: This function should be present in global js of all the stores and should return false for them
function isI18NConvReq(){
	var flag = false;
	var prodPgBoolean = false;
		/*var pageId = $('body').attr('id');
		      if(intShipFlgSwitch == 'TRUE'){
	var cookieData = fnParseCountryCookie();

		            if(cookieData != null && cookieData.countryCode!=DEFAULT_COUNTRY_CODE){
		flag = true;
	}
		      }*/

	
	return flag;
}

/// for creating a cookie to store currently selected country
//this function will be called whenever user will change selected country in the drop down list.
function fnCreateCountryCookie(countryCode, currencyCode, exgRate){
	if(countryCode!=DEFAULT_COUNTRY_CODE && currencyCode!=DEFAULT_CURRENCY_SYMBOL)
	{
	$.cookie("IntnlShip", countryCode+"|"+currencyCode+"|"+exgRate);
	}

}

//This function can be used to fetch the currently selected country by the //user and the exchange rates for the country. This function will parse the //cookie and store the values in global variables.
function fnParseCountryCookie(){
	var cookieData = null;
	if(i18nCookieData != null){
		cookieData = i18nCookieData;
	}else{
		var cokkieVal = $.cookie("IntnlShip");
		if( cokkieVal != null && typeof cokkieVal != "undefined" && cokkieVal.split('|').length == 4){
		var intnlShippingValue = cokkieVal.split('|');
		countryCode = intnlShippingValue[0];
		currencyCode = intnlShippingValue[1];
		exgRate = intnlShippingValue[2];
			quoteId = intnlShippingValue[3];

		cookieData=new Object();
		cookieData.countryCode =countryCode;
		cookieData.currencyCode =currencyCode;
		cookieData.exgRate =exgRate;
			cookieData.quoteId =quoteId;

		i18nCookieData = cookieData;
	}
	}

	return cookieData;
}
/*** Functions added for international shipping changes : Ends ***/
