var html = '';
var price = 0;
var content = '';
prevcity ="";
prevzipcode = "";
prevstate ="";
prevcounty="";
var state="";
var install_price = 0;
var base_install_price = 0;
var ua='va';
var processTaxwareResponse = false;
var solnSelling="";
var storeId = $('input#storeId').attr('value');
var itemPartnumber = $('input#itemPartnumber').attr('value');
var parentCatentryId=$('input#catentryProduct').attr('value');
var itemId = $('input#itemId').attr('value');

$(document).ready(function(){
	
	// to display the first option in detail
	var onLoadURL =  $('input#onLoadURL').attr('value');
	var callBackId =  $('input#callBackId').attr('value');
	if(typeof onLoadURL != 'undefined' && onLoadURL!=""){
		ajaxCall(onLoadURL,'productOptions',null,callBackId);
	}
	
	original_price = parseFloat($('#base_price').text());
	price = parseFloat($('#base_price').text());
	addOptions('');
	
	//scroll the jumpLinks
	$('#jumpLinks a').livequery('click', function() {
 		if (location.pathname.replace('/^//,') == this.pathname.replace('/^//,') && location.hostname == this.hostname) {
   		var $target = $(this.hash);
   		$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
   		if ($target.length) {
	  		var targetOffset = $target.offset().top;
  			$('html,body').animate({scrollTop: targetOffset}, 1000);
    		return false;
   		}  
   	}
  });
	
	//handle the Sears Recommended message
	$('.recommended').livequery('click', function(){
		$('.whyRec').hide();
		$(this).next().fadeIn();
	});
	$('.whyRec').livequery('click', function(){
		$('.whyRec').fadeOut();
	});
	
		//handle the no thanks options
		$('.nothanks').livequery('click', function(){
			$(this).parent().parent().find('input').not('.nothanks, #limitedMfr').removeAttr('checked');
		});
	
	//add options to the sim cart
	

	$('.product_option input').livequery('click', function(){
	//.not('.ao, #btnSubmitAddress')
	//$('.product_option.po input').not('#install_address').livequery('click', function(){
		
		if($(this).attr('id') == 'btnSubmitAddress' || $(this).attr('class') == 'ao') return;
		
		html = '';
		//alert('hello 1');
		content = $(this).next().text();
		if($(this).hasClass('addChk')){
			content = $(this).parent().prev().prev().text();
		}
		$('.added_options .option, .accTitle').remove();
		var title_added = false;
		
		//uncheck any nothanks options in the same container
		if(!($(this).hasClass('nothanks'))){
			$(this).parent().parent().find('input.nothanks').removeAttr('checked');
		}
		
		//added for omniture tracking
		var selectedItem = $(this).parent().parent().attr('id');
		if(selectedItem == 'po_warranty' || selectedItem == 'po_config' || selectedItem == 'po_install'){
			switch(selectedItem){
				case 'po_warranty':
					s.pageName.Value = 'Product Summary >  Extended Service';
					omnitureTracking('Extended Service');
					break;
					
				case 'po_config':
					s.pageName.Value = 'Product Summary >  Prod Config';
					omnitureTracking('Prod Config');
					break;
				
				case 'po_install': 
					s.pageName.Value = 'Product Summary >  Install';
					omnitureTracking('Install');
					break;
			}
		}
		//iterate through every checked option
		addOptions(content, title_added);
	});
	
	//handle the learn more function
	$('.viewmore').livequery('click', function(){
		if($(this).hasClass('viewless')){
			$(this).removeClass('viewless');
			$(this).parent().parent().find('.more').slideUp();
		} else {
			$(this).addClass('viewless');
			$(this).parent().parent().find('.more').slideDown();
			var parentDiv = $(this).parent().parent().attr('id');
			switch(parentDiv){
				case 'po_warranty' :
					s.pageName.Value = 'Product Summary > Extended Service > Learn More';
					omnitureTracking('Extended Service > Learn More');
					break;
					
				case 'po_install' :
					s.pageName.Value = 'Product Summary > Install > Learn More';
					omnitureTracking('Install > Learn More');
					break;
			}
		}
		return false;
	});
	
	
	
	//zipcode changer
	$('.zipChangeLnk').livequery('click', function(){
		zipModal();
		return false
	});
	
	$('.zipChangeBtn').livequery('click', function(){
		if($('.zipcode').val() == ''){
			return false;
		}
		$(this).hide().prev().show();
		$('.zipcode').css('borderColor','#fff').attr('readonly','readonly');
		return false
	});
	
	$('.zipcode').keyup(function(e){
		if(e.keyCode == 13){
			if($('.zipcode').val() == ''){
				return false;
			}
			$(this).next().show().next().hide();
			$('.zipcode').css('borderColor','#fff').attr('readonly','readonly');
		}
	});
	
	$('.addChk').livequery('click', function(){
		if($(this).parent().hasClass('selected')){
			$(this).next().text('Add to Cart').parent().removeClass('selected');
		} else {
			$(this).next().text('Added').parent().addClass('selected');
		}
	});
	
	$('.edit_collapsed').livequery('click', function(){
		$(this).parent().hide().nextAll().slideDown();
		$(this).parent().parent().removeClass('collapsed');
	});
	
	//display the installation options
	/*if($('#optInstall1:checked').length > 0){
		$('.install_info').show();
	}*/
	
	//uncheckh the ao_list options
	$('h5 > .ao').removeAttr('checked');
	
	/*$('#optInstall1').livequery('click', function(){
		$('.install_info').slideToggle();
	});*/
	$('#optInstall1').livequery('click', function(){
		
		if($('#optInstall1:checked').length > 0){
			if ($('#haulAway:checked').length > 0){
				$('input[name=haulAway]').attr('checked', false);
				$('.added_options .option, .accTitle').remove();	
				addOptions('SEARS Professional Installation');			
			}
			$('.install_info').show();
			$('.address_info').show();
			$('.haulaway').hide();
			
		}else{
				$('.install_info').hide();
				$('.haulaway').show();
			}
			
				
	});
	
	
	//submit the address and show the options list
	/*$('#btnSubmitAddress').livequery('click', function(){
		submitAddress();
	});*/
	
	
	/*//add up the install options
	$('.ao_list > div > input').livequery('click', function(){
		install_price = 0;
		$(this).parent().parent().find('input:checked').each(function(){
			install_price += parseFloat($(this).val());
		});
		$('.total_cost').text('$' + Math.round(install_price*100)/100);
		$('#optInstall1').val(Math.round(install_price*100)/100);
		$('.added_options .option, .accTitle').remove();
		addOptions('SEARS Professional Installation');
	});*/
	
	//display the options list
	$('.install_options > h5 > input').livequery('click', function(){
		//alert($(this).parent().next().css('display'));
		if($(this).parent().next().css('display') != 'block'){
			$('.ao_list').slideUp();
			$(this).parent().next().slideDown();
			install_price = base_install_price;
			$('.ao').not('.baseInstall').removeAttr('checked');
			$('.total_cost').text('$' + Math.round(install_price*100)/100);
		}
	});
	
	/*$('.product_option.closed a').livequery('click', function(){
		var url = $(this).attr('href');
		$(this).parents('.closed').removeClass('closed').load(url);
		return false;
	});*/

});

function addressPopUp(){
$("#whyNeedAddressNote").dynamicPopup({filename:dynamicPopupPath+"&vName=whyNeedAddressNote",contentname:".gcPleaseNote",windowWidth:"300px",windowHeight:"100px"})
}

function zipModal(){
	$('p.zipError').hide();
	
	
		$('#zipModal, #zipOverlay').fadeIn();
		
		$('#zipModal img').unbind().click(function(){
			submitZip();
		});
		$('#zipModal').show();
		$('#zipCode').keyup(function(e){
			if(e.keyCode == 13){
				submitZip();
			}
		});
		
		$('.zipClose').click(function(){
			$('#zipModal, #zipOverlay').fadeOut();
			return false;
		});
}
	
		function submitZip(){
			var zc = $('#zipCode').val();
			if(zc==''){
				var storeId = $('input#storeId').attr('value');
				zc=getCookie('zipCode'+storeId);
			}
			var catalogId= $('input#catalogId').attr('value');
			var storeId = $('input#storeId').attr('value');
			if(validateZip(zc)){
				$('#zipModal, #zipOverlay').fadeOut();
				setCookie('zipCode'+storeId,zc);
				ajaxCallForZipCodeChange(storeId,catalogId,parentCatentryId);
				$('#user_zip').text(zc);
			} else {
				$('p.zipError').fadeIn();
			}
		}
		
		function validateZip(field) {
			var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
	    return zipCodePattern.test(field);
		}


function addOptions(content, title_added){


			var parentCatentryId = '';
			var orderItemId = '';
				
			var optionsCatentryId = '';
			var optionType = '';
			var itemType = '';
			var quantity = '';
		
			price = original_price;
			html = '';
			$('.added_options').empty();
			
						
			$('.product_option input:checked').not('.ao').each(function(){
			if (($(this).val())==""){
				($(this).val(0));
				}
			/*if (($(this).hasClass('baseInstall'))){
				if (($(this).val())==""){
				($(this).val(0));
				}
			}*/
			
			
			price = parseFloat(price) + parseFloat($(this).val());	
				//don't add if the input is a nothanks or a Recommended Product or the Installation checkbox
				if(!($(this).hasClass('nothanks')) && !($(this).hasClass('addChk')) && this.id != 'optInstall1'  && this.id.split('_')[0] != "Installation"){
				
					html += '<div class="option"> \
										<span class="option_title">' + $(this).next().text() + '</span> \
										<span class="option_price">' + $(this).next().next().text() + '</span> \
										<div class="clearfloat"></div> \
									</div>';
			
			//	if(!($(this).hasClass('ao')) && !($(this).hasClass('baseInstall')) && !($(this).hasClass('nothanks')) && !($(this).hasClass('addChk')) && this.id != 'optInstall1' && this.id.split('_').length >= 4 && this.id.split('_')[0] != "Installation"){
				
									
				//what to do with recommended products
				} else if($(this).hasClass('addChk')){
					
					if(!title_added){
						html += '<h5 class="accTitle">' + $('#po_accessories > h5').text() + '</h5>';
						title_added = true;
					}
					html += '<div class="option"> \
										<span class="option_title">' + $(this).parent().prev().prev().text() + '</span> \
										<span class="option_price">' + $(this).parent().prev().text() + '</span> \
										<div class="clearfloat"></div> \
									</div>';
									
		    //what to do with the Installation Option
				} else if(this.id == 'optInstall1'){
					 
				base_install_price = $('#optInstall1').val();	
			/*	if ($('.haulAway:checked').length > 0){
				alert("hi");
				$('input[name=optInstall]').attr('checked', false);*/
				
				//$('.haulAway:checked').length = 0;
			
				install_price = base_install_price;	
				html += '<div class="option"> \
								<span class="option_title">SEARS Professional Installation</span> \
								<span class="option_price">+$' + Math.round(install_price*100)/100 + '</span> \
								<div class="clearfloat"></div> \
							</div>'
					
				}	
					
			});
			
			//append the html to the cart
			$('.added_options').append(html);
			$('.added_options .option_title').each(function(){
			if($(this).text() == content){
					//alert(content + ' ' + $(this).text());
	//				$(this).parent().highlightFade('#F1F37E');
					return;
				}
			});
			if($('#savingsAmt').text()!=""){
				price -= parseFloat($('#savingsAmt').text());
			}
			
			$('#mainTotal').text('$' + Math.round(price*100)/100);
			//$('.main_item_total').highlightFade('#C4F4BE');
			//$('#base_price').text(Math.round(price*100)/100);
			
			//$('.mainInfo').height($('#summary').height() + 50);
				
		
}
function doSubmitAddress(parentCatentryId){
	//clearing the error message first
	//document.getElementById("errorMsgSystem").innerHTML = '';
	//document.getElementById("errorMsgSystem").style.display='none';
	
	document.getElementById("address_info").style.display = '';
	document.getElementById("AJAXload").style.display = '';
	document.getElementById("AJAXloadRow").style.display = '';
	var address1 = trim(document.getElementById("address_1").value);
	var address2 = trim(document.getElementById("address_2").value);
	var city = trim(document.getElementById("address_city").value);
	state = trim(document.getElementById("address_state").value);
	var zipCode = trim(document.getElementById("address_zip").value);

	err = document.getElementById("errorMsg");
	err.style.display= "none";

	if (address1 == ""){
		if (address2 != ""){
			address1= address2;
			address2 = "";
		}
	}

	var retVal = validateAddress(address1,address2,city,state,zipCode,parentCatentryId);
	
	if(retVal == 1 ) {
		document.getElementById("AJAXload").style.display = 'none';
		document.getElementById("AJAXloadRow").style.display = 'none';
	}
	
	if (retVal == 0 ) {
		var tmpCounty = document.getElementById("county");
	   	if (tmpCounty!=null) {
	   		if (tmpCounty.length > 1) {
	    		prevcounty = tmpCounty.value;
	    	}
    	}

		var editstatus = 0;
	   	if(prevcity != city ||
        	prevzipcode != zipCode ||
        	prevstate != state ) {

        	prevcity = city;
        	prevzipcode = zipCode;
        	prevstate = state;
        	editstatus = 1;
        }

		var selectedTownship = 0;
		var tmpTownship = document.getElementById("township");
		if (tmpTownship!=null) {
			prevtownship = tmpTownship.value;
		}
		
		if (prevtownship != "") {
			selectedTownship = 1;
		}
		//alert ("BEFORE AJAX - prevcounty is " + prevcounty + " prevtownship is " + prevtownship + " prevzipcode is " + prevzipcode);

        if(retVal == 0 && editstatus == 1 && selectedTownship == 0) {
        	ajaxCallForAddress(address1,address2,city,state,zipCode,prevcounty, false, parentCatentryId);

        }
        else if (retVal == 0 && editstatus == 0 && selectedTownship == 0) {
        	// clear any errors and resubmit validation
        	// automatically post the address if valid address
        	document.getElementById("errorMsg").innerHTML = '';
       		ajaxCallForAddress(address1,address2,city,state,zipCode,prevcounty, true, parentCatentryId);

        } else if (selectedTownship == 1) {
        	// Township selected
        	//alert ("SELECTED TOWNSHIP");
        	selectTownship(prevtownship, parentCatentryId);
        	postSubmitAddress(parentCatentryId,state);
        }
	}

	return false;

}


function fnIsNumeric(value){
	var regEx = /^[0-9]+$/;
	if (!regEx.test(value)){
		return false;
	}
	return true;	
}

function validateAddress(address1,address2,city,state,zipCode,parentCatentryId){
	// only check country logic when it's enabled, default to US
	var cntry="US";
	 	
	// check valid zip code
	if (cntry == "US") {
		var zip = fnIsNumeric(zipCode);
	}
	
 	if(address1 == ""){
		err = document.getElementById("errorMsg");
		err.style.display= "";
		err.innerHTML = "<strong>Please enter address line 1.</strong>";
		
		return 1;
 	}
 	if(city == ""){
		err = document.getElementById("errorMsg");
		err.style.display= "";
		err.innerHTML = "<strong>Please enter a City.</strong>";
		
		return 1;
 	}

	if (cntry == "US") {
	 	if(zipCode == ""){
			err = document.getElementById("errorMsg");
			err.style.display= "";
			err.innerHTML = "<strong>Please enter a Zip code.</strong>";			
			return 1;
	 	}
	 	if(!zip){
			err = document.getElementById("errorMsg");
			err.style.display= "";
			err.innerHTML = "<strong>Please enter a valid 5-digit ZIP code. </strong>";
	
			return 1;
	 	}
	 	if(zipCode.length != 5){
			err = document.getElementById("errorMsg"); 
			err.style.display= "";
			err.innerHTML = "<strong>Please enter a valid 5-digit ZIP code. </strong>";
			return 1;
		}
	} 
	
	//No error, return 0
	return 0;
}

/*function ajaxCallForAddress(address1,address2,city,state,zipCode,prevcounty, submitOnSuccess, parentCatentryId) {
	var url = "HandleInstallationControllerCmd?city="+city+"&zipCode="+zipCode+"&state="+state+"&addr2="+address2+"&addr1="+address1+"&ua=va&step=1&storeId=10153&catentryId=1234&jspStoreImgDir=http://c.sears.com/082820/&origin=ProducPage&partnumber=123";
	
	ajaxCall(url,'callback',null,'install_address');

}

function callback(value,id){
	alert(value);
	alert('hi');
	document.getElementById(id).innerHTML = value;
}*/


function ajaxCallForAddress(address1,address2,city,state,zipCode,prevcounty, submitOnSuccess, parentCatentryId) {
	//document.getElementById("address_info").style.display = 'none';
	processTaxwareResponse = false;
	//alert("submitOnSuccess " + submitOnSuccess); 
	var county="";
	if($('#county').val() != null || $('#county').val() != undefined){
		county = $('#county').val()
	}
	
	parentCatentryId=$('input#catentryProduct').attr('value');
	//var url = "http://localhost/shc/s/SocialContentCmd?storeid=10153&vName=Applincaes";
	var url = "HandleInstallationControllerCmd?city="+city+"&zipCode="+zipCode+"&state="+state+"&addr2="+address2+"&addr1="+address1+"&ua="+ua+"&step=1&storeId="+storeId+"&catentryId="+itemId+"&jspStoreImgDir=http://c.sears.com/082820/&origin=ProductPage&partnumber="+itemPartnumber+"&county="+county+"&parentCatentryId="+parentCatentryId;
	//var url="http://pulse.ecom.sears.com:1187/shc/s/HandleInstallationControllerCmd?city=New%20York&zipCode=10001&state=NY&addr2=asdfsd&addr1=asdfa&ua=va&orderItemsId=8525047&step=2&storeId=10153&jspStoreImgDir=http://pulse.ecom.sears.com:7304/0000/";
	$.ajax({
		type:'GET',
		dataType:'text',
		url:url,
		success:addressPageOpt.onSuccess,
		//complete:Community.dynPreview,
		error:addressPageOpt.onFailure
	});
}
    var addressPageOpt = {
	     //Handle successful response
	    onSuccess: function(t) {
	    	var responseEntry = trim(t);
	    	var responseValue;
	    	//state = ('#address_state').val();
	    	document.getElementById("address_info").style.display = 'none';
	    	document.getElementById("AJAXload").style.display = 'none';
			document.getElementById("AJAXloadRow").style.display = 'none';
	    	if (responseEntry != null && responseEntry != '') {
	    		responseValue = responseEntry.split("=");
	    		   		
	    		if (responseValue.length == 2) {
	    			// There is a response value if the length is greater than or equal to 2.
	    		
	    			if (responseValue[0].indexOf('COUNTY') != -1) {
	    			// If responseValue[0] contains COUNTY, this is a response for multiple counties.

	    				var countyValue = responseValue[1];
	    				var countySplit = countyValue.split("|");
	    				var count;

	        		    for(count = 0; count < countySplit.length; count++){
					         var selObj = document.getElementById("county");
					         if (countySplit[count] != undefined) {
					         	selObj.options[count] = new Option(countySplit[count]);
					         }
						}
						document.getElementById("countyTable").style.display = '';
						document.getElementById("countyRow").style.display = '';
						if(document.getElementById("countyRowMsg")){
							document.getElementById("countyRowMsg").style.display = ''; 
							document.getElementById("countyRowUnknown").style.display = '';
						}
						document.getElementById("townshipTable").style.display = 'none';
						ua='ca';
						$('#address_info').show();
						processTaxwareResponse = true;
						
					} 					
					
				
				} else if (responseValue.length == 1) {
				
					// There is only a single response of SUCCESS or EXCEPTION after confirming the address county.
					
					// Do not display county selection again.
					document.getElementById("countyRow").style.display = 'none';
					if(document.getElementById("countyRowMsg")){
						document.getElementById("countyRowMsg").style.display = 'none'; 
						document.getElementById("countyRowUnknown").style.display = 'none';
					}
						
					if (responseValue[0].indexOf('SUCCESS') != -1) {
					
						//alert ("SUCCESS AND CONTINUE");
						
						postSubmitAddressNew(parentCatentryId,state);
						//submitAddressNew();
					} else if (responseValue[0].indexOf('EXCEPTION') != -1) {
						var errMsgStr = "";
						var exceptionValue = responseValue[0].split(":");
						
						// EXCEPTION:errkey
						var inCount =2;// document.getElementById("InstallationCount").innerHTML; //'${inCount}';

						var yesId = 'Installation_'+inCount+'_yes_'+parentCatentryId;
						var noId = 'Installation_'+inCount+'_no_'+parentCatentryId;
						var systemException = false;
						
						if (exceptionValue.length == 2) {
							var errKey = exceptionValue[1];
							
							if (errKey.indexOf('_ERR_INCORRECT_STATE_CODE') != -1) {
								errMsgStr = "The state code entered was invalid.";
							} else if (errKey.indexOf('_ERR_INCORRECT_ZIP_CODE') != -1) {
								errMsgStr = "The zip code you entered is incorrect.";
							} else if (errKey.indexOf('_ERR_STATE_ZIP_CITY_COMBINATION') != -1) {
								errMsgStr = "Error in city, zipcode and state combination.";
							} else if (errKey.indexOf('_ERR_GEOCODE_NULL') != -1) {
								errMsgStr = " The U.S. state or city and ZIP code you entered in your shipping information do not match. Please check these and try again.";
							}else if (errKey.indexOf('_MSG_INCLUDED_WITH_DELIVERY') != -1) {
								errMsgStr = "Installation for this product is actually free with delivery - you will not be charged for installation.";
								makeNo(noId, yesId, parentCatentryId);
								intendedMessage = true;
							} else if (errKey.indexOf('_MSG_NOT_AVAILABLE') != -1) {
								errMsgStr = "Installation is not available for this product in your area.";	
								makeNo(noId, yesId, parentCatentryId);
								intendedMessage = true;
							} else {
								errMsgStr = "We are temporarily unable to handle your installation request. Please try again.";
								//makeNo(noId, yesId, parentCatentryId);
								systemException = true;
							}							
						} else {
							errMsgStr = "We are temporarily unable to handle your installation request. Please try again.";
							//makeNo(noId, yesId, parentCatentryId);
							systemException = true;
						}
					
						if (systemException) {
							err = document.getElementById("errorMsgSystem");  
	            			err.style.display= "";
	            			err.innerHTML = "<strong>"+errMsgStr+"</strong>";
	            			$('#address_info').show();
						} else {					
							err = document.getElementById("errorMsg");  
	            			err.style.display= "";
	            			err.innerHTML = "<strong>"+errMsgStr+"</strong>";
	            			$('#address_info').show();
	            		}
            			
            			processTaxwareResponse = true;
            			
            			//alert ("ERROR");

					}
				} 
				

				if (!processTaxwareResponse) {
				
					// Process another response value
					//alert("INSTALLATION OPTIONS");
					 if(document.getElementById("learnMore")){
					  	document.getElementById("learnMore").style.display="";						
					  }
					var anotherResponseValue = responseEntry.split("#");
					//postSubmitAddressNew(parentCatentryId,state);
					document.getElementById("install_address").innerHTML = anotherResponseValue[0];
					if($('.first_option span').text().split('$')[2] == null||$('.first_option span').text().split('$')[2] == 'undefined'  ||$('.first_option span').text().split('$')[2]=="")
						$('#optInstall1').val(($('.first_option span').text()).substring(1));
					else
						$('#optInstall1').val(0);	
					addOptions('SEARS Professional Installation');
					//alert($('#install_address.first_option span').val());
					//addOptions('SEARS Professional Installation');
					//Reporting starts
					var addOnCount;					
					if (document.getElementById("totalISSQuestionsAsked") != null) {
						addOnCount = document.getElementById("totalISSQuestionsAsked").innerHTML;
					}
					var s_account;
					if (typeof omAcct != 'undefined') {
						s_account = omAcct;
					}
					if (typeof s != 'undefined') {
 						s=s_gi(s_account);
 						s.linkTrackVars="eVar39";
 						s.eVar39=addOnCount;
 						s.tl(this, 'o', 'Installation Questions Asked');
					}
					//Reporting ends
					
					if (anotherResponseValue.length == 2) {
						var multipleTownship = anotherResponseValue[1];
						var multipleTownshipValue = anotherResponseValue[1].split("=");
	
						if (multipleTownshipValue[0].indexOf('TOWNSHIP') != -1) {
							// If multipleTownshipValue[0] contains TOWNSHIP, this is a response for multiple townships.
	
		    				var townshipValue = multipleTownshipValue[1];   				
		    				var townshipSplit = townshipValue.split("|");
		    				var count;
	
		        		    for(count = 0; count < townshipSplit.length; count++){
						         var selObj = document.getElementById("township");
						         if (townshipSplit[count] != undefined) {
						         	selObj.options[count] = new Option(townshipSplit[count]);
						         }
							}
							document.getElementById("townshipTable").style.display = '';
							document.getElementById("townshipRow").style.display = '';
							if(document.getElementById("townshipRowMsg")){
								document.getElementById("townshipRowMsg").style.display = ''; 
								document.getElementById("townshipRowUnknown").style.display = '';
							}
							document.getElementById("countyTable").style.display = 'none';
						}
					} else {
						
						postSubmitAddressNew(parentCatentryId,state);
					//	submitAddressNew();
					}
				
				}
				
	    	}
    	},
    	
        // Handle other errors
        onFailure: function(t) {
       // alert('fail');
            err = document.getElementById("errorMsg");  
            err.style.display= "";
            err.innerHTML =="<p>Error processing your request, please try again later.</p>";
        }
    }   
      

function trim(inword){
	   word = inword;//.toString();
	   var i=0; 
	   var j=word.length-1;
	   while(word.charAt(i) == " ") i++;
	   while(word.charAt(j) == " ") j--;
	   	if (i > j) {
			return word.substring(i,i);
		}
		else {
			return word.substring(i,j+1);
		}
	}  
	

function postSubmitAddressNew(parentCatentryId,state) {
		
		$('#installation_address').clone().prependTo('#temp');
		var html = '';
		var address1 = trim(document.getElementById("address_1").value);
		var address2 = trim(document.getElementById("address_2").value);
		var city = trim(document.getElementById("address_city").value);
		var state = trim(document.getElementById("address_state").value);;
		var zipCode = trim(document.getElementById("address_zip").value);
		
		var parentCatentryIdParam = "'" + parentCatentryId + "'";
		var stateParam = "'" + state + "'";
		
		$('#installation_address').show();
		$('#install_address').show();
		
		document.getElementById("installation_address").innerHTML =("<h4>Address where installation will occur:</h4><br>");
		$('#installation_address').append(address1+' '+address2+'<br>'+city+', '+state+' '+zipCode);
		//document.getElementById("installation_address").innerHTML = address1+' '+address2+'<br />'+city+', '+state+' '+zipCode;
		$('#installation_address').append('<br><a href="javascript:void(null);" class="chgAddress" onClick="changeAddress(' + parentCatentryIdParam + ',' + stateParam + ')">Change this</a>');
		//$('#installation_address').append('<a id="chgAddress" class="chgAddress" href="javascript:void(null);">Change this</a>');
		return false;

}

function changeAddress(parentCatentryId,state){
		
		if(document.getElementById("learnMore")){
			document.getElementById("learnMore").style.display="none";			
		}	
			$('#installation_address').hide();
			$('#install_address').hide();
			document.getElementById("AJAXload").style.display = 'none';
			document.getElementById("AJAXloadRow").style.display = 'none';
			$('#address_info').show();
			
			$(countyTable).hide();
			$(county).empty();
			
			$(townshipTable).hide();
			$(township).empty();
			$('#btnSubmitAddress').unbind().livequery('click', function(){
				postSubmitAddressNew();
			
			});
			
			return false;
}

function updateInstPrice(checkboxId, parentCatentryId, mainInstCatentryId) {
	//alert('in updateinstprice');
	//alert($('#'+checkboxId).val());
	//alert(($('#' + parentCatentryId + '_'+mainInstCatentryId+'_total_cost').text()).substring(1));
	
		
	var baseInstPrice=($('#' + parentCatentryId + '_'+mainInstCatentryId+'_total_cost').text()).substring(1);
	var optInstPrice=$('#'+checkboxId).val();
	if (document.getElementById(checkboxId).checked == true){
			var totPrice = parseFloat(baseInstPrice) + parseFloat(optInstPrice);
	}
	else if (document.getElementById(checkboxId).checked == false) {
	 	totPrice = parseFloat(baseInstPrice) - parseFloat(optInstPrice);
	 }
	$('#' + parentCatentryId + '_'+mainInstCatentryId+'_total_cost').html('$'+Math.round(totPrice*100)/100);
	$('#optInstall1').val(($('#' + parentCatentryId + '_'+mainInstCatentryId+'_total_cost').text()).substring(1));
	//$('#optInstall1').val('+'+baseInstPrice);
	addOptions();
	
	}
	


function ajaxCallForZipCodeChange(storeId,catalogId,parentCatId){
	var ajaxUrl="GetProductOptionPrices?storeId="+storeId+"&catalogId="+catalogId+"&zipCode="+zipCode+"&parentCatId="+parentCatId+"&origin=productPage";
	$.ajax({
		type:'GET',
		dataType:'xml',
		url:ajaxUrl,
		success:zipCodeChange.onSuccess,
		error:zipCodeChange.onFailure
	});	
}

var zipCodeChange={

	onFailure: function() {
        //	alert('fail');
            err = document.getElementById("errorMsg");  
            err.style.display= "";
            err.innerHTML =="<p>Error processing your request, please try again later.</p>";
        },
    onSuccess: function(data) {
    		$(data).find('PAPrices').each(function(i){
    		var _global = $(this);
			var paCatId = _global.find('PACatEntryId').text();
			//alert(paCatId);
			var price = _global.find('Price').text();
			//alert(price);
			var id= "optProtect"+paCatId;
			//alert(id);
			document.getElementById(id).value=price;
			});
	}
}

function displayQuestions(childId,parentId) {
	var allMainId = document.getElementById("ALL_MAIN_"+parentId).innerHTML;
	if (allMainId!=null && allMainId!='') {
		var mainId = allMainId.split("_");
	    var count;
	    for(count = 0; count < mainId.length; count++){

			var div =document.getElementById(mainId[count]+"_"+parentId);
			div.style.display="none";
		}
	}
	//70000124_40732522
	document.getElementById(childId+"_"+parentId).style.display="block";

	//For Adding installation option to order summary when clicking one of the installation base option.
 	var instDiv = '';
    var elementsArray = '';
    var radioButton;
    var totCurrInstPrice = 0;
    var divId = parentId+"_installation_options";
 	var priceTemp='';
   	if(null != document.getElementById(divId)) {
            instDiv =document.getElementById(divId);
            if(null != instDiv.getElementsByTagName("input")) {
            	elementsArray =instDiv.getElementsByTagName("input");
			}
            var count;
            for(count = 0; count < elementsArray.length; count++)
            {
                  if(elementsArray[count].type=="radio")
                  {
                        radioButton=elementsArray[count];
                        if(radioButton.checked==true)
                        {
                              var childId=radioButton.id.split("_")[2];
                              var div =document.getElementById(childId+"_"+parentId);
                              var checkBoxes=div.getElementsByTagName("input");
                              var count2;
                              var priceTemp;
                              for(count2 = 0; count2 < checkBoxes.length; count2++)
                              {
                                    if(checkBoxes[count2].type=="checkbox")
                                    {
                                          if(checkBoxes[count2].checked==true) {
                                                priceTemp = checkBoxes[count2].value;
                                                priceTemp = parseFloat(priceTemp);
                                                totCurrInstPrice = totCurrInstPrice + priceTemp;
                                          }
                                    }
                              }
                        }
                  }
            }
      }
     var baseInstPrice=($('#' + parentId + '_'+childId+'_total_cost').text()).substring(1);
      $('#optInstall1').val(baseInstPrice);  
     	
      addOptions('SEARS Professional Installation');	



}
function mouseOver(thisDiv) {
	$(thisDiv).toggleClass('hover');
}

