// JavaScript Document

// Home Affordability Calculator 
function replaceAll(oldStr,findStr,repStr) {
	  var srchNdx = 0;  
	  var newStr = ""; 
	  while (oldStr.indexOf(findStr,srchNdx) != -1)  							
	  {
			newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));							
			newStr += repStr;
			srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);           
	  }
	  newStr += oldStr.substring(srchNdx,oldStr.length);          
	  return newStr;
}
	
function selectcell() {
	  document.inputForm.moInc.select()
	  document.inputForm.moInc.focus()
}

function chknos(nos)
{
	var str = nos.value;
	if(str.length == 0) {
		return false;
	}
	oneDecimal = false;
	for (var i = 0; i <str.length; i++) {
		var y = str.substring(i, i + 1);
		 if (y == "." && !oneDecimal) {
			oneDecimal = true;
			continue
		}
		 if (y < "0" || y > "9") {
			 alert("Please enter positive numbers only. Calculator will use the default value for this entry. ");
			 return false;
		 }
	}
	 return true;
}


function number(nos,def)
{
	if(!chknos(nos)) {
		 return def;
	}
	var use = nos.value;
	if(use == "" || use == null || (0 + use) == 0) {
		 return def;
	}
	return parseFloat(use); 
}
	
	
function f1(nos, y) {
	var str = "" + Math.round(nos);
	if (str.length == 0){
	   str = "0";
	}
	str = "$" + str;
	i = y - str.length;
	while (0 < i--) {
		str = " " + str;
	}
	return str;
}


function f2(nos, y, dec) {
	var str = "" + Math.round(eval(nos)*Math.pow(10,dec));
	while (str.length <= dec) {
		 str = "0" + str;
	}
	var decpoint = str.length - dec;
	str = str.substring (0,decpoint) + "." +
	str.substring (decpoint, str.length);
	if (str.length == 0) {
		str = "0";
	}
	str = str;
	i = y - str.length;
	while (0 < i--) {
		 str = " " + str;
	}
	return str;
}


function f3(nos, y) {
	var str = "" + Math.round(nos);
	if (str.length == 0) {
		 str = "0";
	}
	i = y - str.length;
	while (0 < i--) {
		str = " " + str;
	}
	return str;
}


var newLoan = 0;

//main compute function 
function compute(input)
{
	compute_aggressive(input);
	var table = input.form;
	percentDown = number(table.percentDown, 3);

	moTtlInc = replaceAll(table.moInc.value,',','');
	moTtlInc = replaceAll(moTtlInc,'$','');

	moDebt = replaceAll(table.moDebt.value,',','');
	moDebt = replaceAll(moDebt,'$','');
	
	//Default  Closing Cost value is set
	percentCC = number(table.percentCC,0);

	if (percentDown < 5) {
		percentDown = 3.0; 
	}
	
	if (percentDown >= 20) {
		pmi_rate = 0;
		availInc = moTtlInc * 0.33;
		if ((moTtlInc * 0.38 - moDebt) <= (moTtlInc * 0.33)) {
			availInc = moTtlInc * 0.38 - moDebt;
		}
	}
	
	if (percentDown < 20) {
		availInc = moTtlInc * 0.28;
		if ((moTtlInc * 0.36 - moDebt) <= (moTtlInc * 0.28)) {
			availInc = moTtlInc * 0.36 - moDebt;
		}
	}
	
	if (percentDown <= 15) {
	   pmi_rate = 0.0073 - (percentDown - 3) * 0.000108;
	}
	
	if (percentDown > 15 && percentDown < 20) {
		pmi_rate = 0.0060 - (percentDown - 15) * 0.00076;
	}

	//Default ratios for the conservative Estimate this can be changed
	ratio1 = 0.29;
	ratio2 = 0.41;
	
	availInc = moTtlInc * ratio1;
		if ((moTtlInc * ratio2 - moDebt) <= (moTtlInc * ratio1)) {
			availInc = moTtlInc * ratio2 - moDebt;
		}

	intHRatio = 0.29; // default value set to 29%
	hratio = intHRatio * moTtlInc;
	HErratio = intHRatio * 100;

	intDIRatio = 0.41; //Default is set as 41%
	diratio = intDIRatio * moTtlInc;
	DIrratio = intDIRatio * 100;
	//alert ("Selected value"+intDIRatio);

	taxRate = number(table.taxRate, 1.2) / 1200;
	intRate = table.rate.options[table.rate.selectedIndex].text;
	term = table.term.options[table.term.selectedIndex].text;
	insRate = number(table.insRate, 0.3) / 1200;

	downTotal = replaceAll(table.down.value,',','');
	downTotal = replaceAll(downTotal,'$','');


	//moFees = number(table.fees, 0) / 12;
	loan = (1 - Math.pow(intRate/1200 + 1, -term*12))*
	(availInc) / (intRate/1200);
	moTax = loan * taxRate * (1/(1 - percentDown/100));
	moIns = loan * insRate * (1/(1 - percentDown/100));
	mopmi = pmi_rate * loan /12;
	for ( var i = 1; i <= 100; i++) {
		moPI2 = availInc - moTax - moIns - mopmi;
		moPI1 = (Math.round((moPI2)*Math.pow(10,3)))/1000;
		newLoan = (1 - Math.pow(intRate/1200 + 1, -term*12)) * moPI1 / (intRate/1200);
		moTax = newLoan * taxRate * (1/(1 - percentDown/100));
		moIns = newLoan * insRate * (1/(1 - percentDown/100));
		mopmi = pmi_rate * newLoan /12;
		moPI2 = availInc - moTax - moIns - mopmi;
		moPI = (Math.round((moPI2)*Math.pow(10,3)))/1000;
		if ((moPI1 - moPI) == 0) {
			i = 100;
		}
	}
	downPay = newLoan * ((1/(1 - percentDown/100)) - 1);
	propValue = newLoan + downPay;
	downClose = propValue * percentCC/100;
	down_close = downClose + downPay;
	addDown = downTotal - down_close;
	table.moInc.value = currency(f3(moTtlInc, 1));
	table.moDebt.value = currency(f3(moDebt, 1));
	table.down.value = currency(f3(downTotal, 1));
	table.taxRate.value = f2(taxRate*1200, 1, 2);
	table.insRate.value = f2(insRate*1200, 1, 2);
	//table.fees.value = f3(moFees*12, 1);
	//table.percentDown.value = f2(percentDown, 1, 1);
	table.percentCC.value = f2(percentCC, 1, 1);
	totalPay = moPI + moTax + moIns + mopmi;

	if ( totalPay > hratio) {
		//alert("Your housing expense-to-income ratio should not exceed " + f3(HErratio,2) + " %.");
	}

	intDebtPay = totalPay + moDebt;

	if ( intDebtPay > diratio) {
		//alert("Your Long-Term Debt-to-Income Ratio can't exceed " + DIrratio + " %. Please re-enter the values");
	}

	if (newLoan <= 0) totalPay =0;
		table.totalPay.value = currency(f1(totalPay, 10));
	if (newLoan <= 0) moTax = 0;
		table.moTax.value = currency(f1(moTax, 10));
	if (newLoan <= 0) moIns =0;
		table.moIns.value = currency(f1(moIns, 10));
	//table.moFees.value = f1(moFees, 10);
	if (newLoan <= 0) downClose = 0;
		table.downClose.value = currency(f1(downClose, 10));
	if (newLoan <= 0) mopmi = 0;
	table.mopmi.value = currency(f1(mopmi, 10));
	if (newLoan <= 0) down_close = 0;
		table.down_close.value = currency(f1(down_close, 10));
	if (newLoan <= 0) addDown = 0;
		table.addDown.value = currency(f1(addDown, 10));
	if (moPI <= 0) moPI = 0;
		table.moPI.value=currency(f1(moPI, 10));
	if(newLoan <= 0) newLoan = 0;
		table.maxLoan.value = currency(f1(newLoan, 10));
	if (newLoan <= 0) propValue = 0;
		table.propValue.value = currency(f1(propValue, 10));
	if (newLoan <= 0) downPay = 0;
	table.downPay.value = currency(f1(downPay, 10));
	intRate=intRate*1000
	document.cookie="condition_loan="+intRate.toString()+term.toString()+(Math.round(newLoan)).toString()
	}

function checkLoan(form) {
   var moInc = document.inputForm.moInc.value;
   if (isNaN(newLoan) || newLoan == 0 || newLoan < 1000 || moInc == 0) {
		alert("Maximum Mortgage Amount is either blank, zero or less than 1000. You must enter enough income to generate a mortgage loan amount of 1000 or greater to run an Amortization Table.")
   document.inputForm.moInc.select()
   document.inputForm.moInc.focus()
   
	}else{
		window.open("amortz.html","Amortz","menubar,scrollbars,width=520,height=400")
	}
}

//function to compute the Aggressive Estimate
function compute_aggressive(input){

	var table = input.form;
	percentDown = number(table.percentDown, 3);

	moTtlInc = replaceAll(table.moInc.value,',','');
	moTtlInc = replaceAll(moTtlInc,'$','');
	moDebt = replaceAll(table.moDebt.value,',','');
	moDebt = replaceAll(moDebt,'$','');
	
	if(parseInt(moTtlInc) < parseInt(moDebt)){
		alert("Your monthly income cannot be less than your monthly debt");
		return false;
	}
	
	//Default  Closing Cost value is set
	percentCC = number(table.percentCC,0);
	
	if (percentDown < 5) {
		percentDown = 3.0; 
	}
	
	if (percentDown >= 20) {
		pmi_rate = 0;
		availInc = moTtlInc * 0.33;
		if ((moTtlInc * 0.38 - moDebt) <= (moTtlInc * 0.33)) {
			availInc = moTtlInc * 0.38 - moDebt;
		}
	}
	
	if (percentDown < 20) {
		availInc = moTtlInc * 0.28;
		if ((moTtlInc * 0.36 - moDebt) <= (moTtlInc * 0.28)) {
			availInc = moTtlInc * 0.36 - moDebt;
		}
	}
	
	if (percentDown <= 15) {
	   pmi_rate = 0.0073 - (percentDown - 3) * 0.000108;
	}
	
	if (percentDown > 15 && percentDown < 20) {
		pmi_rate = 0.0060 - (percentDown - 15) * 0.00076;
	}
	
	//default ratios for aggressive calculation which can be changed
	ratio1 = 0.50;
	ratio2 = 0.50;
	
	availInc = moTtlInc * ratio1;
		if ((moTtlInc * ratio2 - moDebt) <= (moTtlInc * ratio1)) {
			availInc = moTtlInc * ratio2 - moDebt;
		}
	
	
	intHRatio_agg = 0.50; //default value set for aggressive estimate 50%

	hratio_agg = intHRatio_agg * moTtlInc;
	HErratio_agg = intHRatio_agg * 100;
	
	intDIRatio_agg = 0.50; //Default is set as 50% for Aggressive estimate 
	
	diratio_agg = intDIRatio_agg * moTtlInc;
	DIrratio_agg = intDIRatio_agg* 100;
	
	taxRate = number(table.taxRate, 1.2) / 1200;
	intRate = table.rate.options[table.rate.selectedIndex].text;
	term = table.term.options[table.term.selectedIndex].text;
	insRate = number(table.insRate, 0.3) / 1200;

	downTotal = replaceAll(table.down.value,',','');
	downTotal = replaceAll(downTotal,'$','');


	//moFees = number(table.fees, 0) / 12;
	loan = (1 - Math.pow(intRate/1200 + 1, -term*12))*
	(availInc) / (intRate/1200);
	moTax = loan * taxRate * (1/(1 - percentDown/100));
	moIns = loan * insRate * (1/(1 - percentDown/100));
	mopmi = pmi_rate * loan /12;
	for ( var i = 1; i <= 100; i++) {
		moPI2 = availInc - moTax - moIns - mopmi;
		moPI1 = (Math.round((moPI2)*Math.pow(10,3)))/1000;
		newLoan = (1 - Math.pow(intRate/1200 + 1, -term*12)) * moPI1 / (intRate/1200);
		moTax = newLoan * taxRate * (1/(1 - percentDown/100));
		moIns = newLoan * insRate * (1/(1 - percentDown/100));
		mopmi = pmi_rate * newLoan /12;
		moPI2 = availInc - moTax - moIns - mopmi;
		moPI = (Math.round((moPI2)*Math.pow(10,3)))/1000;
		if ((moPI1 - moPI) == 0) {
			i = 100;
		}
	}
	downPay = newLoan * ((1/(1 - percentDown/100)) - 1);
	propValue = newLoan + downPay;
	downClose = propValue * percentCC/100;
	down_close = downClose + downPay;
	addDown = downTotal - down_close;
	table.moInc.value = currency(f3(moTtlInc, 1));
	table.moDebt.value = currency(f3(moDebt, 1));
	table.down.value = currency(f3(downTotal, 1));
	table.taxRate.value = f2(taxRate*1200, 1, 2);
	table.insRate.value = f2(insRate*1200, 1, 2);
	//table.fees.value = f3(moFees*12, 1);
	//table.percentDown.value = f2(percentDown, 1, 1);
	table.percentCC.value = f2(percentCC, 1, 1);
	totalPay = moPI + moTax + moIns + mopmi;

	if ( totalPay > hratio_agg) {
		//alert("Your housing expense-to-income ratio should not exceed " + f3(HErratio_agg,2) + " %.");
	}

	intDebtPay = totalPay + moDebt;

	if ( intDebtPay > diratio_agg) {
		//alert("Your Long-Term Debt-to-Income Ratio can't exceed " + DIrratio_agg + " %. Please re-enter the values");
	}

	if (newLoan <= 0) totalPay =0;
		table.totalPay_agg.value = currency(f1(totalPay, 10));
	if (newLoan <= 0) moTax = 0;
		table.moTax_agg.value = currency(f1(moTax, 10));
	if (newLoan <= 0) moIns =0;
		table.moIns_agg.value = currency(f1(moIns, 10));
	//table.moFees.value = f1(moFees, 10);
	if (newLoan <= 0) downClose = 0;
		table.downClose_agg.value = currency(f1(downClose, 10));
	if (newLoan <= 0) mopmi = 0;
	table.mopmi.value = currency(f1(mopmi, 10));
	if (newLoan <= 0) down_close = 0;
		table.down_close_agg.value = currency(f1(down_close, 10));
	if (newLoan <= 0) addDown = 0;
		table.addDown_agg.value = currency(f1(addDown, 10));
	if (moPI <= 0) moPI = 0;
		table.moPI_agg.value=currency(f1(moPI, 10));
	if(newLoan <= 0) newLoan = 0;
		table.maxLoan_agg.value = currency(f1(newLoan, 10));
	if (newLoan <= 0) propValue = 0;
		table.propValue_agg.value = currency(f1(propValue, 10));
	if (newLoan <= 0) downPay = 0;
	table.downPay_agg.value = currency(f1(downPay, 10));
	intRate=intRate*1000
	document.cookie="condition_loan="+intRate.toString()+term.toString()+(Math.round(newLoan)).toString()
	}

function checkLoan(form) {
   var moInc = document.inputForm.moInc.value;

   if (isNaN(newLoan) || newLoan == 0 || newLoan < 1000 || moInc == 0) {
		alert("Maximum Mortgage Amount is either blank, zero or less than 1000. You must enter enough income to generate a mortgage loan amount of 1000 or greater to run an Amortization Table.")
   document.inputForm.moInc.select()
   document.inputForm.moInc.focus()
   
	}else{
		window.open("amortz.html","Amortz","menubar,scrollbars,width=520,height=400")
	}

}



<!-->
function currency(pNum) {
	//-- Returns passed number as string in $xxx,xxx.xx format.
	var tRtnValue = "";
	if (pNum != "") {
		var n = pNum.toString().replace(/\$|\,/g,'');
		if (isNaN(n)) {n = "0";}
		var tSign = (n == (n = Math.abs(n)));
		n = Math.floor(n * 100 + 0.50000000001);
		var tCents = n % 100;
		if (tCents < 10) {
			tCents = "0" + tCents;
		}
		n = Math.floor(n / 100).toString();
		for (var i = 0; i < Math.floor((n.length - (1 + i)) / 3); i++) {
			n = n.substring(0, n.length - (4 * i + 3)) + ',' + n.substring(n.length - (4 * i + 3));
		}
		tRtnValue = (((tSign)?'':'-') + '$' + n + '.' + tCents);
	}else{
		tRtnValue = 0;
	}
	return tRtnValue;
}

function valid_number(string) {
	var sTmp = "";
	var sValid = "0123456789.";
	for (var i=0; i< string.length; i++) {
		 if (sValid.indexOf(string.charAt(i)) != -1 )  
			sTmp += string.charAt(i);
	}
	return(sTmp)
}

//function for calculating the amortization
function getAmortization(a,n,p,y,m) {
	var i=0;
	var frm = document.MORTGAGE;
	var sATline="";
	var oAmortizationTable=document.getElementById("amortizationtable");
	var sCR=String.fromCharCode(13);
	var sTab=String.fromCharCode(27);

	/* Calculate amortization and write table to text area **/
	var payment = getPayment(a,n,p);
	frm.PAYMENT.value = currency(Math.round(payment*100)/100);
	viewresults = document.MORTGAGE.view.options[document.MORTGAGE.view.selectedIndex].value;
	if (viewresults == "yes") {
		oAmortizationTable.style.visibility="visible";
		var string = "";
		//generating the table for the display below the calculation with the details needed
		string += "<p align=left><br><font class='smalltitle' align=left>Amortization Table</font></p>";
		string += "<table width=450  class='smalltable' cellpadding=2 border=0><tr><td colspan=7 class='smalltitle'  align=center>Monthly Payment = " + (Math.round(payment*100)/100) + "</td><td><a href='#' onclick=showPopup('printPreview.php') id='preview'> Print Preview</a></td></tr>";
		string += "<tr><td class='smalltitle'>&nbsp;</td><td class='smalltitle'>Month</td><td class='smalltitle'>Year </td><td class='smalltitle'>Balance</td><td class='smalltitle'>Principal</td><td class='smalltitle'>Interest</td><td class='smalltitle'>Payment</td><td class='smalltitle'>Total Interest</td> </tr>";
		var balance=a;
		var interest = 0.0;
		var principal=0.0;
		var totalinterest=0.0;
		var month = m;
		var year = y;
		var mon;
		for (i=1;i<=n;i++) {
			interest = balance*p/1200;
			totalinterest += interest;
			principal = payment-interest;
			balance -= principal;
			if(month == 1)
				mon = "jan";
			else if(month == 2)
				mon = "Feb";
			else if(month == 3)
				mon = "Mar";
			else if(month == 4)
				mon = "Apr";
			else if(month == 5)
				mon = "May";
			else if(month == 6)
				mon = "Jun";
			else if(month == 7)
				mon = "Jul";
			else if(month == 8)
				mon = "Aug";
			else if(month == 9)
				mon = "Sep";
			else if(month == 10)
				mon = "Oct";
			else if(month == 11)
				mon = "Nov";
			else 
				mon = "Dec";
				
			sATline = "<tr><td>"+i+"</td><td>"+mon.toString()+"</td><td>"+ year.toString()+ "</td>";
			sATline +=  "<td>"+currency(Math.round(balance*100)/100)+"</td>";
			sATline += "<td>"+currency(Math.round(principal*100)/100)+"</td>";
			sATline += "<td>"+currency(Math.round(interest*100)/100)+"</td>";
			sATline += "<td>"+currency(Math.round(i*payment*100)/100)+"</td>";
			sATline += "<td>"+currency(Math.round(totalinterest*100)/100) + "</td></tr>";
			string += sATline;
			
			if(month == 12)
			{	month =1;
				year = parseInt(year)+1;
			}else{
				month = parseInt(month )+ 1;
			}		
		}
		string += "</table>";
		oAmortizationTable.innerHTML = string;
	}else{
		oAmortizationTable.innerHTML = "";
		oAmortizationTable.style.visibility="hidden";
	}
	
}

function getSpaces(n) {
	var i=0; 
	var sSpaces="";
	for (i=0;i<n;i++) {sSpaces += " ";}
	return sSpaces;
}

//function for getting the payment
function getPayment(a,n,p) {
	/* Calculates the monthly payment from annual percentage
	   rate, term of loan in months and loan amount. **/
	var acc=0;
	var base = 1 + p/1200;
	for (i=1;i<=n;i++) 
		{ acc += Math.pow(base,-i); }
	return a/acc;
}
	

function showPopup(drp) 
{
	var url = drp;
	var w   = 620;
	var h   = 340; 
	if (arguments.length == 3){
		w   = width;
		h   = height;
	}
	
	
	if (document.all)
	var xMax = screen.width, yMax = screen.height;
	else
	{ 
	if (document.layers)
	var xMax = window.outerWidth, yMax = window.outerHeight;
	else
	var xMax = 640, yMax=480;
	}
	if (w>xMax) w = xMax * .9;
	if (h>yMax) h = yMax * .9;
	var l = (xMax - w)/2, t = (yMax-h)/2;
	
	window.open(url,"_blank",'screenX='+l+',left='+l+',screenY='+t+',top='+t+',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,fullscreen=0,width='+w+',height='+h);
}

function perform(){
	var newAmount = replaceAll(document.getElementById('amount').value,',','');
	newAmount = replaceAll(newAmount,'$','');
	getAmortization(newAmount,document.getElementById('term').value,document.getElementById('apr').value,document.getElementById('year').value,document.getElementById('month').value)
}

function switchcalcs(whichbutton,otherbutton)
{
mya = document.getElementById(whichbutton);
mya2 = document.getElementById(otherbutton);
mydiv = document.getElementById('d_'+whichbutton);
mydiv2 = document.getElementById('d_'+otherbutton);
myaClassName = mya.className;
myaClassName2 = mya2.className;

if (myaClassName=="calc")
  {
  mya2.className = 'calc';
  mydiv2.className = 'hidecalc';
  mydiv.className = 'showcalc';
  mya.className = 'calc_on';
  }
}