
// CONSTANTS
var separator = ",";  // use comma as 000's separator
var decpoint = ".";  // use period as decimal point
var percent = "%";
var currency = "$";  // use dollar sign for currency

function formatNumber(number, format, print) {  // use: formatNumber(number, "format")
if (print) document.write("formatNumber(" + number + ", \"" + format + "\")<br>");

if (number - 0 != number) return null;  // if number is NaN return null
var useSeparator = format.indexOf(separator) != -1;  // use separators in number
var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
var useCurrency = format.indexOf(currency) != -1;  // use currency format
var isNegative = (number < 0);
number = Math.abs (number);
if (usePercent) number *= 100;
format = strip(format, separator + percent + currency);  // remove key characters
number = "" + number;  // convert number input to string

 // split input value into LHS and RHS using decpoint as divider
var dec = number.indexOf(decpoint) != -1;
var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

 // split format string into LHS and RHS using decpoint as divider
dec = format.indexOf(decpoint) != -1;
var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

 // adjust decimal places by cropping or adding zeros to LHS of number
if (srightEnd.length < nrightEnd.length) {
  var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
  nrightEnd = nrightEnd.substring(0, srightEnd.length);
  if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

// patch provided by Patti Marcoux 1999/08/06
  while (srightEnd.length > nrightEnd.length) {
	nrightEnd = "0" + nrightEnd;
  }

  if (srightEnd.length < nrightEnd.length) {
	nrightEnd = nrightEnd.substring(1);
	nleftEnd = (nleftEnd - 0) + 1;
  }
} else {
  for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
	if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
	else break;
  }
}

 // adjust leading zeros
sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
while (sleftEnd.length > nleftEnd.length) {
  nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
}

if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
if (isNegative) {
  // patch suggested by Tom Denn 25/4/2001
  output = (useCurrency) ? "(" + output + ")" : "-" + output;
}
return output;
}

function strip(input, chars) {  // strip all characters in 'chars' from input
var output = "";  // initialise output string
for (var i=0; i < input.length; i++)
  if (chars.indexOf(input.charAt(i)) == -1)
	output += input.charAt(i);
return output;
}

function separate(input, separator) {  // format input using 'separator' to mark 000's
input = "" + input;
var output = "";  // initialise output string
for (var i=0; i < input.length; i++) {
  if (i != 0 && (input.length - i) % 3 == 0) output += separator;
  output += input.charAt(i);
}
return output;
}

function floor(number){
	return Math.floor(number * Math.pow(10,2)) / Math.pow(10,2);
}

function oneEighthRoundUp(n){
	x = parseInt(n / 0.125);
	r = n % 0.125;
	if(r == 0)
		return n;
	else
		return (x + 1) * 0.125;
}

function findRemainingBalance(LoanAmount, rate, terms, termspaid)
{
	var base = Math.pow(1 + (rate/1200), terms);
	var basepaid = Math.pow(1 + (rate/1200), termspaid);
	return LoanAmount * (base - basepaid) / (base - 1);
}

function findMonthlyPayment(LoanAmount, rate, terms)
{
	var base = Math.pow(1 + (rate/1200), terms);
	return LoanAmount * (rate/1200) * base / (base - 1);
}

function oldfindMonthlyPayment(LoanAmount, rate, terms)
{
	var MonthlyPI;
	var base = 1;
	var mbase = 1 + rate;
	for(i=0; i<terms; i++){
		base = base * mbase;
	}
	MonthlyPI = floor(LoanAmount * rate / (1 - (1 / base)));
	return MonthlyPI;
}

function MonthlyPaymentCalc(EstTaxIns){
	var LoanAmount = MM_findObj("LoanAmount").value;
	LoanAmount = LoanAmount.replace(/,/g, '');
	LoanAmount = LoanAmount.replace(/\$/g, '');

	var rate = MM_findObj("IntRate").value;
	rate = rate.replace('%', '');
	if(!rate) rate = 0;

	var terms = parseInt(MM_findObj("Years").value) * 12;
	if(!terms) terms = 0;
	
	var MonthlyPI = findMonthlyPayment(LoanAmount, rate, terms);
	
	var EstMonthlyTax = MM_findObj("id_EstMonthlyTax").value;
	EstMonthlyTax = EstMonthlyTax.replace(/,/g, '');
	EstMonthlyTax = EstMonthlyTax.replace(/\$/g, '');
	EstMonthlyTax = eval(EstMonthlyTax);
	if(!EstMonthlyTax) EstMonthlyTax = 0;
	
	var EstMonthlyIns = MM_findObj("id_EstMonthlyIns").value;
	EstMonthlyIns = EstMonthlyIns.replace(/,/g, '');
	EstMonthlyIns = EstMonthlyIns.replace(/\$/g, '');
	EstMonthlyIns = eval(EstMonthlyIns);
	if(!EstMonthlyIns) EstMonthlyIns = 0;
	
	if(EstTaxIns != "notaxins"){
		var EstPropertyValue = MM_findObj("id_EstPropertyValue").value;
		EstPropertyValue = EstPropertyValue.replace(/,/g, '');
		EstPropertyValue = EstPropertyValue.replace(/\$/g, '');
		
		EstMonthlyTax = floor(EstPropertyValue * .0085 / 12);
		EstMonthlyIns = floor(EstPropertyValue * .0025 / 12);
	}
	
	var TotMonthlyPayment = floor(MonthlyPI + EstMonthlyIns + EstMonthlyTax);
	if(!MonthlyPI || MonthlyPI == "Infinity")
		MM_findObj("id_PrincipalInterest").innerHTML = "n/a";
	else
		MM_findObj("id_PrincipalInterest").innerHTML = formatNumber(MonthlyPI, "$,##0.00");
	
	if(EstTaxIns != "notaxins"){
		MM_findObj("id_EstMonthlyTax").value = formatNumber(EstMonthlyTax, "$,##0.00");
		MM_findObj("id_EstMonthlyIns").value = formatNumber(EstMonthlyIns, "$,##0.00");
	}
	
	if(!TotMonthlyPayment || TotMonthlyPayment == "Infinity" || !MonthlyPI || MonthlyPI == "Infinity")
		MM_findObj("id_TotMonthlyPayment").innerHTML = "n/a";
	else
		MM_findObj("id_TotMonthlyPayment").innerHTML = formatNumber(TotMonthlyPayment, "$,##0.00");
}

function IIR(p, pmt, terms){
	var app, x, y, lastopr, ny, np, stp, Pmt, i, found;
	
	app = pmt;
	i = .001;
	
	stp = 0.01;
	lastopr = 1;
	found = 0;
	
	while(found == 0){	
		i = i + (stp * lastopr);

		x = (i / 12 + 1);
		y = -1 * terms;
		x = 1 - Math.pow(x, y);
		Pmt = (p * (i/12)) / x;

		if((Pmt >= (app - .0001)) && (Pmt <= (app + .001))){
			found = 1;
		}
		
		if((found == 0) && (Pmt < app)){
			if(lastopr == -1){
				stp = stp / 2;
				lastopr = 1;
			}else{
				stp = stp * 2;
			}
		}
		
		if((found == 0) && (Pmt > app)){
			if(lastopr == 1){
				stp = stp / 2;
				lastopr = -1;
			}else{
				lastopr = -1;
			}
		}
	}
	
	i = i * 100;

	return i;

}


function calcAPR(loanamount, fees, terms, rate){
	var principle = loanamount - fees;
	var payment = findMonthlyPayment(loanamount, rate, terms);
	var result = IIR(principle, payment, terms);
	
	return result;
}

function calcARMAPR(loanamount, fees, terms, rate, index, margin, initialterm, initialcap, annualcap, lifecap){
	var principle = loanamount - fees;
	var initialpayment = findMonthlyPayment(loanamount, rate, terms);
	var balance = findRemainingBalance(loanamount, rate, terms, initialterm);
	var postinitialtermrate = oneEighthRoundUp(index + margin);
	var postinitialtermpayment = findMonthlyPayment(balance, postinitialtermrate, terms - initialterm);
	var paymentsum = (initialpayment * initialterm) + (postinitialtermpayment * (terms - initialterm));
	var avgmonthlypayment = paymentsum / terms;
	var result = IIR(principle, avgmonthlypayment, terms);
	
	return result;
}