// JavaScript Document
//This function rounds numbers to the nearest 10,000
function roundAccuracy(num, accuracy){
var factor=Math.pow(10,-4);
return Math.round(num*factor)/factor;
}
// This function formats numbers by adding commas
function numberFormat(nStr,prefix){
    var prefix = prefix || '';
    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 prefix + x1 + x2;
}

// This function calculates Monthly Payment and Additional Allowable Debt ranges, then calculates Principal (loan amount) from those figures at the desired interest rate for a term of 30 years
function calc()
{
document.forms[0].payment_low.value=(Math.round([document.forms[0].income.value*0.30]*100)/100).toFixed(2);
document.forms[0].payment_high.value=(Math.round([document.forms[0].income.value*0.33]*100)/100).toFixed(2);

document.forms[0].debt_low.value=(Math.round([document.forms[0].income.value*0.13]*100)/100).toFixed(2);
document.forms[0].debt_high.value=(Math.round([document.forms[0].income.value*0.12]*100)/100).toFixed(2);

R = document.forms[0].interest.value/100;

i = R/12;

N = 360; // Term in months

// Next two variables are monthly payments subtracted by 21.5% (for tax and insurance)
M1 = document.forms[0].payment_low.value-(document.forms[0].payment_low.value*0.215);

M2 = document.forms[0].payment_high.value-(document.forms[0].payment_high.value*0.215);

numerator1=M1*(Math.pow([1+i],N)-1);
numerator2=M2*(Math.pow([1+i],N)-1);
denominator=i*Math.pow([1+i],N);

document.forms[0].price_low.value=numberFormat(roundAccuracy(Math.round(numerator1/denominator).toFixed(2)));
document.forms[0].price_high.value=numberFormat(roundAccuracy(Math.round(numerator2/denominator).toFixed(2)));
}