﻿

function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}






function setcalc(princ){
var newamount='';
for (var i = 0; i < princ.length; i++) {
var ch = princ.substring(i, i + 1)
if ((ch < "0" || "9" < ch) && ch != '.' && ch != ','&& ch != '$') {

}else{
newamount = newamount + ch
}
}
document.calc.principal.value=newamount;
computeForm();
}

function computeForm() {

if (document.calc.downpayment.value == null || document.calc.downpayment.value.length == 0)
document.calc.downpayment.value = 0;

if ((document.calc.interest.options[document.calc.interest.selectedIndex].value == null || document.calc.interest.options[document.calc.interest.selectedIndex].value.length == 0) ){
alert("You must choose an interest rate.");
return false;
}

if ((document.calc.payments.options[document.calc.payments.selectedIndex].value == null || document.calc.payments.options[document.calc.payments.selectedIndex].value.length == 0) ){
alert("You must choose number of months.");
return false;
}


if ((document.calc.principal.value == null || document.calc.principal.value.length == 0) ){
alert("You must choose an principal.");
return false;
}
amount = document.calc.principal.value
newamount = ""
for (var i = 0; i < amount.length; i++) {
var ch = amount.substring(i, i + 1)
if ((ch < "0" || "9" < ch) && ch != '.') {

}else{
newamount = newamount + ch
}
}

var i = document.calc.interest.options[document.calc.interest.options.selectedIndex].value;
if (i=="0.0"){

months =  document.calc.payments.options[document.calc.payments.options.selectedIndex].value;

returnpayment = newamount /months;
}else{

i=i/100;
i /= 12;

var pow = 1;
for (var j = 0; j < document.calc.payments.options[document.calc.payments.options.selectedIndex].value; j++)
pow = pow * (1 + i);

var returnpayment = ((eval(newamount) - document.calc.downpayment.value) * pow * i) / (pow - 1);
}
document.calc.calcresults.value = '$' + addCommas(Math.round(returnpayment));
return;
}
