$(document).ready(function(){

	var count=0;
	$('#actionsForm span').each(function(){
		count += 1;
	});
	if(count == 1){
		$('#actionsForm span').attr('style','display:none');
		if($('#actionsForm span input').val() != 'ship' && ($('#actionsForm small#pd_shippingCal_msg') != null && $('#actionsForm small#pd_shippingCal_msg')!= undefined)){
			$('#actionsForm small#pd_shippingCal_msg').attr('style','display:none');
		}
	}
	
	if(isI18NConvReq()){
		$('#actionsForm span').addClass('intShipHide');
	}
	
	var zipCodeInd =$('input#zipCodeInd').attr('value');
	var eligForAuto=$('input#eligForAuto').attr('value');
	var vendorStore=$('input#vendorStore').attr('value');
	
	if(eligForAuto == 'true' && ((typeof  allRegiSS != 'undefined' && allRegiSS.length > 0) || zipCodeInd == '1')){
		$("#cntr_open_ak_hi").remove();
	}else{
		$("#cntr_open_ak_hi").css("display","block");
		$("#cntr_open_ak_hi").show();
	}
	var SAVE_STORY = $('#p0_price').html();
	if(typeof  allRegiSS != 'undefined' && allRegiSS.length > 0 && ($('input#notViewOnly').attr('value') == 'notViewOnly') && (SAVE_STORY != '')) {			    
		document.getElementById("qty").style.display = 'block'; 
	}
	
	var storeIdReq = $('input#storeIdReq').attr('value');
		
			
	if(storeIdReq==10151)
 		{
		 	var pickUpValue=$('input#pickUpEnable').attr('value');
			 fnPartNum(pickUpValue);
		}
		else
		{
			var tempPartNumber=$('input#partnumber').attr('value');
			updateRecentlyViewedCookie(tempPartNumber,storeIdReq);
		}
		
});

//Function to update recently viewed cookie
function updateRecentlyViewedCookie(partNum,strId){
	//Check if allRegiSS.length is greater than zero
	//If yes then it is zipcode priced item
	// Append 0 if the item is zipcode priced else append 1 for normal items
	if(strId!=10151)
	{
		if(typeof  allRegiSS != 'undefined'){
				if(allRegiSS.length > 0){
				partNum+="|0"; 
			}else{
				partNum+="|1"; 
			}
		}
		else{
			partNum+="|1"; 
		}
	}
	var partNumFromUrl = partNum+'#'+strId;
	if(getCookie('RecentViewPartNum')==''){
		//create a cookie if its not present
		document.cookie = "RecentViewPartNum="+partNumFromUrl+"^;";
	}else{
		//append values to the cookie if exist
		var cookievalue = getCookie('RecentViewPartNum');
		var temp = getNewCookieValue(cookievalue,partNumFromUrl);
		document.cookie="RecentViewPartNum="+temp+";";
	}
}

function getNewCookieValue(cookievalue,partNumFromUrl){
	var temcookiesplit = cookievalue.split('^');
	
	var finalUrl='';
	var returnUrl='';
	var partNumArray=new Array();
	var tempLength = temcookiesplit.length;
	
	for (var i=0;i<tempLength-1;i++){	            
	    if(temcookiesplit[i] != partNumFromUrl){
	    	finalUrl= finalUrl+temcookiesplit[i]+'^';
	    }
	}
	
	returnUrl=partNumFromUrl+'^'+finalUrl;
	return returnUrl;
	
}

//Genarate Part Number if store is Kmart
function fnPartNum(pickUpValue){
	var tempPartNumber=$('input#partnumber').attr('value');
	var pick=pickUpValue;
	
	//Checking whether the store is KMart
	if(storeIdReq==10151) {
		if(pick==1) {
			// appending "0" to part number if product is store pickup enabled
			tempPartNumber+="|0";
			updateRecentlyViewedCookie(tempPartNumber,storeIdReq);
		}else {
			// appending "1" to part number if product is not store pickup enabled
			tempPartNumber+="|1";
			updateRecentlyViewedCookie(tempPartNumber,storeIdReq);
		}	
	}
}

var distrCenter = $('input#distributionCenter').attr('value');
var searsShipCalc = $('input#searsShipCalc').attr('value');
var isInStock = $('input#isInStock').attr('value');
var storeIdReq = $('input#storeIdReq').attr('value');
var storeId = $('input#storeId').attr('value');
var variant = $('input#variant').attr('value');
var regAvlMainFlag = $('input#regAvlMainFlag').attr('value');
var regAvailStoreId = $('input#regAvailStoreId').attr('value');
var maskedName = $('input#maskedName').attr('value');
var mfgPartNumber = $('input#mfgPartNumber').attr('value');
var pickUpVar = '';
var partnumber = $('input#partnumber').attr('value');
var itemId = $('input#itemId').attr('value');
var storeName = $('input#storeName').attr('value');
var storeIdFinal = $('input#storeIdFinal').attr('value');
var isSRESEligible = $('input#isSRESEligible').attr('value');
var isSPUEligible = $('input#isSPUEligible').attr('value');
var islayAwayEligible = $('input#islayAwayEligible').attr('value');
var vcsVertical = $('input#vcsVertical').attr('value');
var isAutomotiveV= $('input#isAutomotive').attr('value');
var preSell = $('input#preSell').attr('value');
var Load = document.getElementById('loading_reg');
var shipFlag = "";	
var shipMsgDiv = document.getElementById('pd_msg_new');
var shipEnterZipDiv = document.getElementById('pd_msg_enterZip');
var shipEnterZipMsgDiv = document.getElementById('pd_msg_enterZip_msg');
var displayZipDiv=document.getElementById('displayZip');
var displayZipButtonDiv=document.getElementById('displayZipButton');
var shipCalDiv = document.getElementById('pd_shippingCal_msg');
var shipEnterZipDivNew = document.getElementById('pd_msg_enterZip_extra');	
var shipZipMsg = 'Enter ZIP code to check ship availability:';
var deliveryZipMsg = '<label for=zipCode">Enter your ZIP code to check availability in your area:</label>';
var pickUpZipMsg = 'Enter ZIP code to select a store for pickup:';
var regionalAvlFl = $('input#regionalAvlFl').attr('value')
var isScimEnabled = $('input#scimEnabled').attr('value');
if(storeIdReq=='10154'){
	var catalogId = $('input#catalogId').attr('value');
}
var ddcRegionalAvlFl = '';
var enterZipMsg = '';
var zipMsg = '';
var storeMsg = '';
var catEntryIdScim = '';
var langId = -1;
var cmdStoreId = storeIdFinal;
var availButtonOnLoad= 
	'<input alt=\"check availability button\" id=\"chkAvailBtn\" type=\"image\" src=\"'+jspStoreImgDir+'/img/buttons/btn_check_availability.gif\" width=\"126\" height=\"22\" align=\"absmiddle\" onclick=\"javascript:submitZipCode(this);\"/> ';	      
var shipZipMsg = 'Enter ZIP code to check ship availability:';
var deliveryZipMsg = '<label for=zipCode">Enter your ZIP code to check availability in your area:</label>';
var pickUpZipMsg = 'Enter ZIP code to select a store for pickup:';
var shipCalDiv = document.getElementById('pd_shippingCal_msg');	
var shipCal=$('input#shipCal').attr('value');
var productURL = $('input#productURL').attr('value');
var itemPartnumber = $('input#itemPartnumber').attr('value');
var itemMfrPartnumber = $('input#itemMfrPartnumber').attr('value');
var shipFlag = "";	
if(storeIdReq=='10153' || storeIdReq=='10151' || storeIdReq=='10154'){
	pickUpVar = $('input#ppaPickUpOption').attr('value');
}else{
	pickUpVar = $('input#pickUpOption').attr('value');
}
var pickupVarA = "0" ;
var shipV = 0;
var deliveryV = 0;
var regionalDiv;
var dbFlagVal = 'N';
var pickupStoreIdC = '';
var zipCode = '';
var shipCalciMsg = '<a href=\"javascript:void(null);"\" onclick=\"javascript:urlforShipCal(this)\" >Shipping Calculator</a>';

catentryVal = $('input#itemId').attr('value');

var	deliveryChecked = 'false';
//Set to 'true' if pickup is clicked.
var pickUpSelected = 'false';
var shipSelected = 'false';
var changeStoreFlag = 'N';
var responseFFM = "";
var datefromScim = "";
var isOutOfStock='false';
 var allOptionsFlag ='false';
var shipOption = 0;
var ndd =0;
var deliveryOption = 0;
var pickupOption = '0';
var itemA = '';	
var Load = document.getElementById('loading_reg');
var pickUpAvl = '<div id="pickUpAvailable" class = "">';
var alsoPara = '<p class="also">- also -</p>';
var rtiZipcode = 0;
var delZipMsg = '';
var rtiSuccess ;
var scimCalled ;
var zipPickUp = '';
var zipDel = '';
var	rtiZipMsg = '';

$(function(){
/*Onload functionalities for productpage Handling exceptions and selecting fulfilment onLoad*/
		if(storeIdReq=='10153'){
	    	displayBingCashBack();
	    }	
		if(typeof dynamicPopupPath != 'undefined' && typeof dynpop != 'undefined'){
	  		$(function(){$('div.preOrderSelect a').dynamicPopup({filename: dynamicPopupPath+'&vName=PresellDetails',contentname: '.preOrderNote',windowWidth: '400px',windowHeight: '375px'});});
		}	
		/*Code for caching of the error or popup messages*/
		addToWishlistCalled = gup('addToWishlistCalled');
		cartException = "3";
		wishlistException = "3";
		wishlistErrorFlag = gup('errorMessage');
		wishlistExceptionMessage = "";
		//errorMessageString="";
		var tempErrorMsg="";
		if(typeof errorMessageString !='undefined'){
			tempErrorMsg=errorMessageString;
		}
		cartExceptionMessage = tempErrorMsg;
		
		
		if(addToWishlistCalled == 'YES'){
		    if(wishlistErrorFlag!=""){
		        /*The exception message was picked from the url variable errorMessage*/
		        wishlistException = "1";
		        wishlistExceptionMessage = "Unable to add item to wishlist";
		    }
		    else{
		        /*There was no exception thrown*/
		        wishlistException = "0";
		    }
		}
		if(tempErrorMsg !=""){
		    /*The exception message was picked from the errormessagescart.jspf*/
		   
		    cartException = "1";
		    imgPath = jspStoreImgDir+kmartButtonsDir;
		}

	if(document.getElementById("saveLaterLink")){
        displayErrorPopUp_WishList();
    }
    if(document.getElementById("addCart")&& gup('xCheckOut') == "")
    {	
        displayErrorPopUp_Cart(); 
    }
        	
	if(document.getElementById("xCheckout") && gup('xCheckOut') == "true")
    {	
        displayErrorPopUp_xCheckout(); 
    }        	
    if(regAvlMainFlag == 'true'){	
    	//Reads the zipcodes from the cookie if present.    	
   		chkZipCookies();   	
    } else {
	zipCode = getCookie('zipCode'+storeIdReq); 
	}
	var object;
	
	var Load = document.getElementById('loading_reg');
	addLoadEvent(showPopup);
	var showDelivery = true; 	
	
	if(variant == '0'){

		var actionPartNumberDiv = document.getElementById('actionPartNumber');
	    if(actionPartNumberDiv){
	        document.getElementById('actionPartNumber').value = itemId;
	    }
	}		
		if (distrCenter != null && distrCenter == 'DDC' && regionalAvlFl == 'true'){
		
		 	ddcRegionalAvlFl = 'true';
		}
		
		var pickupStoreId = getCookie('pickupStoreId'+storeIdReq);
		if(pickupStoreId != ""){
	
		    pickupStoreIdC = pickupStoreId;   
		    pickupVarA = "1";

		}
		else{
		    pickupStoreIdC = "0";
		}
		parseUrl();
		if(document.actionsForm.arrivMethd != undefined){
			pickupOnLoad(); 
		}
		
		//if hardline,non ship,zipcode available, delivery avaialble, not in out of stock
		if(((shipV == '0') || (deliveryV=='1')) && (isInStock == '1')){
			if((variant=='0')&& (zipCode!='')  ){   
					if(regAvlMainFlag != 'true')	{
				        displayZipDiv.style.display = "block";
				        shipEnterZipDivNew.style.display = "block";
				        shipEnterZipDiv.style.display = "none";
				        zipCookieDisplay("D");
			        }
			    }     
	        }	
		
		//Countdown - RTI call is made on Page load for Sears SPU/SRES hardline product if zipcode is present in the cookie.
		if((storeIdReq=='10153')  && (pickUpVar == '1') && (zipCode != '' || zipPickUp != '')   && (variant == "0")){
			 /*	RA CONDITION	*/
			 if(regAvlMainFlag != 'true')	{
			 	callRTI();
			 }
		}



/*	Regional Availability starts	*/
if(regAvlMainFlag == 'true'){
	currentPartNo = partnumber;
	catentryVal = $('input#itemId').attr('value');
	pageFlag = 'PRD';
	DDItemList=partnumber;
	dbFlagVal = 'N';	
	
	/* Reading pickup store Unit Id onload */
	var pickupStoreId = getCookie('pickupStoreId'+storeIdReq);
	if(pickupStoreId != ""){
	
	    pickupStoreIdC = pickupStoreId;   
	    pickupVarA = "1";
	
	}
	else{
	    pickupStoreIdC = "0";
	}
	
	
	if(regAvlMainFlag == 'true'){	
		//Reads the zipcodes from the cookie if present.    	
	   	chkZipCookies();   	
	} else {
		zipCode = getCookie('zipCode'+storeIdReq); 
	}
	
	//For displaying availability message for shippable product
	if((distrCenter != '') && (distrCenter != null)  && (isInStock == '1') && ((distrCenter == 'VD') || (distrCenter == 'KCON') || (distrCenter == 'TW') || (distrCenter == 'GC'))){		
	     shipFlag = 'Y';
	     fnOnLoadRAPrdShipRepaint(jsonRegionalAvailability);
	 } else if ((distrCenter != '') && (distrCenter != null)  && (isInStock == '1') && (distrCenter == 'PS')){
	 	shipFlag = 'Y';
	 }
	 if(!fnChkZipCode()){
		if(shipFlag != 'Y')	{
			$('li.delivery').append('<span class="icon"></span> <a id="check" class="checkAvail" href="javascript:;" rel="regionalAvailability" info="'+partnumber+'^N^'+pageFlag+'^'+catentryVal+'">Check Availability</a>');
		}
			$('li.pickup').append(' <span class="icon"></span><a id="check" class="checkAvail" href="javascript:;" rel="regionalAvailability" info="'+partnumber+'^Y^'+pageFlag+'^'+catentryVal+'">Check Availability</a>');
			readyOnLoad();
	}else {
				dbFlagVal = 'Y';
				if(shipFlag != 'Y')	{

					fnOnLoadRAPrdRepaint(jsonRegionalAvailability);
					
				}
				if(pickUpVar == '1')	{
					makeRegionalRTICall();
				}
			}
}

/*	Regional Availability ends	*/	


			
});

$(document).ready(function() {	
	checkProductActions();
	pageFlag='PRD'
});

/* Finds the default option that should be checked on page load*/
function checkProductActions(){
       
     pickupV = 0;
     deliveryV = 0;
     shipV = 0;

    if((distrCenter != '') && (distrCenter != null)  && (isInStock == '1') && ((distrCenter == 'VD') || (distrCenter == 'KCON') || (distrCenter == 'TW') || (distrCenter == 'PS') || (distrCenter == 'GC'))){
    	shipV = 1;
    }
    if((distrCenter != '') && (distrCenter != null) && (isInStock == '1') && (distrCenter == 'DDC') ){
    	deliveryV = 1;
    }
    if(pickUpVar == '1'){
    	pickupV = 1;
    }

    if((shipV == 1) && (pickupV == 1) && (isAutomotiveV == 'true' ) && (preSell == '' || preSell == undefined ) ) {
    	pickupOption = '1';
        checkRadioButtons('pickup');
        pickUpSelected = 'true';
    } else if((shipV == 1) && (pickupV == 1) && (storeIdReq == 10152) && (preSell != '') && (preSell != undefined ) ){
        shipOption = 1;
        checkRadioButtons('ship');
        shipSelected = 'true';
    } else if((shipV == 1) && (pickupV == 1) && (storeIdReq == 10152) ){
        pickupOption = '1';
        checkRadioButtons('pickup');
        pickUpSelected = 'true';
    }else if((shipV == 0) && (pickupV == 1)&& (storeIdReq == 10152) ){
        pickupOption = '1';
        checkRadioButtons('pickup');
        pickUpSelected = 'true';
    }else if( pickupV == 1 &&  storeIdReq == 10161){
        pickupOption = '1';
        checkRadioButtons('pickup');
        pickUpSelected = 'true';
    }else if((shipV == 1) && (pickupVarA == 0) ){
        shipOption = 1;
        checkRadioButtons('ship');
        shipSelected = 'true';
    }else if((shipV == 1) && (pickupV == 0)){
        shipOption = 1;
        checkRadioButtons('ship');
        shipSelected = 'true';
    }else if((shipV == 1)){   
        shipOption = 1;
        checkRadioButtons('ship');
    }else if((deliveryV == 1) && (pickupVarA == 0)){
        deliveryOption = 1;
        checkRadioButtons('delivery');
        deliveryChecked = 'true';
    }else if((deliveryV == 1)&& (pickupV == 0)){
        deliveryOption = 1;
        checkRadioButtons('delivery');
        deliveryChecked = 'true';
    }else if((deliveryV == 1)){   
        deliveryOption = 1;
        checkRadioButtons('delivery');
        deliveryChecked = 'true';        
    }else if((pickupV == 1) && ((preSell == '') || (preSell == undefined))){    
        pickupOption = '1';
        checkRadioButtons('pickup');
        pickUpSelected = 'true';
    }     
	fixInfoHeight();
}

/**Function to check the radio button**/
function checkRadioButtons(name){



    var radioLen = document.actionsForm.arrivMethd.length;

    /* If there is only one element in the radio buttons group*/
    if(typeof radioLen == 'undefined'|| radioLen == undefined )
    {
        document.actionsForm.arrivMethd.checked = true;
    }
    else
    {
        for (i=0;i<document.actionsForm.arrivMethd.length;i++)
        {
            if(document.actionsForm.arrivMethd[i].value == name)
            {
                document.actionsForm.arrivMethd[i].checked = true;
                return;
            }
        }
    }
}

/** This function is called onClick of ATC button. It decides 
/** which function to be called based on the radio button 
/** checked and calls the corresponding function **/
function addCartAvailability(param)	{
	//xCClicked="false";
	//for getting the position of the pop up
	var pos = $('#addCart').offset();
	// for scim call	
	//dbFlagVal = 'N';
	if(param != null || param != undefined){
		var pos = $(param).offset();
	}

	var country='US';
	var intlCookie=$.cookie('IntnlShip');
	
	if(getStoreId() == '10153' && intlCookie != null){
	
		var cookieVal=intlCookie.split("|");
		
		country=cookieVal[0];
		
		if(country != 'US'){
			//setting these two cookies manually to NJ zipcode
			var zipCode='10018';
			cookieName = 'zipCode'+getStoreId();
			$.cookie(cookieName,zipCode);
			cookieNameDel = 'zipCode';
			$.cookie(cookieNameDel,zipCode); 
			shipSelected = 'true'
		} 
	}
	if(deliveryChecked == 'true')	{
		
		if(getStoreId() == '10153' && country != 'US'){
			var objImage = document.getElementById('addCart');
			var mesg = "This item is temporarily unavailable for International Shipping.";
			showErrorMsgPopUpBox(objImage,mesg,'Cart');
		}
		else{
		// initializing for Add to cart functionality
		atcDelFlag = true;	
		// set for making ajax call from global.js
		regionalDiv = 'delivery';


		if(!fnChkZipCode())	{
			// open stanard CA pop up
			showCAPopUp(partnumber);
			$('div#availPopup').attr("style","display: block");
			$('div#availPopup div.standardDiv').attr("style","display: block");
			if(param != null || param != undefined){
				$('div#availPopup').css({top: pos.top - 100, left: pos.left - 300 });
			}else{
				$('div#availPopup').css({top: pos.top - 100, left: pos.left + 300 });
			}
			simAddToCart();
		}
		else	{
			// make a SCIM call to get availability
			makeRegionalDeliveryCall(pageFlag, dbFlagVal, catentryVal, "");
			showCAPopUp(partnumber);
		}
		}
	}
	else if(pickUpSelected == 'true')	{
	   
		if(getStoreId() == '10153' && country != 'US'){
			var objImage = document.getElementById('addCart');
			var mesg = "This item is temporarily unavailable for International Shipping.";
			showErrorMsgPopUpBox(objImage,mesg,'Cart');
		}
		else{
		// initializing for Add to cart functionality
		atcDelFlag = true;	
		// set for making ajax call from global.js
		regionalDiv = 'pickup';

		var regionalClass = $('li.pickup').find('a').attr("class");
		if(regionalClass == 'checkAvail')	{
			// open stanard CA pop up
			showCAPopUp(partnumber);
			$('div#availPopup').attr("style","display: block");
			$('div#availPopup div.standardDiv').attr("style","display: block");
			if(param != null || param != undefined){
				$('div#availPopup').css({top: pos.top - 100, left: pos.left - 300 });
			}else{
				$('div#availPopup').css({top: pos.top - 100, left: pos.left + 300 });
			}
			simAddToCart();
		}
		else	{
			// make a Regional RTI call to get availability
			makeRegionalRTICall();
			showCAPopUp(partnumber);
		}
		}
	}
	else if(shipSelected =='true')	{
	    
		submitAddToCart();
	}
}


/** This has the logic for submitting the ATC form **/
function submitAddToCart(isSmartCartFlag){
	
	simAddToCart();
	//xCClicked="false";
    if(document.addToCart.addToCartBtn.value == 'false') {
    
        if(typeof allRegiSS != 'undefined' && allRegiSS.length >0){
            var regZip = getCookie('zipCode');
            document.forms['addToCart'].zipCode.value = regZip;
        }
		var quantity = 0;
		var quantity = document.getElementById('quant').value;
		if(quantity != '' && (isNumeric(quantity) == 0) && (quantity > 0)){
			if(typeof  allRegiSS != 'undefined' && allRegiSS.length >0){
	            var regZip = getCookie('zipCode');
	            document.forms['addToCart'].zipCode.value = regZip;
	        }
	        //Add to cart button has been clicked once
	        document.addToCart.quantity_1.value = quantity;
	        if(pickUpSelected == 'true'){
	        	document.addToCart.ffm_1.value = responseFFM;
	        	document.addToCart.sresDays_1.value = datefromScim;
	        }
	        document.addToCart.submit();
	        document.addToCart.addToCartBtn.value = 'true';
		} else {
			var objImage = document.getElementById('cart_enable');
			var mesg = "Please enter a valid quantity";
		 	showErrorMsgPopUpBox(objImage,mesg,'Cart');
		}
    } 
}



/** This function is called when ship radio button is clicked **/
function showShipMsg(){

	shipSelected = 'true';
	deliveryChecked = 'false';
	pickUpSelected = 'false';
	
	if(storeIdReq == 10151){
		// For Kmart only - 
       // Omniture to tell where the user selected different fulfillment method starts.
       var s_account;
       if (typeof omAcct != 'undefined') {
              s_account = omAcct;
       }
       if (typeof s != 'undefined') {
              s=s_gi(s_account);
              s.linkTrackVars="eVar8";
              s.eVar8="Cart"; // For product page, set to Product. 
              s.tl(this, 'o', 'Change Fulfillment Method');
       }
       // Omniture to tell where the user selected different fulfillment method ends.
       }
	    getRadioButtonValue();  
	    holidayShipCalCombo();
		fixInfoHeight();
	}
	function getRadioButtonValue(){
		  	
		    var len = document.actionsForm.arrivMethd.length;
		    if(len == undefined){  
		        document.addToCart.IndicatorA.value = document.actionsForm.arrivMethd.value;
		        itemA = document.actionsForm.arrivMethd.value;
		        return;
		    }else{
			    for(var i = 0; i < len ;i++){
			        if(document.actionsForm.arrivMethd[i].checked){
			            document.addToCart.IndicatorA.value = document.actionsForm.arrivMethd[i].value;
			            itemA = document.actionsForm.arrivMethd[i].value;
			            return;
			        }
			    }
		    }
		}
		
/** This function is called when pick up radio button is clicked **/
function showPickUpOptions(){ 

	pickUpSelected = 'true';
	deliveryChecked = 'false';
	shipSelected = 'false';
	zipCodeAttr = 3;
	
	zipCodeAttr = 3;
	if(storeIdReq == 10151){
		// For Kmart only - 
       // Omniture to tell where the user selected different fulfillment method starts.
       var s_account;
       if (typeof omAcct != 'undefined') {
              s_account = omAcct;
       }
       if (typeof s != 'undefined') {
              s=s_gi(s_account);
              s.linkTrackVars="eVar8";
              s.eVar8="Cart"; // For product page, set to Product. 
              s.tl(this, 'o', 'Change Fulfillment Method');
       }
       // Omniture to tell where the user selected different fulfillment method ends.
       }
	if(regAvlMainFlag != 'true')	{       
    	shipMsgDiv.style.display = "block";
    }
    getRadioButtonValue();   
    if(regAvlMainFlag != 'true'){ 
     
	    if(zipCode != ''){
	
	    if(variant == "0"){
	        	callRTI();
	    } else{		    	          
		        showEnterZipMsg(3);   
	    }
		        
	    }else{
			showEnterZipMsg(3);
	    }  
     }
}


/** This function is called when delivery radio button is clicked **/
function getDeliveryMsgOnCheck(){
	pickUpSelected = 'false';
	deliveryChecked = 'true';
	shipSelected = 'false';
	scimCalled = false;
	zipCodeAttr = 2;
	if(storeIdReq == 10151){
		// For Kmart only - 
       // Omniture to tell where the user selected different fulfillment method starts.
       var s_account;
       if (typeof omAcct != 'undefined') {
              s_account = omAcct;
       }
       if (typeof s != 'undefined') {
              s=s_gi(s_account);
              s.linkTrackVars="eVar8";
              s.eVar8="Cart"; // For product page, set to Product. 
              s.tl(this, 'o', 'Change Fulfillment Method');
       }
       // Omniture to tell where the user selected different fulfillment method ends.
       }
	    getRadioButtonValue();
	    if(isScimEnabled == 'true'){
	        if(zipCode != '' || zipDel != ''){
	        	if(storeIdReq == 10161){
	        		shipMsgDiv.style.display = "block";
	        	}
				document.getElementById('availZIP').value = zipCode;
				document.getElementById('actionActionType').value ='2';			
					/* RA CONDITION	*/
					if(regAvlMainFlag != 'true')	{
					    displayZipDiv.style.display = "block";
					    shipEnterZipDivNew.style.display = "none";
					    shipEnterZipDiv.style.display = "none";
					    zipCookieDisplay("D");
				    }
	            if (ddcRegionalAvlFl == 'true') {
	            	/*	RA CONDITION	*/
			 		if(regAvlMainFlag != 'true')	{
	                	hardAddTocartBtn(0);
	                }else {
	                	hardAddTocartBtn(1);
	                }
	            }
	        }
	        else{   
	           	if(regAvlMainFlag != 'true')	{           
	      			showEnterZipMsg(2);
        		}  
	        }
	    }else{ 
	    
	        holidayShipCalCombo();
	    }
		fixInfoHeight();
}


function urlforShipCal(objImg){ 
 
    var catEntryId = getCatEntId();
    var flag = '2';
    var qty = getQuantity();
    var  catEntry;    
    if(catEntryId != ''){
        catEntry = catEntryId.split('&'); 
    }
    
    if(qty != '' && (isNumeric(qty) == 0) && (qty > 0) ){
        if (catEntryId != '' && catEntry[0] != null && catEntry[0]!= "undefined") {
            var langId = -1;
            var str = storeIdFinal;
            url = "SCShippingCostView?storeId="+storeIdReq+"&catalogId="+catalogId+"&langId=" + langId + "&id=" + catEntryId + "&flag=" + flag + "&qty=" + qty + "&cmdStoreId=" + str ;
            window.open(url,null,"width=700,height=350,location=no,scrollbars=yes,toolbar=yes,toolbar=no,status=no,menubar=0");
        }
        else{
            var addToCartMsg = 'Please make a selection.';
              
            showErrorMsgPopUpBox(objImg,addToCartMsg,'ShipCal');
            return;
        }
    }
    else{   
        var addToCartMsg = 'Quantity must be a positive number.  Please enter the quantity again.';
        showErrorMsgPopUpBox(objImg,addToCartMsg,'ShipCal');
        return;
    }
}
var pickUpURL;
//** Function which invokes the Store Grid page for SPU items **/
function storeLocator(){ 
	
		var URL = 'ProductDisplay?';
	    var vName = gup('vName');
	    var cName = gup('cName');
	    var sName = gup('sName');
	    var langId = -1;
	    solnSellingURL();
	    if(11201 != storeIdReq){
	    var URL = URL+'partNumber='+partnumber+'&cName='+cName+'&sName='+sName+'&vName='+vName+'&storeId='+storeIdReq+'&catalogId='+catalogId+'&langId='+langId;
	    	var presellDate = document.addToCart.presellDate.value;
	    }
	    else{
	    	var URL = $('input#productURL').attr('value');;
	    	URL =URL+'vName='+vName+'&cName='+cName+'&sName='+sName;
	    }
	    var catEntryId = getCatEntId();
		var IndicatorA = document.addToCart.IndicatorA.value;
		if(regAvlMainFlag == 'true')	{
			IndicatorA = 'pickup';
			zipCode = getCookie('zipCode'+storeIdReq);
		}
	    var grIdentifier = document.addToCart.grIdentifier.value;
	    var atc = document.addToCart.atc.value;
	    var addToCartBtn = document.addToCart.addToCartBtn.value;
	    var grUserType = document.addToCart.grUserType.value;
	    
	    
	    if (catEntryId != '' && catEntryId != "undefined")
	    {
	        var catentryIdValues = getCatEntryIds();
			if(catentryIdValues != '') {
				if(11201 != storeIdReq){
				if(changeStoreFlag == 'Y'){
					var storeLocatorUrl = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+
										  "&grUserType="+grUserType+"&IndicatorA="+IndicatorA+"&zipCode="+zipCode+
										  "&atc="+atc+"&addToCartBtn="+addToCartBtn+"&grIdentifier="+grIdentifier+
										  "&presellDate="+presellDate+"&variant="+variant+
										  "&"+catentryIdValues+"&changeStoreFlag=Y&URL="+URL+pickUpURL;
				} else {
					var storeLocatorUrl = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+
										  "&grUserType="+grUserType+"&IndicatorA="+IndicatorA+"&zipCode="+zipCode+
										  "&atc="+atc+"&addToCartBtn="+addToCartBtn+"&grIdentifier="+grIdentifier+
										  "&presellDate="+presellDate+"&variant="+variant+
										  "&"+catentryIdValues+"&URL="+URL+pickUpURL;
				}
				}
				else{
					var storeLocatorUrl = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+"&zipCode=" + zipCode + "&"+ catentryIdValues + "&URL=" + URL  ;
				}
				if((10153 == storeIdReq || 10151 == storeIdReq) && xCClicked == 'true'){
	    			storeLocatorUrl+="&xCheckOut=true";
	    		}
				window.location = storeLocatorUrl;
			}
	    }
	    else
	    {
	    	alert(addToCartMsg);
	    	if(regAvlMainFlag != 'true')	{           
		        showEnterZipMsg(3);
	        }
			fixInfoHeight();
	    }
	}
	
/** Function which invokes the Store Grid page for SPU items for checkanotherstore link in productpage for kiosk user **/	
function storeLocatorKiosk(isKioskUser,zipCode,parametersToAppend){ 
	
	    var URL = 'ProductDisplay?';
	    var vName = gup('vName');
	    var cName = gup('cName');
	    var sName = gup('sName');
	    var langId = -1;
	    if(11201 != storeIdReq){
	    var URL = URL+'partNumber='+partnumber+'&cName='+cName+'&sName='+sName+'&vName='+vName+'&storeId='+storeIdReq+'&catalogId='+catalogId+'&langId='+langId;
	    	var presellDate = document.addToCart.presellDate.value;
	    }
	    else{
	    	var URL = $('input#productURL').attr('value');;
	    	URL =URL+'vName='+vName+'&cName='+cName+'&sName='+sName;
	    }
	    var catEntryId = getCatEntId();
		var IndicatorA = document.addToCart.IndicatorA.value;
		if(regAvlMainFlag == 'true')	{
			IndicatorA = 'pickup';
		//	zipCode = getCookie('zipCode'+storeIdReq);
		}
	    var grIdentifier = document.addToCart.grIdentifier.value;
	    var atc = document.addToCart.atc.value;
	    var addToCartBtn = document.addToCart.addToCartBtn.value;
	    var grUserType = document.addToCart.grUserType.value;
	    
	    
	    if (catEntryId != '' && catEntryId != "undefined")
	    {
	        var catentryIdValues = getCatEntryIds();
			if(catentryIdValues != '') {
				if(11201 != storeIdReq){
				if(changeStoreFlag == 'Y'){
					var storeLocatorUrl = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+
										  "&grUserType="+grUserType+"&IndicatorA="+IndicatorA+"&zipCode="+zipCode+
										  "&atc="+atc+"&addToCartBtn="+addToCartBtn+"&grIdentifier="+grIdentifier+
										  "&presellDate="+presellDate+"&variant="+variant+"&isAJAXCall=" + isKioskUser+
										  "&"+catentryIdValues+ parametersToAppend+ "&changeStoreFlag=Y+&URL="+URL+parametersToAppend;
				} else {
				var storeLocatorUrl =  "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+
										  "&grUserType="+grUserType+"&IndicatorA="+IndicatorA+"&zipCode="+zipCode+
										  "&atc="+atc+"&addToCartBtn="+addToCartBtn+"&grIdentifier="+grIdentifier+
										  "&presellDate="+presellDate+"&variant="+variant+"&isAJAXCall=" + isKioskUser+
										  "&"+catentryIdValues+parametersToAppend+"&URL="+URL;
				}
				}
				else{
					var storeLocatorUrl = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+catalogId+"&zipCode=" + zipCode + "&"+ catentryIdValues + "&URL=" + URL  ;
				}
				if((10153 == storeIdReq || 10151 == storeIdReq) && xCClicked == 'true'){
	    			storeLocatorUrl+="&xCheckOut=true";
	    		}
	    		if(isKioskUser == 'true'){							
					enablePopUp();								
					showSPUGridPopUp(storeLocatorUrl);							
				}
				else{
					window.location = storeLocatorUrl;
				}
			}
	    }
	    else
	    {
	    	alert(addToCartMsg);
	    	if(regAvlMainFlag != 'true')	{           
		        showEnterZipMsg(3);
	        }
			fixInfoHeight();
	    }
	}
	
function showSPUGridPopUp(storeLocatorUrl){
	 var spuGridCall = {
	    method: 'GET',
	    asynchronous: true,
	    dataType: "html",
	    //Handle successful response
	    onSuccess: function(t) {     
	 	    document.getElementById("SPUGrid").innerHTML = t.responseText;	 	    
	  	 	//bindLinks();
	   	 	},
	     	// Handle errors
	     	onFailure: function(t) {
	     	document.getElementById("messageBox").innerHTML = "The request could not be processed.Please try after sometime";
	     	}	      
	     };  
        new searsAjax(storeLocatorUrl, spuGridCall);         
	}

	function findStores(){
	var changedZipcode =  document.getElementById("zipCode").value;
	
    var ret = validateZip(changedZipcode);   
    if(ret == false){ 
    
    	err = document.getElementById("error");
		err.style.display= "";
		err.innerHTML = 'Please enter a valid 5-digit ZIP code (example: 60515).';	
		return false;
     
    }
    else{
	storeLocatorKiosk("true",changedZipcode,"");
	}
	}


/* Fuction which is called on click of backword arrow of see more store link */
function findPreviousSetOfStores(){
	//current starting of the stores
		
		var forwardCmdVal=document.getElementById("forwardCmd").value;
		if(forwardCmdVal == 'ProductPage'){
				
			document.storePickup.action="StorePickupCommand" ;
		}else{
				
			document.storePickup.action="StorePickupCmd" ;
		}
			
		//current starting of the stores
		var startPos=document.getElementById("sIdxStartPos").value;
		// max store positions
		var maxStore=document.getElementById("maxStoresPerGrid").value ;
		// next starting point of the store
		var nextStartPos=parseInt(startPos,10) - parseInt(maxStore,10);
		document.getElementById("sIdxStartPos").value=nextStartPos;
		var oldZipcode =  document.getElementById("zipCode").value;
	var totNumSPUStores =  document.getElementById("totNumSPUStores").value;
	var parametersToAppend = "&sIdxStartPos="+ nextStartPos + "&totNumSPUStores=" + totNumSPUStores;
	storeLocatorKiosk("true",oldZipcode,parametersToAppend);
}

/* Fuction which is called on click of forward arrow of see more store link */
function findNextSetOfStores(){
	
	var startPos=document.getElementById("sIdxStartPos").value;
	// max store positions
	var maxStore=document.getElementById("maxStoresPerGrid").value ;
	// next starting point of the store
	var nextStartPos=parseInt(startPos,10) +parseInt(maxStore,10);
	document.getElementById("sIdxStartPos").value=nextStartPos;
	var oldZipcode =  document.getElementById("zipCode").value;
	var totNumSPUStores =  document.getElementById("totNumSPUStores").value;
	var parametersToAppend = "&sIdxStartPos="+ nextStartPos + "&totNumSPUStores=" + totNumSPUStores;
	storeLocatorKiosk("true",oldZipcode,parametersToAppend);
}
	
/*	function for ajax call for Regional availability Store pick up	*/

function makeRegionalRTICall()	{
    
    var catentryIdValues = getCatEntryIds();
    url = "RTICall?storeId=" + storeIdReq +"&cmdStoreId=" + storeIdFinal + "&zipCode=" + getRegPickZip() + "&pickupStoreId=" + pickupStoreIdC + "&langId=-1&" 
    		+ catentryIdValues+ "&isSPUEligible=" + isSPUEligible+ "&isSRESEligible=" + isSRESEligible + "&vcsVertical=" + vcsVertical+"&islayAwayEligible="+ islayAwayEligible;

	ajaxCall(url,'responseRegionalRTICntCall','','');
}

/*	call back function for ajax call of Regional availability Store pick up	*/

function responseRegionalRTICntCall(value)	{

	var errorFlag = false;
	datefromScim = "";
	responseFFM = "";
	 var layawayMsg = '';
	 var layawayCheck="";
	response = value.split('#')[0];
	datefromScim = value.split('#')[1];
	qtyAvail = value.split('#')[2];
	storeName = value.split('#')[3];
    storeAddrDet= value.split('#')[4];
    responseFFM = value.split('#')[5];
    if(value.split('#')[6] != null){
		layawayCheck = value.split('#')[6];
	}
    
	var pickMsg = '<span class="icon"></span>Buy online - Pick up in store eligible. ';

	if(response =="Success" && value!='' && response!='')	{
		/*Lay Away Code changes */
		if(LayAwayFlagConfig != null && LayAwayFlagConfig == 'true'){
		    if(layawayCheck!=null &&  layawayCheck=="layaway=Y"){
	    layawayMsg+='Available for layaway at 	'+storeName+','+storeAddrDet+'  ';
	    layawayMsg+='<a id=\"layCalcLink\" onclick="javascript:layawayClick()" href ="javascript:void(0);" style="cursor:pointer">Layaway Calculator</a>';	
	     
	    }
	    else {
	    		layawayMsg+='Not available for Layaway at '+storeName+', '+storeAddrDet+'  ';
			    layawayMsg+='<a id=\"layCalcLink\" href ="javascript:void(0);"  onclick="javascript:layawayClick()"  style="cursor:pointer">Layaway Calculator</a>'; 
			   	
}
	$('span#layawaylinks').html(layawayMsg);
	//layawayMsgClick();
	
}
		
		/*Lay Away Code changes Ends*/
	     
        /*The product is instock*/
        if(datefromScim=="" || datefromScim == null){
		 if(qtyAvail=="" || qtyAvail == null){
			
			/*	Code for without quantity	*/
			pickMsg += 'In stock at '+storeName+', '+storeAddrDet;
				pickMsg += ' <a id=\"changeZip\" class=\"changeZip\" rel=\"regionalAvailability\" info="'+partnumber+'^Y^PRD^'+catentryVal+'" style="cursor:pointer"> Check another store</a>';
			
		 }else{  
			
			/*	Code for with quantity	*/
			pickMsg += 'Only '+qtyAvail+' left at '+storeName+', '+storeAddrDet;
				pickMsg += ' <a id=\"changeZip\" class=\"changeZip\" rel=\"regionalAvailability\" info="'+partnumber+'^Y^PRD^'+catentryVal+'" style="cursor:pointer"> Check another store</a>';			

		 }
    }else	{
				pickMsg += 'In stock at '+storeName+', '+storeAddrDet+ ' in '+ datefromScim +' days';
				pickMsg += ' <a id=\"changeZip\" class=\"changeZip\" rel=\"regionalAvailability\" info="'+partnumber+'^Y^PRD^'+catentryVal+'" style="cursor:pointer"> Check another store</a>';
		}
    }else	{
		
        errorFlag = true;
		/*	Code for check availability link	*/
		pickMsg += ' <a href=\"javascript:;\" id=\"check\" class=\"checkAvail\" rel=\"regionalAvailability\" info="'+partnumber+'^Y^'+pageFlag+'^'+catentryVal+'"> Check Availability</a>';

    }
   	$('li.pickup').html("");
	$('li.pickup').html(pickMsg);
	
	/*	for binding the click links	*/
	readyOnLoad();
	
	if(errorFlag)	{
		// flag for add to cart
		if(atcDelFlag)	{
			storeLocator();
		}
	}
	else	{
		// remove CA pop up only pop up from pick up option
		if(regionalDiv == 'pickup')	{
			$('div#availPopup').remove();
		}
		if(atcDelFlag)	{
			if(storeIdReq=='10153' && ($.cookie("zipCode")!=null && ($.cookie('zipCode'+getStoreId())==null))){
				$.cookie('zipCode'+getStoreId(),$.cookie('zipCode'));
				storeLocator();
			}
			else if(storeIdReq=='10153' && ($.cookie('zipCode'+getStoreId())!=null)){
				storeLocator();
			}else{
			// Successful call add to cart 
			submitAddToCart();
			}
			
		}
	}
}
	

function fnOnLoadRAPrdRepaint(jsonResponse){
	var availMsg = '';
	var errorMsg = '';
	var date = '';
  	var inStockMsg = 'Available for home delivery to ';
    var outStockMsg = 'This item not currently in stock for Delivery for ';
   	var avlMsg = '';
	var regavail = jsonResponse;
	var partNumArr = new Array();
	if(fnChkZipCode() && typeof regavail != 'undefined'){
		var rspPartNum= regavail.regAvailList[0].pn;
		var rspMsg = regavail.regAvailList[0].msg;
		var rspQty = regavail.regAvailList[0].qty;
		var rspScim = regavail.regAvailList[0].scimresponse;
		if(rspMsg == '')	{
			rspMsg = 'InStock';
		}
		//for scim call out of stock
		if(rspScim == "OutOfStock"){
			avlMsg = outStockMsg;
			//out of stock no need to set date
			date = rspScim;
			//setting out of stock for error flag
			rspMsg = 'OutOfStock';				
		}// for scim call failure
		else if(rspScim == "fail"){
			if(rspMsg == "InStock")	{
				avlMsg = inStockMsg;
				// for try again for date link
				date = rspScim;
			}else {
				avlMsg = outStockMsg;
				// for out of stock no need to set date
				date = 'OutOfStock';
			}
		}// for DB call
		else if(rspScim == ''){
			if(rspMsg == "InStock")	{
				avlMsg = inStockMsg;
				// for check earliest date link
				date = rspScim;
			}else {
				avlMsg = outStockMsg;
				// for out of stock no need to set date
				date = 'OutOfStock';
			}
		}//for scim call success
		else {
			avlMsg = inStockMsg;			
			// response contains date
			date = rspScim;
			//setting out of stock for error flag
			rspMsg = 'InStock';				
		}
		if(rspQty != '0')	{
			availMsg = ' '+ rspQty + ' ';
		}
		availMsg += avlMsg;
		//set this flag properly
		errorMsg = rspMsg;

	}				

	if(date != 'OutOfStock') {
		availMsg += 'ZIP Code '+ getRegDelZip() +' as early as ';
	} else {
		availMsg += 'ZIP Code '+ getRegDelZip() +'.';
	}
	
	if((errorMsg == 'InStock'))	{
		if(date == '') {
			availMsg += '<span class="icon"></span><a href="javascript:checkEDateSCIMCall();" class="checkEarliest" rel="checkEarliestRegional" info="'+partnumber+'^N^PRD^'+catentryVal+'">Check for earliest available date.</a>'
		}else if(date == 'fail'){
			availMsg += '<span class="icon"></span><a href="javascript:checkEDateSCIMCall();" class="checkEarliest" rel="checkEarliestRegional" info="'+partnumber+'^N^PRD^'+catentryVal+'">Date retrieval failed. Try again</a>';
		}
		else {
			if(date != 'OutOfStock') {
			    if (date.indexOf('#') !=-1){
	          		date = date.substring(0,(date.length-2));
	        	}
				availMsg += ' '+ date;
			}
		}
	}
	availMsg += ' <a href="javascript:;" id="changeZip" class="changeZip" rel="regionalAvailability" info="'+partnumber+'^N^PRD^'+catentryVal+'">Change ZIP Code.</a>';
		
	if(($('input#emailMeEligible').attr('value') == '1') && (errorMsg == 'OutOfStock')){
		var emailnfo = maskedName+'^ '+partnumber+'^ '+ mfgPartNumber+'^ '+storeName+'^ '+catentryVal+'^ ^ '+jspStoreImgDir+'^ '+kmartButtonsDir+'^ '+storeIdFinal+'^ '+catalogId+'^ ';
		var emailMeLink = '<br><a class="emailMe" href=\"#\" onclick=\"javascript:mePop(\''+emailnfo+'\',\'emailMe\');\" >E-mail me</a> when it\'s available';
		availMsg += emailMeLink;
	}

	var msgString = availMsg;
	if(fnChkZipCode() && typeof regavail != 'undefined'){
	$('li.delivery').html("");
	$('li.delivery').html(msgString).append('<span class="icon"/>');
	} else {
		$('li.delivery').append(' <span class="icon"></span><a id="check" class="checkAvail" href="javascript:;" rel="regionalAvailability" info="'+partnumber+'^N^'+pageFlag+'^'+catentryVal+'">Check Availability</a>');
	}
	
	readyOnLoad();
}
	
	
/*	function for making ajax call for earliest date	*/

function checkEDateSCIMCall()	{

	dbFlagVal = 'N';
	var sPIDTemp = $('input#sPIDTemp').attr('value');
	var deliveryStore = $('input#deliveryStore').attr('value');

	remoteUrl = 'RegionalAvailCmd?pageInd='+pageFlag+'&dbFlag='+dbFlagVal+'&dateSCIM=Y&storeId='+regAvailStoreId+'&ndd=1&zipCode='+getRegDelZip()+'&catEntryId='+catentryVal+'&scimStoreId='+sPIDTemp+'&deliveryStore='+deliveryStore+'&quantity=1';
	request = $.post(remoteUrl,{DDItemList: DDItemList},resCheckEDateSCIMCall);

}

/*	call back function for making ajax call of earliest date	*/

function resCheckEDateSCIMCall(value)	{

	if(dbFlagVal == 'N')	{
		var dateMsg="";
		if(value=="OutOfStock")	{
			dateMsg += 'This item not currently in stock for Delivery for ';
			dateMsg += 'ZIP Code '+ getRegDelZip() +' <a href="javascript:;" id="changeZip" class="changeZip" rel="regionalAvailability" info="'+partnumber+'^N^PRD^'+catentryVal+'">Change ZIP Code.</a>';
			if(($('input#emailMeEligible').attr('value') == '1')){
				var emailnfo = maskedName+'^ '+partnumber+'^ '+ mfgPartNumber+'^ '+storeName+'^ '+catentryVal+'^ ^ '+jspStoreImgDir+'^ '+kmartButtonsDir+'^ '+storeIdFinal+'^ '+catalogId+'^ ';
				var emailMeLink = '<br><a class="emailMe" href=\"#\" onclick=\"javascript:mePop(\''+emailnfo+'\',\'emailMe\');\" >E-mail me</a> when it\'s available';
				dateMsg += emailMeLink;
			}
			$('li.delivery').html("");
			$('li.delivery').html(dateMsg).append('<span class="icon"/>');
			readyOnLoad();
		}
		else if(value == "fail")	{
			dateMsg = '<span class="icon"></span><a href="javascript:checkEDateSCIMCall();" class="checkEarliest" rel="checkEarliestRegional" info="'+partnumber+'^N^PRD^'+catentryVal+'">Date retrieval failed. Try again</a>';
		        $('li.delivery a.checkEarliest').remove();
			$('li.delivery a.changeZip').before(dateMsg); 		
		}
		else	{
			var scimMsg=""; 
	        scimMsg = value;
	        if (value.indexOf('#') !=-1){
	          scimMsg=value.substring(0,(value.length-2));
	        }        
	        if(scimMsg!="--" && scimMsg!="7" && scimMsg!="4" && scimMsg!="9" && scimMsg!="6" && scimMsg!="Failure" && scimMsg!=""){
	        	dateMsg = scimMsg;
		        $('li.delivery a.checkEarliest').remove();
				$('li.delivery a.changeZip').before(dateMsg);        	
	        }
	        else	{
		        $('li.delivery a.checkEarliest').remove();
	        }
		}
	}else {
		// No date repaint
		$('a.checkEarliest').remove();
	}
}

	
/* function for ajax call for delivery option	*/
function makeRegionalDeliveryCall(pageFlag, dbFlagVal, catentryVal, shipFlag)	{

	var sPIDTemp = $('input#sPIDTemp').attr('value');
	var deliveryStore = $('input#deliveryStore').attr('value');
	if(shipFlag =='Y'){
		remoteUrl = 'RegionalAvailCmd?storeId='+regAvailStoreId+'&shipFlag='+shipFlag+'&catEntryId='+catentryVal;
		request = $.post(remoteUrl,{DDItemList: DDItemList},responseRegionalShipCall);
	} else if((dbFlagVal == 'Y') && (shipFlag == ''))	{
		var deliveryDBCall = {
			success : responseRegionalDeliveryCall,
			url : 'RegionalAvailCmd?pageInd='+pageFlag+'&dbFlag='+dbFlagVal+'&dateSCIM=N&storeId='+regAvailStoreId+'&catEntryId='+catentryVal+'&zipCode='+getRegDelZip(),
			type : 'POST',
			data : {DDItemList: DDItemList},
			dataType:'json',
			error: errorFnDeliveryAvailResponse
		};
		request=$.ajax(deliveryDBCall);	
	} else if((dbFlagVal == 'N') && (shipFlag == '')){
		var deliverySCIMCall = {
			success : responseRegionalDeliveryCall,
			url : 'RegionalAvailCmd?pageInd='+pageFlag+'&dbFlag='+dbFlagVal+'&dateSCIM=N&storeId='+regAvailStoreId+'&ndd=1&zipCode='+getRegDelZip()+'&catEntryId='+catentryVal+'&scimStoreId='+sPIDTemp+'&deliveryStore='+deliveryStore+'&quantity=1',
			type : 'POST',
			data : {DDItemList: DDItemList},
			dataType : 'json',
			error: errorFnDeliveryAvailResponse
		};
		request=$.ajax(deliverySCIMCall);			
	}
}

/* call back function for ajax call of delivery option	*/

function responseRegionalDeliveryCall(jsonResponse)	{

	var availMsg = '';
	var errorMsg = '';
	var date = '';
  	var inStockMsg = 'Available for home delivery to ';
    var outStockMsg = 'This item not currently in stock for Delivery for ';	
    	var avlMsg = '';

	    var regavail = jsonResponse.jsonRegionalAvail;   
	    
		var partNumArr = new Array();
	    if(fnChkZipCode() && typeof regavail != 'undefined'){
		var rspPartNum= regavail.regAvailList[0].pn;
		var rspMsg = regavail.regAvailList[0].msg;
		var rspQty = regavail.regAvailList[0].qty;
		var rspScim = regavail.regAvailList[0].scimresponse;
		if(rspMsg == '')	{
			rspMsg = 'InStock';
				}
		//for scim call out of stock
		if(rspScim == "OutOfStock"){
			avlMsg = outStockMsg;
			//out of stock no need to set date
			date = rspScim;
			//setting out of stock for error flag
			rspMsg = 'OutOfStock';				
		}// for scim call failure
		else if(rspScim == "fail"){
			if(rspMsg == "InStock")	{
				avlMsg = inStockMsg;
				// for try again for date link
				date = rspScim;
			}else {
				avlMsg = outStockMsg;
				// for out of stock no need to set date
				date = 'OutOfStock';
				}
		}// for DB call
		else if(rspScim == ''){
			if(rspMsg == "InStock")	{
				avlMsg = inStockMsg;
				// for check earliest date link
				date = rspScim;
			}else {
				avlMsg = outStockMsg;
				// for out of stock no need to set date
				date = 'OutOfStock';
			}
		}//for scim call success
				else{
			avlMsg = inStockMsg;			
			// response contains date
			date = rspScim;
			//setting out of stock for error flag
			rspMsg = 'InStock';				
				}
		if(rspQty != '0')	{
			availMsg = ' '+ rspQty + ' ';
		}
		availMsg += avlMsg;
		//set this flag properly
		errorMsg = rspMsg;
			
	}				

	if(date != 'OutOfStock') {
		availMsg += 'ZIP Code '+ getRegDelZip() +' as early as ';
	} else {
		availMsg += 'ZIP Code '+ getRegDelZip() +'.';
	}
	
	if((errorMsg == 'InStock'))	{
		if(date == '') {
			availMsg += ' <span class="icon"></span><a href="javascript:checkEDateSCIMCall();" class="checkEarliest" rel="checkEarliestRegional" info="'+partnumber+'^N^PRD^'+catentryVal+'">Check for earliest available date.</a>'
		}else if(date == 'fail'){
			availMsg += '<span class="icon"></span><a href="javascript:checkEDateSCIMCall();" class="checkEarliest" rel="checkEarliestRegional" info="'+partnumber+'^N^PRD^'+catentryVal+'">Date retrieval failed. Try again</a>';
				}
		else {
			if(date != 'OutOfStock') {
			    if (date.indexOf('#') !=-1){
	          		date = date.substring(0,(date.length-2));
			}	
				availMsg += ' '+ date;
		}				
	}
		}		
	availMsg += ' <a href="javascript:;" id="changeZip" class="changeZip" rel="regionalAvailability" info="'+partnumber+'^N^PRD^'+catentryVal+'">Change ZIP Code.</a>';

	if(($('input#emailMeEligible').attr('value') == '1') && (errorMsg == 'OutOfStock')){
		var emailnfo = maskedName+'^ '+partnumber+'^ '+ mfgPartNumber+'^ '+storeName+'^ '+catentryVal+'^ ^ '+jspStoreImgDir+'^ '+kmartButtonsDir+'^ '+storeIdFinal+'^ '+catalogId+'^ ';
		var emailMeLink = '<br><a class="emailMe" href=\"#\" onclick=\"javascript:mePop(\''+emailnfo+'\',\'emailMe\');\" >E-mail me</a> when it\'s available';
		availMsg += emailMeLink;
	}
	
	var msgString = availMsg;
	$('li.delivery').html("");
	$('li.delivery').html(msgString).append('<span class="icon"/>');
	readyOnLoad();
	
	if(errorMsg == 'OutOfStock')	{
		// show error pop up
		var pos = $('#addCart').offset();
		$('div#availPopup').attr("style","display: block");			
		$('div#availPopup').css({top: pos.top - 100, left: pos.left + 300});		
		$('div#availPopup div.standardDiv').attr("style","display: none");
		$('div#availPopup div.errorDiv').attr("style","display: block");			
		// for loading image
		$('.errorDiv input#checkZip').css({display: "inline"});
		$('.standardDiv #loadGif').css({display: "none"});
		$('.errorDiv #loadGif').css({display: "none"});						
	}
	else	{
		// remove CA pop up only pop up from delivery option
		if(regionalDiv == 'delivery' || 'delivery intShipHide')	{
			$('div#availPopup').remove();
		}
		if(atcDelFlag)	{
			// Successful call add to cart 
			submitAddToCart();
		}
	}
}



/* Start -Changes for XPress Checkout functionality */

function xCheckOutAvailability(){
	xCClicked="true";
	 setCookie('oneClickCookie','Y');
	if(deliveryChecked == 'true')	{		
		var obj = document.getElementById('xCheckout');		
		//delivery enabled items not eligible for express checkout
		var mesg = "Items being ordered for Delivery are not eligible for Express Checkout";
		//value = "DeliveryXCheckout";
		showErrorMsgPopUpBox(obj,mesg,'XCheckout'); 
		//showErrorPopUpBox(obj,value);		
	}
	else if(pickUpSelected == 'true'){		
		// set for making ajax call from global.js
		if(regAvlMainFlag == 'true'){
			getRegionalSPUAvail();
		}else{
			getNonRegionalAvail();
		}			
	}
	else if(shipSelected == 'true')	{
		submitToXCheckOutFinal();
	}
}

function submitToXCheckOut(){
	
		xCClicked="true";
	if(regAvlMainFlag != 'true' && pickUpSelected == 'true'){
        getNonRegionalAvail();
    }else{
		submitToXCheckOutFinal();
    }
}

function submitToXCheckOutFinal(){

		xCClicked="true";
  		var quantity = 0;
		var quantity = document.getElementById('quant').value;
		if(quantity != '' && (isNumeric(quantity) == 0) && (quantity > 0)){
			if(typeof  allRegiSS != 'undefined' && allRegiSS.length >0){
	            var regZip = getCookie('zipCode');
	            document.forms['addToCart'].zipCode.value = regZip;
	        }
	        document.addToCart.quantity_1.value = quantity;
	        getUrlforXCheckout('true','','');
		} else {
			var objImage = document.getElementById('cart_enable');
			var mesg = "Please enter a valid quantity";
		 	showErrorMsgPopUpBox(objImage,mesg,'XCheckout');
		} 
}

function getUrlforXCheckout(regFlag,sfm_1,availDays){

		//XCHECKOUT button has been clicked once
	  	
			var sid = document.addToCart.storeId.value;
			var lid = document.addToCart.langId.value;
			var cid = document.addToCart.catalogId.value;
			var indicatorA = document.addToCart.IndicatorA.value;
			var vName = document.addToCart.vName.value;
			var cName = document.addToCart.cName.value;
			var sName = document.addToCart.sName.value;
			var addToCartBtn = document.addToCart.addToCartBtn.value;
			var catEntryId = document.addToCart.catEntryId_1.value;
			var partNumber = document.addToCart.partNumber.value;
			var grUserType = document.addToCart.grUserType.value;
			var grIdentifier=document.addToCart.grIdentifier.value;
			var quantity_1=document.addToCart.quantity_1.value;
			var presellDate=document.addToCart.presellDate.value;
			var variant=document.addToCart.variant.value;
			var atc=document.addToCart.atc.value;
			if('0' == variant){
				var zipCode=getCookie('zipCode'+storeIdReq);
			}
			
			var urlForXCheckout="";
		   if(regFlag =='true'){
			   urlForXCheckout = "ExpressCheckoutOrderItemAddCmd?storeId=" + sid + "&langId="+lid+ "&catalogId="+cid+"&IndicatorA="+
			   indicatorA+"&vName="+vName+"&cName="+cName+"&sName="+sName+"&URL=OrderItemDisplay&quantity_1="+
			   quantity_1+"&catEntryId_1="+catEntryId+"&atc="+atc+"&partNumber="+partNumber+"&addToCartBtn="+addToCartBtn
			   +"&variant="+variant+"&grUserType="+grUserType+"&xCheckOut=true&ffm_1="+sfm_1+"&sresDays_1="+availDays;
			   
			   /* Setting the cookie value to avoid back button issue*/
			   setCookie('oneClickCookie','Y');
		   }else{
		   	var catentryIdValues = getCatEntryIds();
		   	var URL = 'ProductDisplay?partNumber='+partnumber+'&cName='+cName+'&sName='+sName+'&vName='+vName+'&storeId='+storeIdReq+'&catalogId='+cid+'&langId='+lid;
				if(catEntryId!='' && catEntryId != "undefined" && catentryIdValues != '') {
			   		urlForXCheckout = "StorePickupCommand?storeId="+storeIdReq+"&langId=-1&catalogId="+cid+
									  "&grUserType="+grUserType+"&IndicatorA="+indicatorA+"&zipCode="+zipCode+
									  "&atc="+atc+"&addToCartBtn="+addToCartBtn+"&grIdentifier="+grIdentifier+
									  "&presellDate="+presellDate+"&variant="+variant+
									  "&"+catentryIdValues+"&changeStoreFlag=Y&URL="+URL+"&xCheckOut=true";
	   		  	}
		   }		   
		   window.location = urlForXCheckout;
}

function getRegionalSPUAvail(){

	
	//for getting the position of the pop up
	var pos = $('#xCheckout').offset();
	// for scim call	
	dbFlagVal = 'N';
	regionalDiv = 'pickup';
	var regionalClass = $('li.pickup').find('a').attr("class");
	if(regionalClass == 'checkAvail' || pickupStoreIdC == '0')	{
		// open standard CA pop up
		showCAPopUp(partnumber);
		$('div#availPopup').attr("style","display: block");
		$('div#availPopup div.standardDiv').attr("style","display: block");
		$('div#availPopup').css({top: pos.top - 100, left: pos.left - 400});
	}
	else	{
		// make a Regional RTI call to get availability
		makeXCheckoutRTICall();
		showCAPopUp(partnumber);
	}			
}

function getNonRegionalAvail(){
	var nonRegZip=getCookie('zipCode'+storeIdReq);
	var spuStoreId=getCookie('pickupStoreId'+storeIdReq);
	var obj = document.getElementById('xCheckout');		
	var mesg = "Please Enter a Zip Code to Check The Availabilty in Near By Stores"
	if(nonRegZip==''){
		showErrorMsgPopUpBox(obj,mesg,'XCheckout'); 
	}else{
		if(nonRegZip!='' && spuStoreId ==''){
			getUrlforXCheckout('false','','');
		}else{
			submitToXCheckOutFinal();
		}		
	}
}

function makeXCheckoutRTICall()	{
    
    var catentryIdValues = getCatEntryIds();
    url = "RTICall?storeId=" + storeIdReq +"&cmdStoreId=" + storeIdFinal + "&zipCode=" + getRegPickZip() + "&pickupStoreId=" + pickupStoreIdC + "&langId=-1&" 
    		+ catentryIdValues+ "&isSPUEligible=" + isSPUEligible+ "&isSRESEligible=" + isSRESEligible + "&vcsVertical=" + vcsVertical;

	ajaxCall(url,'fnRTIResponseForXCheckout','','');
}

function fnRTIResponseForXCheckout(value){
	
	response = value.split('#')[0];
	datefromScim = value.split('#')[1];
	    
	if(response =="Success" && value!='' && response!='' && (datefromScim=="" || datefromScim == null)){
		getUrlforXCheckout('true','','');
	}else if(response == "Success" && !(datefromScim=="" || datefromScim == null)){
		getUrlforXCheckout('true','SRES',datefromScim);
	}else if(response == "Failure" && isSRESEligible == "0"){
		getUrlforXCheckout('false','','');
	}
	
}

function displayBingCashBack(){

	$('div#bing').hide();
	var BINGCSHBCK=getCookie('BINGCSHBCK');
	if(BINGCSHBCK!=null && BINGCSHBCK!='' && BINGCSHBCK=='ISx20070515x00001d'){
	    $('div#bing').show();
	}

}
/* End of Change for XPress Checkout functionality */

/********** Repainting Functions ******/

function fnOnLoadRAPrdShipRepaint(jsonResponse)	{
	var value = jsonResponse;
	var availMsg = '';
	var shippingmsg ='';
	
	if(searsShipCalc =='true'){
		shippingmsg = " Shipping";
	}else{
		shippingmsg = " Ground Shipping"
	}
	if(	value != ''){
		availMsg += value+shippingmsg;
	}
	
	$('li.inShip').html(availMsg).append('<span class="icon"/>');	
}


// preorder out of stock email me function
function attrSelectionCheck(objImg) {

	var emailMeInfo = maskedName+'^ '+itemPartnumber+'^ '+itemMfrPartnumber+'^ '+storeName+'^ '+itemId+'^ ^ '+jspStoreImgDir+'^ '+kmartButtonsDir+'^ '+storeIdReq+'^ '+catalogId+'^ ';
	if(variant == '1'){
		if((!_Pd.prod.isCol) && _Pd.prod.numItems<1) {
			showErrorMsgPopUpBox(objImg,addToCartMsg,'preSellEmailMe');
			return;
		}
		var qty = rObj('quant').value;
		if(!(qty != '' && (isNumeric(qty) == 0) && (qty > 0))) {
			var msg = 'Quantity must be a positive number.  Please enter the quantity again.';
			showErrorMsgPopUpBox(objImg,msg,'preSellEmailMe');
			return;
		}
		checkItemLevelCatEntry('1');
		emailMeInfo = maskedName+'^ '+partnumber+'^ '+ manufacturerPartNumber+'^ '+storeName+'^ '+_Pd.prod.prodList[emailPIndex].sProd+'^ ^ '+jspStoreImgDir+'^ '+kmartButtonsDir+'^ '+storeIdReq+'^ '+catalogId+'^ ';			
	}
	mePop(emailMeInfo,'emailMe');
	
}
/********** Utility Functions *********/

//Retrieves  the catentryId 
	function getCatEntId() {
	    var catEntId = "";
	    var gty_GR='';
	    if( variant == '0' ){
	    	catEntId = $('input#itemId').attr('value')+'&gty_GR='+gty_GR;
	    } else if(variant=='1') {
	    	
	    	if(document.addToCart.catEntryId_1.value.length > 0 && !(document.addToCart.catEntryId_1.value == 'undefined')) {
				var qty = checkQty();				
				if(qty > 0){
				    catEntId = document.addToCart.catEntryId_1.value+'&gty_GR='+qty ;
				}
	        }
	    }
	    return catEntId;                       
	}

//encoding URL
function enCodeUrl(url){
    
    var strValue = "";
    var urlLen = url.length;
     for(var i=0;i<urlLen;i++){         
        var ch = url.charAt(i);
        if(ch=="="){
            strValue = strValue + "%3d";
        }
        else if(ch=="&")
        {
            strValue = strValue + "%26";
        }
        else{
            strValue =  strValue + ch;
        }
    }
    return strValue;
}

function getCatEntryIds() {

    var url = "";
    var catId="";
    if(variant=='0'){
     var qty = getQuantity();
		if(qty > 0) {
			url = '&catEntryId_1='+itemId+'&quantity_1='+qty;
		}
    } else if(variant=='1'){
        if(document.addToCart.catEntryId_1.value.length > 0) {
            var qty = checkQty();
            if(qty > 0){
                catId = document.addToCart.catEntryId_1.value;
                if(catId == '' || catId == 'undefined' || catId == 0){
                 var strURL = document.location.search;
					if (strURL.search("catEntryIdScim") != -1){
					    
					    var temp=new Array();
					    temp=strURL.split("&");
					    for(var i=0;i<temp.length;i++){
					        if(temp[i].search("catEntryIdScim") != -1){
					        	catId=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
					    	}
					    }
					
					}
                 }
                url = '&catEntryId_1=' + catId + '&quantity_1=' + qty;
            }
        }
        else{
                var strURL = document.location.search;
				if (strURL.search("catEntryIdScim") != -1){
				    
				    var temp=new Array();
				    temp=strURL.split("&");
				    for(var i=0;i<temp.length;i++){
				        if(temp[i].search("catEntryIdScim") != -1){
				        	catId=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
				    	}
				    }
				
				}
				var strURLqty = document.location.search;        
				if (strURLqty.search("qty_GR") != -1){
				    
				    var tempqty=new Array();
				    tempqty=strURLqty.split("&");
				    for(var i=0;i<tempqty.length;i++){
				        if(tempqty[i].search("qty_GR") != -1){
				        	qty=tempqty[i].substring(tempqty[i].indexOf("=")+1,tempqty[i].length);
				   		}
				    }
				
				}
                url = '&catEntryId_1=' + catId + '&quantity_1='+qty;
        }
    }
    return url;
}

//Validates the value entered for quantity.
	function getQuantity(){
		var quantity = '';
		if(variant == '0'){
		if ( document.getElementById('quant') == null)
		 return 1; 
			var qty = document.getElementById('quant').value;
			if(qty != '' && (isNumeric(qty) == 0) && (qty > 0)){
				quantity = qty;
			}
			else{
				quantity = 0;
				var mesg = "Please enter a valid quantity";
	        	var objImage = document.getElementById("avlbtn");
			 	showErrorMsgPopUpBox(objImage,mesg,'Availability');
			}
		} else if (variant == '1'){
		
			var qty = checkQty();
	        if(qty > 0){
	            quantity = qty;
	        }
		}
		return quantity;
	}
	


/** Function to validate if given variable is numeric or not **/
function isNumeric(strVal){
  for(var i=0; i<strVal.length; i++)
  {
	var key = strVal.charCodeAt(i);
	if((key < '48') || (key >'57')){
		return 1;
	}
  }
  	return 0;
}



function chkZipCookies(){

	zipPickUp = getCookie('zipCode'+storeIdReq); 
	zipDel = getCookie('zipCode');
	var tempPUZip = zipPickUp;
	var tempDelZip = zipDel;
	
	//If only Delivery related zipcode is present set the Pickup zipcode.
	if(( zipPickUp == '' && zipDel != '')){
		tempPUZip = zipDel;
		setCookie('zipCode'+storeIdReq,tempPUZip); 
	}
	
	//If only Pickup related zipcode is present set the delivery zipcode.
	if( zipPickUp != '' && zipDel == ''){
		tempDelZip = zipPickUp;
		setCookie('zipCode',tempDelZip); 
	}
	zipPickUp = tempPUZip;
	zipDel  = tempDelZip;
	
}

function showEnterZipMsg(actionType){
	   	if(regAvlMainFlag != 'true')	{           
			 if(storeIdReq != 10152){
			 
			    document.getElementById('availZIP').value = zipCode;
			    document.getElementById('actionActionType').value = actionType;
			 
			    getRadioButtonValue();
			    
			    if(actionType == 2 ){	     
			        /* For Delivery*/
			        shipEnterZipMsgDiv.innerHTML = deliveryZipMsg;        
			        if (ddcRegionalAvlFl == 'true') {
			            hardAddTocartBtn(0);
			        }
			    }else if (actionType == 3){ 
		       		/* For Pickup*/	        
			        shipEnterZipMsgDiv.innerHTML = pickUpZipMsg;
		
			        if (ddcRegionalAvlFl == 'true') {
			            hardAddTocartBtn(0);
			        }
		    	} else{   
		        /* For ship*/
					shipEnterZipDiv.innerHTML = shipZipMsg;
		    	}
		 		shipMsgDiv.style.display = "block";
				shipEnterZipDiv.style.display = "block";
				shipEnterZipDivNew.style.display = "none";
				displayZipDiv.style.display = "none";
				shipEnterZipMsgDiv.style.display = "block";
			    if (shipCal == 1){  
			    	$(shipCalDiv).show();
			    	//International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
			    	
			    }
				fixInfoHeight();
			}
		}
	}
	
	function holidayShipCalCombo(){  
		/*	RA CONDITION	*/
		if(regAvlMainFlag != 'true')	{
		    shipEnterZipDiv.style.display = "none";
			shipEnterZipMsgDiv.style.display="none";
		     if(shipCal == 0){  
		        shipMsgDiv.style.display = "none";	        
		        displayZipButtonDiv.style.display = "none";
		    } else if (shipCal == 1){  
		    	displayZipDiv.style.display = "none";
		        shipMsgDiv.style.display = "block";
		        $(shipCalDiv).show();
		        //International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
		        displayZipDiv.style.display = "none";
		    }
	    }else {
	    	// for RA don't do anything
	    }
		fixInfoHeight();
	}
	
	/*This function is called when the "Check Availability" button is clicked*/
	function submitZipCode(objImg) {	

	    var actionType = document.getElementById('actionActionType').value;
	    zipCode = document.getElementById('availZIP').value; 
	    if(typeof zipCode !='undefined' && zipCode !=''){
	    	zipCode=$.trim(zipCode);
	    }
	    if (checkZipPA(zipCode,objImg)){
	        /*Sets a session cookie for zip code*/	        setCookie('zipCode'+storeIdReq,zipCode);
	        if(actionType == 2){
	        	//Delivery Option
	        	pickUpSelected = 'false';
	            callSCIM();
	        }else if(actionType == 3) {
		        //Store Pickup Option
	            storeLocator();
	        }else 
	        {
	            showShipMsg();
	        }
	    }

	}
	
	function checkZipPA(zip,objImg) 
	{
	  var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
	  var passed = lv_pattern.test(zip); 
	  if (!passed) 
	  {
	        var mesg = 'Please enter a valid 5-digit ZIP code (example: 60515).';     
	        showErrorMsgPopUpBox(objImg,mesg,'ZipCodeEnter');
	        return false;
	  }
	  else 
	  {
	    return true;
	  }
	}
	
	//Make SCIM call to fetch delivery date or other related data.
	function callSCIM(){

		var nddAvailability = $('input#nDDAvailable').attr('value');
		if(nddAvailability == 'nDDAvailable'){
			ndd=1;
		} 
		var catEntryId = getCatEntId();
		if (catEntryId != '' && (typeof catEntryId != "undefined") && catEntryId != null && catEntryId!= 'undefined'){
		    var quant = getQuantity();
			var sPIDTemp = $('input#sPIDTemp').attr('value');
			var deliveryStore = $('input#deliveryStore').attr('value');
			url = "SCIMCall?storeId=" + storeIdFinal + "&ndd="+ ndd +"&zipCode=" + zipCode+ "&partnumber=" + partnumber  + "&catEntryId=" + catEntryId + '&scimStoreId='+sPIDTemp+'&deliveryStore='+deliveryStore+'&quantity=' + quant ;

			//Countdown - Called only for SPU/SRES hardline products of Sears for verticals
			if((storeIdReq=='10153') && (pickUpVar == '1') && (variant == "0")){
				ajaxCall(url,'fnDeliverybackCntDwn','','');
			}else{
				ajaxCall(url,'fnDeliveryback','','');
			}
			
		}else{
			alert(addToCartMsg);
	    	if(regAvlMainFlag != 'true')	{           
		        showEnterZipMsg(2);
	        }
			fixInfoHeight();
		}
	}
	
	//onKeyPress event of zipCode_actions Input element (Zipcode text box)
	function KeyPress(e){

	    var keynum;
	    if(window.event) /* IE*/
	    {
	        keynum = e.keyCode;
	        if (keynum == 13) {
	            submitZipCode(e);
	        }
	    }
	    else if(e.which) /* Netscape/Firefox/Opera*/
	    {
	        keynum = e.which;
	        
	        if (keynum == 13){
	            submitZipCode(e);
	        }
	    }

	}
	function checkQty() {
	    var qty = rObj('quant').value;
	    if(qty != '' && (isNumeric(qty) == 0) && (qty > 0) ) {
	        return qty;
	    }
	     else {
	        return 0;
	    }
	    return 0;
	}

/**************** Save For later Logic Starts ****************/

//On click of Wishlist link in the in the Save to List dropdown
function productWishlist(objImg){
	//var userType = '<c:out value="${userType}"/>';

        var qty=1;
        var grUserType = getCookie('GiftRegApp'+storeIdReq);
        var catEntryIds = getCatEntryIds();
        var catEntryIdScim = getCatEntId();
        object = document.getElementById("saveToList"); 
   		leftVal = findPos(object)[0];
	 	topVal  = findPos(object)[1];
	 	objImg ="wishlist";
        /*mainUrl is constructed to be passed as parameter to GiftRegistryDisclaimer page from popupWishlistSubmit function*/
        if(catEntryIdScim == '' || catEntryIdScim == 'undefined' || catEntryIdScim == 0){
			var strURL = document.location.search;
    
			if (strURL.search("catEntryIdScim") != -1){
			    
			    var temp=new Array();
			    temp=strURL.split("&");
			    for(var i=0;i<temp.length;i++){
			        if(temp[i].search("catEntryIdScim") != -1){
			        catEntryIdScim=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
			    	}
			    }			
			}
        }
        
        mainUrl="partNumber="+partnumber;
        if(grUserType != ""){
            mainUrl = mainUrl + '&grUserType='+grUserType;
        }
        if(catEntryIdScim != '' && catEntryIdScim != "undefined"){
            mainUrl = mainUrl + catEntryIds;
        }
        var ProductUrl = 'SHCGiftRegistryProductDetailsCmd?storeId='+storeIdReq+'&catalogId='+catalogId+'&wishListId=1&URL=ProductDisplay&partNumber='+partnumber+'&catEntryIdScim='+catEntryIdScim; 
        if(variant == '1'){
          qty = checkQty();
		}
        if (qty >0){
            if(catEntryIdScim != '' && catEntryIdScim != "undefined" && catEntryIdScim != 0){
			     Load.style.display = "block";
                 ajaxCall(ProductUrl,'getProductStatus','',objImg);   
            }else{
                var mesg = 'Please make a selection before adding to WishList';
                showErrorMsgPopUpBox(object,mesg,'Wishlist');
            }
         }else{
             var mesg = 'Quantity must be a positive number.  Please enter the quantity again.';
             showErrorMsgPopUpBox(object,mesg,'Wishlist');
        }    
}

//On click of the Save to Registry link in the Save to List dropdown
function productRegistry(objImg){

    //var userType = '<c:out value="${userType}"/>';    
        var url = "";
        var qty=1;
        var grUserType = getCookie('GiftRegApp'+storeIdReq);
        var catEntryIds = getCatEntryIds();
        var catEntryIdScim = getCatEntId();
        object = document.getElementById("saveToList"); 
   		leftVal = findPos(object)[0];
	 	topVal  = findPos(object)[1];
        if(catEntryIdScim == '' || catEntryIdScim == 'undefined' || catEntryIdScim == 0){
            var strURL = document.location.search;
			if (strURL.search("catEntryIdScim") != -1){
			    var temp=new Array();
			    temp=strURL.split("&");
			    for(var i=0;i<temp.length;i++){
			        if(temp[i].search("catEntryIdScim") != -1){
			        	catEntryIdScim=temp[i].substring(temp[i].indexOf("=")+1,temp[i].length);
			    	}
			    }			
			}
        }
        
        url = 'AddToGiftRegistry?storeId='+storeIdReq+'&catalogId='+catalogId+'&grUserType=' + grUserType;
        mainUrl="partNumber="+partnumber;
        if(grUserType != ""){
            mainUrl = mainUrl + '&grUserType='+grUserType;
        }
        if(catEntryIdScim != '' && catEntryIdScim != "undefined"){
            mainUrl = mainUrl + catEntryIds;
        }
        var ProductUrl ="";
        if (objImg == "gt" )
        {
        	 ProductUrl = 'SHCGiftRegistryProductDetailsCmd?isGiveTogether=true&storeId='+storeIdReq+'&catalogId='+catalogId+'&URL=ProductDisplay&partNumber='+partnumber+'&catEntryIdScim='+catEntryIdScim; 
        	}
		else {
			ProductUrl = 'SHCGiftRegistryProductDetailsCmd?isGiveTogether=false&storeId='+storeIdReq+'&catalogId='+catalogId+'&URL=ProductDisplay&partNumber='+partnumber+'&catEntryIdScim='+catEntryIdScim; 
		}
        if(variant == '1'){
          qty = checkQty();
        }
        if (qty >0){
            
            if(catEntryIdScim != '' && catEntryIdScim != "undefined" && catEntryIdScim != 0){
                 Load.style.display = "block";
                 ajaxCall(ProductUrl,'getProductStatus','',objImg);   
                
            }else{
                var mesg = 'Please make a selection before adding to giftregistry';
                showErrorMsgPopUpBox(object,mesg,'GiftRegistry');
            }
        }else{
             var mesg = 'Quantity must be a positive number.  Please enter the quantity again.';
             showErrorMsgPopUpBox(object,mesg,'GiftRegistry');
        }
	}

//On click of the Save for Later link in the Save to List dropdown
function productSaveLater(objImg){
	if(storeId == 10156){
    	object = document.getElementById("saveToListTGI");
    }else{
	object = document.getElementById("saveToList"); 
    }
	if(variant == '1'){
       if(document.addToCart.catEntryId_1.value == 'undefined' || !(document.addToCart.catEntryId_1.value.length > 0)) {
            var mesg = 'Please make a selection before adding to save for later';
            showErrorMsgPopUpBox(object,mesg,'save for later');
            return;
        }
        var qty = checkQty();
        if(!(qty>0)){
            var mesg = 'Quantity must be a positive number.  Please enter the quantity again.';
            showErrorMsgPopUpBox(object,mesg,'save for later');
            return;
        }
    }    
	var catEntryIds = getCatEntryIds();
	var catEntryIdScim = getCatEntId();
    var url="AddToWishlist?langId=-1&storeId="+storeIdReq+"&catalogId="+catalogId+"&partNumber="+partnumber+"&URL=AddToWishListSuccessView&errorViewName=AddToWishListErrorView&redirectView=AddToWishListRedirectView";

    var grUserType = getCookie('GiftRegApp'+storeIdReq);
    
    if(grUserType != ""){
        url = url + '&grUserType='+grUserType;
    }

    if(catEntryIdScim != '' && catEntryIdScim != "undefined"){
        ajaxCall(url + catEntryIds,'returnSaveForLater','','');
    }else
    {
        var mesg = 'Please make a selection before adding to save for later';
        showErrorMsgPopUpBox(object,mesg,'save for later');
    }   
}

/*
Function called after the ajaxCall completes execution on clicking
of add to Save for Later link
*/
function returnSaveForLater(value){
    if(storeId == 10156){
    	object = document.getElementById("saveToListTGI");
    }else{
    object = document.getElementById("saveToList");
    }
    flag = '';
    if(value == "Success"){
        if(document.getElementById("remembered")!=null){
           var remem = document.getElementById("remembered").value;
           if(remem=="yes")
               flag = 'error8';
         }
        else        
          flag = 'error6';
          SaveToOpsErrorPopUpBox(object,flag);
    }else if(value == "Redirect"){
        showLogonForm();
    }else{
		//wishlistExceptionMessage is used in getErrorStatus() while displaying the error msg pop-ups
        wishlistExceptionMessage = value;
        SaveToOpsErrorPopUpBox(object,flag);
    }
        
}

/*
Function called after the ajaxCall completes execution on clicking
of Add to Registry link and Add to Wishlist link in the Save to List dropdown
*/
function getProductStatus(value,isGT){

    var qty_GR='';
    var actionStatus=value.substring(0,8);
    if((actionStatus == "registry")||(actionStatus == "wishlist")){
	    var RegistryType=value.substring(0,8);
	    var catEntryIdScim=value.substring(8,value.length);
	    if(variant == '1'){
	          qty_GR = checkQty();
	    }
	    if (isGT =="gt") {
        	location.href = "GiveTogetherSignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
        }
        if (isGT =="wishlist") {
        	location.href = "GiftRegistryWishlistSignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
        }
        else {
        location.href = "GiftRegistrySignOnView?storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=ProductDisplay&partNumber="+partnumber+"&catEntryIdScim="+catEntryIdScim+"&RegistryType="+RegistryType+"&fromCreate=productPage&qty_GR="+qty_GR;
        }
    }else{

	    flag = value;
	    newDiv=document.createElement('div');
        newDiv.className='errorPop';
        newDiv.id='errorBox';
        newDiv.innerHTML=value;
        document.body.appendChild(newDiv);
        Load.style.display = "none";
        var errBox=document.getElementById('errorBox');
        var oy = topVal;
        var ox = leftVal;
	    if(browser=="Internet Explorer"){
            var docWidth=document.body.scrollWidth;
            var docHeight=(document.body.scrollHeight);
            var boxH=errBox.offsetHeight;
            var boxW=errBox.offsetWidth;
	        if ((ox-100)<0){
	            errBox.style.top=(oy-350)+"px";
	            errBox.style.left=(ox-40)+"px";
	            document.getElementById('errorBox').focus();
	        } 
	        else if ((ox-100)>(docWidth-boxW)){
	            errBox.style.top=(oy-100)+"px";
	            errBox.style.left=(docWidth-boxW-10)+"px";
	            document.getElementById('errorBox').focus();
	        } 
	        else{
	            errBox.style.top=(oy-150)+"px";
	            errBox.style.left=(ox-100)+"px";
	            document.getElementById('errorBox').focus();
	        }
	    }else {
		    var docWidth=document.documentElement.clientWidth;
		    var docHeight=document.documentElement.clientHeight;
		    var boxH=errBox.offsetHeight;
		    var boxW=errBox.offsetWidth;
	        if ((ox-100)<0) {
	            errBox.style.top=(oy-100)+"px";
	            errBox.style.left=(ox)+"px";
	            document.getElementById('errorBox').focus();
	        } 
	        else if ((ox-100)>(docWidth-boxW)){
	            errBox.style.top=(oy-100)+"px";
	            errBox.style.left=(docWidth-boxW-10)+"px";
	            document.getElementById('errorBox').focus();
	        } 
	        else{
	            errBox.style.top=(oy-100)+"px";
	            errBox.style.left=(ox-100)+"px";
	            document.getElementById('errorBox').focus();
	        }
	    }
    }
}

/*
 * Function called when the user is guest and had clicked on add to wishlist. This function is
 * is called after the first ajax call is made. We pass a parameter guest=1 which differentiates a 
 * a user who has already regsitered and is browsing and the guest user who had just clicked on
 * add to wishlist button.
 */
function showLogonForm() {   
    
    var logonUrl = "LogonForm?langId=-1&storeId="+storeIdReq+"&catalogId="+catalogId+"&URL=";
    var addToWishlistUrl = "AddToWishlist?langId=-1&storeId="+storeIdReq+"&catalogId="+catalogId+"&partNumber="+partnumber+"&productURL="+productURL+"&guest=1&";
    var vertical = gup('vName');
    var category = gup('cName');
    var subcategory = gup('sName');
    var grUserType = getCookie('GiftRegApp'+storeIdReq);
    
    if(grUserType != "")
        addToWishlistUrl = addToWishlistUrl + '&grUserType='+grUserType;
    if(vertical !="")
        addToWishlistUrl = addToWishlistUrl + '&vName='+vertical;
    if(category !="")
        addToWishlistUrl = addToWishlistUrl + '&cName='+category;
    if(subcategory !="")
        addToWishlistUrl = addToWishlistUrl + '&sName='+subcategory;
    
    var catEntryIds = getCatEntryIds();
    addToWishlistUrl = addToWishlistUrl+catEntryIds;
    addToWishlistUrl = enCodeUrl(addToWishlistUrl);
    window.location = logonUrl+addToWishlistUrl;
    
}


/**************** Save For later Logic Ends ****************/

/***************** Solution Selling Changes  Starts ****************/

//This method populates the addToCart form with the selected option details
function simAddToCart(object){

      //Setting the extra params that has to be passed when added to cart.
      var solSelCatEntryId =  '';
      var solSelPOType = '';
      var instSelCatEntryId =  '';
      var instSelPOType = '';
      var instSelCatEntryId1 =  '';
      var instSelPOType1 = '';
      var deluxeDet = '';
      var cValue='';
      var pType='';
      var c1Value='';
      var p1Type='';
      var optFlag ='false'; 
     
     /*
      if($('#po_warranty input:checked').length > 0 || $('#po_install input:checked').length > 0 || $('#po_maintenance input:checked').length > 0 && $('#po_config input:checked').length > 0 ){
      		var optFlag ='true'; 
      }   */  
      
               if(solnSellingFlag == 'true' || solnSellingFlag == true){
                  	 var optnSelectedCount=0;	
                  	  $('.product_option input:checked').each(function(){
                        	    optFlag ='true'; 
                        	    optnSelectedCount++;
                        	     if($(this).hasClass('baseInstall') ||$(this).hasClass('radio') ){
                             		var c1Value= this.id.split('_')[2];
                              		if (c1Value!='COST'){
                              			var p1Type=this.id.split('_')[6];
                              			if(c1Value != 'undefined'){
                              			  instSelCatEntryId1 = instSelCatEntryId1  + c1Value + ',';
                              			  instSelPOType1 = instSelPOType1 + p1Type + ',' ;
                                        }
                                    }
                              	                             		
                          	}
                              if($(this).hasClass('ao')){
                             		var cValue= this.id.split('_')[2];
                              		if (cValue!='COST'){
                              			var pType=this.id.split('_')[6];
                              			if(cValue != 'undefined'){
                              			  instSelCatEntryId = instSelCatEntryId  + cValue + ',';
                                          instSelPOType = instSelPOType + pType + ',' ;
                                        }
                                    }
                              	                             		
                          	}else{
                          		var catentryValue = "input#"+$(this).attr('class')+"hide"; 
                            		var poType = "input#"+$(this).attr('class')+"type";
                            		if(typeof ($(catentryValue).val()) != 'undefined'){
                                    	if($(poType).val() != 'DO'){  
                                          solSelCatEntryId = solSelCatEntryId  + $(catentryValue).val() + ',';
                                          solSelPOType = solSelPOType  + $(poType).val() + ',';
                                    	} else {
                                          deluxeDet = deluxeDet  + $(catentryValue).val() + ',';
                                    	}
                              		}
                            }
                                     		
                          });
                          
                                  
                          
                          
                          solSelCatEntryId = solSelCatEntryId  + instSelCatEntryId1 + instSelCatEntryId;
                          var clength= solSelCatEntryId.length -1;
                          solSelCatEntryId= solSelCatEntryId.substring(0,clength);
                          //alert(solSelCatEntryId);
                          solSelPOType = solSelPOType  + instSelPOType1 + instSelPOType;
                          var plength= solSelPOType.length -1;
                          solSelPOType= solSelPOType.substring(0,plength);
                          //alert(solSelPOType);
                          var dlength = deluxeDet.length -1;
                          deluxeDet= deluxeDet.substring(0,dlength);
                          //alert(deluxeDet);
                        
                        var addr1 ="";
                        if(document.getElementById("address_1")!=null)  
                        addr1= document.getElementById("address_1").value;
                        
                        var addr2 ="";
                        if(document.getElementById("address_2")!=null)
                        addr2= document.getElementById("address_2").value;
						
						var city="";
						if(document.getElementById("address_city")!=null)
						city= document.getElementById("address_city").value;
						
						var state="";
						if(document.getElementById("address_state")!=null)
						state= document.getElementById("address_state").value;
						
						var addrZip="";
						
						if(document.getElementById("address_zip")!=null)						
						addrZip= document.getElementById("address_zip").value;
						
						var instPrice = 0;
						if($('#po_install p.po input#optInstall1').text()!= null || $('#po_install p.po input#optInstall1').text()!= ''){
							instPrice = $('#po_install p.po input#optInstall1').val();
						}
						var optnCount=0;
						var allOptionsFlag = false;
						$('.options_list .product_option').each(function(){
							optnCount++;
						});
						
						if(optnCount == optnSelectedCount){
							allOptionsFlag = true;
						}
						
                        document.addToCart.allOptionsFlag.value = allOptionsFlag;
                        document.addToCart.optionFlag.value = optFlag;
                        document.addToCart.poCatEntryId.value = solSelCatEntryId;
                        document.addToCart.poLineItemType.value = solSelPOType;
                        document.addToCart.questionScimCode.value = deluxeDet;
                        document.addToCart.addr1.value = addr1;
                        document.addToCart.addr2.value = addr2;
                        document.addToCart.city.value = city;
                        document.addToCart.state.value = state;
                        document.addToCart.addrZipCode.value = addrZip;
                        document.addToCart.instPrice.value = instPrice;
                        
                       
}

}

// This function is called to append selected options to storepickup URL
function solnSellingURL(){
	
	var optionFlag= document.addToCart.optionFlag.value;
	var poCatEntryId=document.addToCart.poCatEntryId.value;
	var poLineItemType=document.addToCart.poLineItemType.value;
	var questionScimCode=document.addToCart.questionScimCode.value;
	var instPrice=document.addToCart.instPrice.value;
	/*
	var addr1= document.getElementById("address_1").value;
	var addr2= document.getElementById("address_2").value;
	var city= document.getElementById("address_city").value;
	var state= document.getElementById("address_state").value;
	var addrZip= document.getElementById("address_zip").value;
	*/
	var addr1=document.addToCart.addr1.value; 
    var addr2=document.addToCart.addr2.value;
    var city=document.addToCart.city.value;
    var state=document.addToCart.state.value;
    var addrZip=document.addToCart.addrZipCode.value;
	var storeId = $('input#storeId').attr('value');
	pickUpURL="&allOptionsFlag="+allOptionsFlag+"&optionFlag="+optionFlag+"&poCatEntryId="+poCatEntryId+"&questionScimCode="+questionScimCode+"&poLineItemType="+poLineItemType+"&addr1="+addr1+"&addr2="+addr2+"&city="+city+"&state="+state+"&addrZipCode="+addrZip+"&instPrice="+instPrice;
	return pickUpURL;
}

/***************** Solution Selling Changes  ends ****************/
/* Code changes for Lay away */
var fromProductPage = null;
function getLayawayCalDetails2(){
	var catentryIdValues = getCatEntryIds();
	var regionalZip = $('#layawayPopup div:visible #checkZipText2').val();
	globalZipCode = regionalZip;
	var layAwayFlag = "true";
	fromProductPage=true;
		var layawayUrl="LayawayCmd?currPrice="+currPriced+"&partNumber="+partNum+"&storeId="+storeId+"&zipCode="+regionalZip+"&layAwayFlag="+layAwayFlag+"&seasonalInd="+seasonalInd+"&cmdStoreId=" + cmdStoreId +"&pickupStoreId=" + pickupStoreIdC + "&langId=-1&"+"&fromProductPage=" + fromProductPage+'&sCriteria=LWS'+'&startFrom=0'+'&isAjax=true'+"&catalogId="+catalogId+
		"&layawayStartDate="+layawayStartDate+"&layawayEndDate="+layawayEndDate; 
	$("#loadImg").css("visibility", "visible");
	request=$.getJSON(layawayUrl,fnLayAwaySuccess);
}

function checkLayAwayZip2(){
	var regionalZip = $('#layawayPopup div:visible #checkZipText2').val();
	var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
	var passed = lv_pattern.test(regionalZip); 
	if (!passed) {
		showLayErrorMsg();
		return false;
	}else {
		return true;
	}
}

function showLayErrorMsg(){
	var validatePopup = "<div id='validatePopup' class='layAwayValidatePopup'>"
							+"<h3>Enter Zip Code</h3>\n"
							+"<h2>Please enter a valid 5-digit ZIP code (example: 60515).</h2>"
							+"\n\n<input type='submit' name='ok' value='OK' onclick='remove(this.parentNode);' style='margin-bottom:10px'>\n";
	$('#layawayPopup').append(validatePopup);
}

var globalIntArr = null;
var globalPageNo = 1;

function fnGetInstPageData(){
	var installmentMsg = '<li id="firstInstallment">Amount due on ';
	var fistFlag = true;
	for (var i = (globalPageNo*4)-4; i < (globalPageNo*4); i++){ 
		if(fistFlag){
			if(globalIntArr[i] !=null && globalIntArr[i]!= '' && globalIntArr[i]!="undefined"){
			
				installmentMsg+=globalIntArr[i].installmentDate+':  <span>$'+globalIntArr[i].dueAmount+'</span></li>';
				fistFlag = false;
			}
		}else{
		if(globalIntArr[i] !=null && globalIntArr[i]!= '' && globalIntArr[i]!="undefined" ){
		
				installmentMsg+='<span id="installmentId"><li>'+globalIntArr[i].installmentDate+':  <span>$'+globalIntArr[i].dueAmount+'</span></li></span>';
			}
		}
	}

	if(fromProductPage == true){
	installmentMsg+='<li>'+$('div#intTotalAmount').html()+'</li>';
	}
	
	if(globalPageNo > 1 || globalIntArr.length > globalPageNo*4){
		installmentMsg+='<li id="pagination">';
		
		if(globalIntArr.length > globalPageNo*4){
			installmentMsg+='<div class="adnl" id="next" onclick="fnShowNextPage();"></div>'
		}
		if(globalPageNo > 1){
			installmentMsg+='<div class="lessImage" id="prev" onclick="fnShowPrevPage();"></div>'
			//installmentMsg+='<div id="prev"><img src="/contentserver/StaticContent/Sears/img/layawayLess.gif"  onclick="fnShowPrevPage();" no-repeat 41px -25px; height:20px; width:60px; overflow:hidden; float:right; text-align:left; /></div>'
			
		}
		
		installmentMsg+='</li>';
	}
	return installmentMsg;
}

function fnShowNextPage(){
	globalPageNo +=1;
	var installmentMsg = fnGetInstPageData();
	$('ul.schedule').html(installmentMsg);

}

function fnShowPrevPage(){
	globalPageNo -=1;
	var installmentMsg = fnGetInstPageData();
	$('ul.schedule').html(installmentMsg);
}


function fnLayAwaySuccess(response){

	//var response = eval('(' + response + ')');
	$("#loadImg").css("visibility", "hidden");
	var initialFee= "";
	var downPayment= "";
	var contractValue= "";
	var installmentarray="";
	var address = response.storeAddress;
	var successResponse = address.split('#')[0];
	if(successResponse =="Success"){
		//Code for success
		
		if(response != null && response.initailFee !=null && response.initailFee !=""){
			initialFee =  response.initailFee;
		}
		if(response != null && response.downPayment !=null && response.downPayment !=""){
			downPayment =  response.downPayment;
		}
		if(response != null && response.contractValue !=null && response.contractValue!=""){
			contractValue =  response.contractValue;
		}
		if(response != null && response.installments !=null && response.installments !=""){
			installmentarray = response.installments;
		}
	
	
		//response.installments[1].dueAmount
		var installmentMsg ='';
		var firstInstallment = '';
			if(typeof(installmentarray) != 'undefined' && installmentarray != null && installmentarray != ""){
				globalIntArr = installmentarray;
				globalPageNo=1;
				var installmentMsg = fnGetInstPageData();
				$('ul.schedule').html(installmentMsg);
			}
		
		var location = address.split('#')[3];
		var location1 = address.split('#')[4];
		var initailFeeMsg = '';
		var address1Msg='';
		var address2Msg='';
		var zipCodeMsg='';
		var downPaymentMsg='';
		var totalContactValue='';
		var fullStoreAddress='';
			if(initialFee != null && initialFee!=""){
				initailFeeMsg+='<label for="layZip1">Initial fee:</label><strong>$'+initialFee+'</strong>';				
				$('li#initial').html(initailFeeMsg);
				$('li#initial').css("margin-right","0px");
			}
			if(downPayment != null && downPayment!=""){
				downPaymentMsg+='Down Payment Due Today:<strong>$'+downPayment+'</strong>';				
				$('li#downPayment').html(downPaymentMsg);
			}
			if(contractValue != null && contractValue!=""){
				totalContactValue+='<strong>Total contract amount: <span> $'+contractValue+'</span></strong>';				
				$('span#totalContract').html(totalContactValue);
			}
		if(location !=null && location!=""){
			address1Msg+='<span id="address1">'+location+'</span>';
			$('#PickupStoreMsg').removeClass('hidden')
			fullStoreAddress+=address1Msg;
		}
		if(location1 !=null && location1!=""){
		address2Msg +='<span id="address2">'+location1+'</span>';
		//$('span#storeAddress').html(address2Msg);
		//$('span#errorSpan').remove();
		fullStoreAddress+=address2Msg;
		$('li#error2').remove();
		}
		
		//displaying the full address of the store
		$('span#storeAddress').html(fullStoreAddress);
		
		if(globalZipCode != null && globalZipCode!=""){
		
		zipCodeMsg+=' <span class="selZIP">'+globalZipCode+'</span>   <a id="layAwayChangeZIP" href="#" style="margin-left: 20px;">change</a>';
		$('#checkZipText2, #checkZipHidden, #loadImg').addClass('hidden')
		
		$('span#checkLowerZip').html(zipCodeMsg);
		}
		
		$('#layAwayChangeZIP').click(function(){
				$('#checkZipText2, #checkZipHidden , #loadImg').removeClass('hidden')
				$(this).hide()
				return false
			})
	//Code for success ends	
	}	

	
	//ECOM-43179
	
	if(successResponse !="Success"){
			//Removing the store address from the jsp
			$('#PickupStoreMsg').addClass('hidden')
			$('span#address1').remove();
			$('span#address2').remove();
		
			//Adding the error message
			var errorMsg='<li id="error2" class="error"> We are sorry, but we cannot find a store with Layaway within 50 miles of that ZIP </li>';
			$('span#errorSpan').addClass('error');			
			$('span#errorSpan').html(errorMsg);
	}
	
}

function layawayClick(){
    var partNum = $('input#akHiPartNumber').attr('value');
    var currPrice= $("input#alaskaCurrPrice").attr('value');
	fromProductPage=true;
	var orderId="";
	var address1="";
	var address2="";
	var zipCode="";
	var catentryIdValues = getCatEntryIds();
	var catentry=getCatEntId();
	var catentryZero=getCatEntId().substring(0,1);
	if(currPrice == ''){
		currPrice=0.00;
	}
	
	var layawayStartDate="";
	var layawayEndDate="";
	if(typeof(startDate) != "undefined" && startDate != '' && startDate != null){
		layawayStartDate = startDate;
	}
	if(typeof(endDate) != "undefined" && endDate != '' && endDate != null){
		layawayEndDate = endDate;
	}

	if (catentry != '' && catentryZero != null && catentryZero != "undefined") {
		
		layawayPopup({type:'modal', id:'layawayPopup', Class:'searsPopup', closeTxt:'Close', addContent:		
function (){
	$('<div class="content" style="padding:0px !important;"/>').appendTo('#layawayPopup');
	$.ajax({
		url: 'LayawayJsp?currPrice='+currPrice+'&partNum='+partNum+'&seasonalInd='+seasonalInd+'&storeId='+storeId+'&imageId='+imageId+'&fromProductPage='+ fromProductPage+'&orderId='+ orderId+'&layawayStartDate='+ layawayStartDate+'&layawayEndDate='+ layawayEndDate,
		success:function(data){
				$('#layawayPopup .content').append(data);
				$('#layawayPopup .pTitle').append(prdTitle);
				content.find('input#CloseButton').unbind().click(function(){
					content.remove();
					modal.remove();
					return false;
				});

				if(typeof(instJson) != 'undefined' && instJson != null){
					globalIntArr = instJson;
					globalPageNo=1;
					var installmentMsg = fnGetInstPageData();
	
					$('ul.schedule').html(installmentMsg);
				}
				
				$('#layawayPopup').show();
				
				// $('a.layawayQues').dynamicPopup({filename: dynamicPopup+'&vName=layawayCal',contentname: '.layawayQuestions',windowWidth: '300px',windowHeight: '240px'});
			}
		}
	);
}
		
			});
	}else{
		var addToCartMsg = 'Please select a Color/Size';
		var object = document.getElementById("layaway_links"); 
		showErrorMsgPopUpBox(object,addToCartMsg,'LayawayCalculator');
		return false;
	}	
}



var modal =null;
var content =null;
function layawayPopup(settings){
	var dims = layawayDims()
	if(settings.type == 'modal'){
		if($.browser.mozilla){buffer=250}else{buffer=0}
		modal = $('<div id="layawayModal"/>').css({width:dims.h, height:$('body').height()+buffer}).appendTo('body')
		modal.unbind().click(function(){
			content.remove()
			modal.remove()
		})
	}
	content = $('<div id="'+settings.id+'"class="'+settings.Class+'"/>').css({top:dims.vs+30, left:(dims.h/2)-400}).appendTo('body')
	$('<div class="closeBtn"><a href="#">'+settings.closeTxt+'</a></div>').appendTo(content)
	content.find('.closeBtn a').unbind().click(function(){
		content.remove()
		modal.remove()
		return false
	})
	content.hide();
	
	settings.addContent()
}

function layawayDims(){
	return {
			v:window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
			h:window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
			vs:document.documentElement.scrollTop || document.body.scrollTop,
			hs:document.documentElement.scrollLeft || document.body.scrollLeft
	}
}



function layawayQues(){
var newWin = window.open('/shc/s/BrowseStaticPageCmd?storeId='+storeId+'&catalogId='+catalogId+'&langId=-1'+'&cmdStoreId='+storeId+'&catalogInd=DZD&dzName=W4&vName=layawayCal','Layaway_Questions','width=750,height=550,location=no,status=no,scrollbars=yes,menubar=no,toolbar=no'); 
newWin.focus();
newWin.moveTo(40,40);
}

function layawayTerms(){
if(storeId == '10153')
{
	var newWin = window.open(jspStoreImgDir+'pdf/Sears online layaway agreement 8-6-09_Online layaway launch version.pdf'); 
}
if(storeId == '10151')
{
	var newWin = window.open(jspStoreImgDir+'pdf/Kmart Layaway Contract Agreement 08-14-09_Online layaway launch version.pdf'); 
}
newWin.focus();
newWin.moveTo(40,40);
}
/* Code changes for Lay away ends*/

function displayErrorPopUp_WishList(){
	    //Setting an empty to string to type of error message
	    var value = "";
	    if(wishlistException != "3"){
	       var remember = document.getElementById("remembered");
	        //Add to wishlist button has been clicked
	        if(wishlistException == "0"){
	          if(remember == "yes"){
	            value = "error10";
	          }else{
	            //Item was added successfully
	            value="error6";
	          }
	          //Item was added successfully
	          value="error6";
	
	        }
	        object = document.getElementById("saveToList");
	        showErrorPopUpBox(object,value);
	    }
	}
	
	function displayErrorPopUp_xCheckout(){
	    //Setting an empty to string to type of error message
	    var value = "";
	    if(cartException != "3"){
	        //The add to cart button had been clicked
	        if(cartException == "1"){
	        	if (errorMessageKey == '_ERR_FORMATCONFLICT_SAC' || errorMessageKey == '_ERR_FORMATCONFLICT_NSAC') {
	        		// Automotive Phase 2
	        		showAutoErrorMsgPopUpBox (errorMessageKey, cartExceptionMessage, '', '', imgPath, 'ProductPage');
	        	} else {
		        	
	            	//An exception had occured
	            	object = document.getElementById("xCheckout");
	            	showErrorPopUpBox(object,value);
	            }
	        }
	    }
	}
	
	function displayErrorPopUp_Cart(){
	    //Setting an empty to string to type of error message
	    var value = "";
	    if(cartException != "3"){
	        //The add to cart button had been clicked
	        if(cartException == "1"){
	        	if (errorMessageKey == '_ERR_FORMATCONFLICT_SAC' || errorMessageKey == '_ERR_FORMATCONFLICT_NSAC') {
	        		// Automotive Phase 2
	        		showAutoErrorMsgPopUpBox (errorMessageKey, cartExceptionMessage, '', '', imgPath, 'ProductPage');
	        	} else {
		        	
	            	//An exception had occured
	            	object = document.getElementById("addCart");
	            	showErrorPopUpBox(object,value);
	            }
	        }
	    }
	}
	
	function  showPopup(){ 
		
		//var varRegistryType = $('input#registryType').attr('value');

		/*To check whether the user clicked registry or wishlist*/
		var strURL = document.location.search;
		
		if (strURL.search("RegistryType=registry") != -1){
		    varRegistryType = "registry";
		}
		else if (strURL.search("RegistryType=wishlist") != -1){
		     varRegistryType = "wishlist";
		}    
		else{
		      varRegistryType = ""; 
		}
		
		if(varRegistryType == "registry"){
			productRegistry();
		}
		if(varRegistryType == "wishlist"){
			productWishlist();
		}
	}
	
	/*This function is called on load of the page and is mainly used when pickup option is the default one
  This is on FIRST TIME page load*/
	function pickupOnLoad(){

	    /* Function called to check the which options are available and 
	       which radio button to be checked on Page load in different scenarios.*/
	    checkProductActions();
	    /*  to check wether holiday messaging and shipping calculator is avaiable and
	       if yes then populate the values in the respective div's.*/
	    if(shipCal == 1){
	        shipCalDiv.innerHTML = shipCalciMsg;
	        if(isI18NConvReq()){
	       		 shipCalDiv.innerHTML = "";
	        }
	    }
	    
	    /*This function is called to display the content within the actions widget.*/
	    if(pickupOption == '1'){
	    	if(regAvlMainFlag != 'true')	{           
 		        shipMsgDiv.style.display = "block"; 
	        }
	        /*Pickup option is the default one*/
	        if(storeIdReq!=10161){
	        if(variant == "0"){ 
	            showPickUpOptions();
	        } else{
		    	if(regAvlMainFlag != 'true')	{           
			        showEnterZipMsg(3);
		        }
	        }
	        }
	    
	    }else if (deliveryOption == 1){ 
			/*	RA CONDITION	*/
			if(regAvlMainFlag != 'true')	{
            	shipMsgDiv.style.display = "block";
            }
            getDeliveryMsgOnCheck();
	    }
	    else if ( shipOption == 1){
	        showShipMsg();
	    }   
		fixInfoHeight();
	}
	
	function parseUrl(){
    
	    var vName_Param= gup('vName');
	    if(vName_Param != "")
	    {
	        document.addToCart.vName.value = vName_Param;
	    }
	    
	    var cName_Param= gup('cName');        
	    if(cName_Param != ""){
	        document.addToCart.cName.value = cName_Param;
	    }
	    
	    var sName_Param= gup('sName');
	    if(sName_Param != ""){
	        document.addToCart.sName.value = sName_Param;
	    }   
	    
	    var grUserTypeJS = getCookie('GiftRegApp'+storeIdReq);   
	    if((grUserTypeJS != "") && (grUserTypeJS == 'REGISTRANT')){
	        AddToReg.style.display = "block";
	    }
	    if((grUserTypeJS != "")){
	        document.addToCart.grUserType.value = grUserTypeJS;
	    }
	}
	
	
	//Called after the SCIM ajax call
	function fnDeliverybackCntDwn(value){ 
	
		var availButton='';
        if (ddcRegionalAvlFl == 'true'){
           availButton=availabilityButton(0);
        }else{
           availButton=availabilityButton(1);
        }
	   scimCalled = true;
	   var displayZipMsg='<p>ZIP Code <b>' + zipCode + '</b>';
       var startUL='<ul class=availability>';
       var endUL='</ul>';
      
       var nddMessage='<li class=expDeliv> Eligible for next day delivery. Proceed to checkout for details.</li>';
       if(value=="OutOfStock"){
          if(variant == '0'){
                delZipMsg = '<li class=notinStock>This item is out of stock in this Zip Code.  <br><a href=\"javascript:setNextPage(\''+subCategoryDisplayURL+'\');\">View similar items</a></li>    ';
          }
          else{
           delZipMsg = '<li class=notinStock>This item is out of stock in this Zip Code.</li>    ';
       
          }
          if($('input#emailMeEligible').attr('value') == '1'){
			var emailMeLink='<li class=noIcon><a href=\"#\" onclick=\"javascript:mePop(\''+maskedName+'^ '+partnumber+'^ '+mfgPartNumber+'^ '+storeName+'\',\'emailMe\');\" >Email Me</a> when in stock.</li>';
            delZipMsg= delZipMsg + emailMeLink;
          }

           delZipMsg=startUL+delZipMsg+endUL;
            
            /* Make RTI call only if the zipcode with which SCIM is made is different from the zipcode with 
            which previous RTI call was made.*/
        	if(zipCode != rtiZipcode){
            	deliveryChecked = 'true';
				callRTI();
			}
			else{
				if(rtiSuccess == true){
 					delZipMsg = delZipMsg + pickUpAvl + alsoPara + rtiZipMsg;
 				} else if(rtiSuccess == false){
 					delZipMsg += '<p><a href=\"javascript:;"\" onclick=\"javascript:showEnterZipMsg(2)\" >Enter another ZIP code</a></p>'+availButton;
				}
			}
				
            shipEnterZipDivNew.innerHTML = delZipMsg;
            displayZipDiv.innerHTML=displayZipMsg;
			shipMsgDiv.style.display = "block";
			shipEnterZipMsgDiv.style.display = "block";
			if (shipCal == 1){  
				$(shipCalDiv).show();
				//International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
			}
			shipEnterZipDiv.style.display = "none";
			shipEnterZipDivNew.style.display = "block";
			displayZipDiv.style.display = "block";
            if (ddcRegionalAvlFl == 'true') {
                hardAddTocartBtn(0);  
             } 
        }

    else{    
    	    var scimMsg=""; 
            var prodZipNDD=0;
            scimMsg = value;
            if (value.indexOf('#') !=-1){
              prodZipNDD=1;
              scimMsg=value.substring(0,(value.length-2));
            }

            dateMsg="";
            if(scimMsg!="--" && scimMsg!="7" && scimMsg!="4" && scimMsg!="9" && scimMsg!="6" && scimMsg!="Failure" && scimMsg!=""){

            	delZipMsg = '<li class=inStock>In Stock for Delivery </li>  ';
            	dateMsg= '<li class=noIcon> The earliest available delivery date is:<b> ' + scimMsg + '</b></li>  ';
            	if(prodZipNDD=="1"){
                    dateMsg=dateMsg+nddMessage;
                }
            }          

            else if(scimMsg=="6"){
	            delZipMsg = '<li class=noIcon>Not Available for Delivery</b> for your zip  ' + zipCode + '</li>';
	            dateMsg= '<li class=noIcon>Your zip code falls outside of our current home delivery coverage, but we can often make other arrangements. You can still Add To Cart and proceed to checkout where you will receive further direction for assistance or enter another zip code. </li> ';
            }

           else{      
            delZipMsg = '<li class=noIcon> Available for Delivery  for your zip  ' + zipCode + '. Typically, this product is available for delivery in 5 - 7 business days</li>';
              if(prodZipNDD=="1" && scimMsg=="--"){
                    dateMsg=dateMsg+nddMessage;
              }
            }
            if (ddcRegionalAvlFl == 'true') {
                hardAddTocartBtn(1);  
            }
            delZipMsg=startUL+delZipMsg+dateMsg+endUL;
            
            
        	 /* Make RTI call only if the zipcode with which SCIM is made is different from the zipcode with 
            which previous RTI call was made.*/
        	if(zipCode != rtiZipcode){
            	deliveryChecked = 'true';
				callRTI();
			}
			else{
			  if(rtiSuccess == true){
 					delZipMsg = delZipMsg + pickUpAvl + alsoPara + rtiZipMsg;
 			  } else if(rtiSuccess == false){
 					delZipMsg += '<p><a href=\"javascript:;"\" onclick=\"javascript:showEnterZipMsg(2)\">Enter another ZIP code</a></p>'+availButton;
 				
				}
			}
		
            
            shipEnterZipDivNew.innerHTML = delZipMsg;
            displayZipDiv.innerHTML=displayZipMsg;
             
			shipMsgDiv.style.display = "block";
		    shipEnterZipMsgDiv.style.display = "block";
			if (shipCal == 1){  
				$(shipCalDiv).show();
				//International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
		    }
		    shipEnterZipDiv.style.display = "none";
		    shipEnterZipDivNew.style.display = "block";
		    displayZipDiv.style.display = "block";
        }
		
		if(pickUpSelected == 'true'){
	        	$('div#pickUpAvailable').addClass('onlyPickUp');
        } else {
        	if($('div#pickUpAvailable').hasClass('onlyPickUp')){
        		$('div#pickUpAvailable').removeClass('onlyPickUp');
        	}
        }
		       	
		fixInfoHeight();
	}
	
	function availabilityButton(val){
	    var availButton = '';

        if(val == 0){  
            availButton=  '<input alt=\"check availability button\" id=\"chkAvailBtn\" type=\"image\" src=\"'+jspStoreImgDir+'img/buttons/btn_check_availability.gif\" width=\"126\" height=\"22\" style=\"display: none;\"/>  ';
        }else{    
          availButton= '<input alt=\"check availability button\" id=\"chkAvailBtn\" type=\"image\" src=\"'+jspStoreImgDir+'img/buttons/btn_check_availability.gif\" width=\"126\" height=\"22\"  align=\"absmiddle\" onclick=\"javascript:submitZipCode(this);\"/> ';	      
        } 
        return  availButton;
	}
	
	
	function callRTI() { 

	 	rtiZipcode = zipCode;
	    var catentryIdValues = getCatEntryIds();
	    url = "RTICall?storeId=" + storeIdReq +"&cmdStoreId=" + storeIdFinal + "&zipCode=" + zipCode + "&pickupStoreId=" + pickupStoreIdC + "&langId=-1&" 
	    		+ catentryIdValues+ "&isSPUEligible=" + isSPUEligible+ "&isSRESEligible=" + isSRESEligible + "&vcsVertical=" + vcsVertical;
	
		if((storeIdReq=='10153') && (pickUpVar == '1') && (variant == "0")){
			ajaxCall(url,'fnRTICallbackCntDwn','','');
		} else {
	    	ajaxCall(url,'fnRTICallback','','');
	    }
	}
	
	
	
/*The call back function after the ajaxcall made in the callRTI()*/
function fnRTICallback(value){    

	response = value.split('#')[0];
	datefromScim = value.split('#')[1];
		
	if(response =="Success" && value!='' && response!=''){ 
    
        /*The product is instock*/        
          storeMsg = getCookie('address'+storeIdReq);
        if(datefromScim=="" || datefromScim == null){		
        	zipMsg = '<b>In Stock for Store Pick Up at:</b><p>' + storeMsg + '<br><a href=\"javascript:clickChangeStore()\">change store</a></p>';
        }else{
        	zipMsg = '<b>In Stock at:</b><p>' + storeMsg +'<br> in '+ datefromScim +' days ' +'<br><a href=\"javascript:clickChangeStore()\">change store</a></p>';
        }

       if (ddcRegionalAvlFl == 'true'){
               availButton=availabilityButton(0);
               hardAddTocartBtn(1);
        }else{
               availButton=availabilityButton(1);
              
        }  
        zipMsg=zipMsg+availButton;
        displayZipDiv.innerHTML = zipMsg;
		document.getElementById('availZIP').value =zipCode;
        document.getElementById('actionActionType').value ='3';
		
		shipMsgDiv.style.display = "block";
		shipEnterZipDivNew.style.display = "none";
		shipEnterZipDiv.style.display = "none";
		shipEnterZipMsgDiv.style.display = "block";
        displayZipDiv.style.display = "block";
        displayZipButtonDiv.style.display = "block";
		if (shipCal == 1){   
			$(shipCalDiv).show();
			//International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
	    }
    }
    else{ 
        showEnterZipMsg(3);
    }
	fixInfoHeight();
}



/*CountDown - The call back function after the ajaxcall made in the callRTI()*/
function fnRTICallbackCntDwn(value){ 
   
	
		response = value.split('#')[0];
		datefromScim = value.split('#')[1];
		qtyAvail = value.split('#')[2];
		storeName = value.split('#')[3];
	    storeAddrDet= value.split('#')[4];
		storeMsg = getCookie('address'+storeIdReq);
		
		zipCodeAttr = 2;
		
		//If pickup option is selected by user
		if(pickUpSelected == 'true'){
			zipCodeAttr = 3;
			document.getElementById('actionActionType').value ='3';
		}	else {
			//If delivery option is selected by user.
			zipCodeAttr = 2;
			document.getElementById('actionActionType').value ='2';
			
		}
		var changeStrLink = '';
		if(shipSelected == 'false'){
			changeStrLink = '<a href=\"javascript:clickChangeStr(zipCodeAttr)\">Enter another ZIP code</a>';
		}
		if(response =="Success" && value!='' && response!=''){ 
	     	rtiSuccess = true;
	        /*The product is instock*/        
	          if(datefromScim=="" || datefromScim == null){                                
	             if(qtyAvail=="" || qtyAvail == null){
	             	
	                rtiZipMsg = '<p><strong>Nearest Available<br \=""/>For Store Pick Up:</strong><br>';
	                rtiZipMsg += storeName+ '<br \=""/>' + storeAddrDet+'<br \=""/><br>';
	                rtiZipMsg += changeStrLink;
	                rtiZipMsg += '</p></div>';          
	                                                              
	             }else{  
	             
	                rtiZipMsg = '<p><strong>Nearest Available<br \=""/>For Store Pick Up:</strong><br>';
	                rtiZipMsg += storeName+ '<br \=""/>' +storeAddrDet+'<br \=""/>';
	                rtiZipMsg += '<span class="inventoryLeft"><strong>Only '+qtyAvail+' Left!</strong></span><br>';
	                rtiZipMsg += changeStrLink;
	                rtiZipMsg += '</p></div>';
	             
	             }
	        }else{
	            
	            rtiZipMsg = '<p><strong>In Stock at:</strong><br>' +storeName+ '<br \=""/>';
	            rtiZipMsg += storeAddrDet +' in '+ datefromScim +' days <br>';
	            rtiZipMsg += changeStrLink;
	            rtiZipMsg += '</p></div>'
	        }
	     
	         
	       if (ddcRegionalAvlFl == 'true'){
	               availButton=availabilityButton(0);
	               hardAddTocartBtn(1);
	        }else{
	               availButton=availabilityButton(1);
	              
	        }  
	        
	        //If RTI call is made along with the SCIM call we will just append the RTI response to the SCIM response.
	        if(deliveryChecked == 'true'){
				if(scimCalled == true){
				shipEnterZipDivNew.innerHTML = shipEnterZipDivNew.innerHTML+ pickUpAvl + alsoPara +rtiZipMsg;
				} else {
					displayZipDiv.innerHTML = '<p>ZIP Code <b>' + zipCode + '</b>';
					shipEnterZipDivNew.innerHTML = shipEnterZipDivNew.innerHTML+ pickUpAvl +rtiZipMsg;
				}
				deliveryChecked = 'false';
				fixInfoHeight();
				return;
	        }
	        
	        rtiZipMsg=rtiZipMsg+availButton;
	        displayZipDiv.innerHTML = pickUpAvl + rtiZipMsg;
			document.getElementById('availZIP').value =zipCode;
			
			shipMsgDiv.style.display = "block";
			shipEnterZipDivNew.style.display = "none";
			shipEnterZipDiv.style.display = "none";
			shipEnterZipMsgDiv.style.display = "block";
	        displayZipDiv.style.display = "block";
	        displayZipButtonDiv.style.display = "block";
			if (shipCal == 1){   
				$(shipCalDiv).show();
				//International Shipping 
			    	if(isI18NConvReq()){
			        	shipCalDiv.style.display = "none"; 
			        }
		    }
	    }else if(response =="Failure" && value!='' && response!='' && deliveryChecked == 'true'){
		      rtiSuccess = false;
	          rtiZipMsg = '';
			  if(scimCalled == true){
			  	shipEnterZipDivNew.innerHTML = delZipMsg + '</b><p style="text-align:center"><a href=\"javascript:void(null);"\" onclick=\"javascript:showEnterZipMsg(2)\" >Enter another ZIP code</a></p>'+availButtonOnLoad;
			  }
	          deliveryChecked = 'false';
	    }
	    else if(shipSelected == 'false'){ 
	    	rtiSuccess = false;
	        showEnterZipMsg(3);
	    }
	      if(pickUpSelected == 'true'){
		        $('div#pickUpAvailable').addClass("onlyPickUp");
	        } else {
	        	if($('div#pickUpAvailable').hasClass('onlyPickUp')){
	        		$('div#pickUpAvailable').removeClass('onlyPickUp');
	        	}
	        }
		fixInfoHeight();
	}
	

//On click of continue button in Gift Registry pop-up.
	function popupSubmit(isGT){
          Load.style.display = "block";
          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 = getCatEntryIds();
                  var rew = "~";
                  cattId = cattId.replace(/&/g,rew);
                  mainUrl = mainUrl.replace(/&/g,rew);
                  if(document.getElementById("remembered")!=null){
                       var remem = document.getElementById("remembered").value;
                       if(remem=="yes")
                            location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;                                                           
                        else
                            location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
                  else {
                  if (isGT =="gt") {
                  location.href = "GiveTogether?nextView=GTCreateListView&storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  } else {
                      location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                }
                    }
                }
                else{
                  	var url = "";
				    var grUserType = getCookie('GiftRegApp'+storeId);
				    var catEntryIds = getCatEntryIds();
				    var externalId = extId;
				    url = 'AddToGiftRegistry?storeId='+storeId+'&catalogId='+catalogId+'&grUserType=' + grUserType + '&externalId=' + externalId;
				    ajaxCall(url + catEntryIds ,'getAddToRegistryStatus','',isGT);
                }
            }
          }
          
          if (document.GRForm.registry.checked){
            if (document.getElementById("registry").value == 'create'){
                 var cattId = getCatEntryIds();
                 var rew = "~";
                 cattId = cattId.replace(/&/g,rew);
                 mainUrl = mainUrl.replace(/&/g,rew);
                 if(document.getElementById("remembered")!=null){
                    var remem = document.getElementById("remembered").value;
                    if(remem=="yes")
                        location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=WeddingRegistryCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&cattId='+cattId+'&mainUrl='+mainUrl;                                                          
                    else
                        location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
                  else {
                  	if (isGT =="gt") {
                  		location.href = "GiveTogether?nextView=GTCreateListView&storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
                 	 } else {
                      location.href = "WeddingRegistryCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&cattId="+cattId+"&mainUrl="+mainUrl;
              }
          }
     }
          }
     }
    
function getAddToRegistryStatus(value,isGT){
    Load.style.display = "none";
    object = document.getElementById("saveToList");
    flag = '';
    
    if(value.substring(7,value.length) == 'ItemsExceeded'){
    
    	flag = value.substring(7,value.length);
    
    }
    else {
    
	    if(value.substring(0,7) == "Success"){
	        if(document.getElementById("remembered")!=null){
	           var remem = document.getElementById("remembered").value;
	           if(remem=="yes")
	                flag = 'error11'+value.substring(7,value.length);
	           else
	                flag = 'error7'+value.substring(7,value.length);
	        } else
	            flag = 'error7'+value.substring(7,value.length);
	   	}
   }
    SaveToOpsErrorPopUpBox(object,flag,isGT);
    //cursor_Default();
}

function SaveToOpsErrorPopUpBox(o,err,isGT)
    {
    if(!document.getElementById('errorBox1')){
       
        var topPosition=0;
        var leftPosition=0;
        newDiv=document.createElement('div');
        newDiv.className='errorPop';
        newDiv.id='errorBox1';
        newDiv.innerHTML=getErrorStatus(err,isGT);
        document.body.appendChild(newDiv);
        var errBox=document.getElementById('errorBox1');
        var oy = findPosY(o);
        var ox = findPosX(o);
         
       
        if(browser=="Internet Explorer"){
            var docWidth=document.body.scrollWidth;
            var docHeight=(document.body.scrollHeight);
            var boxH=errBox.offsetHeight;
            var boxW=errBox.offsetWidth;
          
            if ((ox-100)<0)
            {
                errBox.style.top=(oy-350)+"px";
                errBox.style.left=(ox-15)+"px";
                topPosition=oy-350;
                leftPosition=ox-40;
            } 
            else if ((ox-100)>(docWidth-boxW))
            {
                errBox.style.top=(oy-100)+"px";
                errBox.style.left=(docWidth-boxW-10)+"px";
                topPosition=oy-100;
                leftPosition=docWidth-boxW-10;
            } 
            else 
            {   
                errBox.style.top=(oy-100)+"px";
                errBox.style.left=(ox-100)+"px";
                topPosition= oy-100;
                leftPosition= ox-100;
            }
            
            if(topPosition <=0 || leftPosition<=0)
            {
                errBox.style.top=docWidth/7+"px";
                errBox.style.left=docHeight/1.1+"px";
            }
        } else {
                var topPosition=0;
                var leftPosition=0;
                var docWidth=document.documentElement.clientWidth;
                var docHeight=document.documentElement.clientHeight;
                var boxH=errBox.offsetHeight;
                var boxW=errBox.offsetWidth;
               
                if ((ox-100)<0)
                {
                    errBox.style.top=(oy-100)+"px";
                    errBox.style.left=(ox)+"px";
                    topPosition=oy-100;
                    leftPosition=ox;
                } 
                else if ((ox-100)>(docWidth-boxW))
                {
                    errBox.style.top=(oy-100)+"px";
                    errBox.style.left=(docWidth-boxW-10)+"px";
                    topPosition=oy-100;
                    leftPosition=docWidth-boxW-10;
                } 
                else 
                {
                    errBox.style.top=(oy-100)+"px";
                    errBox.style.left=(ox-100)+"px";
                    topPosition=oy-100;
                    leftPosition=ox-100;
                }
            
                if(topPosition <=0 || leftPosition<=0)
                {
                    errBox.style.top=docWidth/7+"px";
                    errBox.style.left=docHeight/1.1+"px";
                }   
        }
    }
}

function zipCookieDisplay(fullfilment){
		if(fullfilment=="SPU"){  	
			displayZipDiv.innerHTML='<p>ZIP Code <b>' + zipCode + '</b><p><a href=\"javascript:void(null);"\" onclick=\"javascript:showEnterZipMsg(3)\" >Check another ZIP Code</a></p>'+availButtonOnLoad;
		        
		}else{
			displayZipDiv.innerHTML='<p>ZIP Code <b>' + zipCode + '</b><p><a href=\"javascript:void(null);"\" onclick=\"javascript:showEnterZipMsg(2)\" >Check another ZIP Code</a></p>'+availButtonOnLoad;;   
		}
		
		
			
}

//for Sears card monthly payment pop_up

/*
		
function searsCardMonthly(){			
			
			var newWin = window.open('/shc/s/BrowseStaticPageCmd?storeId='+storeId+'&catalogId='+catalogId+'&langId=-1'+'&cmdStoreId='+storeId+'&catalogInd=DZD&dzName=W4&vName=searsCardMonthly','Sears_Card_Monthly','width=750,height=550,location=no,status=no,scrollbars=yes,menubar=no,toolbar=no'); 
			newWin.focus();
newWin.moveTo(40,40);
				
			}
			
			
		*/	
			
			
			
			
		//	For pop up of sears card monthly
			
			function searsCardMonthly() {
			pageURL= jspStoreImgDir+'pdf/Estimated_Minimum_Monthly_Payment_Table.pdf';
			title = 'MonthlyPaymentDetails';						
			var targetWin = window.open (pageURL,title,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=750,height=550');
}

			
function popupWishlistSubmit(){    
          Load.style.display = "block";
          var storeId = document.getElementById("storeId").value;
          var langId = document.getElementById("langId").value;
          var catalogId = document.getElementById("catalogId").value;
          var frompage ="WishlistPage";
          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 = getCatEntryIds();
                  var rew = "~";
                  cattId = cattId.replace(/&/g,rew);
                  mainUrl = mainUrl.replace(/&/g,rew);
                  if(document.getElementById("remembered")!=null){
                    var remem = document.getElementById("remembered").value;
                    if(remem=="yes")
                        location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=GiftRegistryWishListCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&frompage='+frompage+'&cattId='+cattId+'&mainUrl='+mainUrl;
                    else
                        location.href = "GiftRegistryWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&frompage="+frompage+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
                  else
                      location.href = "GiftRegistryWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&frompage="+frompage+"&cattId="+cattId+"&mainUrl="+mainUrl;
                }
                else{
                  	var url = "";  
				    var grUserType = getCookie('GiftRegApp'+storeId);
				    var catEntryIds = getCatEntryIds();
				    var externalId = extId;
				    url = 'AddToGiftRegistry?storeId='+storeId+'&catalogId='+catalogId+'&grUserType=' + grUserType +'&externalId=' + externalId;
				    ajaxCall(url + catEntryIds ,'getAddToNewWishList','',''); 
                }
            }
          }
          
          if (document.GRForm.registry.checked){
            if (document.getElementById("registry").value == 'create'){
                 var cattId = getCatEntryIds();
                 var rew = "~";
                 cattId = cattId.replace(/&/g,rew);
                 mainUrl = mainUrl.replace(/&/g,rew);
                 if(document.getElementById("remembered")!=null){
                    var remem = document.getElementById("remembered").value;
                    if(remem=="yes")
                        location.href = "LogonForm?storeId="+storeId+"&catalogId="+catalogId+"&langId="+langId+'&URL=GiftRegistryWishListCreateView?storeId='+storeId+'&langId='+langId+'&catalogId='+catalogId+'&frompage='+frompage+'&cattId='+cattId+'&mainUrl='+mainUrl;
                    else
                        location.href = "GiftRegistryWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&frompage="+frompage+"&cattId="+cattId+"&mainUrl="+mainUrl;
                  }
                  else
                      location.href = "GiftRegistryWishListCreateView?storeId="+storeId+"&langId="+langId+"&catalogId="+catalogId+"&frompage="+frompage+"&cattId="+cattId+"&mainUrl="+mainUrl;
              }
          }
     }
 
 function getAddToNewWishList(value){
	    Load.style.display = "none";
	    object = document.getElementById("saveToList");
	    flag = '';
	    if(value.substring(7,value.length) == 'ItemsExceeded'){
	    	flag = value.substring(7,value.length);
	    }
     	else {
	    if(value.substring(0,7) == "Success"){
	        if(document.getElementById("remembered")!=null)
	        {
	           var remem = document.getElementById("remembered").value;
	           if(remem=="yes")
	                flag = 'error12'+value.substring(7,value.length);
	           else
	                flag = 'error9'+value.substring(7,value.length);
	        }
	        else
	            flag = 'error9'+value.substring(7,value.length);
	
	    }
   }
    SaveToOpsErrorPopUpBox(object,flag);
   //cursor_Default();
}

function hardAddTocartBtn(val){
    /*0 add to cart disabled
      1 add to cart enabled*/
    var elemEn = document.getElementById('addCart');
    var elemEnEX = document.getElementById('productXC');
    if(val == 0){
        if(elemEn){    
        	elemEn.style.display = "none";  
        }   
        if(elemEnEX){
        	elemEnEX.style.display = "none";
        }
    }else if(val == 1){
        if(elemEn){
        	elemEn.style.display = "block"; 
       }
       if(elemEnEX){
        	elemEnEX.style.display = "block";
        }    
    }
}

	//Called after the SCIM ajax call
	function fnDeliveryback(value){ 

		var availButton='';
        if (ddcRegionalAvlFl == 'true'){
           availButton=availabilityButton(0);
        }else{
           availButton=availabilityButton(1);
        }
       var displayZipMsg='<p>ZIP Code <b>' + zipCode + '</b><p><a href=\"javascript:void(null);"\" onclick=\"javascript:showEnterZipMsg(2)\" >Check another ZIP Code</a></p>'+availButton;
       var startUL='<ul class=availability>';
       var endUL='</ul>';
      
       var nddMessage='<li class=expDeliv> Eligible for next day delivery. Proceed to checkout for details.</li>';
       if(value=="OutOfStock"){
          isOutOfStock='true';
          if(variant == '0'){
                zipMsg = '<li class=notinStock>This item is out of stock in this Zip Code.  <br><a href=\"javascript:setNextPage(\''+subCategoryDisplayURL+'\');\">View similar items</a></li>    ';
          }
          else{
           zipMsg = '<li class=notinStock>This item is out of stock in this Zip Code.</li>    ';
       
          }
          if($('input#emailMeEligible').attr('value') == '1'){
			var emailMeLink='<li class=noIcon><a href=\"#\" onclick=\"javascript:mePop(\''+maskedName+'^ '+partnumber+'^ '+mfgPartNumber+'^ '+storeName+'\',\'emailMe\');\" >Email Me</a> when in stock.</li>';
            zipMsg= zipMsg + emailMeLink;
          }

	        zipMsg=startUL+zipMsg+endUL;
            shipEnterZipDivNew.innerHTML = zipMsg;
            displayZipDiv.innerHTML=displayZipMsg;
			shipMsgDiv.style.display = "block";
			shipEnterZipMsgDiv.style.display = "block";
			if (shipCal == 1){  
			    shipCalDiv.style.display = "block";
			    if(isI18NConvReq()){
			        shipCalDiv.style.display = "none"; 
			        }
			}
			shipEnterZipDiv.style.display = "none";
			shipEnterZipDivNew.style.display = "block";
			displayZipDiv.style.display = "block";
            if (ddcRegionalAvlFl == 'true') {
                hardAddTocartBtn(0);  
             } 
        }

    else{    
    	    isOutOfStock='false';
    	    var scimMsg=""; 
            var prodZipNDD=0;
            scimMsg = value;
            if (value.indexOf('#') !=-1){
              prodZipNDD=1;
              scimMsg=value.substring(0,(value.length-2));
            }

            
            dateMsg="";
            if(scimMsg!="--" && scimMsg!="7" && scimMsg!="4" && scimMsg!="9" && scimMsg!="6" && scimMsg!="Failure" && scimMsg!=""){

            	zipMsg = '<li class=inStock>In Stock for Delivery </li>  ';
            	dateMsg= '<li class=noIcon> The earliest available delivery date is:<b> ' + scimMsg + '</b></li>  ';
            	if(prodZipNDD=="1"){
                    dateMsg=dateMsg+nddMessage;
                }
            }          

            else if(scimMsg=="6"){
	            zipMsg = '<li class=noIcon>Not Available for Delivery</b> for your zip  ' + zipCode + '</li>';
	            dateMsg= '<li class=noIcon>Your zip code falls outside of our current home delivery coverage, but we can often make other arrangements. You can still Add To Cart and proceed to checkout where you will receive further direction for assistance or enter another zip code. </li> ';
            }

           else{      
            zipMsg = '<li class=noIcon> Available for Delivery  for your zip  ' + zipCode + '. Typically, this product is available for delivery in 5 - 7 business days</li>';
              if(prodZipNDD=="1" && scimMsg=="--"){
                    dateMsg=dateMsg+nddMessage;
              }
            }
            if (ddcRegionalAvlFl == 'true') {
                hardAddTocartBtn(1);  
            }
            zipMsg=startUL+zipMsg+dateMsg+endUL;
             
            shipEnterZipDivNew.innerHTML = zipMsg;
            displayZipDiv.innerHTML=displayZipMsg;
             
			shipMsgDiv.style.display = "block";
		    shipEnterZipMsgDiv.style.display = "block";
			if (shipCal == 1){  
		        shipCalDiv.style.display = "block";
		        if(isI18NConvReq()){
			        shipCalDiv.style.display = "none"; 
			        }
		    }
		    shipEnterZipDiv.style.display = "none";
		    shipEnterZipDivNew.style.display = "block";
		    displayZipDiv.style.display = "block";
        }
		fixInfoHeight();
	}