// <script> for mtgcalculator.js

function trim(str)
{
     return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function dosum(formvariable, calculateamortize) {
teststate = true
 frm = document.frmCalculator;
 while (teststate) {
      if (trim(frm.txtMortgageAmount.value) == "" && trim(frm.txtMortgageAmount.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
} 
function GenerateValue(formvariable) 
{  
  var tmp1, tmp2, tmp3, tmp4 
  tmp1 = parseFloat(frm.txtMortgageAmount.value);
		
  if (isNaN(tmp1)) tmp1=0;
  tmp2 = parseFloat(frm.txtInterestRate.value);
		
  if (isNaN(tmp2)) tmp2=0;
  tmp3 = parseFloat(frm.ddMortgageLength.options[frm.ddMortgageLength.selectedIndex].value);
		
  if (isNaN(tmp3)) tmp3=0;
  if (frm.hidPaymentFrequency.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.txtPaymentAmount.value = formatCurrency(Payment);
   frm.txtTotalInterest.value = formatCurrency(Interest);
  return(true)
}


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);
}


function GeneratePage(formvariable, calculateamortize)
{
	var tmp1, tmp2
	tmp1 = document.frmCalculator.txtMortgageAmount.value;
	tmp2 = document.frmCalculator.txtInterestRate.value;
	tmp3 = document.frmCalculator.ddMortgageLength.options[document.frmCalculator.ddMortgageLength.selectedIndex].value;
	   if (calculateamortize.name == "btnCalculate") {
		  return(false)
		}

		body = ("<HEAD><TITLE>Amortization Table</TITLE></HEAD>");	  
		body = (body + "<link href='style.css' rel='stylesheet' type='text/css'>");
		body = (body +"<BODY style='background-color: #ffffff; background-image:none; margin:10px'>");
		body = (body +"<h3>Amortization Table</h3>");
		body = (body +"An Amortization Table calculates the periodic payment breakdown for each specific category listed.<br><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 border='0' cellpadding='0' cellspacing='1' width='100%' class='text'>");
		body = (body +"<TR><TD ALIGN=CENTER class='text'><B>Year</B></TD><TD ALIGN=RIGHT class='text'><B>Interest&nbsp;</B></TD><TD ALIGN=RIGHT class='text'><B>Principal&nbsp;</B></TD><TD ALIGN=RIGHT class='text'><B>Balance&nbsp;</B></TD></TR>\n");
		createtable(formvariable)
		body = (body +"</TABLE></CENTER>");      
		msgWindow=window.open("","displayWindow","toolbar=no,width=400,height=400,directories=no,status=no,scrollbars=yes,resize=no,menubar=no")
		msgWindow.document.write(body)
		msgWindow.document.close()
		return(true)
}

function createtable(formvariable)
{
	var tmp3
 if (frm.hidPaymentFrequency.value = "Monthly")
  { 
	tmp3 = 12;
  }
  else
  {
	tmp3 = 26 ;
  }
   var currInterest = 0
   var currPrin = 0
   prevBalance = frm.txtMortgageAmount.value;
   InterestRate = ( frm.txtInterestRate.value /100) / tmp3;
   MonthlyPayment = Payment;   
   currDate = new Date();
   currStart = currDate.getFullYear(); //document.frmCalculator.START.options[document.frmCalculator.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 class='text'>"+ currStart +"</TD><TD ALIGN=RIGHT class='text'>"+ formatCurrency(currInterest) +"&nbsp;</TD><TD ALIGN=RIGHT class='text'>"+ formatCurrency(currPrin) +"&nbsp;</TD><TD ALIGN=RIGHT class='text'>"+ formatCurrency(currBalance)+"&nbsp;</TD></TR>");
      currInterest = 0
      currPrin = 0
      currStart = parseInt(currStart)
      currStart += 1
      if(currBalance<=0) {
         return(true)
      }  
   }
   return (true)
}

function MyCheckEnteredValue(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!");
			element.focus();
			element.select();
			return false;
		}

	element.value=lField; 
	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;
}
