/* pmf1.js */

pd = 'paydata'; /* saving calculator data */
numDays = 60;  /* days until cookie expires (eg. 183 days = 6 months) */

/* function that adds commas to the currency value (i.e. $1000000.00 -> $1,000,000.00) */

function addCommas(currencyValue){
	currencyValue = "" + currencyValue;
	var dollars = 0;
	var cents = "";
	if (currencyValue.indexOf(",") != -1){
		return currencyValue;
	} else if (currencyValue.indexOf(".") != -1 ){
		dollars = currencyValue.substring(0,currencyValue.indexOf("."));
		cents = currencyValue.substring(currencyValue.indexOf("."),currencyValue.length);
	} else if (currencyValue > 0){
		dollars = currencyValue;
	} else {
		return currencyValue;
	}
	var returnValue = "";
	for (var i=1;i<=dollars.length;i++){
		if (i % 3 == 1 && i != 1){
			returnValue = "," + returnValue;
		}
		returnValue = dollars.charAt(dollars.length - i) + returnValue;
	}
	returnValue += cents;
	return returnValue;
}

/*  the following two functions check that all numeric values are real number 
and remove double decimals */

function check(a){
   	var pest = 0;
   	var b = "";
   	for(i = 0; i <= a.length; i++){
   		var u = a.charAt(i);
      	if((u >= "0" && u <= "9") || u == "."){
        	if(u == "."){
        		var pest = pest + 1;
        		if(pest == 2){
					break;
				}
			}
			var b = b + u;
		}
	}
	return b;
}

function doSum(a){
	a.value = check(a.value);
}

/* tests versions for which will support pop up windows */
function versTest(){
	var one = '';
	var two = '';
	if((navigator.appName.substring(0,8)=="Netscape" && (navigator.appVersion.substring(0,3) == "3.0" ||  navigator.appVersion.substring(0,3) =="4.0"))){
		var one='true';
	}
	if((navigator.appName.substring(0,9) == "Microsoft" && navigator.appVersion.substring(0,3) == "3.0" && navigator.appVersion.indexOf("Macintosh")>=0)){
		var two='true';
	}
	if(one=='true' || two=='true' || (navigator.appName.substring(0,9) == "Microsoft" && navigator.appVersion.indexOf("MSIE 3.0")>=0 && navigator.appVersion.indexOf("Windows 3.1")>=0)){
		return true;
	}else{
		return false;
	}
}

/* tests if version is msie 3.0 for mac */
function msTest(){
	if(navigator.appName.substring(0,9) == "Microsoft" && (navigator.appVersion.substring(0,3) == "3.0" && navigator.appVersion.indexOf("Macintosh")>=0)){
		return true;
	}else{
		return false;
	}
}

function nineTest(){
	if(navigator.appName.substring(0,9) == "Microsoft" && (navigator.appVersion.substring(0,3)=="3.0" || navigator.appVersion.indexOf("MSIE 3.0")>=0) && (navigator.appVersion.indexOf("Macintosh")==-1 || navigator.appVersion.indexOf("Windows 3.1")== -1)){
		return true;
	}else{
		return false;
	}
}

/* opens pop up window to display validation messages in netscape 3.0 and 4.0 */

function fixpro(n,q){
	if(versTest() == true){
		if(msTest() == true){
			var winNam = '';
		}else{
			var slash = location.href.lastIndexOf("/")+1;
			var filNam = location.href.substring(0,slash);
			var winNam = filNam+'empty.asp';
		}
		fix = window.open(winNam,'FIX','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=300,height=100');
		if(navigator.appName.substring(0,8) == "Netscape"){
			fix.focus();
      	}
		fix.document.write('<html>\n<head><title>Pay Your Mortgage Off Faster</title>');
		fix.document.write('</head>\n<body bgcolor="#ffffff"><form name="fixer">');
		fix.document.write(n + '<p>' + q + '<p>');
		fix.document.write('<center><input type=button value="OK" onclick="self.close()">');
		fix.document.write('</center></form>\n</body>\n</html>');
		fix.document.close();
	}else{
		alert(n+'\n'+q)
	}
}

/* function confirms that the value entered into a field falls within 
the pre-determined minimum and maximum values, and displays an error 
message with the allowable numeric range for the field data in a pop 
up validation window */

function checkNumber(quest,input, min, max, msg){
	var str = input.value;
    for (var i = 0; i < str.length; i++) {
		var ch = str.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && ch != '.') {
  			alert(msg);
            return false;
        }
    }
    if(input.value != ""){
    	var num = 0 + str;
    	if (num < min || max < num){
    		var sendn = msg + ":";
    		var sendq = "You have entered " + input.value + ". Please enter a number between " + min + " and " + max + ".";
  			fixpro(sendn,sendq);
        	return false;
    	}
    	input.value = str;
    	return true;
    }
}

/* calls upon the functions to determine if the numbers entered are valid 
and to calculate the results of the entered data for example - mortgage 
payment, gds and tds ratios, and loan to value. this function is executed 
everytime a value is changed in a field */

function computeField(quest,input,min,max,msage){
	doSum(input);
	return (checkNumber(quest,input,min,max,msage));
}

/* returns the selected index value of select lists in the calculator to be 
used in calculations */

function getIndex(n){
	return n.selectedIndex;
}

function calcRdefine(intrate,compound, freq){
	return Math.pow((1.0 + ((intrate / 100) / compound)),(compound/freq)) - 1.0;
}

function calcBal(mortgage,intrate,compound,freq,payment,term){
	rdefine = calcRdefine(intrate,compound, freq);
	return (mortgage * (Math.pow((1.0 + rdefine),(term)))) -  ((payment * ((Math.pow((1.0 + rdefine),(term))) - 1.0))/rdefine);
}

/* rounds off monetary numbers to two decimals (pennies) */

function roundPen(n){
	if(n > 0){
		pennies = n * 100;
		pennies = Math.round(pennies);
		strPennies = "" + pennies;
		len = strPennies.length;
		return strPennies.substring(0, len - 2) + "." + strPennies.substring(len - 2, len);
	}else{ 
		return 0;
	}
}

/* this function calculates the loan to value ratio */

function LTVcalc(MORTGAGE, MORTGAGE2, APPRAISE){
	return (MORTGAGE/APPRAISE) + (MORTGAGE2/APPRAISE);
}

function Ratios(PAY1, PAY2, HEAT, TAX, DEBT, INCOME){
	return (PAY1/INCOME)+(PAY2/INCOME)+(HEAT/INCOME)+(TAX/INCOME)+(DEBT/INCOME);
}

/* this function calculates the monthly mortgage payment based on the user's input */

function calcPay(MORTGAGE, AMORTYEARS, INRATE, COMPOUND, FREQ){
	var compound = COMPOUND / 12;
	var monTime = (AMORTYEARS * 12);
	var RATE = (INRATE * 1.0) / 100;
	var yrRate = RATE / COMPOUND;
	var rdefine = Math.pow((1.0 + yrRate),compound) - 1.0;
	var PAYMENT = (MORTGAGE * rdefine * (Math.pow((1.0 + rdefine),monTime))) / ((Math.pow((1.0 + rdefine),monTime)) - 1.0);
	if(FREQ == 12){
        return PAYMENT;
	}
	if(FREQ == 26){
        return PAYMENT / 2.0;
	}
	if(FREQ == 52){
        return PAYMENT / 4.0;
	}
	if(FREQ == 24){
        var compound2 = COMPOUND/FREQ;
        var monTime2 = (AMORTYEARS * FREQ);
        var rdefine2 = Math.pow((1.0 + yrRate),compound2) - 1.0;
		var PAYMENT2 = (MORTGAGE * rdefine2 * (Math.pow((1.0 + rdefine2),monTime2))) / ((Math.pow((1.0 + rdefine2),monTime2)) - 1.0);
		return PAYMENT2;
	}
}

function retTerm(n){
	if(n == 0){
		return 0;
	}
	if(n == 1){
		return 6;
	}
	if(n == 2){
		return 12;
	}
	if(n == 3){
		return 24;
	}
	if(n == 4){
		return 36;
	}
	if(n == 5){
		return 60;
	}
	if(n == 6){
		return 84;
	}
	if(n == 7){
		return 120;
	}
	if(n == 8){
		return 300;
	}
}

function retFreq(n){
	if(n == 0){
		return 0;
	}
	if(n == 1){
		return 12;
	}
	if(n == 2){
		return 24;
	}
	if(n == 3){
		return 26;
	}
	if(n == 4){
		return 52;
	}
}

function calcTotal(MORTGAGE, LTV){
	if(LTV > .75 && LTV <= .80){
		return MORTGAGE * 1.0125;
	}
	if(LTV > .80 && LTV <= .85){
		return MORTGAGE * 1.02;
	}
	if(LTV > .80){
		return MORTGAGE * 1.025;
	}
	if(LTV <= .75){
		return MORTGAGE
	}
}

/* saves cookie containing data to be used in amortization schedule */

function quickCook(MTGAMT,AMORTYEARS,RATE,TERM,FREQ,WHATYEAR){
	if (WHATYEAR && WHATYEAR == -1 ){
		var timeKindA = 0;
	}else{
        WHATYEAR = 0;
        var timeKindA = 1;
	}
	var AMORTPMT = calcPay(MTGAMT, AMORTYEARS, RATE, 2, FREQ);
	var intrate = RATE / 100;
	var INTFACTOR = Math.pow((1 + intrate / 2),(2 / FREQ)) - 1;
	var expire = new Date ();
	expire.setTime (expire.getTime() + (numDays * 24 * 3600000)); /* 2 months */
	var pdData = " " ;
	pdData = pdData + '`' + MTGAMT + '`' + AMORTPMT + '`' + INTFACTOR + '`' + FREQ + '`' + (AMORTYEARS * FREQ) + '`' + 0 + '`' + 0 + '`' + (TERM / 12) + '`' + timeKindA + '`' + RATE * 1.0 / 100 + '`' + 0 + '`' + WHATYEAR + '`' + 0 + '`' + 0 + '`' + 0 + '`' + 0 + '`' + 0;
	document.cookie = pd + "=" + escape(pdData) +"; expires=" + expire.toGMTString()+"; path=/" ;
}

/* validates all the fields and calculates values to be entered into 
the text boxes at the bottom of the page when the user clicks on compute 
or compute amortization */

function compute(form,year){

	if(document.paycalculator.desterm.selectedIndex == 0){
		fixpro('Mortgage Term:','You have not answered this question, click on the PLEASE CHOOSE button to select your option.');
		return false;
	}
	if(document.paycalculator.pfreq.selectedIndex == 0){
		fixpro('Payment Frequency:','You have not answered this question, click on the PLEASE CHOOSE button to select your option.');
		return false;
	}
	if((document.paycalculator.namortyears.value < 0 || document.paycalculator.namortyears.value > 40)){
		fixpro('Amortization Period - Years:','Please enter a number between 0 and 40.');
		return false;
	}
	if((document.paycalculator.mortamt.value == null|| document.paycalculator.mortamt.value.length == 0)|| (document.paycalculator.mortamt.value <10000|| document.paycalculator.mortamt.value > 1000000) ){
		fixpro('Mortgage Amount:','Please enter a number between 10000 and 1000000.');
		return false;
	}
	if((document.paycalculator.rate.value == null || document.paycalculator.rate.value.length == 0)||(document.paycalculator.rate.value < 2 || document.paycalculator.rate.value > 25)){
		fixpro('Interest Rate:','Please enter a number between 2.0 and 25.0.');
		return false;
	}																						  // + document.paycalculator.namortmonths.value
	if(retTerm(document.paycalculator.desterm.selectedIndex) > (document.paycalculator.namortyears.value*12)){
		fixpro('Mortgage Term:','The selected mortgage term is greater than the amortization period entered.  Increase the amortization period or choose a shorter mortgage term.');
		return false;
	}

	term = retTerm(document.paycalculator.desterm.selectedIndex);
	freq = retFreq(document.paycalculator.pfreq.selectedIndex);
	amortyears = document.paycalculator.namortyears.value;
	mortgageA = document.paycalculator.mortamt.value;
	intrate = document.paycalculator.rate.value;
	var payment = calcPay(mortgageA, amortyears, intrate, 2, freq);
	var intFact = Math.pow((1 + (intrate / 100) / 2),(2 / freq)) - 1;
	// need to determin the number of payments so we can correctly determin the Amortization period
	// and the remaing balance
	var principalBal = mortgageA;
	var aYear = 0;
	var annualCount = 1;
	var year1 = 0;
	var year2 = 0;
	var year3 = 0;
	var year5 = 0;
	var year10 = 0;
	var year25 = 0;

	for(payAdd = 1; principalBal > 0; payAdd++){
        var checkLump = 0;
        var printPayments = Math.ceil(1 / freq);// expressed in Years    
        var printYear = printPayments * freq;// expressed in Payments
        // set flag if this payment is an anniversary
		if((payAdd - 1) / Math.floor(freq) == annualCount){
      		var aYear = 1;
		}
        // interest and principal payment
        var interestPayment = roundPen(principalBal * intFact) * 1.0;
        var principalPayment =  roundPen(payment - interestPayment) * 1.0;
        var checkBal = (principalPayment > principalBal) ? principalBal : principalPayment;
        var principalBal =  roundPen(principalBal - checkBal) * 1.0;
        // lumpsum payment if requested
        if(aYear == 1 && 0 >= annualCount){
        	var checkLump = (lumpAmt > principalBal) ? principalBal : lumpAmt;
       		var principalBal = roundPen(principalBal - checkLump) * 1.0;
		}
        // eliminates balance (adds it to principal paid) if less than half
        if(principalBal < ((interestPayment+principalPayment) / 2)){
          	var checkBal = checkBal + principalBal;
       		var principalBal = 0;
		}
        // resets the anniversary
        if(aYear == 1){
         	var annualCount = annualCount + 1;
          	var aYear = 0;
		}

        if((payAdd / freq) == 1){
  			year1 = principalBal;
        } else if((payAdd / freq) == 2){
         	year2 = principalBal;
        } else if((payAdd / freq) == 3){
          	year3 = principalBal;
        } else if((payAdd / freq) == 5){
          	year5 = principalBal;
        } else if((payAdd / freq) == 10){
           	year10 = principalBal;
        } else if((payAdd / freq) == 25){
           	year25 = principalBal;
        }
	}

	var totalYears = (payAdd - 1) / freq;
	form.newamortyears.value = Math.floor(totalYears);;
	form.mainpay.value = '$' + addCommas(roundPen(payment));
	form.mainyr1.value = '$' + addCommas(roundPen(year1));
	form.mainyr2.value = '$' + addCommas(roundPen(year2));
	form.mainyr3.value = '$' + addCommas(roundPen(year3));
	form.mainyr5.value = '$' + addCommas(roundPen(year5));
	form.mainyr10.value = '$' + addCommas(roundPen(year10));
	form.mainyr25.value = '$' + addCommas(roundPen(year25));
	quickCook(mortgageA,amortyears,intrate,term,freq,year);
	return true;
}

/* loads the amortization schedule file once it is certain that all values 
entered into the form are correct. */

function amortLink(whatyear){
	if(navigator.appVersion.substring(0,3) == 2.0 &&  navigator.appName.substring(0,8)=="Netscape" && (navigator.appVersion.indexOf("Macintosh")>=0||navigator.appVersion.indexOf("PowerPC")>=0)){
		var timere = compute(document.forms['paycalculator'],whatyear);
		if(timere == true){
			setTimeout("document.form2.submit()",100);
		}
	}else{
		if(compute(document.forms['paycalculator'],whatyear) == true){
			document.form2.submit();
		}
	}
}

function amortonLink(){
	if(compute(document.forms['paycalculator'])==true){
		document.form2.submit();
		return false;
	}else{
		return false;
	}
}

function payBal(){
	if(navigator.appVersion.substring(0,3) == 2.0 &&  navigator.appName.substring(0,8)=="Netscape" && navigator.appVersion.indexOf("Macintosh")>=0){
		setTimeout("compute(document.forms['paycalculator'])",200);
	}else{
		compute(document.forms['paycalculator']);
	}
}

