function floor(number) { 
	// Round to nearest 100th of a decimal point
	return Math.floor(number*100)/100;
}

function calculateMonthlyPayment(numYearsInputID,interestRateInputID,loanAmountInputID,monthlyPaymentInputID) {
	// Calculate monthly payment based on loan amount, years, and interest
	var numYears			= document.getElementById(numYearsInputID);
	var interestRate		= document.getElementById(interestRateInputID);
	var loanAmount			= document.getElementById(loanAmountInputID);
	var monthlyPayment		= document.getElementById(monthlyPaymentInputID);
	var monthlyInterest		= unformatCurrency(interestRate.value) / 1200;
	var base				= 1;
	var monthlyBase			= 1 + monthlyInterest;
	for (i=0; i<numYears.value * 12; i++) {
		base				= base * monthlyBase;
	}
	var compoundedInterest	= (1 - (1/base));
	monthlyPayment.value	= formatCurrency(floor(unformatCurrency(loanAmount.value) * monthlyInterest / compoundedInterest)) + " per month";
}

function calculateMortgageAmount(interestRateInputID,monthlyPaymentInputID,loanAmountInputID) {
	// Calculate loan amount based on monthly payment, interest rate
	var numYears			= 30;
	var interestRate		= document.getElementById(interestRateInputID);
	var monthlyPayment		= document.getElementById(monthlyPaymentInputID);
	var loanAmount			= document.getElementById(loanAmountInputID);
	
	var monthlyInterest		= unformatCurrency(interestRate.value) / 1200;
	var base				= 1;
	var monthlyBase			= 1 + monthlyInterest;
	for (i=0; i<numYears * 12; i++) {
		base				= base * monthlyBase;
	}
	var compoundedInterest	= (1 - (1/base));
	loanAmount.value	= "Loan Amount of " + formatCurrency(floor(unformatCurrency(monthlyPayment.value) / monthlyInterest * compoundedInterest));
}

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);
}

function unformatCurrency(currencyString) {
	currencyString = currencyString.toString(); // must ensure that inparam is of type string to perform formatting upon it
	currencyString = currencyString.replace("$","");
	currencyString = currencyString.replace("%",""); // will handle percentages as well
	currencyString = currencyString.replace(/,/g,"");
	currencyString = parseFloat(currencyString);
	return currencyString;
}

function formatPercentage(num) {
	num = num.toString().replace(/\%|\,/g,'');
	if(isNaN(num)) { 
		num = "0";
	}
	return floor(num) + " %";
}

