// Define the default form values.
var defaultPrincipal = 0, defaultDown = 0, defaultRate = 6, defaultDuration = 15;

function cleanCurrency(n) { return parseFloat(n.toString().replace(/\$|\,/gi,'')); }
function cleanPercent(n)  { return parseFloat(n.toString().replace(/\%/gi,"")); }

function compute(form) {
  // Retrieve the form values.
  var principal = form.principal.value;
  var down      = form.downpayment.value;
  var rate      = form.rate.value;
  var duration  = form.duration.value;
  var payment   = 0;
  
  // Clean the numbers.
  principal = cleanCurrency(principal);
  down      = cleanCurrency(down);
  rate      = cleanPercent(rate);
  duration  = parseFloat(duration);
  
  // Set default values.
  if (isNaN(principal)) principal = defaultPrincipal;
  if (isNaN(down))      down      = defaultDown;
  if (isNaN(rate))      rate      = defaultRate;
  if (isNaN(duration))  duration  = defaultDuration;
  
  // Calculate the monthly payments.
  if (principal > 0) {
    monthlyInterest = rate / (1200); // (12 * 100) = 1,200
    durationMonths  = duration * 12;
    payment = (principal - down) * (monthlyInterest / (1 - Math.pow((1+monthlyInterest), -durationMonths)));
    payment = Math.round(payment * 100) / 100;
    
    // Assign the monthly payment.
    form.payment.value     = formatCurrency(payment);
  }
  
  // Assign the current values to the form, in the desired format.
  form.principal.value   = formatCurrency(principal);
  form.downpayment.value = formatCurrency(down);
  form.rate.value        = formatPercent(rate);
  form.duration.value    = duration;
}

function formatPercent(n) { return cleanPercent(n) + '%'; }


/***********************************************************
 * Function:  formatCurrency()
 * Original:  Cyanide_7 (leo7278@hotmail.com)
 * Web Site:  http://www7.ewebcity.com/cyanide7
 *
 * This funciton and many more are available free online at
 * The JavaScript Source!! http://javascript.internet.com
 ***********************************************************/
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);
return (((sign)?'':'-') + '$' + num);
}