// from howmuchcaniafford.html
function calc_howMuchCanIAfford(form){ // used to be count(form)
    if (( trim(form.mortAmt.value) != "" && trim(form.numYears.value) != "" && trim(form.propTax.value) != "" && trim(form.debt.value) != "" && trim(form.mortRate.value) != "")) {   	
		var tmp1,tmp2, tmp3, tmp4, tmp5, tmp6 ,tmp7, tmp8, tmp9, tmp10, tmp11, tmp12, tmp13, tmp14, tmp15
		tmp1 = parseFloat(form.mortAmt.value); if (isNaN(tmp1)) tmp1=0;
		tmp2 = parseFloat(form.numYears.value); if (isNaN(tmp2)) tmp2=0;
		tmp3 = parseFloat(form.mortRate.value); if (isNaN(tmp3)) tmp3=0;
		tmp4 = parseFloat(form.propTax.value); if (isNaN(tmp4)) tmp4=0;
		tmp5 = parseFloat(form.debt.value); if (isNaN(tmp5)) tmp5=0;
		tmp6 = 0;
		tmp7 = tmp4/12;
		tmp8= tmp5;
	    tmp9 = tmp3/1200;
	    tmp10= tmp2 * 12;
	    tmp11 = (1 + tmp9);
		for (i=1; i < tmp10; i++) {
		    tmp11 = tmp11 * (1 + tmp9);
	    }
	    tmp12  = tmp1 * tmp11 * tmp9 / (tmp11 - 1);
	    tmp13 = tmp12 + tmp7 + tmp8;
	    tmp14= (tmp12 + tmp7) / 0.28;
	    tmp15 = tmp13 / 0.35;
	    if (tmp14 > tmp15) {
			tmp6 = 12 * tmp14;
	    } else {
			tmp6 = 12 * tmp15;
	    }
	    form.mortPay.value = round(tmp12);
		form.totalPay.value = round(tmp13);
	    form.reqdSal.value = round(tmp6);
	}
} 

// from howmuchcaniborrow.html
function calc_howMuchCanIBorrow(form) { // used to be count(form)
	var tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9, tmp10, tmp11
	if ( trim(form.income.value) != "" &&  trim(form.other.value) != "" &&  trim(form.taxes.value) != "" &&  trim(form.insurance.value) != "" &&  trim(form.auto.value) != "" &&  trim(form.cards.value) != "" &&  trim(form.term.value) != "" &&  trim(form.rate.value) != ""){
    	tmp12 = Math.round(eval(form.income.value * .28) + eval(form.other.value * .28) - form.taxes.value - form.insurance.value);
    	tmp13 = Math.round(eval(form.income.value * .36) + eval(form.other.value * .36) - form.taxes.value -  form.insurance.value - form.auto.value - form.cards.value);
	    if (tmp12>tmp13) {
	    	form.payment.value = tmp13
	    } else {
	    	form.payment.value = tmp12
	    }
	    tmp1 = parseFloat(form.rate.value); if (isNaN(tmp1)) tmp1=0;
	    tmp2 = parseFloat(form.term.value); if (isNaN(tmp2)) tmp2=0;
	    tmp3 = parseFloat(form.payment.value); if (isNaN(tmp3)) tmp3=0;
	    tmp4 = parseFloat(tmp1 / 1200); 
	    tmp5 = parseFloat(tmp2 * 12);
	    tmp6 = parseFloat(1 + tmp4);
	    tmp7 = parseFloat(Math.pow(tmp6, tmp5));
	    tmp8 = parseFloat(1 / tmp7);
	    tmp9 = parseFloat(1 - tmp8);
	    tmp10 = parseFloat(tmp9 / tmp4);
	    tmp11 = parseFloat(tmp3 * tmp10);
		form.amount.value = Math.round(tmp11);
    } else {
		alert("Please enter valid numerical data in all fields!");
		return false;
	}
}

// from howmucharemypayments.html
function calc_howMuchAreMyPayments(frm) {  // used to be dosum(frm) 
	// frm = document.temps;
	var mi = frm.IR.value / 1200;  
	var counter = 1;  
	var mcounter = 1 + mi;  
	for (i=0; i<frm.YR.value * 12; i++) {   
		counter = counter * mcounter  
	}  
	frm.PI.value = round(frm.LA.value * mi / ( 1 - (1/counter)))  
	frm.MT.value = round(frm.AT.value / 12)  
	frm.MI.value = round(frm.AI.value / 12)  
	var dasum = frm.LA.value * mi / ( 1 - (1/counter)) + frm.AT.value / 12 + frm.AI.value / 12;
    frm.MP.value = round(dasum);
}

// from howmuchofadownpayment.html
function calc_howMuchDownPayment(frm){ // used to be dosum(frm), and just dosum() before I commented the line below and added the parm
	// var frm = document.main;	
	var tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8, tmp9, tmp10
	tmp1 = parseFloat(frm.home.value);	if (isNaN(tmp1)) tmp1=0;
	tmp2 = parseFloat(frm.dp_percent.value); if (isNaN(tmp2)) tmp2=0;
	tmp3 = parseFloat(frm.rate.value); 	if (isNaN(tmp3)) tmp3=0;
	tmp4 = parseFloat(frm.close_points.value); 	if (isNaN(tmp4)) tmp4=0;
	tmp5 = parseFloat(frm.term.options[frm.term.selectedIndex].value); if (isNaN(tmp5)) tmp5=0;
	tmp6 = parseFloat(frm.tax.value);  if (isNaN(tmp6)) tmp6=0;
	tmp7 = parseFloat(frm.insurance.value); if (isNaN(tmp7)) tmp7=0;
	frm.mortgage.value = round(tmp1 - ((tmp2 / 100) * tmp1));	
	tmp8 = parseFloat(frm.mortgage.value); 	if (isNaN(tmp8)) tmp8=0;
	frm.dp_amount.value = round(tmp1 * (tmp2 / 100));
	tmp9 = parseFloat(frm.dp_amount.value); if (isNaN(tmp9)) tmp9=0; 
	frm.mo_tax.value = round(tmp6 / 12);
	tmp10 = parseFloat(frm.mo_tax.value); if (isNaN(tmp10)) tmp10=0;
	frm.mo_ins.value = round(tmp7 / 12); 
	tmp11 = parseFloat(frm.mo_ins.value); if (isNaN(tmp11)) tmp11=0; 
	frm.points.value = round((tmp4 / 100) * tmp8);
	frm.close_cost.value = round(990 + (.01 * tmp8));
	frm.prepaids.value = round(((.015 * tmp8) * .8333) + (.0035 * tmp8));
	frm.mo_pmt.value = round(getPayment(tmp8, tmp3, tmp5));
	frm.totPmt.value = round(eval(frm.mo_pmt.value) + tmp10 + tmp11);
	frm.totalCash.value = round(tmp9 + eval(frm.points.value) + eval(frm.close_cost.value) + eval(frm.prepaids.value));
	frm.apr.value = getAPR(tmp5, tmp3, tmp8, frm.mo_pmt.value);
}
// from howmuchofadownpayment.html	
function getPayment(amount, rate, term) {
	rate = rate / 100;
	var payment = (amount * rate) / (1 - Math.pow((1 + (rate/12)), (-1 * (term*12))));
	return payment/12;
}
// from howmuchofadownpayment.html	
function oldTerm(rate, bal, mo_pmt) {
	var ppy = 12;
	rate = rate / 100;
	monthsLeft = -1 * (Math.log(1-(bal/mo_pmt)*(rate/ppy)))/Math.log(1+(rate/ppy));
	return monthsLeft;
}
// from howmuchofadownpayment.html
function getAPR (term, rate, amount, pmt) {
	months = term * 12;
	if (rate > 1) rate = rate / 100; 
	tmp1 = Math.round(((.01 * amount) + 375 + (((amount * rate) / 365) * 30))*100)/100;
	tmp2 = rate / 12;
	tmp3 = Math.round((amount - tmp1) * 100) / 100;
	cmpd = Math.pow( (1 + tmp2) , (-1 * months) );
	apr = ((pmt * (1 - (cmpd) )) / tmp3) * 12 * 100;
	apr = Math.round(apr * 1000) / 1000;
	return apr;
}

// from iwanttocompare3differentloans.html
function calc_loanPayment(form) { //used to be computeForm(form)
	if ((trim(form.payments.value)!= "") && (trim(form.interest.value)!= "") && (trim(form.principal.value)!= "")) {
		var tmp1, tmp2
		tmp1 = form.interest.value;
		if (tmp1 > 1.0){
			tmp1 = tmp1 / 100.0;
			form.interest.value = tmp1;
		}
		tmp1 /= 12;
		tmp2 = 1;
		for (var counter = 0; counter < form.payments.value; counter++)
	  		tmp2 = tmp2 * (1 + tmp1);
	    
		form.payment.value = (form.principal.value * tmp2 * tmp1) / (tmp2 - 1);
	}
}

// from howmuchcanisavebyconsolidating.html
function calc_consolidationSavings(form) { // used to be calculateForm(form)
	if ((trim(form.payments.value)!= "") && (trim(form.interest.value)!= "") && (trim(form.principal.value)!= ""))	{
		var i = form.interest.value;   
		if (i > 1.0) { 
			i = i / 100.0;        
			form.interest.value = i;    
		}   
		i /= 12;   
		var counter = 1;  
		for (var j = 0; j < form.payments.value; j++) // { 
			counter = counter * (1 + i);    
			
		form.payment.value 	= round(form.principal.value * counter * i) / (counter - 1);
		form.payment.value  = round(form.payment.value);    
		form.totalint.value = (form.payment.value * form.payments.value)-form.principal.value;
		form.totalint.value = round(form.totalint.value);
		// }
	}
}

// from amortizationscheduleandcalculator.html
function calc_amortizationSchedule(formvariable, calculateamortize) {
	var teststate = true;
 	// frm = document.MORTGAGE;
 	var frm = formvariable;
 	while (teststate) {
    	if (trim(frm.AMOUNT.value) == "" && trim(frm.RATE.value) == "") { 
    		alert("You have left a required value blank. Please type a number") ;
         	break;
	  	}
      	if (!GenerateValue(formvariable)){
			break;
      	}
     	if (!GeneratePage(formvariable, calculateamortize)){
        	break;
     	}
      	if (teststate) {
        	teststate = false;
      	}
	}
   	teststate = true;
} 
// from amortizationscheduleandcalculator.html
function GenerateValue(formvariable) {  
	var tmp1, tmp2, tmp3, tmp4;
	var frm = formvariable;
	tmp1 = parseFloat(frm.AMOUNT.value); if (isNaN(tmp1)) tmp1=0;
	tmp2 = parseFloat(frm.RATE.value); if (isNaN(tmp2)) tmp2=0;
	tmp3 = parseFloat(frm.YEARS.options[frm.YEARS.selectedIndex].value); if (isNaN(tmp3)) tmp3=0;
	if (frm.FREQUENCY.value = "Monthly") { 
		tmp4 = 12;
	} else {
		tmp4 = 26 ;
	}
	Payment = (tmp1*((tmp2/(tmp4*100))/(1-(Math.pow(1+(tmp2/(tmp4*100)),((tmp3*tmp4)*-1))))));
	Interest = ((Payment*(tmp3*tmp4))-tmp1);
	frm.PAYMENT.value = formatCurrency(Payment);
	frm.INTEREST.value = formatCurrency(Interest);
	return(true)
}
// from amortizationscheduleandcalculator.html
function GeneratePage(formvariable, calculateamortize){
	var tmp1, tmp2
	tmp1 = formvariable.AMOUNT.value;
	tmp2 = formvariable.RATE.value;
	tmp3 = formvariable.YEARS.options[formvariable.YEARS.selectedIndex].value;
	if (calculateamortize.name == "cmdCalc") {
		return(false)
	}

   	if (confirm("An Amortization Table calculates the periodic payment breakdown for each specific category listed.")) {
		body = ("<HEAD><TITLE>Amortization Table</TITLE></HEAD>");	  
		body = (body + "<link href='../styles.css' rel='stylesheet' type='text/css'>");
		body = (body +"<BODY class='mainText' BGCOLOR = '#FFFFFF'>");
		body = (body +"<span class='mainText'>Amortization Table</span><br>");
		body = (body +"The following table is based on the information entered in the calculator form.<br>");
		body = (body +"Mortgage Amount: " +formatCurrency(tmp1));
		body = (body +"<BR>Interest Rate: " + tmp2 + " %");
		body = (body +"<BR>Mortgage Length: " + tmp3 + " Years ");
		body = (body +"<BR><br><table class='mainText' border='0' width='80%'>");
		body = (body +"<TR><TD ALIGN=CENTER BGCOLOR=#EFEFE9><B>Year</B></TD><TD ALIGN=RIGHT BGCOLOR=#EFEFE9><B>Interest&nbsp;</B></TD><TD ALIGN=RIGHT BGCOLOR=#EFEFE9><B>Principal&nbsp;</B></TD><TD ALIGN=RIGHT BGCOLOR=#EFEFE9><B>Balance&nbsp;</B></TD></TR>\n");
		createtable(formvariable)
		body = (body +"</TABLE></CENTER>");      
		msgWindow=window.open("","displayWindow","toolbar=no,width=500,height=300,directories=no,status=no,scrollbars=yes,resize=no,menubar=no")
		msgWindow.document.write(body)
		msgWindow.document.close()
		return(true);
	}
	return(false);
}
// from amortizationscheduleandcalculator.html
function createtable(formvariable){
	var frm = formvariable;
	var tmp3
	if (frm.FREQUENCY.value = "Monthly")  { 
		tmp3 = 12;
	} else {
		tmp3 = 26 ;
	}
   var currInterest = 0
   var currPrin = 0
   prevBalance = frm.AMOUNT.value;
   InterestRate = ( frm.RATE.value /100) / tmp3;
   MonthlyPayment = Payment;   
   currStart = formvariable.START.options[formvariable.START.selectedIndex].value;  
   for(i=1;i<=30;i++) {
      for(j=1;j<=tmp3;j++) {
         periodInterest = prevBalance * InterestRate;
         periodPrin = MonthlyPayment - periodInterest;
         currBalance = prevBalance - periodPrin;
         currInterest += periodInterest;
         currPrin += periodPrin;
         prevBalance = currBalance;
      }
      if( currBalance <= 0 )   currBalance = 0;
      body = (body +"<TR><TD ALIGN=CENTER>"+ currStart +"</TD><TD ALIGN=RIGHT>"+ formatCurrency(currInterest) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ formatCurrency(currPrin) +"&nbsp;</TD><TD ALIGN=RIGHT>"+ formatCurrency(currBalance)+"&nbsp;</TD></TR>");
      currInterest = 0
      currPrin = 0
      currStart = parseInt(currStart)
      currStart += 1
      if(currBalance<=0) {
         return(true)
      }  
   }
   return (true)
}
// from amortizationscheduleandcalculator.html
function formatCurrency(num) {	
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' +  num + '.' + cents);
}


// from howmucharemypayments.html, howmuchcaniborrow.html and amortizationscheduleandcalculator.html (and replaces the one with the same name from howmuchofadownpayment.html)
function MyCheckEnteredValue(element) {
	var lField = ltrim(rtrim(String(element.value)));
	myReg=new RegExp("^[0-9]*\\.?[0-9]*$"); 
	if (!(myReg.test(lField) && lField!='.' && lField!='$')) {
		alert("Only numeric values are allowed!");
		element.focus();
		element.select();
		return false;
	}
	element.value=lField; 
	return true;
}
// from howmucharemypayments.html
function MyCheckEnteredValuePercent(element) {
	/*
	var lField = ltrim(rtrim(String(element.value)));
	myReg=new RegExp("^[0-9]*\\.?[0-9]*?$"); 
	if (!(myReg.test(lField) && lField!='.' )) {
		alert("Only numeric values are allowed ");
		return false;
	}
	//100% test
	if (parseFloat(lField)>100) {
		alert("Percentage values must be between 0 and 100!")
		return false;
	}
	*/
	// validity test...
	if (!(checkInput(element, 0, 100, "Percentage values must be between 0 and 100!\n"))){
		return false;
	}
	return true;
}

// from howmuchcaniafford.html, howmuchcanisavebyconsolidating.html and iwanttocompare3differentloans.html
function checkInput(input, min, max, msg){   
	msg = msg + " field has invalid data: " + input.value;
	/*
	var lField = ltrim(rtrim(String(input.value)));
	myeareg=new RegExp("^[$]?[0-9]*\\.?[0-9]"); 
	if (!(myeareg.test(lField) && lField!='.'))	{          
		alert("Only numeric values are allowed!");
		input.focus();
		input.select();
		return false;
	}   	
	*/
	if (!(MyCheckEnteredValue(input))){
		return false;
	}
	var num = parseFloat(input.value);
	if (num < min || max < num)	{
		alert(msg + " not in range [" + min + ".." + max + "]"); 
		return false;    
	}      
	return true;
}

function rtrim(argvalue) {
	while (1) {
    	if (argvalue.substring(argvalue.length - 1, argvalue.length) != " "){
      		break;
    	}
    	argvalue = argvalue.substring(0, argvalue.length - 1);
  	}
  	return argvalue;
}

function ltrim(argvalue) {
	while (1) {
    	if (argvalue.substring(0, 1) != " "){
      		break;
    	}
    	argvalue = argvalue.substring(1, argvalue.length);
  	}
    return argvalue;
}

// Round a field two (2) decimals
function round(number) {
  return Math.round(number*Math.pow(10,2))/Math.pow(10,2);
}

function trim(str) {
     return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
