//*******************************************
//DO NOT REMOVE THIS COPYWRITE INFO!
//Mortgage Qualification Calculator V1.2
//2003 Daniel C. Peterson ALL RIGHTS RESERVED
//Created: 01/18/2003
//Last Modified: 01/18/2003
//This script may not be copied, edited, distributed or reproduced
//without express written permission from
//Daniel C. Peterson of Web Winder Website Services
//For commercial use rates, contact:
//Dan Peterson:
//Web Winder Website Services
//P.O. Box 11
//Bemidji, MN  56619
//dan@webwinder.com
//http://www.webwinder.com
//Commercial User Licence #:5114-1170-94-1128
//Commercial Licence Date:2007-12-22
//*******************************************



function stripNum(num) {

   num=num.toString();


   var len = num.length;
   var rnum = "";
   var test = "";
   var j = 0;

   var b = num.substring(0,1);
   if(b == "-") {
      rnum = "-";
   }

   for(i = 0; i <= len; i++) {

      b = num.substring(i,i+1);

      if(b == "0" || b == "1" || b == "2" || b == "3" || b == "4" || b == "5" || b == "6" || b == "7" || b == "8" || b == "9" || b == ".") {
         rnum = rnum + "" + b;

      }

   }

   if(rnum == "" || rnum == "-") {
      rnum = 0;
   }

   rnum = Number(rnum);

   return rnum;

}



function computeMonthlyPayment(prin, numPmts, intRate) {

var pmtAmt = 0;

if(intRate == 0) {
   pmtAmt = prin / numPmts;
} else {
   
   if (intRate >= 1.0) {
     intRate = intRate / 100.0;
   }
   intRate /= 12;

   var pow = 1;
   for (var j = 0; j < numPmts; j++)
      pow = pow * (1 + intRate);

   pmtAmt = (prin * pow * intRate) / (pow - 1);

}

return pmtAmt;

}




function formatNumber(num) {

var isNeg=0;

    if(num < 0) {
       num=num*-1;
       isNeg=1;
    }

    
	onum=Math.round(num*100)/100;
		
	integer=Math.floor(onum);

	if (Math.ceil(onum) == integer) {
		decimal="00";
	} else{
		decimal=Math.round((onum-integer)*100)
	}
	decimal=decimal.toString();
	if (decimal.length<2) decimal="0"+decimal;

	integer=integer.toString();
	var tmpnum="";
	var tmpinteger="";
	var y=0;

	for (x=integer.length;x>0;x--) {
		tmpnum=tmpnum+integer.charAt(x-1);
		y=y+1;
		if (y==3 & x>1) {
			tmpnum=tmpnum+",";
			y=0;
		}
	}

	for (x=tmpnum.length;x>0;x--) {
		tmpinteger=tmpinteger+tmpnum.charAt(x-1);
	}
		
	finNum=tmpinteger+"."+decimal;

    if(isNeg == 1) {
       finNum = "-" + finNum;
    }

	return finNum;
}


function computeForm(form, lang) {

//IF REQUIRED FIELDS EMPTY, ALERT AND KILL SCRIPT
if(form.grossPay.value == "" || form.grossPay.value == 0) {
	if (lang==null || lang == "en") {
	   alert("Please enter your gross annual income.");
	} else if (lang=="es") {
   	alert("Por favor, anote su ingreso bruto anual.");
	}
   form.grossPay.focus();
   } else
if(form.intRate.value == "" || form.intRate.value == 0) {
	if (lang==null || lang == "en") {
	   alert("Please enter the annual interest rate you expect to pay.");
	} else if (lang=="es") {
   	alert("Por favor, anote la tasa de interés anual que usted espera para pagar.");
	}
   form.intRate.focus();
   } else {
//START REQUIRED FIELD VARIFICATION

//SET OPTIONAL BLANK FIELDS EQUAL TO ZERO;
var VmonthlyDebtPmts = stripNum(form.moDebts.value);
if(VmonthlyDebtPmts == 0) {
   VmonthlyDebtPmts = 0;
   } else {
   VmonthlyDebtPmts = VmonthlyDebtPmts;
   }

var VmoInsurance = stripNum(form.moInsurance.value);
if(VmoInsurance == 0) {
   VmoInsurance = 0;
   } else {
   VmoInsurance = VmoInsurance;
   }

var VmoPropTax = stripNum(form.moPropTax.value);
if(VmoPropTax == 0) {
   VmoPropTax = 0;
   } else {
   VmoPropTax = VmoPropTax;
   }


//COMPUTE MONTHLY INCOME BASED ON ANNUAL INCOME
var VgrossPay = stripNum(form.grossPay.value);
var monthlyIncome = VgrossPay /12;

//MORTGAGE PAYMENT CAN'T EXCEED 28% OF MONTHLY INCOME
var maxIncomePmt = monthlyIncome * .28;

//MORTGAGE PAYMENT PLUS DEBT PMTS CAN'T EXCEED 36% OF MONTHLY INCOME
var maxDebtToIncomePmt = .36 * monthlyIncome - eval(VmonthlyDebtPmts);

//USE THE LOWER OF 28% OR 36% AS MAXIMUM HOUSE PAYMENT
var maxHousePmt = 0;
if(maxIncomePmt > maxDebtToIncomePmt) {
   maxHousePmt = maxDebtToIncomePmt;
   } else {
   maxHousePmt = maxIncomePmt;
   }

//IF MAX HOUSE PAYMENT IS LESS THAN $1, ALERT & KILL SCRIPT
if(maxHousePmt < 1) {
   form.downPay2.value = "";
   form.loanAmt.value = "";
   form.homePrice.value = "";
   form.moPay.value = "";
	if (lang==null || lang == "en") {
	   alert("Based on industry standards you would not qualify for a home mortgage. In order to qualify you will need to either increase your annual income or lower your monthly debt payments, or a combination of both.")
	} else if (lang=="es") {
   	alert("Sobre la base de las normas de la industria que usted no califica para un hogar hipoteca. Para calificar usted necesitará ya sea a aumentar su ingreso anual o mensual inferior pagos de la deuda, o una combinación de ambos.");
	}
   } else {
//START HOUSE PAYMENT VERIFICATION

//ADJUST HOUSE PAYMENT DOWN TO REFLECT MONTHLY INSURANCE & TAX
maxHousePmt = eval(maxHousePmt) - (eval(VmoInsurance) + eval(VmoPropTax));

//COMPUTE MAXIMUM HOME PRICE BASED ON DOWN PAYMENT
var VdownPmt = stripNum(form.downPay.value);

//GATHER VARIABLES FOR PAYMENT AND PRINCIPLE COMPUTATIONS
var VintRate = stripNum(form.intRate.value);
     if(VintRate >= 1) {
     VintRate = VintRate / 100;
     } else {
     VintRate = VintRate;
     }

    VintRate = VintRate / 12;


    var Vterm = 0;
    if(form.term.selectedIndex == 0) {
       Vterm = 180;
       } else
       if(form.term.selectedIndex == 1) {
       Vterm = 240;
       } else {
       Vterm = 360;
       }

//COMPUTE PRINCIPAL PAID ON MAXIMUM MONTHLY PAYMENT

var pow = 1;

for (var j = 0; j < Vterm; j++)
    pow = pow * (1 + VintRate);

var maxPmtLoanAmt = ((pow - 1) * maxHousePmt) / (pow * VintRate);

//CALCULATE CLOSING COSTS
var Vpoints = stripNum(form.points.value);
if(Vpoints >= 1) {
   Vpoints /= 100;
}
var VotherCosts = stripNum(form.otherCosts.value);
var closeCost = eval(maxPmtLoanAmt * Vpoints) + eval(VotherCosts);

var VhomePrice = eval(maxPmtLoanAmt) + eval(VdownPmt) - eval(closeCost);

//ENTER TOTALS
var VdownPay2 = eval(VdownPmt) - eval(closeCost);
form.downPay2.value = "$" + formatNumber(VdownPay2);
form.loanAmt.value = "$" + formatNumber(maxPmtLoanAmt);
form.homePrice.value = "$" + formatNumber(VhomePrice);
var finalMoPay = computeMonthlyPayment(maxPmtLoanAmt, Vterm, VintRate * 12 * 100)
//form.moPay.value = "$" + formatNumber(maxMoPmt);
form.moPay.value = "$" + formatNumber(maxHousePmt);

//DISPLAY SUMMARY
if (lang==null || lang == "en") {
	form.enterHelp.value = ("After testing your entries against mortgage industry standards the highest priced house you could qualify for is " + form.homePrice.value + ".  Obviously this amount is merely an estimate.  The actual amount will vary from lender to lender.")
} else if (lang=="es") {
	form.enterHelp.value = ("Después de probar sus fichas en contra de las normas de la industria hipoteca el precio más alto casa usted puede calificar para es de " + form.homePrice.value + ".  Es evidente que esta cantidad es sólo una estimación. La cantidad real puede variar de prestamista a prestamista.")
}

//DISPLAY SUMMARY
if (lang==null || lang == "en") {
	form.resultHelp.value = ("Place your mouse over the question marks at left to see an explanation of each result.")
} else if (lang=="es") {
	form.resultHelp.value = ("Coloque el puntero del ratón sobre la cuestión marcas a la izquierda para ver una explicación de cada uno de los resultados.")
}

//END HOUSE PAYMENT VERIFICATION
      }

//END REQUIRED FIELD VARIFICATION
   }

}

//GIVE ENTRY INSTRUCTIONS
function help01(form) {
document.calc.enterHelp.value = ("ENTER: Your gross annual household income.  This is the amount before taxes are deducted.");
}
function help01_es(form) {
document.calc.enterHelp.value = ("ANOTE: Los ingresos brutos anuales de su familia. Esta es la cantidad  antes de la deducción de impuestos.");
}

function skipTo(form) {
form.enterHelp.value = "";
form.downPay.focus();
}

function help02(form) {
document.calc.enterHelp.value = ("ENTER: The total of your non-mortgage monthly debt payments. This would include car loans, student loans, credit card payments and so on.");
}
function help02_es(form) {
document.calc.enterHelp.value = ("ANOTE: El total de su no-hipoteca mensual de los pagos de la deuda. Esto incluiría los préstamos de automóviles, préstamos estudiantiles, pagos con tarjeta de crédito y así sucesivamente.");
}

function help03(form) {
document.calc.enterHelp.value = ("ENTER: The amount you have available to cover the mortgage down payment and closing costs.");
}
function help03_es(form) {
document.calc.enterHelp.value = ("ANOTE: La cantidad de que usted dispone para cubrir el enganche (pago inicial) de la hipoteca y los costos de cierre.");
}

function help04(form) {
document.calc.enterHelp.value = ("ENTER: The annual interest rate you expect to pay on this mortgage. You can enter the rate either as a percentage (8.25) or as a decimal (.0825), whichever you prefer.");
}
function help04_es(form) {
document.calc.enterHelp.value = ("ANOTE: La tasa de interés anual que usted estima pagar en esta hipoteca. Usted puede anotar la tasa como porcentaje (8.25) o como decimal (.0825), como usted prefiera.");
}

function help05(form) {
document.calc.enterHelp.value = ("ENTER: The monthly insurance payment you expect to pay. As a rule of thumb, you can expect to pay .125% (home price X .00125) of the purchase price per month.");
}
function help05_es(form) {
document.calc.enterHelp.value = ("ANOTE: El pago mensual de seguros que usted estima hacer. Como regla general, usted puede estimar pagar  .125 % (precio de la casa X .00125) del precio de la casa por mes.");
}

function help06(form) {
document.calc.enterHelp.value = ("ENTER: The monthly property tax payment you expect to pay. As a rule of thumb, you can expect to pay .027% (home price X .00027) of the purchase price per month.");
}
function help06_es(form) {
document.calc.enterHelp.value = ("ANOTE: El pago mensual de impuesto sobre la propiedad que usted estima pagar. Como regla general, usted puede estimar pagar .027 %  (precio de la casa X .00027)  del precio de compra por mes.");
}

function help07(form) {
document.calc.enterHelp.value = ("ENTER: The number of closing costs points you expect to pay. A typical number of closing points is 2.");
}
function help07_es(form) {
document.calc.enterHelp.value = ("ANOTE: El número de puntos de costos de cierre que usted estima pagar. Un t&iacute;pico n&uacute;mero de puntos de cierre es 2.");
}

function help08(form) {
document.calc.enterHelp.value = ("ENTER: Other closing costs, such as loan origination fees.");
}
function help08_es(form) {
document.calc.enterHelp.value = ("ANOTE: Otros costos de cierre, tales como cargo por apertura de préstamo.");
}

function help09(form) {
document.calc.enterHelp.value = ("ENTER: Length of Mortgage.");
}
function help09_es(form) {
document.calc.enterHelp.value = ("ANOTE: Plazo de la hipoteca.");
}


//GIVE RESULT EXPLANATIONS
function help10(form) {
document.calc.resultHelp.value = ("RESULT: This is your down payment amount less your total estimated closing costs.");
}
function help10_es(form) {
document.calc.resultHelp.value = ("RESULTADO: Este es su pago inicial (enganche) menos el total de sus costos estimados de cierre.");
}

function help11(form) {
document.calc.resultHelp.value = ("RESULT: This is the maximum mortgage you would qualify for based on your current entries.");
}
function help11_es(form) {
document.calc.resultHelp.value = ("RESULTADO: Esta es la hipoteca máxima a la que usted calificaría con base en sus anotaciones actuales.");
}

function help12(form) {
document.calc.resultHelp.value = ("RESULT: This is home price you could afford (the total of your down payment and your maximum mortgage amount.");
}
function help12_es(form) {
document.calc.resultHelp.value = ("RESULTADO: Este es el precio de la casa que usted puede asumir (el total de su pago inicial -enganche- y su monto máximo de  hipoteca.");
}

function help13(form) {
document.calc.resultHelp.value = ("RESULT: This is your maximum monthly mortgage payment based upon your current entries.");
}
function help13_es(form) {
document.calc.resultHelp.value = ("RESULTADO: Este es su pago máximo mensual de hipoteca, con base en sus anotaciones actuales.");
}

