// 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("Por favor, ingrese números positivos únicamente. La calculadora usará para esta entrada el valor prefijado para esta. ");
			 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("Su cociente de la costo-a-renta de la cubierta no debe excederse " + f3(HErratio,2) + " %.");
	}

	intDebtPay = totalPay + moDebt;

	if ( intDebtPay > diratio) {
		//alert("Su cociente de largo plazo de la Deuda-a-Renta no puede excederse " + DIrratio + " %. Vuelva a entrar por favor los valores");
	}

	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("Cantidad Máxima de Hipoteca si el espacio se mantiene en blanco, cero o menos de 1000. Usted debe ingresar suficiente renta para generar un monto de préstamo de hipoteca de 1000 o mayor para hacer funcionar la tabla de amortización.")
   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("Su ingreso mensual no puede ser menor que sus gastos mensuales");
		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("Su cociente de la costo-a-renta de la cubierta no debe excederse " + f3(HErratio_agg,2) + " %.");
	}

	intDebtPay = totalPay + moDebt;

	if ( intDebtPay > diratio_agg) {
		//alert("Su cociente de largo plazo de la Deuda-a-Renta no puede excederse " + DIrratio_agg + " %. Vuelva a entrar por favor los valores");
	}

	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("Cantidad Máxima de Hipoteca si el espacio se mantiene en blanco, cero o menos de 1000. Usted debe ingresar suficiente renta para generar un monto de préstamo de hipoteca de 1000 o mayor para hacer funcionar la tabla de amortización.")
   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)
}

