var isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
var ie    = (document.all) ? true : false;
var ns4   = (document.layers) ? true : false;
var ns6   = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;
var iens6 = document.all||document.getElementById;

// JavaScript Document
function writeTotalFinanceAmount(tmpVal) {
   layerWrite('divtotfinamount', 'pdivtotfinamount', tmpVal,tmpVal);
   if(ns4) document.pdivtotfinamount.document.divtotfinamount.left = getNumberAlignment(tmpVal);
}

function writeMonthlyPayAmount(tmpVal) {
   layerWrite('divmonpayamount', 'pdivmonpayamount', '<font class="bodytext-header2-alt"><b>$'+tmpVal+'</b></font>',tmpVal);
   if(ns4) document.pdivmonpayamount.document.divmonpayamount.left = getNumberAlignment(tmpVal);
}

function doPriceSubmit() {
   f = document.calculator;
   fprice   = document.priceForm;
   ffee     = document.feeForm;
   tmpval = new Number(clean_number(fprice.price.value));
   if ( isNaN(tmpval) || tmpval < 0 )
   {
      alert("Please enter a valid vehicle sales price value.");
      return false;
   }
   tmpval = new Number(clean_number(fprice.taxrate.value));
   if ( isNaN(tmpval) || tmpval < 0 )
   {
      alert("Please enter a valid sales tax percentage value.");
      return false;
   }
   var carprice   = new Number(clean_number(fprice.price.value));
   // tax amount
   fprice.taxamount.value = formattedInt(Math.round(getTaxAmount(carprice, tmpval)));
   // fee
   var fee  = getFee(carprice);
   ffee.fee.value = formattedInt(Math.round(fee));
   // Set result to 0 if price is 0
   if(carprice == 0) {
      writeTotalFinanceAmount('$0');
      var monPay = 0.0001;
      writeMonthlyPayAmount(monPay);
   }
   //process();
}
function doTaxSubmit(isPercent) {
   fprice   = document.priceForm;
   var carprice = new Number(clean_number(fprice.price.value));
   if ( isNaN(carprice) || carprice < 0 )
   {
      alert("Please enter a valid vehicle sales price value.");
      return false;
   }
   if(isPercent == 'true') {
      var vtax = new Number(clean_number(fprice.taxrate.value));
      if ( isNaN(vtax) || vtax < 0 )
      {
         alert("Please enter a valid vehicle sales tax value.");
         return false;
      }
      fprice.taxamount.value = formattedInt(Math.round(getTaxAmount(carprice, vtax)));
   }
   else {
      var vtaxmount = new Number(clean_number(fprice.taxamount.value));
      if ( isNaN(vtaxmount) || vtaxmount < 0 )
      {
         alert("Please enter a valid vehicle sales tax amount.");
         return false;
      }
      fprice.taxrate.value = formattedDouble(getTaxRate(carprice, vtaxmount));
   }
}
function doFinanceRateSubmit() {
   document.calculator.userfinancerate.value = document.financeForm.financerate.value;
}
function doFinanceTermSubmit() {
   document.calculator.userfinancemonthflag.value = "true";
}
function doOtherSubmit() {
   process();
}

function init() {
   f = document.calculator;
   fprice   = document.priceForm;
   ffee     = document.feeForm;
   fcredit  = document.creditForm;
   tmpval = new Number(clean_number(fprice.price.value));
   if ( isNaN(tmpval) || tmpval < 0 )
   {
      alert("Please enter a valid vehicle sales price value.");
      return false;
   }
   if(tmpval == 0) {
      writeTotalFinanceAmount('$0');
      var monPay = 0.0001;
      writeMonthlyPayAmount(0);
      return;
   }
   else { // reformat price
      fprice.price.value = formattedInt(Math.round(tmpval));
   }
   var carprice = new Number(clean_number(fprice.price.value));
   var taxAmount = new Number(clean_number(fprice.taxamount.value));
   if(taxAmount == 0) {
      taxAmount  = getTaxAmount(carprice, clean_number(fprice.taxrate.value));
      fprice.taxamount.value = formattedInt(Math.round(taxAmount));
   }
   var fee  = new Number(clean_number(ffee.fee.value));
   if(fee == 0) {
      fee  = getFee(tmpval);
      ffee.fee.enabled = true;
      ffee.fee.value = formattedInt(Math.round(fee));
      
   }
   // ReFormat Tradein
   tmpval = new Number(clean_number(fcredit.tradein.value));
   if ( !isNaN(tmpval) || tmpval > 0 ) {
      fcredit.tradein.value = formattedInt(Math.round(tmpval));
   }
   tmpval = new Number(clean_number(fcredit.incentive.value));
   if ( !isNaN(tmpval) || tmpval > 0 ) {
      fcredit.incentive.value = formattedInt(Math.round(tmpval));
   }
   tmpval = new Number(clean_number(fcredit.downpayment.value));
   if ( !isNaN(tmpval) || tmpval > 0 ) {
      fcredit.downpayment.value = formattedInt(Math.round(tmpval));
   }
/*   tmpval = new Number(clean_number(fcredit.payoff.value));
   if ( !isNaN(tmpval) || tmpval > 0 ) {
      fcredit.payoff.value = formattedInt(Math.round(tmpval));
   } */
   process();
}

function process() {
   f = document.calculator;
   fprice = document.priceForm;
   ffinance = document.financeForm;
   
   if ( validateData() ) {
      calculate();
   }
}

function calculate() {
   f = document.calculator;
   fprice   = document.priceForm;
   ffee     = document.feeForm;
   fcredit  = document.creditForm;
   ffinance = document.financeForm;
   var taxAmount  = new Number(clean_number(fprice.taxamount.value));
   var totalCost  = 0;
   var totalFin   = 0;
   var monthlyPay = 0;
   var carprice   = new Number(clean_number(fprice.price.value));
   var fee        = new Number(clean_number(ffee.fee.value));
   var incentive = new Number(clean_number(fcredit.incentive.value));
   var down      = new Number(clean_number(fcredit.downpayment.value));
   var tradein   = new Number(clean_number(fcredit.tradein.value));
   var payoff    = 0;
   if(carprice != 0) {
       // total cost
       totalCost  = carprice + taxAmount + fee;
       totalFin   = totalCost - incentive - down - tradein + payoff;
       monthlyPay = getMonthlyPayment(totalFin, new Number(ffinance.financerate.value), new Number(ffinance.financemonth.value));
   }
   // Display data for new calculation
   writeTotalFinanceAmount('$'+formattedInt(Math.round(totalFin)));
   writeMonthlyPayAmount(formattedDouble(monthlyPay));
}
function calculateTotal() {
   f = document.calculator;
   fprice   = document.priceForm;
   ffee     = document.feeForm;
   fcredit  = document.creditForm;
   ffinance = document.financeForm;
   var taxAmount  = new Number(clean_number(fprice.taxamount.value));
   var totalCost  = 0;
   var totalFin   = 0;
   var monthlyPay = 0;
   var carprice   = new Number(clean_number(fprice.price.value));
   var fee        = new Number(clean_number(ffee.fee.value));
   var incentive = new Number(clean_number(fcredit.incentive.value));
   var down      = new Number(clean_number(fcredit.downpayment.value));
   var tradein   = new Number(clean_number(fcredit.tradein.value));
   var payoff    = 0;
   if(carprice != 0) {
       // total cost
       totalCost  = carprice + taxAmount + fee;
       totalFin   = totalCost - incentive - down - tradein + payoff;
       
   }
   // Display data for new calculation
   writeTotalFinanceAmount('$'+formattedInt(Math.round(totalFin)));
    
}
function matchData() {
   f        = document.calculator;
   fprice   = document.priceForm;
   ffee     = document.feeForm;
   fcredit  = document.creditForm;
   ffinance = document.financeForm;
   f.price.value   = fprice.price.value;
   f.taxrate.value = fprice.taxrate.value;
   f.taxamount.value = fprice.taxamount.value;
   f.fee.value     = ffee.fee.value;
   f.incentive.value    = fcredit.incentive.value;
   f.downpayment.value  = fcredit.downpayment.value;
   f.tradein.value      = fcredit.tradein.value;
 //  f.payoff.value       = fcredit.payoff.value;
   f.financerate.value  = ffinance.financerate.value;
   f.financemonth.value = ffinance.financemonth.value;
}
function validateData() {
    f = document.calculator;
    fprice   = document.priceForm;
    ffee     = document.feeForm;
    fcredit  = document.creditForm;
    ffinance = document.financeForm;
    var tmpval;

    tmpval = new Number(clean_number(fprice.price.value));
    if ( isNaN(tmpval) || tmpval <= 0 )
    {
        alert("Please enter a valid vehicle sales price value.");
        return false;
    }
    tmpval = new Number(clean_number(fprice.taxrate.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid sales tax percentage value.");
        return false;
    }

    tmpval = new Number(clean_number(ffee.fee.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid dealer fees value.");
        return false;
    }

    tmpval = new Number(clean_number(fcredit.incentive.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid cash incentive value.");
        return false;
    }

    tmpval = new Number(clean_number(fcredit.downpayment.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid down payment value.");
        return false;
    }

    tmpval = new Number(clean_number(fcredit.tradein.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid trade-in value.");
        return false;
    }
/*    tmpval = new Number(clean_number(fcredit.payoff.value));
    if ( isNaN(tmpval) || tmpval < 0 )
    {
        alert("Please enter a valid pay off value.");
        return false;
    }
*/	
    tmpval = new Number(clean_number(ffinance.financerate.value));
    if ( isNaN(tmpval) || tmpval < 0 || tmpval > 100)
    {
        alert("Please enter a valid finance rate value.");
        return false;
    }

    tmpval = new Number(clean_number(ffinance.financemonth.value));
    if ( isNaN(tmpval) || tmpval < 0  )
    {
        alert("Please enter a valid finance term value.");
        return false;
    }
  /*  else {
        if((document.calculator.userfinancerate.value == null || document.calculator.userfinancerate.value == '') &&
            document.calculator.userfinancemonthflag.value == "true"
        ) {
            ffinance.financerate.value = '';
            alert("Please enter the Market Finance Rate");
            return false;
        }
        else {
            return true;
        }
    } */
    return true;
}
function clean_number(num)
{
   num = num.toString().replace(/\$|\,/g,'');
   return num;
}
function formattedDouble(num){
   var index = 0, lastindex = 0;
   var res= "";
   var strNum = new String(num);
   var len = strNum.length;
   index = strNum.indexOf(".");
   if(len > 0) {
      if (index > 0) {
         lastindex = len - index -1;
         if (lastindex > 2)
            res = strNum.substring(0, index+3);
         else if(lastindex == 1) {
	    res = strNum + "0";
         }
         else
            res = strNum;
         return formattedFloat(res);
      }
      else
         return formattedInt(strNum);
   }
   else
      return res;
}

function formattedInt(num){
    var delim="", newNum="", curChr="";
    var strNum =  new String(num);
    var len = strNum.length;
    if(len == 0) return "0";
    for (var i=1; i<=len; i++) {
       delim = ""; curChr = strNum.substring(len-i,len-i+1);
       if ((i == 4 || i == 7 || i == 10 || i == 13) && curChr!="-"  )
          delim=",";
       newNum = curChr + delim + newNum;
    }
    return newNum;

}
function formattedFloat(num){
    var delim="", newNum="", curChr="";
    var strOrg =  new String(num);
    var len = strOrg.length;
    if(len == 0) return "0.00";
    index = strOrg.indexOf(".");
    var strNum = formattedInt(strOrg.substring(0,index));
    strDec = strOrg.substring(index);
    
    return strNum + strDec;
}

function getTaxAmount(amount, taxrate) {
   var taxmount = 0;
   if(amount == 0 || taxrate == 0)
      return 0;
   return (amount*taxrate/100);
}

function getTaxRate(amount, taxamount) {
   var taxmount = 0;
   if(amount == 0 || taxamount == 0)
      return 0;
   return (taxamount*100/amount);
}

function getFee(amount) {
   return amount*1.5/100;
}

function getMonthlyPayment(finAmount, finRate, finTerm) {
   if(finRate <= 0) return finAmount/finTerm;
   var finJ = finRate/1200;
   var monPay = finAmount * ( finJ/(1.0 - Math.pow((1.0+finJ),-finTerm)));
   return monPay;
}

function layerWrite(id, nestref, text, styleVal) {
   var t = styleVal;
   if (ns4) {
       var lyr = (nestref)? eval('document.'+nestref+'.document.'+id+'.document') : document.layers[id].document;
       lyr.open();
       lyr.write(text);
       lyr.close();
   }
   else {
      var crossobj = document.getElementById? document.getElementById(nestref) : document.all[nestref];
      crossobj.innerHTML = text;
	 
   }
   
}
