//CODE FOR PRODUCT OPTION AND SHOPPING CART STARTS
var totalSteps=0;
var subTotal = 0.00;

var giftCardFlag = false;

$(function (){
	$(window).scroll(function (){
		var items = $(".col_2 div.summary");
		
		items.each(
			function(){
				if(!this.initialPosition)
				{
					this.initialPosition = findPos(this)[1];
					this.finalPosition = findPos($("#footer")[0])[1];
					this.height = this.offsetHeight;
				}
			});		
		
		items.stop();
		items.each(
			function(){
				var EXTRA = 10;
				if (getScrollTop()>this.initialPosition)
				{
					if ((getScrollTop() + this.height + EXTRA) < this.finalPosition)
					{
						items.animate({marginTop:(getScrollTop()-this.initialPosition+EXTRA)+"px"});
					}
					else
					{
						items.animate({marginTop:(this.finalPosition-this.initialPosition-this.height - EXTRA*2)+"px"});
					}
				}
				else
				{
					items.animate({marginTop:"0px"});
				}
			});		
	});
});
function doSubmitAddress(){
		$('#temp').html($('#installation_info > #installation_address').clone());
		var html = '';
		$('#temp > #installation_address > p > input').not('#temp > #installation_address > p > input#btnSubmitAddress').each(function(){
			if($(this).attr('id') != 'address_city'){
				html += $(this).val() + ' ';
			} else {
				html += '<br />' + $(this).val() + ', ' + $('#address_state').val() + ' ';
			}
		});
		html += '<a id="chgAddress" href="#">Change this</a>';
		
		$('#installation_info > #installation_address').html('<h4>Address where installation will occur:</h4><div id="install_address">' + html + '</div>');
		$('#installation_info > h3').hide();
		$('#installation_options').slideDown();
		
		$('#chgAddress').unbind().click(function(){
			$('#installation_info > #installation_address').remove();
			$('#installation_options').before($('#temp > #installation_address').clone());
			$('#installation_info > h3').show();
			$('#temp').empty();
			$('#btnSubmitAddress').unbind().click(function(){
				doSubmitAddress();
				return false;
			});
			$('#installation_options').slideUp();			
			return false;
		});
		
		return false;
}


function doTotalCost(){
	var total_cost = 0;
	$('#installation_options > div > input:checked').each(function(){
		total_cost += parseFloat($(this).val());
	});
	$('#total_cost').html('$' + total_cost.toFixed(2)).highlightFade({ color: '#f6f9ca', speed: 2000 });
}

function getScrollTop()
{
	return window.pageYOffset || document.documentElement.scrollTop;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}

//Auto-Fill function accepts id of input and fills it with the given value.
function autoFill(id, v){
	$(id).css({ color: "#b2adad" }).attr({ value: v }).bind('click focus', function(){
		var loginVal = $(this).val();
		if(loginVal==v){
			$(this).val("").css({ color: "#333" });
		}
	}).blur(function(){
		if($(this).val()==""){
			$(this).css({ color: "#b2adad" }).val(v);
		}
	});
	
}

function hideOptions() {
	
	var dl = document.getElementsByTagName('dl');
	for (d=0;d<dl.length;d++){
		if (dl[d].className=="options"){
			var id = dl[d].id;
			document.getElementById(id).className="options disabled";
			document.getElementById(id+"_details").style.display="none";
			totalSteps++;
		}
	}
	document.getElementById("linkToContinue").disabled=true;
	document.getElementById('shoppingButton').innerHTML=document.getElementById("GreyButton").innerHTML;
	document.getElementById('shoppingButton').style.cursor = "none";
}

// HOVER TR HOVER //
function nextStep(id, num,alpha) {		
	
	var id = id.id;
	var stepIndicator =  id.split('_')[1]; 
	var n = num-1;
	var tableName = null;
	var optionType = null;
	var currentStepNum = null;
	var nextStepCode = null;
		
	if(alpha) {
		if(alpha == "giftCard" || alpha == "giftCard2"){
			giftCardFlag = true;
		}
	}
	
	if(stepIndicator == "edit"){
		optionType = id.split('_')[2];
		currentStepNum = "step"+n;
		if(giftCardFlag == true) {
			tableName = currentStepNum+"_table_"+alpha;
		}
		else {
			tableName = currentStepNum+"_table";
		}
				
	}

	else{
		optionType = id.split('_')[0];
		tableName = optionType+"_"+id.split('_')[1]+"_"+id.split('_')[3]+"_table";
		if(optionType == "Deluxe"){
			currentStepNum = "step"+id.split('_')[1];
		}
		
	}
	var table = document.getElementById(tableName);
	
	if(id==currentStepNum+"_edit_"+optionType || id==currentStepNum+alpha+"_edit_"+optionType){
		var parentCatIds = new Array();
		if(alpha=="giftCard"){
			// Adding extra code for gift card
					//On Editing disable Shopping Cart and Drop-down Box		
			document.getElementById("errMessage").style.display="none";
			document.getElementById("linkToContinue").disabled=true;
			table.style.display='';		
			document.getElementById(id).style.display='none';
			document.getElementById(currentStepNum+"_msg1").innerHTML='';
			
		}
				
		var optionTypes = new Array();
		if(giftCardFlag == false) { 
			if(optionType == "SetUp and Connection"){
				if(document.getElementById("Connection Available").innerHTML == "true"){
					var connectionType = document.getElementById(currentStepNum+"_optionType");
					if(connectionType != null && typeof(connectionType) != "undefined" ){
						optionTypes[0] = connectionType.innerHTML;
					}
				}
				if(document.getElementById("Deluxe Available").innerHTML == "true"){
					var deluxeType = document.getElementById(currentStepNum+alpha+"_optionType");
					if(optionTypes[0] != null){
						optionTypes[1] = deluxeType.innerHTML;
					}
					else {
						optionTypes[0] = deluxeType.innerHTML;
					}
				}
			}
			else {
				optionTypes[0] = optionType;
			}
			
			for(var count =0; count < optionTypes.length; count++){
				var parentIds = getParentIds(optionTypes[count]);
				for(var i=0; i< parentIds.length; i++){
					if(optionTypes[count] != 'Deluxe') {
						document.getElementById(currentStepNum+"_"+parentIds[i]+"_msg1").style.display='none';
						document.getElementById(optionTypes[count]+"_"+n+"_"+parentIds[i]+"_table").style.display='';
						document.getElementById(currentStepNum+"_"+parentIds[i]+"_msg2").style.display='';
						if(optionTypes[count] == 'Installation' || optionTypes[count] == 'Connection') {
							document.getElementById(optionTypes[count]+"_Message").style.display='none';
						}
					}
					else {
						document.getElementById(currentStepNum+alpha+"_"+parentIds[i]+"_msg1").style.display='none';
						document.getElementById(currentStepNum+alpha+"_"+parentIds[i]+"_msg2").style.display='';
						document.getElementById(optionTypes[count]+"_"+n+"_"+parentIds[i]+"_table").style.display='';
					}
				}
			}
		}
		
	} 
	else {
		
		var radioButtonName = id + "_radio";
		var rowName = id;
		var radioButton = document.getElementById(radioButtonName);
		var row = document.getElementById(rowName);
		if (table && radioButton && row) {
		    var rows = table.getElementsByTagName('tr');
	       	radioButton.checked = true;
	    	for (var i = 0; i < rows.length; i++) {
	            rows[i].className = '';
	    	}
	    	row.className = 'selected';
	    }
	    if(alpha == "giftCard"){
	    	var dispError = false;
	    	currentStepNum = "step"+n;
	    	document.getElementById(currentStepNum+"_edit_"+alpha).style.display='';
			var tableName = currentStepNum+"_table_"+alpha;
			var table = document.getElementById(tableName);
			var toName = document.getElementById('item_to').value;
			var fromName = document.getElementById('item_from').value;
			var message = '';
			if(document.getElementById('item_msg').value != 'Up to 110 characters') {
				message = document.getElementById('item_msg').value;
			}
			
			if (!validation(toName)){	
				document.getElementById("errMessage").style.display="";
				document.getElementById("itmToErr").style.display="";
				dispError = true;
			}
			else{
				document.getElementById("itmToErr").style.display="none";
			}
			if (!validation(fromName)){	
				document.getElementById("errMessage").style.display="";
				document.getElementById("itmFromErr").style.display="";
				dispError = true;
			}
			else{
				document.getElementById("itmFromErr").style.display="none";
			}
			if (message.length>110){	
				document.getElementById("errMessage").style.display="";
				document.getElementById("itmMsgErr").style.display="";
				dispError = true;
			}
			else{
				document.getElementById("itmMsgErr").style.display="none";
			}
			if(dispError == true) {
				document.productOptionsForm.url.value="";
				document.getElementById("noChange").selected = "selected";
			}
			if(dispError==false){
				document.getElementById("errMessage").style.display="none";
				table.style.display='none';
				document.getElementById(currentStepNum+"_msg1").innerHTML="<b>To: </b> "+toName + "\n<br>\n<b>From: </b> " + fromName + "\n<br>\n<b>Message: </b>" +message;
				createGiftURL();
				document.productOptionsForm.submit();
			}
		}
		else if (alpha){
			
			var stepOptionType="SetUp and Connection";
			document.getElementById(currentStepNum+"_edit_"+stepOptionType).style.display='';
			var rowName = id;
			var scimCode = id.split('_')[2];
			var parCatEntryId = id.split('_')[3];
			var td=document.getElementById("po_name_"+optionType+"_"+scimCode+"_"+parCatEntryId);
			document.getElementById(currentStepNum+alpha+"_"+parCatEntryId+"_msg2").style.display='none';
			document.getElementById("Deluxe_"+n+"_"+parCatEntryId+"_table").style.display="none";
			table.style.display='none';
			document.getElementById(currentStepNum+alpha+"_"+parCatEntryId+"_msg1").innerHTML = td.innerHTML;
			document.getElementById(currentStepNum+alpha+"_"+parCatEntryId+"_msg1").style.display = '';
			if(optionType == "Deluxe"){
				var deluxeFlag = true;
				var connectionFlag = true;
				deluxeFlag = isOptionSelectedForAllItems("Deluxe");	
				if(document.getElementById("Connection Available").innerHTML == "true"){	
					connectionFlag = isOptionSelectedForAllItems("Connection");	
				}				
				if(deluxeFlag && connectionFlag) {			
					openStep(num);		
				}
			}
			
		} 
		else {
			
			if(typeof currentStepNum == "undefined" || currentStepNum == null )	{
				
				if(optionType != "Required" && optionType != "Optional")
				{
					var poCatEntryId = id.split('_')[2];
					var parCatEntryId = id.split('_')[3];
					currentStepNum = "step"+id.split('_')[1];
					var parentIds=getParentIds(optionType);
					for(var i = 0; i < parentIds.length; i++){
						if(document.getElementById("selected_"+optionType+"_"+parentIds[i]+"_CatEntryId").innerHTML != ''){
							document.getElementById(optionType+"_"+id.split('_')[1]+"_"+parentIds[i]+"_table").style.display='none';
							document.getElementById(currentStepNum+"_"+parentIds[i]+"_msg1").style.display='';
							if(parCatEntryId != parentIds[i]) {
								document.getElementById(currentStepNum+"_"+parentIds[i]+"_msg2").style.display='none';
							}
						}
						
					}
					
					if(optionType == "Connection" || optionType == "Deluxe"){
						stepOptionType = "SetUp and Connection";
					}
					else stepOptionType = optionType;
					document.getElementById(currentStepNum+"_edit_"+stepOptionType).style.display='';
					document.getElementById(currentStepNum+"_"+parCatEntryId+"_msg2").style.display='none';
					table.style.display='none';
					
					if(optionType == 'Installation' || optionType == 'Connection') {
						if(poCatEntryId != 'no') {
							document.getElementById(optionType+"_Message").style.display='';
						}
					}
					
					var selectedOptionName = "po_name_"+optionType+"_"+poCatEntryId+"_"+parCatEntryId;
					var selectedOptionPrice = "po_price_"+optionType+"_"+poCatEntryId+"_"+parCatEntryId;
					var selectedPOName = document.getElementById("selected_"+optionType+"_"+parCatEntryId+"_CatEntryId").innerHTML;
					var selectedPOPrice = "selected_"+optionType+"_price_"+parCatEntryId;
				
					//if(optionType != "Deluxe" && optionType != "Requied" || optionType != "Optional"){
					var optionName = document.getElementById(selectedOptionName);
					var optionPrice = document.getElementById(selectedOptionPrice);
					var updateFlag = true;
					if( selectedPOName.length != 0){
						recalculateSubtotal(id,"subtract");
					}
								
					if(poCatEntryId == "no"){
						document.getElementById(selectedPOPrice).innerHTML="$0.0<!--poCatId=0-->";
						document.getElementById("selected_"+optionType+"_"+parCatEntryId+"_CatEntryId").innerHTML = "0";
						document.getElementById(currentStepNum+"_"+parCatEntryId+"_msg1").innerHTML=optionName.innerHTML;
					}
					else{
						document.getElementById(selectedPOPrice).innerHTML="<strong>"+document.getElementById(selectedOptionPrice).innerHTML+"</strong><!--poCatId="+poCatEntryId+"-->";
						document.getElementById("selected_"+optionType+"_"+parCatEntryId+"_CatEntryId").innerHTML = poCatEntryId;
						document.getElementById(currentStepNum+"_"+parCatEntryId+"_msg1").innerHTML=optionName.innerHTML + " " + optionPrice.innerHTML;
						recalculateSubtotal(id,"add");
					}
					document.getElementById(currentStepNum+"_"+parCatEntryId+"_msg1").style.display = '';
					//}
				}
				else if(optionType == "Required" || optionType == "Optional"){
					//var optionType = id.split('_')[0];
					var stepCount = id.split('_')[1];
					var accItemId = id.split('_')[2];
					var parentId = id.split('_')[3];
					
					var selectedElm = document.getElementById(optionType+"_"+stepCount+"_"+accItemId+"_"+parentId+"_checkBox");
					var selOption = eval(selectedElm);
					if(selectedElm.checked == true){
						recalculateSubtotal(id,"add");
					}
					else{
						recalculateSubtotal(id,"subtract");
					}
					
				}
				
			}
			if(optionType != "Required" && optionType != "Optional"){
				
				if(optionType == "Connection" || optionType == "Deluxe"){
						var connectionFlag = true;
						var deluxeFlag = true;
						
						if(document.getElementById("Deluxe Available").innerHTML == "true")	{
							deluxeFlag = isOptionSelectedForAllItems("Deluxe");
						}
						if(document.getElementById("Connection Available").innerHTML == "true")	{
							connectionFlag = isOptionSelectedForAllItems("Connection");
						}
						if(connectionFlag == true && deluxeFlag == true) {
							openStep(num);
						}
						else 
							return;
				}
				else if(isOptionSelectedForAllItems(optionType)){
					openStep(num,false);
				}
			}
			else{
				
				var currentStep = num-1;
				if(document.getElementById("step"+currentStep+"_optionType").innerHTML == 'Optional') {
						openStep(num);
				}					
			}
		}
		var lastStep = 0;
		var finalStep = 0;
		var currentStep = 0;
		
		if(optionType != "Required" && optionType != "Optional"){
			if(document.getElementById("step"+num+"_optionType") != null) {
				if(document.getElementById("step"+num+"_optionType").innerHTML == 'Required') {
					lastStep = ++num;
					openStep(lastStep);
				}
				if(lastStep != 0) {
					currentStep = lastStep;
					finalStep = ++lastStep;
				}
				else {
					currentStep = num;
					finalStep = ++num;
				}
				if(document.getElementById("step"+currentStep+"_optionType") != null) {
					if(document.getElementById("step"+currentStep+"_optionType").innerHTML == 'Optional') {
						openStep(finalStep);
		
					}
				}
					
			}
		}
		
		return true;
		
	}		
	
}


function openStep(n,zipCodeChange) {

	if(n <= totalSteps){
		var step = document.getElementById('step' + n);
		step.className = 'options';
		var step_a = document.getElementById('step' + n + '_details');
		step_a.style.display = '';
		if(zipCodeChange == true && typeof zipCodeChange != "undefined"){
			expandFirstOption();
		}

	} else {
		document.getElementById("linkToContinue").disabled=false;
		document.getElementById('shoppingButton').innerHTML=document.getElementById("RedButton").innerHTML;
		document.getElementById('shoppingButton').style.cursor = "hand";
		if(giftCardFlag == false) {
			document.productOptionsDetails.allOptSelected.value = "true";
		}
	}
}

function selectThis(id, num)
{
	var id = id.id;
	var n = num-1;
	var currentStepNum = "step" + n;
	var tableName = currentStepNum + "_table";
	var table = document.getElementById(tableName);
		
	var radioButtonName = id + "_radio";
	var rowName = id;
	var radioButton = document.getElementById(radioButtonName);
	var row = document.getElementById(rowName);
	if (table && radioButton && row) {
		var rows = table.getElementsByTagName('tr');
		radioButton.checked = true;
		for (var i = 0; i < rows.length; i++) {
			rows[i].className = '';
		}
		row.className = 'selected';
	}
	var td=document.getElementById(rowName).getElementsByTagName('td');
	document.getElementById(currentStepNum+"_msg2").style.display='none';
	table.style.display='none';
	document.getElementById(currentStepNum+"_msg1").innerHTML=td[1].innerHTML + " " + td[2].innerHTML;
}

function hoverTR(id)
{
	
	var id = id.id;
	var radioButtonName = id + "_radio";
    var rowName = id;
	var radioButton = document.getElementById(radioButtonName);
	var row = document.getElementById(rowName);
    if(radioButton && row) {
    	if (!radioButton.checked) {
    		row.className = 'selected';
    	}
    }
	return true;
}

function outTR(id)
{
    var result = null;
	var id = id.id;
    var radioButtonName = id + "_radio";
    var rowName = id;
    var radioButton = document.getElementById(radioButtonName);
    var row = document.getElementById(rowName);

    if (radioButton && row) {
        if (radioButton.checked) {
            row.className = 'selected';
        } else {
            row.className = '';
        }
        if (radioButton.checked) {
            result = radioButton;
        }
    }
    return result;
}

function clearChecks(id)
{
    var id=document.getElementById(id);
    var input=id.getElementsByTagName('input');
    for (c=0; c<input.length; c++) {
        if(input[c].type="checkbox"){
            if (input[c].checked == true) {
            	recalculateSubtotal(input[c].id,"subtract");
            	input[c].checked = false;
            }
        }
    }
}

function isOptionSelectedForAllItems(optionType){
	var parentIds=getParentIds(optionType);
	var checkedValue = false;
	for(var i = 0; i < parentIds.length; i++) {
		var productOption = 'document.productOptionsDetails.'+optionType+'_'+parentIds[i];
		var option = eval(productOption);
		var optionLength =option.length;
		for(var j=0; j < optionLength; j++){
			checkedValue = option[j].checked;
			if(checkedValue)
				break;
		} 
		if(!checkedValue)
			break;
	}
	return checkedValue;
}


function getLocationName(optionType,orderIdCount){
	return "selected_"+optionType+"_"+parentIds[i];
}

function getParentIds(optionType){
	var parentIdCount = document.getElementById(optionType+"_ItemCount").innerHTML;
	var finalParentIds = new Array();
	for(var i=0; i<parentIdCount; i++){
		var currentCount = i+1;
		finalParentIds[i] = document.getElementById(optionType+"_CatId_"+currentCount).innerHTML;
	}
	return finalParentIds;
}


function getAllParentIds(){
	var allParentIdCount = document.getElementById("totalItemCount").innerHTML;
	var finalParentIds = new Array();
	for(var i=0; i<allParentIdCount; i++){
		var currentCount = i+1;
		finalParentIds[i] = document.getElementById("AllParentIds_"+currentCount).innerHTML;
	}
	return finalParentIds;
	
}


function getAllParentOrderItemIds(){

	var allOrderItemIdCount = document.getElementById("orderItemCount").innerHTML;
	var finalOrderItemIds = new Array();
	for(var i=0; i<allOrderItemIdCount; i++){
		var currentCount = i+1;
		finalOrderItemIds[i] = document.getElementById("AllOrderItemIds_"+currentCount).innerHTML;
	}
	
	var parOrderItemIds = "";
	for(var e=0; e < finalOrderItemIds.length; e++) {
		if(e == 0) {
            parOrderItemIds = finalOrderItemIds[e];
        }
	    else {
        	parOrderItemIds = parOrderItemIds+","+finalOrderItemIds[e];
        }
    }
    return parOrderItemIds;
}



function isValidZipFromCookie() {
	
	var storeId = document.getElementById("contextStoreId").innerHTML;
	cookieZipCode=getCookie('zipCode'+storeId);
	if ( cookieZipCode == null || cookieZipCode.length<1) {
		cookieZipCode = "";
		return false;
	}
	if (checkZipPP(cookieZipCode)) {
		return true;
	}
	else
		return false;
}

function zipChanged(flag) {
	var storeId = document.getElementById("contextStoreId").innerHTML;
    var useZip="";
    var len;
    var sameZipCodeInd = 0;
    useZip=document.zipForm.zipCode.value;
    if(!flag) {
    	var cookieZipCode = getCookie('zipCode'+storeId);
    	if(cookieZipCode == useZip) {
    		sameZipCodeInd = 1;
    	}
    }
    if ( checkZipPP(useZip) && sameZipCodeInd == 0) {
   	    setCookie('zipCode'+storeId,useZip);
    	var zipCodeChange = true;
    	pOAjaxCall(zipCodeChange);
    	var zipDiv = document.getElementById("zip_required");
        zipDiv.innerHTML="<strong>Delivery ZIP code - "+document.zipForm.zipCode.value+"</strong>";
    }
    else {
    	expandFirstOption();
    }
}


function checkZipPP(zip) {

	var lv_pattern = /^\d{5}$|^\d{5}\-?\d{4}$/;
	var passed = lv_pattern.test(zip); 
	if (!passed) {
		alert("Please enter a valid 5-digit ZIP code (example: 60515).");
		return false;
	}
	else {
		return true;
	}
}



function expandFirstOption(){
	if(document.getElementById("step1_details") != null) {
		document.getElementById("step1_details").style.display = '';
		if(document.getElementById("step1_optionType") != null) {
			var optionType = document.getElementById("step1_optionType").innerHTML;
			if(optionType != 'Optional') {
				var parentIds = getParentIds(optionType);
				for(var i = 0; i < parentIds.length; i++) {
					if(document.getElementById("step1_"+parentIds[i]+"_msg1")!= null) {
						document.getElementById("step1_"+parentIds[i]+"_msg1").style.display='none';
						document.getElementById("step1_"+parentIds[i]+"_msg2").style.display='';
						document.getElementById(optionType+"_1_"+parentIds[i]+"_table").style.display='';
					}
				}
			}
			else {
				openStep(2);
			}
			if(optionType == 'Required') {
				openStep(2);
				if(document.getElementById("step2_optionType") != null) {
					if(document.getElementById("step2_optionType").innerHTML == 'Optional') {
						openStep(3);
					}
				} 
					
			}
		}
	}
}


function pOAjaxCall(zipCodeChange) {
	var allParentCatEntryIds = getAllParentIds();
	for(var k = 0; k < allParentCatEntryIds.length; k++){
		mainAjax(allParentCatEntryIds[k],zipCodeChange);
	}
}

function mainAjax(parentCatEntryId,zipCodeChange) {
 	//global var for AJAX request
	var prodOptionZipOpt = {
    	method: 'GET',
  		asynchronous: true,
  		postBody: '',
	 	//Handle successful response
   		onSuccess: function(t) {
    	    var response = t.responseXML.documentElement;
            if ( response ) {
            	var status = response.getElementsByTagName('ZipCode');
                var statusValue = status[0].getElementsByTagName('Status')[0].firstChild.data;
                if ( statusValue == "OK" ) {
                	var e;
                    var eValue;
                    var allFormElements = document.productOptionsDetails.elements;
                    var eCount = allFormElements.length;
                    var selectedPAPriceDiv = document.getElementById("selected_Protection_price_"+parentCatEntryId+"");
                    var paEntries = response.getElementsByTagName('PAPrices');
                    if(document.getElementById("AgreementCount") != null) {
                        var paCount = document.getElementById("AgreementCount").innerHTML;
                    }
					for (var i = 0; i < paEntries.length; i++) {
                        	
                        var paId = paEntries[i].getElementsByTagName('PACatEntryId')[0].childNodes[0].nodeValue;
                        var paPrice = paEntries[i].getElementsByTagName('Price')[0].firstChild.data;
                        var paPriceDivElm = 'po_price_Protection_'+paId+'_'+parentCatEntryId+'';
                        var paPriceDiv = document.getElementById(paPriceDivElm);
                        if(formatCurrency(paPrice) != "0.00") {
							if(paPriceDiv != null) {
								document.getElementById("Protection_"+paCount+"_"+paId+"_"+parentCatEntryId).style.display = '';
                            	paPriceDiv.innerHTML = "$"+formatCurrency(paPrice);
                            	
                            	if (selectedPAPriceDiv.innerHTML.indexOf(paId) > 0 ) {
                                 	 
                                 	 //recalculate subtotal
                                 	 var oldPAPriceStr = parsePriceString(selectedPAPriceDiv.innerHTML);
	                                 var baseTotalStr = document.getElementById("subTotal").innerHTML;
	                                 baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
	                                 baseTotalStr = baseTotalStr.replace(",", "");
	                                 var newTotal = parseFloat(baseTotalStr) + parseFloat(paPrice) - parseFloat(oldPAPriceStr);
	                                 document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
	
	                                 //reset selected PA price
	                                 selectedPAPriceDiv.innerHTML = "<strong>$"+formatCurrency(paPrice)+"</strong><!--poCatId="+paId+"-->";
                                 }
                            }
                        }
                        else  {
                        	if(	document.getElementById("Protection_"+paCount+"_"+paId+"_"+parentCatEntryId) != null) {
                        		document.getElementById("Protection_"+paCount+"_"+paId+"_"+parentCatEntryId).style.display = "none";
                        	}
                        }
                  	}
                        
                    // For Assembly

                    var selectedASPriceDiv = document.getElementById("selected_Assembly_price_"+parentCatEntryId+"");
  
                    var asEntries = response.getElementsByTagName('ASPrices');
                    if(document.getElementById("AssemblyCount") != null) {
                    	var asCount = document.getElementById("AssemblyCount").innerHTML;
                    }
                    for (var i = 0; i < asEntries.length; i++) {
                    	
                        var asId = asEntries[i].getElementsByTagName('ASCatEntryId')[0].childNodes[0].nodeValue;
                        var asPrice = asEntries[i].getElementsByTagName('Price')[0].firstChild.data;
                        var asPriceDivElm = 'po_price_Assembly_'+asId+'_'+parentCatEntryId+'';
                        var asPriceDiv = document.getElementById(asPriceDivElm);
                        
                        if(formatCurrency(asPrice) != "0.00") {
							if(asPriceDiv != null) {
								document.getElementById("Assembly_"+asCount+"_"+asId+"_"+parentCatEntryId).style.display = '';
	                        	asPriceDiv.innerHTML = "$"+formatCurrency(asPrice);
	                    		if (selectedASPriceDiv.innerHTML.indexOf(asId) > 0 ) {
	                                 //recalculate subtotal
	                                 
	                                 var oldASPriceStr = parsePriceString(selectedASPriceDiv.innerHTML);
	                                 var baseTotalStr = document.getElementById("subTotal").innerHTML;
	                                 baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
	                                 baseTotalStr = baseTotalStr.replace(",", "");
	                                 var newTotal = parseFloat(baseTotalStr) + parseFloat(asPrice) - parseFloat(oldASPriceStr);
	                                 document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
	
	                                 //reset selected AS price
	                                 selectedASPriceDiv.innerHTML = "<strong>$"+formatCurrency(asPrice)+"</strong><!--poCatId="+asId+"-->";
                                 }
                    		}
                        }
                        else  {
	                        if(	document.getElementById("Assembly_"+asCount+"_"+asId+"_"+parentCatEntryId) != null) {
    	                    	document.getElementById("Assembly_"+asCount+"_"+asId+"_"+parentCatEntryId).style.display = "none";
                       		}
                        	
                        }
        	                          
                    }
                    
                    // For Installation

        			var selectedINPriceDiv = document.getElementById("selected_Installation_price_"+parentCatEntryId+"");
                    var inEntries = response.getElementsByTagName('INPrices');

                    if(document.getElementById("InstallationCount") != null) {
                    	var inCount = document.getElementById("InstallationCount").innerHTML;
                    }
                    
                    for (var i = 0; i < inEntries.length; i++) {
                        var inId = inEntries[i].getElementsByTagName('INCatEntryId')[0].childNodes[0].nodeValue;
                        var inPrice = inEntries[i].getElementsByTagName('Price')[0].firstChild.data;
                        var inPriceDivElm = 'po_price_Installation_'+inId+'_'+parentCatEntryId+'';
                        var inPriceDiv = document.getElementById(inPriceDivElm);
                        if(formatCurrency(inPrice) != "0.00") {
							if(inPriceDiv != null) {
								document.getElementById("Installation_"+inCount+"_"+inId+"_"+parentCatEntryId).style.display = '';														
                        		inPriceDiv.innerHTML = "$"+formatCurrency(inPrice);
                        		if (selectedINPriceDiv.innerHTML.indexOf(inId) > 0 ) {
                             		//recalculate subtotal
                             		var oldINPriceStr = parsePriceString(selectedINPriceDiv.innerHTML);
                                   	var baseTotalStr = document.getElementById("subTotal").innerHTML;
                                	baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
	                                baseTotalStr = baseTotalStr.replace(",", "");
	                                var newTotal = parseFloat(baseTotalStr) + parseFloat(inPrice) - parseFloat(oldINPriceStr);
	                                document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
    	        	                //reset selected AS price
        		                    selectedINPriceDiv.innerHTML = "<strong>$"+formatCurrency(inPrice)+"</strong><!--poCatId="+inId+"-->";
                    	         }
                        	}
                        }
                        else  {
                            if(	document.getElementById("Installation_"+inCount+"_"+inId+"_"+parentCatEntryId) != null) {
                        		document.getElementById("Installation_"+inCount+"_"+inId+"_"+parentCatEntryId).style.display = "none";
                    		}
                        }
                 
                   }
                  

                   // For Connection
                    
                   var selectedCNPriceDiv = document.getElementById("selected_Connection_price_"+parentCatEntryId);
                   var cnEntries = response.getElementsByTagName('CNPrices');
                   if(document.getElementById("ConnectionCount") != null) {
                   		var cnCount = document.getElementById("ConnectionCount").innerHTML;
                   }
                    
                   for (var j = 0; j < cnEntries.length; j++) {
                    	
                        var cnId = cnEntries[j].getElementsByTagName('CNCatEntryId')[0].childNodes[0].nodeValue;
                        var cnPrice = cnEntries[j].getElementsByTagName('Price')[0].firstChild.data;
                        var cnPriceDiv = document.getElementById("po_price_Connection_"+cnId+"_"+parentCatEntryId);
                    	if(formatCurrency(cnPrice) != "0.00") {
                    		if(cnPriceDiv != null) {
								document.getElementById("Connection_"+cnCount+"_"+cnId+"_"+parentCatEntryId).style.display = '';														                            	
                    			cnPriceDiv.innerHTML = "$"+formatCurrency(cnPrice);
                    			if ( selectedCNPriceDiv.innerHTML.indexOf(cnId) > 0 ) {
	                                 //recalculate subtotal
	                                 var oldCNPriceStr = parsePriceString(selectedCNPriceDiv.innerHTML);
	                                 
	                                 var baseTotalStr = document.getElementById("subTotal").innerHTML;
	                                 baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
	                                 baseTotalStr = baseTotalStr.replace(",", "");
	                                 var newTotal = parseFloat(baseTotalStr) + parseFloat(cnPrice) - parseFloat(oldCNPriceStr);
	                                 document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
	                                 //reset selected CN price
	                                 selectedCNPriceDiv.innerHTML = "<strong>$"+formatCurrency(cnPrice)+"</strong><!--poCatId="+cnId+"-->";
	                            }
                   			}
                    		
                    	}
                    	else  {
                    		
                            if(document.getElementById("Connection_"+cnCount+"_"+cnId+"_"+parentCatEntryId) != null) {
                    	   		document.getElementById("Connection_"+cnCount+"_"+cnId+"_"+parentCatEntryId).style.display = "none";
                    		}
                    	}
                    
                    }
                        
	                openStep(1,zipCodeChange);
                } 
                else {
                    // display error message
                    showBox('errorBox');
                    var err1 = document.getElementById("error1");
                    if (status == "INVALID") {
                        err1.innerHTML="Invalid Zip Code. Please enter a valid zip code to continue.";
                    } else {
                        err1.innerHTML="Processing Error. Please try with a valid zip code later.";
                    }
                }
            }
        
        	
   		},
        // Handle other errors
    	onFailure: function(t) {
        	showBox('errorBox');
        	var err1 = document.getElementById("error1");
        	err1.innerHTML="Error processing your request, please try again later.";
    	}
	};  // end of global var prodOptionZipOpt


	var catalogId = document.getElementById("catalogId").innerHTML;
	var storeId = document.getElementById("storeId").innerHTML;
	
    var url = "GetProductOptionPrices?storeId="+storeId+"&catalogId="+catalogId+"&zipCode="+document.zipForm.zipCode.value+"&parentCatId="+parentCatEntryId+"&origin=productPage";
   	new searsAjax(url, prodOptionZipOpt);
}

/*Following Methods are moved to store specific global.js - JS code cleanup
searsAjax( url, opt)
processReqChange()
*/

function parsePriceString(prcStr) {
     prcStr = prcStr.toLowerCase();
     var ret = prcStr.replace("<strong>$","");
     ret = ret.substring(0, ret.indexOf("</strong>"));
     return ret;
}



function getZipFromCookie() {
 	return(getValueFromCookie("StoreZipCode"));
}

function getValueFromCookie(v)
{
 	
 	var value = "";
 	var cookies = document.cookie;
 	
 	if(cookies != null && cookies.length > 0) {
 		var cookieName = v + "=";
    	var begin = cookies.indexOf(";"+v);
  		if (begin == -1) {
    		begin = cookies.indexOf(v);
   			if (begin != 0) return null;
  		} else
    		begin += 2;
    	var end = document.cookie.indexOf(";", begin);
  		if (end == -1)
    		end = cookies.length;
    	value = unescape(cookies.substring(begin + cookieName.length, end));
  	}
 	return(value);
}

function recalculateSubtotal(id,task) {
    
    var itemsInCart = 0;
    itemsInCart = document.getElementById("itemsInCart").innerHTML;
    var tempTotal = subTotal;
    var newTotal = subTotal;
    var id= id;
    var itemCount = 0;
    var optionType = id.split('_')[0];
   
    var selectedPriceDiv = "";
    var optPriceDiv = "";
    var itemQty = "";
    var itemQtyDiv = "";
    var addToTotal = 0.00;
    var selectedOptPrice = 0.00;
   
    if ( optionType != "" && optionType != "Required" && optionType != "Deluxe" && optionType != "Optional") {  
    	
    	// skip Required Accessories & Setups
    	var parentID = id.split('_')[3];
    	var selectedPrice = "selected_"+optionType+"_price_"+parentID ;
        var poid = getPidFromSelectedPriceHtml(optionType, parentID);
        
       	
        if ( poid != "0" ) {
            optPriceDiv = "po_price_"+optionType+"_"+poid+"_"+parentID;
        	
            selectedOptPrice = getPrice(document.getElementById(optPriceDiv).innerHTML);
           
            var count = document.getElementById(parentID).innerHTML;
            itemQtyDiv = "qty_"+count;
            itemQty = document.getElementById(itemQtyDiv).innerHTML;
            if(task == "add"){
            	addToTotal += (parseFloat(selectedOptPrice)*itemQty);
            }
	        if(task == "subtract"){
	            newTotal -= (parseFloat(selectedOptPrice)*itemQty);
	        }
	    }
    }
    
	if( optionType == "Required"){
		
		var stepNum = id.split('_')[1];
		var reqItemID = id.split('_')[2];
		var parentID = id.split('_')[3];
		
    	optPriceDiv = "po_price_" + optionType + "_" +reqItemID+"_"+parentID;
    	selectedOptPrice = getPrice(document.getElementById(optPriceDiv).innerHTML);
    	var count = document.getElementById(parentID).innerHTML;
        itemQtyDiv = "qty_"+count;
    	itemQty = document.getElementById(itemQtyDiv).innerHTML;
    	
    	if(task == "add"){
    		itemsInCart = parseInt(itemQty) + parseInt(itemsInCart) ;
           	addToTotal += (parseFloat(selectedOptPrice)*itemQty);
        }
        if(task == "subtract"){
        	itemsInCart = itemsInCart  - parseInt(itemQty);
	        newTotal -= (parseFloat(selectedOptPrice)*itemQty);
	    }
	}
	
	if( optionType == "Optional"){
		
		var optionalItemID = id.split('_')[2];
		var parentID = id.split('_')[3];
		optPriceDiv = "po_price_" + optionType + "_" +optionalItemID+"_"+parentID;
   		selectedOptPrice = getPrice(document.getElementById(optPriceDiv).innerHTML);
   		if(task == "add"){
   			itemsInCart = parseInt(itemsInCart) + 1;
           	addToTotal += parseFloat(selectedOptPrice);
        }
        if(task == "subtract"){
           	itemsInCart = itemsInCart  - 1;
	        newTotal -= parseFloat(selectedOptPrice);
	        
        }
	   
	}
    document.getElementById("itemsInCart").innerHTML = itemsInCart + "";
    newTotal += addToTotal;
    subTotal = newTotal;
    document.getElementById("subTotal").innerHTML = "$"+formatCurrency(newTotal);
}

function getPidFromSelectedPriceHtml(optionType, parCatEntryId){
   return document.getElementById("selected_"+optionType+"_"+parCatEntryId+"_CatEntryId").innerHTML;
}




function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return (num + '.' + cents);
}


function setShowZipForm(pAFlag,iNFlag,aSFlag,cNFlag){
	
	if(pAFlag == true || iNFlag == true || aSFlag == true || cNFlag == true){	
		return true;
	}
	else 
		return false;
}

function getPrice(priceElm) {
     priceElm = priceElm.toLowerCase();
     price = priceElm.replace("$","");
     price = price.replace("<strong>","");
     price = price.replace("</strong>","");
     return price;
}
/*
function updateSubTotal(id) {
	
	var parentId = id.split('_')[3];
	var poCatId = id.split('_')[2];
	var optionType = id.split('_')[0];
	var selectedPrice = "selected_"+optionType+"_price_"+parentId ;
    var poId = getPidFromSelectedPriceHtml(optionType, parentId);
    
    if(poId != poCatId){
    	var oldPAPriceStr = getPrice(document.getElementById(selectedPrice).innerHTML);
    	var baseTotalStr = document.getElementById("subTotal").innerHTML;
        baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
        baseTotalStr = baseTotalStr.replace(",", "");
        var newTotal = parseFloat(baseTotalStr) - parseFloat(oldPAPriceStr);
        document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
        return true;
    }
    else{
    	return false;
    }
	
}
function updateSubTotal(id) {
	
	var parentId = id.split('_')[3];
	var poCatId = id.split('_')[2];
	var optionType = id.split('_')[0];
	var selectedPrice = "selected_"+optionType+"_price_"+parentId ;
    var poId = getPidFromSelectedPriceHtml(optionType, parentId);
    
    if(poId != poCatId) {
    	var oldPAPriceStr = getPrice(document.getElementById(selectedPrice).innerHTML);
    	var baseTotalStr = document.getElementById("subTotal").innerHTML;
        baseTotalStr = baseTotalStr.substring(1, baseTotalStr.length);
        baseTotalStr = baseTotalStr.replace(",", "");
        var newTotal = parseFloat(baseTotalStr) - parseFloat(oldPAPriceStr);
        document.getElementById("subTotal").innerHTML="$"+formatCurrency(newTotal);
        return true;
    }
    else {
    	return false;
    }
	
}*/

function createShopCartUrl(){
	
	var e;
    var eValue ="";
    var allFormElements = document.productOptionsDetails.elements;
    var eCount = allFormElements.length;
    var parOrderItemId = "";
    var questionScimCode = "";
    var poCatEntryId = "";
    var poItemType = "";
    var delOrderItemId = "";
    var quantity = "";
    var count1 = 0;
    var count2 = 0;
    
    for (var m = 0; m < eCount; m++) {
    	e = allFormElements[m];
        if ((e.type == 'radio') || (e.type == "checkbox")) {
        	if( e.checked == true){
        		eValue = e.value;
        		idOfPO = e.id;
        		var optionType = idOfPO.split('_')[0];
        		var parCatEntryId = idOfPO.split('_')[3];
        	
        		if(optionType == "Deluxe" ){
        			var tempScimCode = idOfPO.split('_')[2];
        			if(tempScimCode != "-1"){
	        			var count = document.getElementById(parCatEntryId).innerHTML; 
	        			orderItemIdElm = "orderItemId_"+count;
    	    			var dindex1 = eValue.indexOf("&QuestionScimCode=");
    	    			if(count1 == 0) {
	        				delOrderItemId = document.getElementById(orderItemIdElm).innerHTML;
    	    				questionScimCode = eValue.substring(eValue.indexOf("&QuestionScimCode=")+18,eValue.length);
        				}
        				else {
        					delOrderItemId = delOrderItemId+","+document.getElementById(orderItemIdElm).innerHTML;
    	    				
        					questionScimCode = questionScimCode+","+eValue.substring(eValue.indexOf("&QuestionScimCode=")+18,eValue.length);
        				}
        				count1++;
           			}
           		}
           		if(optionType != "Deluxe") {
           			 var tempCatEntryId = idOfPO.split('_')[2];   
           			 if(tempCatEntryId != "no") {
           			 	var qtyElm = "";
           			 	if( parCatEntryId != "no") {
        		      		var count = document.getElementById(parCatEntryId).innerHTML;           	
            	           	orderItemIdElm = "orderItemId_"+count;
            	       		qtyElm = "qty_"+count;
            			}
            			var index1 = eValue.indexOf("CatentryId=");
            			var index2 = eValue.indexOf("&ItemType=");
            		    
            			if(count2 == 0) {
            				if(parCatEntryId != "no") {
            					parOrderItemId = document.getElementById(orderItemIdElm).innerHTML;
            					quantity = document.getElementById(qtyElm).innerHTML;
            				}
            				else {
            					parOrderItemId = "NA";
            					quantity = 1.0;
            				}
            				poCatEntryId = eValue.substring(index1+11,index2);
            				poItemType = eValue.substring(index2+10,eValue.length);
            				
            			}
	            		else {
            				if(parCatEntryId != "no") {
            					parOrderItemId = parOrderItemId+","+document.getElementById(orderItemIdElm).innerHTML;
            					quantity = quantity+","+document.getElementById(qtyElm).innerHTML;
            				}
            				else {
	            				parOrderItemId = parOrderItemId+",NA";
	            				quantity = quantity+",1.0";
            				}
            				poCatEntryId = poCatEntryId+","+eValue.substring(index1+11,index2);
            				poItemType = poItemType+","+eValue.substring(index2+10,eValue.length);
            			}
            			count2++;
            		}
            	}
           	}
        }
    }
    document.productOptionsDetails.delOrderItemId.value=delOrderItemId;
 	document.productOptionsDetails.questionScimCode.value=questionScimCode;
	document.productOptionsDetails.poCatEntryId.value=poCatEntryId;
 	document.productOptionsDetails.poOrderItemId.value=parOrderItemId;
    document.productOptionsDetails.poLineItemType.value=poItemType;
  	document.productOptionsDetails.poQuantity.value= quantity;
    document.productOptionsDetails.orderItemIds.value = getAllParentOrderItemIds();
    document.productOptionsDetails.zipCode.value= document.zipForm.zipCode.value;
}

function updatePrices(source) {
	
	var continueFlag = document.productOptionsDetails.allOptSelected.value;
	if(continueFlag == "true" || source == 'deals'){
		if(source == 'deals' && document.productOptionsDetails.optionCount.value == 0) {
			var url = document.productOptionsDetails.url.value;
			window.location = url;
			return;
		}
		createShopCartUrl();
		if(document.productOptionsDetails.addCartFlag.value == 'false'){
			document.productOptionsDetails.submit();
			document.productOptionsDetails.addCartFlag.value= 'true';
		}
		
	}
	
}

function setPrice(optionType,poCatEntryId,parCatEntryId,price) {
	var priceElm = "po_price_"+optionType+"_"+poCatEntryId+"_"+parCatEntryId;
	document.getElementById(priceElm).innerHTML = "$"+formatCurrency(price);
}

function createGiftURL(){

	document.productOptionsForm.URL.value='OrderItemDisplay';
	document.productOptionsForm.to.value=document.getElementById("item_to").value;
	document.productOptionsForm.from.value=document.getElementById("item_from").value;
	if(document.getElementById("item_msg").value == 'Up to 110 characters') {
		document.getElementById("item_msg").value = '';
	}
	document.productOptionsForm.message.value=document.getElementById("item_msg").value;

}

function setSubTotal() {
	subTotal = parseFloat(document.getElementById("totalPrice").innerHTML);
}

function convertBadCharacters(name,id,type) {
	if(typeof(type) != "undefined" && type == 'Display' ) {
		name = name.replace(/%3B/g,";");
		name = name.replace(/%26/g,"&");
		name = name.replace(/%23/g,"#");
		name = name.replace(/%21/g,"!");
		name = name.replace(/%24/g,"$");
		name = name.replace(/%28/g,"(");
		name = name.replace(/%29/g,")");
		name = name.replace(/%2C/g,",");
		name = name.replace(/%2F/g,"/");
		name = name.replace(/%3A/g,":");
		name = name.replace(/%3C/g,"<");
		name = name.replace(/%3D/g,"=");
		name = name.replace(/%3E/g,">");
		name = name.replace(/%3F/g,"?");
		name = name.replace(/%5B/g,"[");
		name = name.replace(/%5C/g,"\\");
		name = name.replace(/%5D/g,"]");
		name = name.replace(/%5E/g,"^");
		name = name.replace(/%60/g,"`");
		name = name.replace(/%7B/g,"{");
		name = name.replace(/%7D/g,"}");
	}
	if(typeof(type) != "undefined" && type == 'Display' ) {
		for(var i=0; i < name.length; i++) {
			name = name.replace("+"," ");
		}
	}
	if(id != 'none') {
		document.getElementById(id).innerHTML = name;
	}	
	return name;
}

function validation(text){
	if(text.length == 0){
		return false;
	}
	else {
		var StrRE1 = /^[a-zA-Z\s]+$/;
		var passed = StrRE1.test(text);
		if (!passed) {
			return false;
		}
		else {
			return true;
		}
	}
}   


function setUrl(storeId, catalogId, value) {

	if(value != 'noChange') {
		var url = getFinalUrl(storeId, catalogId,value);
		document.productOptionsDetails.vName.value="";
		document.productOptionsDetails.sName.value="";
		document.productOptionsDetails.cName.value="";
		document.productOptionsDetails.url.value=url;
		updatePrices('options');
	}
}  

function continueShopping(value) {
	if(value != 'noChange') {
		document.productOptionsForm.url.value=value;
		nextStep(document.getElementById("shoppingButton"),2,'giftCard');
	}

	
}


function setUrlFromSC(storeId, catalogId, value) {
	if(value != 'noChange') {
		
		var url = getFinalUrl(storeId, catalogId, value);	
		window.location = url
	}
}  

function getFinalUrl(storeId, catalogId, value) {
	var catNames = value.split('||');
	var sName='';
	var cName='';
	var vName='';
	if(value != '') {
		if(catNames.length == 3) {
			sName = convertBadCharacters(catNames[2],'none','URL');
	   		cName = convertBadCharacters(catNames[1],'none','URL');
	  	    vName = convertBadCharacters(catNames[0],'none','URL');
	  	    url = "s_"+storeId+"_"+catalogId+"_"+vName+"_"+cName+"_"+sName;
	  	}
		if(catNames.length == 2) {
			cName = convertBadCharacters(catNames[1],'none','URL');
	  	    vName = convertBadCharacters(catNames[0],'none','URL');
	  	    url = "c_"+storeId+"_"+catalogId+"_"+vName+"_"+cName;
		}
		if(catNames.length == 1) {
			vName = convertBadCharacters(catNames[0],'none','URL');
	  	    url = "v_"+storeId+"_"+catalogId+"_"+vName;

		}
	}
	if(value == '') {
		url= "home_"+storeId+"_"+catalogId;
	}
	return url;
}

function setDealUrl(url) {
	document.productOptionsDetails.vName.value="";
	document.productOptionsDetails.sName.value="";
	document.productOptionsDetails.cName.value="";
	document.productOptionsDetails.url.value=url;
	document.productOptionsDetails.dealsFlag.value="YES";
	updatePrices('deals');
}

//CODE FOR PRODUCT OPTION AND SHOPPING CART ENDS

//CODE FOR PRODUCT PAGES STARTS 

// function called from optionstabContent.jsp when the zipcode is alrey there in cookie
function zipChangedProductPageWithZip() 
{	
	var zipCode="";
    	var len;
    	zipCode=document.zipForm.zipCode.value;
      
	//Sets a session cookie for zip code
	setCookie('zipCode'+storeId,zipCode);
	
   	// Ajax Call
	pOAjaxCallProductPage(zipCode);
	
}



// function called from optionstabContent.jsp on click of Go button in product pages
function zipChangedProductPage(objImg) 
{
	var zipCode="";
    var len;
    zipCode=document.zipForm.zipCode.value;
    
    if ( checkZipProductPage(zipCode,objImg) ) 
    {
	    //Sets a session cookie for zip code
	    setCookie('zipCode'+storeId,zipCode);
	    
		// Ajax Call
	    pOAjaxCallProductPage(zipCode);
    }
}

function fnLoadProductOption(){
	var zipCode = getCookie('zipCode'+storeId);
	if ((zipCode != '') && (zipCode != null) && (zipCode != "undefined")){
		// Ajax Call
		pOAjaxCallProductPage(zipCode);
		document.getElementById('zipFormWithZip').style.display='block';
		document.getElementById('zipForm').style.display='none';
	}
}

// function called from optionstabContent.jsp on click of Go button in product pages when zip is prepopulated
function zipChangedProductPageWithZipCode(objImg) 
{  	
	var zipCode="";
    	var len;
    	zipCode=document.zipFormWithZip.zipCode.value;
    
    if ( checkZipProductPage(zipCode,objImg) ) 
    {
	    //Sets a session cookie for zip code
	    setCookie('zipCode'+storeId,zipCode);
	    
		// Ajax Call
	    pOAjaxCallProductPage(zipCode);
    }
}


// function to validate the zipcode
function checkZipProductPage(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;
	}
}

// Calling Ajax call to get the values for protection agreement / connections ans installations
function pOAjaxCallProductPage(zipCodeFinal) 
{
	if(document.getElementById("catent")){		
	var parentCatEntryId = document.getElementById("catent").innerHTML;
	}
	if(document.getElementById('zippe')){
	document.getElementById('zippe').innerHTML=zipCodeFinal;
	}
	var prodOptionZipOpt = {
    method: 'GET',
  	asynchronous: true,
  	postBody: '',
 	//Handle successful response
   	onSuccess: function(t) {
	        	
	var response;
	if(browser == 'Netscape Navigator'){
		var parser = new DOMParser();
	 	response = parser.parseFromString(t.responseText,"text/xml");
	 }else{
	 	response = t.responseXML.documentElement;
	 }
	
	if ( response ) 
	{
		var tempForm = document.zipForm;
		if(tempForm)
		{ 	
			var protectionAgreement = document.getElementById('zipForm').pa.value;
			var installations = document.getElementById('zipForm').io.value;
			var connection = document.getElementById('zipForm').cn.value;
		}
		else
		{	
			if(document.zipFormWithZip){
			
				var protectionAgreement = document.getElementById('zipFormWithZip').pa.value;
				var installations = document.getElementById('zipFormWithZip').io.value;
				var connection = document.getElementById('zipFormWithZip').cn.value;
			}

		}

		
		var status = response.getElementsByTagName('ZipCode');
		var statusValue = status[0].getElementsByTagName('Status')[0].firstChild.data;
		
		if ( statusValue == "OK" ) 
		{
	        	
			//PROTECTION AGREEMENTS
			if(protectionAgreement == "true")
			{
				var paEntries = response.getElementsByTagName('PAPrices');
				if(paEntries != null)
				{
		   			for (var i = 0; i < paEntries.length; i++) 
		   			{
			       		var paId = paEntries[i].getElementsByTagName('PACatEntryId')[0].childNodes[0].nodeValue;
			        	var paPrice = paEntries[i].getElementsByTagName('Price')[0].firstChild.data;
			     		document.getElementById("price_"+paId).innerHTML = formatCurrencyA(paPrice); 
			     		document.getElementById("catent_1_"+paId).style.display = "none"; 
			     		document.getElementById("catent_2_"+paId).style.display = "block"; 
					}
		     	}
			}
		
		
			//INSTALLATIONS
			var inFlag = 0;
	        var inEntries = response.getElementsByTagName('INPrices');
	        for (var j = 0; j < inEntries.length; j++) 
	        {
	        	if(j ==0) 
	        	{

		        	var inId = inEntries[j].getElementsByTagName('INCatEntryId')[0].childNodes[0].nodeValue;
	                var inPrice = inEntries[j].getElementsByTagName('Price')[0].firstChild.data;
	                
	                if(formatCurrency(inPrice) != "0.00") 
	                {
	                	inFlag = 1;
	               		if(document.getElementById("Installation_"+inId) != null) 
	               		{
	                    	document.getElementById("NoInstallation").style.display = "none";
	              			document.getElementById("Installation_"+inId).style.display = "inline";
	                  	  	document.getElementById("price_"+inId).innerHTML = formatCurrencyA(inPrice);
					  	}
					}
					else 
					{
						if(document.getElementById("Installation_"+inId) != null) 
						{
					  		document.getElementById("Installation_"+inId).style.display = "none";
					 	}
					}	  
				}
	     	}
	        
	        if(installations == "true")
	        {
	        	if(document.getElementById("protectthree")){
				document.getElementById("protectthree").style.display = "none";
				}
				if(document.getElementById("protectfour")){
				document.getElementById("protectfour").style.display = "block";
				}
				if(inFlag == 0) 
				{
					if(document.getElementById("NoInstallation")){
					document.getElementById("NoInstallation").style.display = "block";
				}
			} 
			} 
					    
         	//	CONNECTIONS
         	var cnEntries = response.getElementsByTagName('CNPrices');
      
            for (var j = 0; j < cnEntries.length; j++) 
            {
	        	var cnId = cnEntries[j].getElementsByTagName('CNCatEntryId')[0].childNodes[0].nodeValue;
                var cnPrice = cnEntries[j].getElementsByTagName('Price')[0].firstChild.data;
                if(formatCurrency(cnPrice) != "0.00") 
                {
                	document.getElementById("Connection_"+cnId).style.display = "block";
                  	document.getElementById("price_"+cnId).innerHTML = formatCurrencyA(cnPrice);
				}
				else
				{
					if(document.getElementById("Connection_"+cnId) != null) 
					{
				  		document.getElementById("Connection_"+cnId).style.display = "none";
				  	}
				}	                
			}
			if(connection == "true")
        	{
        		if(document.getElementById("protectfive")){
				document.getElementById("protectfive").style.display = "none";
				}
				if(document.getElementById("protectsix")){
				document.getElementById("protectsix").style.display = "block";
				}
				if(document.getElementById("protectseven")){
				document.getElementById("protectseven").style.display = "block";
				}
			}
			if(document.getElementById('tab3') != undefined){
			
			document.getElementById('tab3').style.display="block";
			}
  	}
	    }
    },
        // Handle other errors
	    onFailure: function(t) {
        showBox('errorBox');
        var err1 = document.getElementById("error1");
        err1.innerHTML="Error processing your request, please try again later.";
    	}
	};  // end of global var prodOptionZipOpt
	if(document.getElementById("ajaxStoreIdProductPage")){
	var storeId = document.getElementById("ajaxStoreIdProductPage").innerHTML;
	}
	if(document.getElementById("ajaxCatalogIdProductPage")){	
	var catalogId = document.getElementById("ajaxCatalogIdProductPage").innerHTML;
	}
    	//var url = "GetProductOptionPrices?storeId="+storeId+"&catalogId="+catalogId+"&zipCode="+document.zipForm.zipCode.value+"&parentCatId="+parentCatEntryId;
    	var url = "GetProductOptionPrices?storeId="+storeId+"&catalogId="+catalogId+"&zipCode="+zipCodeFinal+"&parentCatId="+parentCatEntryId+"&origin=productPage";
    	new searsAjax(url, prodOptionZipOpt);
	
}


function formatCurrencyA(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return ('$ ' + num + '.' + cents);
}

// CODE FOR PRODUCT PAGES ENDS HERE



function searsAjaxProductPage( url, opt) 
{ 
	try {
	     netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	   } catch (e) {
	     
	   }

 	var req = null; 
 	var onSuccess = opt.onSuccess;
 	var onFailure = opt.onFailure;

 	if (window.XMLHttpRequest) 
 	{
       		req = new XMLHttpRequest();
        	if (req)
        	{
        		
             		req.onreadystatechange = processReqChange;
             		req.open(opt.method, url, opt.asynchronous);
             		req.send(null);
		}
      
 	}
 	else if (window.ActiveXObject) 
 	{
       		req = new ActiveXObject("Microsoft.XMLHTTP");
       		if (req) 
        	{
			
       	  		req.onreadystatechange = processReqChange;
            		req.open(opt.method, url, opt.asynchronous);
            		req.send();
        	}
 	} 

	if (!req) return;


	function processReqChange() {
    		if (req.readyState == 4) {
        		if (req.status == 200) {
				
            	 		onSuccess(req);
        		} 
        		else {
			
				onFailure(req);
        		}
    		}
 	};
}
// GIFT CARD TEXTAREA CHARACTER COUNTDOWN
function countdown(thisValue,count){
	var count = document.getElementById('count'+count);
	var startNum = 120;
	var textAreaValue = thisValue.value.length;
	count.innerHTML = startNum - textAreaValue;
	if (textAreaValue > 120){
		alert('You have reached the 120 character maximum');
		thisValue.value = thisValue.value.substring(0, startNum);
		count.innerHTML = 0;
	}
}


	function clearValue(count){
									
		document.getElementById('tofield_'+count).value = retObj('hidtofield_'+count).value;
		document.getElementById('fromfield_'+count).value = retObj('hidfromfield_'+count).value;
		document.getElementById('message_'+count).value = retObj('hidmessage_'+count).value;
		if(document.getElementById('email_'+count)){
			document.getElementById('recipient_'+count).value = retObj('email_'+count).value;
			document.getElementById('confirm_'+count).value = retObj('email_'+count).value;
		}
				
	}
	
	function updateValue(count){
	

		var tofield = retObj('tofield_'+count).value;
		var fromfield = document.getElementById('fromfield_'+count).value;
		var message = document.getElementById('message_'+count).value;
		
		if(validateForm(count)){
			
			document.UpdateGiftCard.orderitemid.value=retObj('orderfield_'+count).value;
			document.UpdateGiftCard.tofield.value = document.getElementById('tofield_'+count).value;
			document.UpdateGiftCard.fromfield.value = document.getElementById('fromfield_'+count).value;
			document.UpdateGiftCard.messagefield.value = document.getElementById('message_'+count).value;
			if(document.getElementById('email_'+count)){
				document.UpdateGiftCard.recipient.value = document.getElementById('recipient_'+count).value;
				document.UpdateGiftCard.isVGC.value = 1;
			}
			document.forms['UpdateGiftCard'].submit();
		}
	}
	
	
	function retObj(divId){
		return document.getElementById(divId);
	}
	
	
	function validateForm(count){
		if(document.getElementById('email_'+count)){
			if (document.getElementById('recipient_'+count).value == null || document.getElementById('recipient_'+count).value == ""){
				alert('Please enter a Recipients Email ID');
				document.getElementById('recipient_'+count).select();
				document.getElementById('recipient_'+count).focus();
				return false;
			}
			if (document.getElementById('confirm_'+count).value == null || document.getElementById('confirm_'+count).value == ""){
				alert('Please enter a confirm Email ID');
				document.getElementById('confirm_'+count).select();
				document.getElementById('confirm_'+count).focus();
				return false;
			}
			
			if(!validateEmailAddr(document.getElementById('recipient_'+count).value)){
		   		alert("The e-mail address you entered appears incorrect. (Example of a correct address: sears@sears.com.) Please check your information and try again.");
		   		document.getElementById('recipient_'+count).select();
				document.getElementById('recipient_'+count).focus();
				return false;
			}
			if (document.getElementById('recipient_'+count).value != document.getElementById('confirm_'+count).value){
				alert('The recipient email id and confirm email id should be same.');
				return false;
			}
			
			
		}
	 	return true;
	}
	
	function nameValidation(name){
		
			if(!((name.charCodeAt(0)>64 && name.charCodeAt(0)<91)||(name.charCodeAt(0)>96 && name.charCodeAt(0)<123))){
				return 0;
			}
			for(iLoop=1;iLoop<name.length;iLoop++){
				if(!((name.charCodeAt(iLoop)>64 && name.charCodeAt(iLoop)<91)||(name.charCodeAt(iLoop)>96 && name.charCodeAt(iLoop)<123)||(name.charCodeAt(iLoop)>48 && name.charCodeAt(iLoop)<58)||(name.charCodeAt(iLoop)==32)||(name.charCodeAt(iLoop)==39)||(name.charCodeAt(iLoop)==45)||(name.charCodeAt(iLoop)==46))){
				return 0;
				}
	       } 
	        if(iLoop == name.length){
				return 1;
		   }
	  }
	 
	 
	 function validateEmailAddr(email){
		    var regex1 = /^[^\s@]+@([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]\.|[A-Za-z0-9]\.)+([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]|[A-Za-z0-9])$/;
		    var regex2 = /^(root@|abuse@|spam@)/;
		    if(!email.match(regex1)){
		   //   alert("The e-mail address you entered appears incorrect. (Example of a correct address: sears@sears.com.) Please check your information and try again.");
			    return false;
		    } else if(email.match(regex2)){
		        alert(email + " is not allowed");
		        return false;
		    }
		    return true;
		}   
	
// CODE FOR PRODUCT PAGES ENDS HERE

