// Used by all calculators

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 removeCommas(num) {
	num = num.toString();
	num = num.replace(/,/g,"");
	num = num.replace(/\s/g,"");
	return parseFloat(num);
}

function showNum(num) {
	if (!isFinite(num)) num = "--.--";
	else num = addCommas(num.toFixed(2));
	return num;
}

// For Calculator 1

function set_monthly_elig() {
	var monthly = (removeCommas(document.getElementById("budget").value) * .28)/12;
	document.getElementById("monthly_elig").value = showNum(monthly);
}

function set_total_elig() {
	set_monthly_elig();
	var m = removeCommas(document.getElementById("monthly_elig").value);
	var r = document.getElementById("loan_option").value;
	var n = document.getElementById("loan_term").value * 12;
	var i = r / 12;
	var total =  m / ( (i*Math.pow((1+i),n)) / (Math.pow((1+i),n) - 1) ); // equation for compounding interest!
	document.getElementById("total_elig").value = showNum(total);
}

function set_raise() {
	var net_loan = removeCommas(document.getElementById("total_elig").value) - document.getElementById("debt").value;
	document.getElementById("net_loan_amt").value = showNum(net_loan);
	var cash_needed = removeCommas(document.getElementById("cost").value) - net_loan;
	if (cash_needed < 0) cash_needed = 0;
	document.getElementById("cash_needed").value = showNum(cash_needed);
}

function updateAll1() {
	set_monthly_elig();
	set_total_elig();
	set_raise();
}

// For Calculator 2

function updateAll2() {
	var invest_amt = removeCommas(document.getElementById("invest_amt").value);
	var n = document.getElementById("term").value;
	var r = invest_rates[n];
	var t = n / 12; // number of years
	
	if ( (invest_amt) && (r != 0) && (n != 0) ) {
		var final_val = invest_amt * Math.pow( (1+(r/2)), (2*t));
		document.getElementById("final_val").value = showNum(final_val);
	}
}

// For Calculator 3

function updateAll3() {
	var loan_amt = removeCommas(document.getElementById("loan_amt").value);
	var r = document.getElementById("loan_option").value;
	var n = document.getElementById("loan_term").value * 12;
	var i = r / 12;
	
	if ( (loan_amt) && (r != 0) && (n != 0) ) {
		var monthly_pmt;
		monthly_pmt = loan_amt * ( (i*Math.pow((1+i),n)) / (Math.pow((1+i),n) - 1) );
		document.getElementById("monthly_pmt").value = showNum(monthly_pmt);
	}
}
