var purchase_price = 0;
var down_payment = 0;
var down_payment_percent = 0;
var loan_amount = 0;
var income = 0; // monthly income
var debt = 0;
var back_end = 0.0;
var front_end = 0.0;

function get_dti() {
	RunSJ();

	income = window.document.prequal.m_inc.value;
	debt = window.document.prequal.m_ex.value;
	
	front_end = (Number(get_monthly_payment()) / (income/12))*100;
	back_end = ((Number(get_monthly_payment()) + Number(debt)) / (income/12))*100;
	
	window.document.prequal.analysis.value = String(front_end) + '% / ' + String(back_end) + '%';
	window.document.prequal.f_end.value = front_end;
	window.document.prequal.b_end.value = back_end;
}

function get_monthly_payment() {
 var m = 0;
 var principal = loan_amount; 
 var i_rate = (window.document.prequal.ir.value/10000);
 var term = window.document.prequal.term.value;
 var monthly_interest = i_rate/(12/100);
 var num_months = term * 12;
 
 // M = P * ( J / (1 - (1 + J) ** -N))
 
 m = principal * ( monthly_interest / (1 - Math.pow((1+ monthly_interest), -num_months)));

 return Math.ceil(m);
}

function RunSJ() {
	// remove unecessary characters commas, decimals and trailing zeros dollar signs percent
	
	// get values
	purchase_price = window.document.prequal.p_price.value
		
	if(window.document.prequal.dp.value>100) {
		// downpayment is not a percent
		down_payment = window.document.prequal.dp.value;
	} else {
		// downpayment is a percent
		down_payment_percent = window.document.prequal.dp.value;
		down_payment = purchase_price * (down_payment_percent/100);
	} // end if

	// assign value
	loan_amount = purchase_price - down_payment;
	// print into textbox
	window.document.prequal.la.value = loan_amount;
	window.document.prequal.mp.value = get_monthly_payment();
}
