// this flag is set to false when the user breaks the dependency between the left and right columns by manually changing a field on the right
var sync_flag = true;
var calculatingFromField = false;
var calculatingFromButton = false;
if(!micrositeParam) var micrositeParam=false;

function syncValues() {
  with(document.calculator) {
    cb_vprice.value = cb_vprice.value.replace(/,/g, "");
    cb_tradein.value = cb_tradein.value.replace(/,/g, "");
    cb_downpayment.value = cb_downpayment.value.replace(/,/g, "");
    cb_rebate.value = cb_rebate.value.replace(/,/g, "");
    if (lif_vprice.value != cb_vprice.value && sync_flag) lif_vprice.value = cb_vprice.value;
    if (lif_tradein.value != cb_tradein.value && sync_flag) lif_tradein.value = cb_tradein.value;
    if (lif_downpayment.value != cb_downpayment.value && sync_flag) lif_downpayment.value = cb_downpayment.value;
    if (lif_tax.value != cb_tax.value && sync_flag) lif_tax.value = cb_tax.value;
    if (lif_apr.value == "") lif_apr.value = cb_apr.value;
    if (lif_term.value == "") lif_term.value = cb_term.value;
  }
}

// PARAMS: field - The field that has triggered the call to calculate(). The Calculate button does not pass in anything.
function calculate(field) {
  var calcFrom;

  if (!field && calculatingFromField) {
    return false; // already calculating
  } else {
    calcFrom = "Button";
  }

  if (field && calculatingFromButton) {
    return false; // already calculating
  } else {
    calcFrom = "Field";
  }

  eval("calculatingFrom" + calcFrom + " = true"); // set currently calculating flag

  if (field) { // if a field has triggered the calculation, check that field first
    cleanUpField(field); // The Calculate button does not pass in a field (i.e. it calls calculate() with no params)
    if (checkErrorIncentives(field)) {
      eval("calculatingFrom" + calcFrom + " = false"); // about to exit
      return false; // don't calculate on error
    }
  }

  if (field) { // sync or break sync
    switch (field.name) {
      case "cb_vprice": case "cb_downpayment": case "cb_tradein": case "cb_tax":
        syncValues(); // sync left to right
        break;
      case "lif_vprice": case "lif_downpayment": case "lif_tradein": case "lif_tax":
        breakSync(); // break synching relationship
        break;
    }
  }

  var limit = document.calculator.elements.length;
  for (var i = 0; i < limit; i++) { // Check all fields for errors
    if (checkErrorIncentives(document.calculator.elements[i])) { // if there is an error
      eval("calculatingFrom" + calcFrom + " = false"); // about to exit
      return false; // don't calculate on error
    }
  }

  with(document.calculator) {

    var calcFields = new Array(cb_vprice.value,cb_tradein.value,cb_downpayment.value,cb_rebate.value,cb_apr.value,cb_term.value,cb_tax.value);
    for (i = 0; i < calcFields.length; i++) {
      if (isNaN(calcFields[i]) == true) {
              alert("\"" + calcFields[i]+"\"" + " is not a valid number");
        eval("calculatingFrom" + calcFrom + " = false"); // about to exit
        return false;
            }
    }

    var totalaftertax_cb = parseFloat(cb_vprice.value) * cb_tax.value / 100 + parseFloat(cb_vprice.value);
    var totalaftertax_lif = parseFloat(lif_vprice.value) * lif_tax.value / 100 + parseFloat(lif_vprice.value);
    var totalafterdiscounts_cb = totalaftertax_cb - parseFloat(cb_tradein.value) -
                                 parseFloat(cb_downpayment.value) - parseFloat(cb_rebate.value);
    var totalafterdiscounts_lif = totalaftertax_lif - parseFloat(lif_tradein.value) -
                                  parseFloat(lif_downpayment.value) - parseFloat(lif_rebate.value);
    var totalfinanced_cb = 0;
    var totalfinanced_lif = 0;
    var totalcost_cb = 0;
    var totalcost_lif = 0;

    var i_cb = parseFloat(cb_apr.value / 1200);
    var i_lif = parseFloat(lif_apr.value / 1200);
    var n_cb = parseFloat(cb_term.value);
    var n_lif = parseFloat(lif_term.value);

    if (i_cb > 0) {
      var monthly_cb = totalafterdiscounts_cb * (i_cb / (1 - (1 / Math.pow(1 + i_cb,n_cb))));
    } else{
      var monthly_cb = totalafterdiscounts_cb / cb_term.value;
    }

    if (i_lif > 0) {
      var monthly_lif = totalafterdiscounts_lif * (i_lif / (1 - (1 / Math.pow(1 + i_lif,n_lif))));
    } else{
      var monthly_lif = totalafterdiscounts_lif / lif_term.value;
    }
    document.getElementById('monthly_cb_div').innerHTML = setDecPlaces(monthly_cb.toString(), 2, true);
    document.getElementById('monthly_lif_div').innerHTML = setDecPlaces(monthly_lif.toString(), 2, true);

    totalfinanced_cb = monthly_cb * cb_term.value;
    totalfinanced_lif = monthly_lif * lif_term.value;

    totalcost_cb = Math.round( monthly_cb * parseFloat(cb_term.value) +
                               parseFloat(cb_tradein.value) + parseFloat(cb_downpayment.value) );
    totalcost_lif = Math.round( monthly_lif * parseFloat(lif_term.value) +
                               parseFloat(lif_tradein.value) + parseFloat(lif_downpayment.value) );

    document.getElementById('totalcost_cb_div').innerHTML = setDecPlaces(totalcost_cb.toString(), 0);
    document.getElementById('totalcost_lif_div').innerHTML = setDecPlaces(totalcost_lif.toString(), 0);
  }//end with()
}//end function

function showBB() {
  bbWin = window.open("http://ads.cars.com/adentry/pricing/choose_mym.jhtml","bbpop","width=330,height=500,left=100,top=100");
  bbWin.focus();
}

function resetAll() {
  document.forms.calculator.reset();
  document.calculator.cb_vprice.select();
  document.calculator.cb_vprice.focus();
  document.getElementById('totalcost_cb_div').innerHTML = "0";
  document.getElementById('totalcost_lif_div').innerHTML = "0";
  document.getElementById('monthly_cb_div').innerHTML = "0";
  document.getElementById('monthly_lif_div').innerHTML = "0";
  sync_flag = true; // resync columns
  return false; // prevents onClick="return resetAll()" from reloading page
}

function breakSync() {
  sync_flag = false;
}

function popUp(URL) {
  day = new Date();
  id = day.getTime();
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=480,height=500');");
}

// Returns URL with calc values as params - different for each calculator
function makeURL(path) {
  with (document.forms[0]) {
    path += "?vpLoan=" + cb_vprice.value + "&tvLoan=" + cb_tradein.value + "&stLoan=" + cb_tax.value;
  }
  try {
        if(opener.micrositeParam) {
        path += "&microsite=" + opener.micrositeParam
        }
    }
    catch (exception){
      path += "&microsite=" + micrositeParam;
  }
  return path;
}

// Set the VP from the URL and select it
function initPage() {
  with (document.calculator) {
    cb_vprice.value = NaNToZero(vpLoanParam);
    cb_tradein.value = NaNToZero(tvLoanParam);
    cb_tax.value = NaNToZero(stLoanParam);
    cb_rebate.value = NaNToZero(cb_rebate.value);
    lif_vprice.value = NaNToZero(vpLoanParam);
    lif_tradein.value = NaNToZero(tvLoanParam);
    lif_tax.value = NaNToZero(stLoanParam);
    lif_rebate.value = NaNToZero(lif_rebate.value);
    cb_vprice.select();
    cb_vprice.focus();
  }
}

// Helper function to pass in calculator-specific fields to checkError(), which is calculator-independent.
// Incentives-specific. Requires a field whose name begins with "cb_" or "lif_"
function checkErrorIncentives(field) {

  var prefix = "document.calculator." + field.name.substring(0, field.name.indexOf("_")+1); // "document.calculator.cb_" or "...lif_"
  var suffix = field.name.substring(field.name.indexOf("_")+1, field.name.length); // "vprice" or "tradein" etc...
//  var f = document.calculator; // f points to the form
//  with (document.calculator) {
  switch (suffix) {
    case "vprice":
      if (checkError(field, "vp", eval(prefix + "downpayment.value"), eval(prefix + "tradein.value"),
          eval(prefix + "rebate.value"))) {
        return true;
      }
      break;
    case "downpayment":
      if (checkError(field, "dp", eval(prefix + "vprice.value"), eval(prefix + "tradein.value"),
          eval(prefix + "rebate.value"))) {
        return true;
      }
      break;
    case "tradein":
      if (checkError(field, "tv", eval(prefix + "vprice.value"), eval(prefix + "downpayment.value"),
          eval(prefix + "rebate.value"))) {
        return true;
      }
      break;
    case "tax":
      if (checkError(field, "stPer")) {
        return true;
      }
      break;
    case "rebate":
      if (checkError(field, "rebate", eval(prefix + "vprice.value"), eval(prefix + "downpayment.value"),
          eval(prefix + "tradein.value"))) {
        return true;
      }
      break;
    case "apr":
      if (checkError(field, "rate")) {
        return true;
      }
      break;
    case "term":
      if (checkError(field, "term")) {
        return true;
      }
    break;
  }
}
