// ############################ INITIALIZATION #################################

// ###	Create data object
var estData;
var rptMgt = new estUtils.ReportingMgtClass();
var isEspanol = false;
var currentOffers = true;
var currentLocation1 = window.location;
if(String(currentLocation1).indexOf("espanol") != -1)
{
	isEspanol = true;
}

var debugMode = false;

var term_list = [24,36,48,60,72,84];
var credit_rating_apr = [[7.2,7.2,7.2,7.2,7.8,8.5],[11.5,11.5,11.5,11.5,12.1,11.4],[13.6,13.6,13.6,13.6,14.1,13.2],[15.3,15.3,15.3,15.3,15.7,15.0]];
var apr=0;
var pe_visited = false;


var cr;
var purchaseFlag;
var leaseFlag;
var isZipCodeErr;

var downpayment=0;
var tradein=0;
var owedontrade=0;
var costofaccess=0;
var newDataArray = new Array();
var submitData = false;



function validateData()
{

	cr = document.getElementById('creditRating').value;
	var purchaseBox = document.getElementById('purchase').checked;
	var leaseBox = document.getElementById('lease').checked;
	var zipcode =  document.paymentEstimatorForm.txtZipcode.value;
	var vehicle =  document.getElementById('vehicle').value;
	var model = document.getElementById('drpTrim').value;
	//alert("pe_visited: "+pe_visited);
    /*document.getElementById('purchaseDiv').style.display="none";
    document.getElementById('leaseDiv').style.display="none";*/

	if(pe_visited)
	{
		if((purchaseBox || leaseBox) && !submitData)
		{
			displayFinanceOption();	
		}
		else if(validateCreditRating() && validateZipCode() && validateVehicle() && validateModel())
		{
			submitBtnClicked();		
		}
		/*else(!validateFinanceOption())
		{
			displayFinanceOption();		
		}*/


	}
	//else if(validateCreditRating() && validateFinanceOption() && validateZipCode() && validateVehicle() && validateModel())
	else if(cr!='' && (purchaseBox==true || leaseBox==true) && zipcode!='' && vehicle!='' && model!= '')
	{
		pe_visited = true;
		submitBtnClicked();
	}
}

//For APR
	function getAprForTerm(purchaseDataList, purchaseTermNumber, propFlag)
	{
		if ( !estData.getHasPurchaseData() ) return null;
		//alert("purcahseDataList in APR func: "+purchaseDataList.length+"term: "+purchaseTermNumber);
		var foundPurchaseItem = null;
		for (var idx in purchaseDataList) {
			purchaseItem = purchaseDataList[idx];
			//alert("term in for loop: "+purchaseItem.term);
			if (purchaseItem.term == purchaseTermNumber) {
				foundPurchaseItem = purchaseItem;
				break;
			}
		}
		switch (propFlag){
			case 'apr':
				if(foundPurchaseItem == null){
				return "NONE";
				}
				else{
				return foundPurchaseItem.apr;
				}
			case 'standardOrSpecialApr':	
				if(foundPurchaseItem == null){
				return "NONE";
				}
				else{
				return foundPurchaseItem.standardOrSpecialApr;				
				}
			default: 
				return foundPurchaseItem;
		}
	}

function validateCreditRating()
{
	submitData=true;
	cr = document.getElementById('creditRating').value;
	//alert("cr value: "+cr);
	if(cr == '')
	{
		// alert('Please choose a Credit Rating.'); Find out
		return false;
	}
	else
		return true;
}

function validateFinanceOption()
{
	submitData=false;
	var purchaseBox = document.getElementById('purchase').checked;
	var leaseBox = document.getElementById('lease').checked;
	if(purchaseBox==false && leaseBox==false)
		alert("Please select any finance Option");
	else
		return true;
}

function validateZipCode()
{
	var temp;
	var errorTxt = "";
	var zRes = false;
	temp = document.paymentEstimatorForm.txtZipcode.value;
	if(temp == '') {
		isZipCodeErr = true;
		$('zipCodeErr').style.display="block";
	} 
	else if(isNaN(temp)) {
		isZipCodeErr = true;
		$('zipCodeErr').style.display="block";
		//alert('Please enter valid Zip Code');
	} 
	else {
		DWREngine.setAsync(false);
		PaymentEstimatorFacade.isZipCodeValid(temp, {callback:
			function(b) { zRes = b; }
		});
		isZipCodeErr = false;
		DWREngine.setAsync(true);
		if(!zRes){
			isZipCodeErr = true;
			$('zipCodeErr').style.display="block";
		}
	}
	if(!isZipCodeErr)
	{
		$('zipCodeErr').style.display="none";
	}
	return true;
}

function validateVehicle()
{
	var vehicle =  document.getElementById('vehicle').value;
	if(vehicle == 0) 
	{
		alert('Please choose a Vehicle.');
	}
	else 
		return true;
}

function validateModel()
{
	var model = document.getElementById('drpTrim').value;
	//alert("model:"+model);
	if(model =='')
	{
   	  alert('Please choose a Model.');
	  return false;
	}
	else
	{
		submitData=true;	
		return true;
	}
}

function submitBtnClicked()
{
	//displayFinanceOption();
	displayData();
	
	toMem(strModel);
	toMem(trimBox.value);
	toMem(zipBox.value);
	toMem(zipCodeValue.value);
	toMem(strYear);
	toMem(populateLeaseData);
	
	//calculateAPR('60');
	var crValue=" ";
	if(isEspanol)
	{
		if(cr=="Excelente")
			crValue = "LS0";
		else if(cr=="Muy bueno")
			crValue = "LS1";
		else if(cr=="Bueno")
			crValue = "LS2";
		else if(cr=="Aceptable")
			crValue = "LS3";
		else if(cr=="Pobre")
			crValue = "LS4";
	}
	else
	{
		if(cr=="Excellent")
			crValue = "LS0";
		else if(cr=="Great")
			crValue = "LS1";
		else if(cr=="Good")
			crValue = "LS2";
		else if(cr=="Fair")
			crValue = "LS3";
		else if(cr=="Poor")
			crValue = "LS4";
	}
	//alert("strmodel: "+strModel+"trim: "+trimBox.value+"zipcode: "+zipBox.value+"year: "+strYear);
	rptMgt.setCreditRating(crValue);
	PaymentEstimatorFacade.getPaymentEstimatorDataForTheVehicleTrim(strModel, trimBox.value, zipBox.value, strYear, crValue, populateLeaseData);
	
}

function calculateAPR(term)
{
	var credit_rating = document.getElementById('creditscore').value;
	//var term = document.getElementById('drpPurchaseMonths').value;
	//alert("term:"+term);
	if(credit_rating!=0)
	{
		for(var i=0; i<term_list.length; i++)
		{
			if(term_list[i] == term)
			{
				apr = credit_rating_apr[credit_rating-1][i];
			}
		}
	}
	//alert("credit rating selected: "+credit_rating+" APR value: "+apr+" term:"+term);
}

function displayData()
{
	
	var purchaseBox = document.getElementById('purchase').checked;
	var leaseBox = document.getElementById('lease').checked;
	if(purchaseBox && leaseBox)
	{
		jQuery('#leaseLoadingDiv').css('padding-left','50px');
	}
	else if(leaseBox)
	{
		jQuery('#leaseLoadingDiv').css('padding-left','35px');
	}
	if(purchaseBox)
	{
		jQuery('#purchaseLoadingDiv').css('display','block');
		document.getElementById('purchaseDiv').style.display="none";
	}
	if(leaseBox)
	{
		jQuery('#leaseLoadingDiv').css('display','block');
		document.getElementById('leaseDiv').style.display="none";
	}
}

//Display Purchase or Lease section
function displayFinanceOption()
{
	
	
	
	var purchaseBox = document.getElementById('purchase').checked;
	var leaseBox = document.getElementById('lease').checked;
	//$('mainFinanceData').style.display = 'block';
	document.getElementById('baseMsrpSection1').style.display="block";
	document.getElementById('baseMsrpSection2').style.display="block";
	
	jQuery('#purchaseLoadingDiv').css('display','none');
	jQuery('#leaseLoadingDiv').css('display','none');
	
	if(purchaseBox==true && leaseBox==true)
	{
		document.getElementById('purchaseDiv').style.display="block";
		document.getElementById('purchaseTable').style.top= 0;
		document.getElementById('leaseDiv').style.display="block";
		document.getElementById('leaseDiv').style.left=320;
	}
	else if(purchaseBox==true && leaseBox==false)
	{
		document.getElementById('purchaseDiv').style.display="block";
		document.getElementById('purchaseTable').style.top= 0;
		document.getElementById('leaseDiv').style.display="none";
	}
	else if(purchaseBox==false && leaseBox==true)
	{
		document.getElementById('purchaseDiv').style.display="none";
		document.getElementById('leaseDiv').style.display="block";
		document.getElementById('leaseDiv').style.left=25;
	}
	else if(purchaseBox==false && leaseBox==false)
	{
		//$('mainFinanceData').style.display = 'none';
		//alert('Please select any Finance Option');
		document.getElementById('purchaseDiv').style.display="none";
		document.getElementById('leaseDiv').style.display="none";
		document.getElementById('baseMsrpSection1').style.display="none";
		document.getElementById('baseMsrpSection2').style.display="none";
	}
	
	
	crRatingVal = validateCreditRating();
	if(crRatingVal == false){
	
		hideCreditRating();
		document.getElementById('purchaseDiv').style.display='none';
	
	}
	
	
}


// ############################ BEGIN DWR data acquisition code ################

var strModel;
var trimBox;
var zipBox;
var zipCodeValue;
var strYear;
var SELECT_PROMPT = '--Select a Vehicle--';



var pePath = location.pathname.split(",");
var pePathEs = "/apps/espanol/paymentestimator";
//alert(pePath);

if (pePath == pePathEs){
	var TRIM_PROMPT = '--Seleccionar un modelo--';
}else{
	var TRIM_PROMPT = '--Select a Trim--';
}



var GENERAL_ERROR = 'The payment estimator is temporarily unavailable. Please try again.';

  var largeImages = new Array();
  var offerImages = new Array();
  var offerLinks = new Array();

 function addLargeImagePairing(name, path, offersPath, offersLink) {
	    largeImages[name] = path;
		offerImages[name] = offersPath;
		offerLinks[name] = offersLink;
  }


function modelTrigger(strM, tBox, zBox, yBox) {
	strModel = strM;
	trimBox = tBox;
	zipBox = zBox;
	zipCodeValue = zBox;
	strYear = yBox;

	/*$('loadingDiv').style.display="block";
	$('drpTrim').disabled=true;*/
		
		$('mainFinanceData').style.display = 'block';
       $('mainCarImageTR').style.visibility = 'visible';
       $('mainCarImage').style.visibility = 'visible';

       $('mainCarImage').src = largeImages[strModel];
	   $('offersImage').src = offerImages[strModel];
	   $('offersLink').href = offerLinks[strModel];
	   if(currentOffers)
		{
			if(($('offersImage').src).indexOf('undefined')!=-1 || ($('mainCarImage').src).indexOf('undefined')!=-1)
			{
				$('offersImage').src="/img/shopping_tools/payment_estimator/spacer.gif";
				$('mainCarImage').src="/img/shopping_tools/payment_estimator/spacer.gif";
			}
		}
		if(currentOffers==false)
		{
			$('offers').style.display = "none";
		}
		  
	  $('purchaseDiv').style.display = "none";
	  $('leaseDiv').style.display = "none";
	  $('baseMsrpSection1').style.display="none";
	  $('baseMsrpSection2').style.display="none";

	  
	if((strModel != null) && (strModel != SELECT_PROMPT)) PaymentEstimatorFacade.getTrimDataForTheVehicle(strModel, populateTrims);
	
	
}

function populateTrims(dwrTrimObj) {
    if(debugMode) alert(DWRUtil.toDescriptiveString(dwrTrimObj, 2));

	try {
		trimBox.options.length = 0;
		trimBox.options[0] = new Option(TRIM_PROMPT, '');

		for(var i = 0; i < dwrTrimObj.length; i++)
			trimBox.options[i+1] = new Option(dwrTrimObj[i], dwrTrimObj[i]);
	
		/*$('drpTrim').disabled=false;
		$('loadingDiv').style.display="none";*/
		
		//disableTrim(); //// versa 1.6 trim removal

	} catch(err) {
		//alert(GENERAL_ERROR);
	}
	
	
}

function modelAutoTrigger() {
	if(document.paymentEstimatorForm.vehicle.selectedIndex > 0 &&
	   document.paymentEstimatorForm.drpTrim.selectedIndex > 0 &&
	   document.paymentEstimatorForm.txtZipcode.value != '') {
		//submitBtnClicked();
	}

}

/*var zRes = false;
function submitBtnClicked(optSilent) {
	var temp;
	var errorTxt = "";
	//alert("submitBtnClicked clicked value is: "+optSilent);
	temp = document.paymentEstimatorForm.txtZipcode.value;
	if(temp == '') {
		errorTxt = 'Please enter your Zip Code.';
	} else if(isNaN(temp)) {
		errorTxt = 'Please enter valid Zip Code';
	} else {
		DWREngine.setAsync(false);
		PaymentEstimatorFacade.isZipCodeValid(temp, {callback:
			function(b) { zRes = b; }
		});
		DWREngine.setAsync(true);
		if(!zRes) errorTxt = 'Please enter valid Zip Code';
	}

	if( document.paymentEstimatorForm.drpTrim.selectedIndex == 0) {
		errorTxt = 'Please choose a Model.'
	}

	if( document.paymentEstimatorForm.vehicle.selectedIndex == 0) {
		errorTxt = 'Please choose a Vehicle.';
	}
       if(errorTxt == '') {
		  //alert(strModel);
		toMem(strModel);
		//alert(trimBox.value);
		toMem(trimBox.value);
		toMem(zipBox.value);
		toMem(strYear);
		toMem(populateLeaseData);

		//calculateAPR();
		checkFinanceOption();

       	PaymentEstimatorFacade.getPaymentEstimatorDataForTheVehicleTrim(strModel, trimBox.value, zipBox.value, strYear, populateLeaseData);
	} else {
		if(!optSilent) alert(errorTxt);
	}
}*/

function populateLeaseData(dwrLeaseObj) {
	if(debugMode) alert(DWRUtil.toDescriptiveString(dwrLeaseObj, 2));
		var purchaseDataArray = new Array();
		var purchaseObj = dwrLeaseObj["purchaseDataList"];
		//alert("purchaseObj length: "+purchaseObj.length+" putrchaseDataArray length: "+purchaseDataArray.length);
		for(var i = 0; i < purchaseObj.length; i++) {
			purchaseDataArray[purchaseDataArray.length] = new PurchaseDataClass(parseInt(purchaseObj[i]["term"]),
										    purchaseObj[i]["apr"],parseInt(purchaseObj[i]["aprType"]));
		}
		newDataArray=purchaseDataArray;

		var leaseDataArray = new Array();
		var leaseObj = dwrLeaseObj["leaseDataList"];
		//alert("leaseObj: "+ leaseObj.length+" leaseDataArray length: "+leaseDataArray.length);
		for(var i = 0; i < leaseObj.length; i++) {
			leaseDataArray[leaseDataArray.length] = new LeaseDataClass(parseInt(leaseObj[i]["acquisitionFeeAmt"]),
												leaseObj[i]["mileageCde"],
												parseFloat(leaseObj[i]["moneyFactor"]),
												parseFloat(leaseObj[i]["residualPct"]),
												parseInt(leaseObj[i]["term"]),
												parseInt(leaseObj[i]["leaseType"]));
		}
		//build an estimatordataclass
	//estData = new EstimatorDataClass(2006, parseInt(dwrLeaseObj["baseMsrp"]), parseInt(dwrLeaseObj["destinationFee"]), leaseDataArray);
	var leaseMileagePE='L';  //default is L
	var leaseTermPE=36;
	var purchaseTermPE=60;
	if($('drpLeaseMileage').value == 'S' )
	{
	leaseMileagePE =  'S';
	}
	if($('drpPurchaseMonths').value != 60 )
	{
	purchaseTermPE =  $('drpPurchaseMonths').value;
	}
	if($('drpLeaseMonths').value != 36 )
	{
	leaseTermPE =  $('drpLeaseMonths').value
	}
	
	

	estData = new EstimatorDataClass(2009, parseInt(dwrLeaseObj["baseMsrp"]), parseInt(dwrLeaseObj["destinationFee"]), leaseDataArray, purchaseDataArray, leaseMileagePE,purchaseTermPE,leaseTermPE);

setHtml( 'baseMsrp1', estData.getBaseMSRP(1));

setHtml( 'baseMsrp2', convertToDollar(parseInt(dwrLeaseObj["baseMsrp"])+ parseInt(costofaccess) - parseInt(downpayment) - parseInt(tradein) + parseInt(owedontrade)));

	// User clicked the submit button and we have valid data. For this action
	// we want to fire the crmEvent2 in a consolidated manner. Meaning that
	// lease and loan will both update, but we want one report of this action
	// rather than 2. We have to check that we have Lease data befor we set this.
	// if there is no lease data, then the lease column wont fire and consolidated
	// report wont work.
	if ( estData.getHasLeaseData() )
		rptMgt.setDoConsolidatedReport(true);

	initFormData();
}
//end DWR data acquisition code

// ###	Callback function for KBB trade in value (Loan)
function updateLoanTradeIn( tradeinValue, year, make, model ) {
		
		//alert("calling updateLoanTradeIn callback function");

		rptMgt.setTradeInInfo(year,make,model,tradeinValue);
		$('txtPurchaseTradein').value = tradeinValue;
		estData.getLoanDataObj().setTradeIn( tradeinValue );
		updateMonthlyLoanPayment();
}

// ###	Callback function for KBB trade in value (Lease)
function updateLeaseTradeIn( tradeinValue, year, make, model ) {
		rptMgt.setTradeInInfo(year,make,model,tradeinValue);
		$('txtLeaseTradein').value = tradeinValue;
		estData.getLeaseDataObj().setTradeIn( tradeinValue );
		updateMonthlyLeasePayment();
}

// ###	Initialize form values on page
function initFormData () {
	//Set Base MSRP and Total MSRP fields
	/*for(i=1;i<=4;i++)
	{
		setHtml( 'baseMsrp'+i, estData.getBaseMSRP(1) );
	}*/
	//setHtml( 'totalMsrp', estData.getEstimatedSellingPrice(1) );

	purchaseFlag=false;
	leaseFlag=false;

	var paymentObj = estData.getLoanDataObj().getMonthlyLoanPaymentObj();

	//Assign event handlers
	assignLoanEventHandlers();
	assignLeaseEventHandlers();

	//Populate form values

	if ( estData.getHasPurchaseData() ) { //Check to validate that we have lease data
		jQuery('#purchaseTable>div').css('display','block');
		$('purchaseTermDiv').style.paddingTop = "34px";
		$('purchaseLinks').style.display = "block";
	    $('purchaseLinks1').style.display = "none";

		displayLoanData();
	} else {
	  jQuery('#purchaseTable>div').css('display','none');
	  $('purchaseLinks').style.display = "none";
	  $('purchaseLinks1').style.display = "block";	  
	  $('purchaseLinks1').style.position = "relative";
	  $('purchaseLinks1').style.top = "0px";
	  setHtml('purchaseErrorMsg', 'Sorry for the inconvenience, but we are currently updating the site to bring you the most attractive offers available. Please check back soon, or contact your Nissan Dealer for payment information.' );
	  purchaseFlag=true;
	  if(isEspanol)
	  {
	      setHtml('purchaseErrorMsg', 'Sepa disculpar cualquier inconveniente, es que estamos actualizando el sitio para poder brindarle las mejores ofertas posibles. Vuelva a visitarnos pronto o consulte al concesionario de Nissan respecto a la información de pagos.' );
	  }
	  //Supressing $000.00
	  displayFinanceOption();
	}

	
	
	if ( estData.getHasLeaseData() ) { //Check to validate that we have lease data
		jQuery('#leaseTable>div').css('display','block');
		$('leaseLinks').style.display = "block";
	    $('leaseLinks1').style.display = "none";
		displayLeaseData();
	} else {
	  jQuery('#leaseTable>div').css('display','none');
	  $('leaseLinks').style.display = "none";
	  $('leaseLinks1').style.display = "block";
      setHtml('leaseErrorMsg', 'Sorry for the inconvenience, but we are currently updating the site to bring you the most attractive offers available. Please check back soon, or contact your Nissan Dealer for payment information.' );
	  leaseFlag=true;
	  if(isEspanol)
	  {
	      setHtml('leaseErrorMsg', 'Sepa disculpar cualquier inconveniente, es que estamos actualizando el sitio para poder brindarle las mejores ofertas posibles. Vuelva a visitarnos pronto o consulte al concesionario de Nissan respecto a la información de pagos.' );
	  }
	  //Supressing $000.00
	  displayFinanceOption();
	}

	if(purchaseFlag && leaseFlag)
	{
      $('baseMsrpSection1').style.display="none";
	  $('baseMsrpSection2').style.display="none";
	}


	//display payment estimator objects
	//$('mainFinanceData').style.display = 'block';
	//$('mainFinanceData').style.visibility = 'visible';
	//$('baseMsrpLabel').style.visibility = 'visible';
	$('baseMsrpLabel').style.display = 'block';
	//$('totalMsrpLabel').style.visibility = 'visible';
	//$('totalMsrpLabel').style.display = 'block';

	frameFixHeight();

	try {
			//if((typeof jLangEspanol) != 'undefined') {
			temp = getVehicle();
			if(isEspanol) {
				//$('rDL0').href = '/to' + 'ols/raq/espanol/' + DWRUtil.getText('vehicle').toLowerCase();
				$('rDL0').href = '/to' + 'ols/raq/espanol/' + temp + '?next=Estimator.RAQ.Link1'; //Added tagging
				//$('rDL1').href = '/to' + 'ols/raq/espanol/' + DWRUtil.getText('vehicle').toLowerCase();
				$('rDL1').href = '/to' + 'ols/raq/espanol/' + temp + '?next=Estimator.RAQ.Link1'; //Added tagging
			} else {
				var tempstring=DWRUtil.getText('vehicle').toLowerCase();
				var temp=removeSpaces(tempstring);
				if(tempstring=="sentra se-r") {
					var temp="se-r";
				}
				//$('rDL0').href = '/to' + 'ols/raq/' + DWRUtil.getText('vehicle').toLowerCase();
				$('rDL0').href = '/to' + 'ols/raq/' + temp + '?next=Estimator.RAQ.Link1'; //Added tagging
				//$('rDL1').href = '/to' + 'ols/raq/' + DWRUtil.getText('vehicle').toLowerCase();
				$('rDL1').href = '/to' + 'ols/raq/' + temp + '?next=Estimator.RAQ.Link1'; //Added tagging
			

			}
	} catch(e) {
	}
}

function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
		tstring += splitstring[i];
	return tstring;
}

function trim(str) {
	for(i=0;i<str.length;i++) {
		if(str[i]==" ") {
			str[i]="";
		}
	}
}

function getVehicle()
{
	var tempstring=DWRUtil.getText('vehicle').toLowerCase();
	var temp=removeSpaces(tempstring);
	if(tempstring=="sentra se-r") {
		var temp="se-r";
	}
	return temp;
}
// ############################ LOAN FUNCTIONS #################################

// ###	Assigns onblur and onchange events of various Loan form elements on the
//		page to appropriate event handlers. This wiring creates automatic value
//		updates to the estimatorData object.
function assignLoanEventHandlers () {
	//alert("assignLoanEventHandlers");
	var loanObj = estData.getLoanDataObj();
	var apr2=0;
	$('txtPurchaseEstimatedSellingPrice').onblur = function () {
		loanObj.setEstimatedSellingPrice( $('txtPurchaseEstimatedSellingPrice').value );
		updateMonthlyLoanPayment();
	}

 	$('drpPurchaseMonths').onchange = function () {
		loanObj.setTerm( $('drpPurchaseMonths').value );
		//calculateAPR($('drpPurchaseMonths').value);
		var apr= getAprForTerm(newDataArray, $('drpPurchaseMonths').value,'apr');
		apr2=apr;
		loanObj.setApr(apr);
		updateMonthlyLoanPayment();
		/*displayLoanData();
		submitBtnClicked();*/
	}
	/*$('txtCostOfAccessories').onblur= function (){
		loanObj.setCostOfAccessories($('txtCostOfAccessories').value );
		updateMonthlyLoanPayment();
	}
	/*$('txtPurchaseDownPayment').onblur = function () {
		loanObj.setDownPayment( $('txtPurchaseDownPayment').value );
		updateMonthlyLoanPayment();
	}
	$('txtPurchaseTradein').onblur = function () {
		loanObj.setTradeIn( $('txtPurchaseTradein').value );
		updateMonthlyLoanPayment();
	}*/
	
	$('txtAPR').onload = function () {
		//loanObj.setApr( $('txtAPR').innerHTML );
		loanObj.setApr(apr2);
		updateMonthlyLoanPayment();
	}
}

// ###	Populates page with loan values
function displayLoanData() {
	//alert("displayLoanData");
	//$('zipCodeErr').style.display="none";
	
	var loanObj = estData.getLoanDataObj();
	//Populate form fields with data
	$('txtPurchaseEstimatedSellingPrice').value = loanObj.getEstimatedSellingPrice();
	estUtils.setSelectValue('drpPurchaseMonths',loanObj.getTerm());
	
	if (loanObj.getSAprFlag() ==true) //if 
	{
		$('txtAPR').innerHTML=Math.round((parseFloat(loanObj.getApr())+1)*Math.pow(10,2))/Math.pow(10,2)+ "%"; //We are rounding the decimal point to 2
	}
	else
	{
        	$('txtAPR').innerHTML=Math.round((parseFloat(loanObj.getApr()))*Math.pow(10,2))/Math.pow(10,2)+ "%";
	}
	/*$('txtCostOfAccessories').value = loanObj.getCostOfAccessories();
    $('txtPurchaseDownPayment').value = loanObj.getDownPayment();
	$('txtPurchaseTradein').value = loanObj.getTradeIn();
	$('txtOwedTradein').value = loanObj.getOwedTradeIn();
	//$('txtAPR').value = loanObj.getApr();*/
	$('txtCostOfAccessories').value = costofaccess;
    $('txtPurchaseDownPayment').value = downpayment;
	$('txtPurchaseTradein').value = tradein;
	$('txtOwedTradein').value = owedontrade;
	

       //Display loan payment value
	updateMonthlyLoanPayment();
}


// ## Amount Financed

// LEGACY: Rounds values to 2 decimal places and adds a zero to ensure well rounded cents (ex: $34.80 instead of $34.8)
	function roundValue(number){
	    number = Math.round(number*100)/100;
		return (number == Math.floor(number)) ? number + '.00' : ((number*10 == Math.floor(number*10)) ? number + '0' : number);
	}

// LEGACY: Converts any number ie. 999999 to a dollar value of $999,999 or 999.00 to a dollar value of $999.00.
	function convertToDollar(numValue){
		var signValue = "";
		var intNumberValue = parseFloat(numValue);
		if(intNumberValue < 0) signValue = "-";
		//var strNumberValue = roundValue(Math.abs(intNumberValue)) + ' ';
		var strNumberValue = Math.abs(intNumberValue) + ' ';
		strNumberValue = strNumberValue.substring(0,strNumberValue.length - 1)
		var numLength = strNumberValue.length;
		/*if (strNumberValue.length > 6)
			strNumberValue = "$" + strNumberValue.slice(0,numLength-6) + "," + strNumberValue.slice(numLength-6,numLength)*/
		if (strNumberValue.length > 3)
			strNumberValue = "$" + strNumberValue.slice(0,numLength-3) + "," + strNumberValue.slice(numLength-3,numLength)
		else
			strNumberValue = "$" + strNumberValue.slice(0,numLength)
		return (signValue + strNumberValue);
	}



// ###	Checks to see if the monthly loan payment is valid. If any of the loan
//		form values are invalid, it displays an error. Otherwise it shows the
//		loan payment value on the page.
function updateMonthlyLoanPayment () {
	//alert("updateMonthlyLoanPayment");
	var paymentObj = estData.getLoanDataObj().getMonthlyLoanPaymentObj();
       var loanObj = estData.getLoanDataObj();
	   //alert("Cost Of Accessories()"+loanObj.getCostOfAccessories());
       var amtfinancedObj= (loanObj.getEstimatedSellingPrice() + parseInt(loanObj.getCostOfAccessories())) - (loanObj.getDownPayment()) - (parseInt(loanObj.getTradeIn())) + (parseInt(loanObj.getOwedTradeIn())) ;
	  	
		

          setHtml('baseMsrp2', convertToDollar(amtfinancedObj)); //added on 6/26
		setHtml( 'baseMsrp1', estData.getBaseMSRP(1));
	setHtml('purchaseErrorMsg', '' ); //reset error message;
	if ( paymentObj.getIsError() ) {
		rptMgt.doReset(); //Reset any data collected (like tradein value) that could have caused the error
		setHtml('purchaseErrorMsg', paymentObj.getErrorMsg() );
		document.getElementById('purchaseTable').style.top= 10;
	} else {
		rptMgt.setPurchasePay( paymentObj.getPaymentValue(1) );	//set the purchase price for reporting
		rptMgt.fireReport();									//fire off report
		document.getElementById('purchaseTable').style.top= 10;

		jQuery('#purchaseTable>div').css('display','block');
		$('purchaseTermDiv').style.paddingTop = "34px";
		$('purchaseLinks').style.display = "block";
	    $('purchaseLinks1').style.display = "none";

		setHtml('txtPurchaseMonthlyPayment', paymentObj.getPaymentValue(1) );
		if(isEspanol)
		{
			$('txtPurchaseMonthlyPayment').innerHTML+="<font style='font-size:12px'> al mes&#8224;</font>";
		}
		else
		{
			$('txtPurchaseMonthlyPayment').innerHTML+="<font style='font-size:12px'> per month&#8224;</font>";
		}
        setHtml('txtAmountFinanced', convertToDollar(amtfinancedObj));
		
		
	    if (loanObj.getSAprFlag() ==true)
		{
        	$('txtAPR').innerHTML=Math.round((parseFloat(loanObj.getApr())+1)*Math.pow(10,2))/Math.pow(10,2)+ "%"; //rounding to 2decimals
		}
	   else
		{
        	$('txtAPR').innerHTML=Math.round((parseFloat(loanObj.getApr()))*Math.pow(10,2))/Math.pow(10,2)+ "%";
		}
		setHtml( 'baseMsrp1', estData.getBaseMSRP(1));
		setHtml( 'baseMsrp2', paymentObj.getAmtFinanced(1));
		setHtml( 'baseMsrp3', paymentObj.getAmtFinanced(1));
	}
	//Supressing $000.00
	displayFinanceOption();
}

// ############################ LEASE FUNCTIONS #################################

// ###	Assigns onblur and onchange events of various Lease form elements on the
//		page to appropriate event handlers. This wiring creates automatic value
//		updates to the estimatorData object.
function assignLeaseEventHandlers () {
	//alert("assignLeaseEventHandlers");
	var leaseObj = estData.getLeaseDataObj();
	var loanObj = estData.getLoanDataObj();
	
	$('txtLeaseEstimatedSellingPrice').onblur = function () {
		leaseObj.setEstimatedSellingPrice( $('txtLeaseEstimatedSellingPrice').value );
		updateMonthlyLeasePayment();
	}
	$('drpLeaseMonths').onchange = function () {
		leaseObj.setTerm( $('drpLeaseMonths').value )
		updateMonthlyLeasePayment();
		//$('txtAmountFinanced').value = ((loanObj.getEstimatedSellingPrice())-(loanObj.getDownPayment()+loanObj.getTradeIn()) );
		$('txtAmountFinanced').value = ((leaseObj.getEstimatedSellingPrice()+ leaseObj.getCostOfAccessories())-(leaseObj.getDownPayment()+leaseObj.getTradeIn()) );
	}
	$('txtCostOfAccessories').onblur= function (){
		if($('txtCostOfAccessories').value=="")
		{
			$('txtCostOfAccessories').value = "0";
		}
		leaseObj.setCostOfAccessories($('txtCostOfAccessories').value );
		updateMonthlyLeasePayment();
		loanObj.setCostOfAccessories($('txtCostOfAccessories').value );
		updateMonthlyLoanPayment();
		costofaccess = leaseObj.getCostOfAccessories();
	}
	$('txtPurchaseDownPayment').onblur = function () {
		if($('txtPurchaseDownPayment').value=="")
		{
			$('txtPurchaseDownPayment').value= "0";
		}
		leaseObj.setDownPayment( $('txtPurchaseDownPayment').value );
		updateMonthlyLeasePayment();
		loanObj.setDownPayment( $('txtPurchaseDownPayment').value );
		updateMonthlyLoanPayment();
		downpayment = leaseObj.getDownPayment();
	}
	$('txtPurchaseTradein').onblur = function () {
		if($('txtPurchaseTradein').value=="")
		{
			$('txtPurchaseTradein').value= "0";
		}
		leaseObj.setTradeIn( $('txtPurchaseTradein').value );
		updateMonthlyLeasePayment();
		loanObj.setTradeIn( $('txtPurchaseTradein').value );
		updateMonthlyLoanPayment();
		tradein = leaseObj.getTradeIn();
	}
	$('txtOwedTradein').onblur= function (){
		if($('txtOwedTradein').value=="")
		{
			$('txtOwedTradein').value = "0";
		}
		leaseObj.setOwedTradeIn($('txtOwedTradein').value );
		updateMonthlyLeasePayment();
		loanObj.setOwedTradeIn($('txtOwedTradein').value );
		updateMonthlyLoanPayment();
		owedontrade = leaseObj.getOwedTradeIn();
	}
	$('drpLeaseMileage').onchange = function () {
		leaseObj.setMileageCode( $('drpLeaseMileage').value );
		updateMonthlyLeasePayment();
	}
	$('txtPurchaseDownPayment').onkeypress = function(e) {
		var n = (window.event)?event.keyCode:e.which;
		if(n==13)
		{
			leaseObj.setDownPayment( $('txtPurchaseDownPayment').value );
			updateMonthlyLeasePayment();
			loanObj.setDownPayment( $('txtPurchaseDownPayment').value );
			updateMonthlyLoanPayment();
			changeFocus(this);
		}
		else if(n!=8 && n!=0 &&(n<48 || n>57))
		{
			return false;
		}
	}
	$('txtPurchaseTradein').onkeypress = function(e) {
		var n = (window.event)?event.keyCode:e.which;
		if(n==13)
		{
			leaseObj.setTradeIn( $('txtPurchaseTradein').value );
			updateMonthlyLeasePayment();
			loanObj.setTradeIn( $('txtPurchaseTradein').value );
			updateMonthlyLoanPayment();
			changeFocus(this);
		}
		else if(n!=8 && n!=0 &&(n<48 || n>57))
		{
			return false;
		}
	}
	$('txtOwedTradein').onkeypress= function(e){
		var n = (window.event)?event.keyCode:e.which;
		if(n==13)
		{
			leaseObj.setOwedTradeIn($('txtOwedTradein').value );
			updateMonthlyLeasePayment();
			loanObj.setOwedTradeIn($('txtOwedTradein').value );
			updateMonthlyLoanPayment();
			changeFocus(this);
		}
		else if(n!=8 && n!=0 &&(n<48 || n>57))
		{
			return false;
		}
	}
	$('txtCostOfAccessories').onkeypress= function(e){
		var n = (window.event)?event.keyCode:e.which;
		if(n==13)
		{
			leaseObj.setCostOfAccessories($('txtCostOfAccessories').value );
			updateMonthlyLeasePayment();
			loanObj.setCostOfAccessories($('txtCostOfAccessories').value );
			updateMonthlyLoanPayment();
			changeFocus(this);
		}
		else if(n!=8 && n!=0 &&(n<48 || n>57))
		{
			return false;
		}
	}

	$('txtCostOfAccessories').onfocus= function (){
		if($('txtCostOfAccessories').value=="0")
		{
			$('txtCostOfAccessories').value = "";
		}
	}
	$('txtPurchaseDownPayment').onfocus = function () {
		if($('txtPurchaseDownPayment').value=="0")
		{
			$('txtPurchaseDownPayment').value="";
		}
	}
	$('txtPurchaseTradein').onfocus = function () {
		if($('txtPurchaseTradein').value=="0")
		{
			$('txtPurchaseTradein').value="";
		}
	}
	$('txtOwedTradein').onfocus= function (){
		if($('txtOwedTradein').value=="0")
		{
			$('txtOwedTradein').value="";
		}
	}

}

function changeFocus(obj)
{
	//alert("obj id: "+obj.id);
	id = obj.id;
	switch(id)
	{
		case 'txtPurchaseDownPayment': $('txtPurchaseTradein').focus();break;
		case 'txtPurchaseTradein': $('txtOwedTradein').focus();break;
		case 'txtOwedTradein': $('txtCostOfAccessories').focus();break;
		case 'txtCostOfAccessories': break;
	}
}

// ###	Populates page with loan values
function displayLeaseData() {
	//alert("displayLeaseData");
	//$('zipCodeErr').style.display="none";

	var leaseObj = estData.getLeaseDataObj();
	//Populate form fields with data
	$('txtLeaseEstimatedSellingPrice').value = leaseObj.getEstimatedSellingPrice();
	
	
	/* MY removed to order the dropdown by frontend
	estUtils.setSelectOptions(	'drpLeaseMonths',
								estUtils.getTermsForMileageCode( leaseObj.getMileageCode(), estData.getLeaseDataList() ) );
	*/
	
	estUtils.setSelectValue('drpLeaseMonths',leaseObj.getTerm());
	
	
	/*$('txtPurchaseDownPayment').value = leaseObj.getDownPayment();
	$('txtPurchaseTradein').value = leaseObj.getTradeIn();*/

	$('txtCostOfAccessories').value = costofaccess;
    $('txtPurchaseDownPayment').value = downpayment;
	$('txtPurchaseTradein').value = tradein;
	$('txtOwedTradein').value = owedontrade;

	
	estUtils.setSelectValue('drpLeaseMileage',leaseObj.getMileageCode());

	//Display lease payment values
	updateMonthlyLeasePayment();
       //alert('done lease display');
}

// ###	Checks to see if the monthly lease payments are valid. If any of the lease
//		form values are invalid, it displays an error. Otherwise it shows the
//		lease payment values on the page.
function updateMonthlyLeasePayment () {
	//alert("updateMonthlyLeasePayment");
	var paymentObj = estData.getLeaseDataObj().getMonthlyLeasePaymentObj();
       var leaseObj = estData.getLeaseDataObj();
       var acquisitionFee = 595;
       var capCost = parseInt(leaseObj.getEstimatedSellingPrice()) + acquisitionFee;
       var amtfinancedObj= (leaseObj.getEstimatedSellingPrice() + leaseObj.getCostOfAccessories()) - ( leaseObj.getDownPayment() - leaseObj.getTradeIn() + leaseObj.getOwedTradeIn() ) ;


	setHtml('leaseErrorMsg', '' ); //reset error message;

	if ( paymentObj.getIsError() ) {
		//alert("in lease: "+ paymentObj.getErrorMsg());
		rptMgt.doReset(); //Reset any data collected (like tradein value) that could have caused the error
		setHtml('leaseErrorMsg', paymentObj.getErrorMsg() );
	} else {

			jQuery('#leaseTable>div').css('display','block');
			$('leaseLinks').style.display = "block";
		    $('leaseLinks1').style.display = "none";

		rptMgt.setLeasePay( paymentObj.getPaymentValue(1) );	//set the lease price for reporting
		rptMgt.fireReport();									//fire off report

		setHtml('leLoanPayment', paymentObj.getPaymentValue(1) );
		if(isEspanol)
		{
			$('leLoanPayment').innerHTML+="<font style='font-size:12px'>  al mes&#8224;</font>";
		}
		else
		{
			$('leLoanPayment').innerHTML+="<font style='font-size:12px'>  per month&#8224;</font>";
		}
		setHtml('leAdjCap', paymentObj.getAdjustedCapCost(1) );
	//	setHtml('leSecurityDeposit', paymentObj.getSecurityDeposite(1) );
		setHtml('leFirstPayment', paymentObj.getFirstPayment(1) );
		setHtml('leCapCost', convertToDollar(capCost)  );

               //object call
 	        //setHtml('leAcquisitionFee', paymentObj.getAcquisitionFee(1) );

		setHtml('leAcquisitionFee', convertToDollar(acquisitionFee) );

		setHtml('leCapCostReduction', paymentObj.getCapCostReduction(1) );
		setHtml('leCapCostReduction1', paymentObj.getCapCostReduction(1) );
		setHtml('leTotalDueSigning', paymentObj.getTotalDue(1) );
		setHtml( 'baseMsrp4', paymentObj.getAmtFinanced(1));

	}
	//Supressing $000.00
	displayFinanceOption();
  //alert('done');
}

// ### manage debug mode
try {
if ( location.search.toLowerCase().indexOf("pedebug=on") != -1 ) {
		crmDeleteCookie('peDebugCookie','/',location.hostname);
		crmSetCookie('peDebugCookie',1,'','/',location.hostname);
		debugMode = true;
} else if ( location.search.toLowerCase().indexOf("pedebug=off") != -1 ) {
		crmDeleteCookie('peDebugCookie','/',location.hostname);
		debugMode = false;
} else {
		if ( crmGetCookie('peDebugCookie') == 1 )
			debugMode = true;
		else
			debugMode = false;
}
} catch(e) {
    debugMode = false;
}

//debugMode = true;

if(!debugMode) DWREngine.setErrorHandler(function(e) { 
												  
												  //alert(GENERAL_ERROR); 
												  
												  });

/* --------------------------------------------------------------------------------------------------------------------------------*/