function executeMC(){
  validate();
}

function checkForZero(field) {
  if (field.value == 0 || field.value.length == 0) {
    alert ("This field can't be 0!");
    field.focus(); 
  } else {
    calculatePayment(field.form);
  }
}
function validate(){
  // straight to calculation (?)
  calculatePayment();
}

function validateLegit(form) {
  if (form.price.value == 0 || form.price.value.length == 0) {
    alert ("The Price field can't be 0!");
    form.price.focus(); 
  } else if (form.ir.value == 0 || form.ir.value.length == 0) {
    alert ("The Interest Rate field can't be 0!");
    form.ir.focus(); 
  } else if (form.term.value == 0 || form.term.value.length == 0) {
    alert ("The Term field can't be 0!");
    form.term.focus(); 
  } else {
    calculatePayment(form);
  }
}

function calculatePayment(form){
  /*
  // found the following formula here: http://www.hughchou.org/calc/formula.html  
  M = P * ( J / (1 - (1 + J) ** -N))
  
  P = principal, the initial amount of the loan
  I = the annual interest rate (from 1 to 100 percent)
  L = length, the length (in years) of the loan, or at least the length over which the loan is amortized.
  The following assumes a typical conventional loan where the interest is compounded monthly. First I will define two more variables to make the calculations easier:
  
  J = monthly interest in decimal form = I / (12 x 100)
  N = number of months over which loan is amortized = L x 12
  */
  var amount = getVal('#amount');
  var downPayment = getVal('#down-payment');

  var p = amount - downPayment; // principal amount of loan
  var i = getVal('#rate'); // annual interest rate
  var l = getVal('#term'); // length (in years) of the loan
  var j = i / (12 * 100); // monthly interest, in decimal form
  var n = 12 * l; // the number of months over which loan is amortized

  var pmt = p * (j / (1 - Math.pow((1 + j), -n)));
  
  var cc = getVal('#common-charges');
  var taxes = getVal('#taxes');
  var result = pmt + cc + taxes;
  
  $('#result').show();
  $('#result-field').html(formatCurrency(result));
}

function getVal(dom_id){
  try {
    var val = $(dom_id).val();
    val = val.split('$').join('');
    return parseFloat(val);	
  } catch(ex) {
    return 0;
  }
}

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 (((sign)?'':'-') + '$' + num + '.' + cents);
}


$(document).ready(function(){
  $('#mcSubmit').click(function(){
    executeMC();
  });
  executeMC();
});