window.onerror=null
var bState = true;
var rec = 0;
var oTable = new Array();

var bColor = '#FFFFFF' // white
var fColor = '#000000' //black
oReq = new Collection("AMOUNT","RATE","","","","")
oVal = new Collection("AMOUNT","RATE","","","","")
oTst = new Collection("N","N","","","","")

function controller(oForm, oBtn) {
   while (bState) {
      if (!Required(oForm))
         break;
      if (!Validate(oForm))
         break;
      if (!Create())
         break;
      if (!SetValue(oForm))
         break;
      if (!Amortize(oForm, oBtn))
         break;
      if (bState) {
          bState = false
      }
   }
   bState = true
}

function Required(oView) {
   for (i in oView ) {
      for (j in oReq) {
          if (i == oReq[j]) {      
             if (isMissing(oView[i])) {
               return(false)
             }
          }
      } 
  }
  return(true)
}

function isMissing(oCtrl) {
   if (oCtrl.value == "") {  
      alert("You have left a required value blank. Please type a number");
      oCtrl.focus();
      oCtrl.select();	
      return(true)
      }
   else
      { 
      return(false)
   }
}

function Validate(oView) {
   for (i in oView) {
      for (j in oVal) {
        if (i==oVal[j] && oTst[j]=="N") {      
           if (isTest(oView[i], oTst[j])) {
               return(false)
           }
        }
     }
  }
  return(true)
}

function isTest(oCtrl, oTest) {
   if (oTest=="N" && !isNumber(oCtrl.value) ) {
      alert(oCtrl.value+" contains an invalid character. Please type a number");
      oCtrl.focus();
      oCtrl.select();
      return(true)
      }
      else
      { 
      return(false)
   }
}

function isNumber(input) {
var result = ""
var nperiods = 0;
   for (var i=0;i<input.length;i++) {
      var ch = input.substring(i, i+1);
      if (!isNaN(parseInt(ch))) {
         result = result + ch
      } 
      if (ch==".") {
        nperiods++;
      }
      if (nperiods==1){
         result = result + ch  
      }
   }
   if (result == ""){
     return(false);
   }
return(true)
}

function makeNumber(input) {
var result = ""
var nperiods = 0;
   for (var i=0;i<input.length;i++) {
       var ch = input.substring(i, i+1);
       var flag = true;
       if (!isNaN(parseInt(ch))) {
          result = result + ch
       }           
       if (ch==".") {
         nperiods++;
       }
       if (nperiods==1){
          result = result + ch  
          nperiods = 0;
       }
     }
  return(result)
}

function Create() {
   Mortgage = new Loan(50000, 8, 30, 0, 0, "Monthly", 0 );
   return(true)
}

function SetValue(oView) {
   // get the properties mapped from the form
   Mortgage.Amount = makeNumber(oView.AMOUNT.value);
   // works like a masked edit
   oView.AMOUNT.value = calcRound(Mortgage.Amount);
   Mortgage.Rate = makeNumber(oView.RATE.value);
   Mortgage.Term = get_selection(oView.YEARS);
   Mortgage.Frequency = get_selection(oView.FREQUENCY);
   // set the number of periods
   Mortgage.calcPeriods();
   // set the monthly payment
   Mortgage.calcPayment();
   // set the total interest due
   Mortgage.calcInterest();
   // update the form view
   Show()
   return(true)
}

function Amortize(oForm, oBtn) {
   if (oBtn.name == "cmdCalc") {
      return(false)
   }
   if (confirm("We need to start another window\nto display the Amortization Table.")) {
      // need to create the table before you can show it
      createRecords();
      // display the table
      showAmortize(oForm);
      return(true)
    }
  return(false)
}

function createRecords(){
   // re-init the record counter and container array
   rec = 0;
   oTable = new Array();
   // initialize variables
   var currInt = 0;
   var currPrin = 0;
   prevBalance = Mortgage.Amount;
   InterestRate = ( Mortgage.Rate /100) / Mortgage.Periods;
   MonthlyPayment = Mortgage.Payment;
   //currStart = '1997';
   currStart = get_selection(document.MORTGAGE.START);
  
   // let the loops begin
   for(i=1;i<=30;i++) {
      for(j=1;j<=Mortgage.Periods;j++) {
         periodInt = prevBalance * InterestRate;
         periodPrin = MonthlyPayment - periodInt;
         currBal = prevBalance - periodPrin;
         currInt += periodInt;
         currPrin += periodPrin;
         prevBalance = currBal;
      }
      if( currBal <= 0 ){ 
         currBal = 0;
      }

      // set the parameters
      Year = currStart;
      Interest = calcRound(currInt);
      Principle = calcRound(currPrin);
      Balance = calcRound(currBal);
      // increment the container 
      rec++
      // add a record to the table
      addRecord(Year, Interest, Principle, Balance);
      // re-init the private variables
      currInt = 0;
      currPrin = 0;
      currStart = parseInt(currStart);
      currStart += 1;
      // are we done?
      if(currBal<=0) {
         return(true)
      }       
   }
   return (true)
}

function showAmortize(oForm) {
   // create the header
   text = ("<HEAD><TITLE>Amortization Table</TITLE></HEAD>");
   text = ("<script language='JavaScript' src='payment.js'></script>\n");
   text = ("<script language='JavaScript' src='closer.js'></script>\n");
   text = ("<link href=\"calc.css\" rel=\"stylesheet\" type=\"text/css\">\n");
   text = (text +"<BODY text=#000000 BGCOLOR="+bColor+" topmargin=0 marginheight=0><BR>\n");
   text = (text +"<DIV ALIGN='CENTER'><CENTER><TABLE BORDER='0' WIDTH='320' CELLPADDING='0' CELLSPACING='0'>\n");
   text = (text +"<TR><TD WIDTH='100%'>\n");
   text = (text +"<H4 ALIGN=CENTER><br><FONT FACE='ARIAL' COLOR="+fColor+" size=4>Amortization Table</FONT></H4>\n");
   text = (text +"<UL class='hdrInfo'><p>The following table is based on the information entered in the calculator form.</p>\n");
   text = (text +"<li><FONT FACE='ARIAL' SIZE=+1 COLOR="+fColor+"> Mortgage Amount: \n" +calcRound(Mortgage.Amount)+"</li>\n");
   text = (text +"<li><FONT FACE='ARIAL' SIZE=+1 COLOR="+fColor+">   Interest Rate: " + Mortgage.Rate + " %</li>\n");
   text = (text +"<li><FONT FACE='ARIAL' SIZE=+1 COLOR="+fColor+"> Mortgage Length: " + Mortgage.Term + " Years</li>\n");
   text = (text +"<li><FONT FACE='ARIAL' SIZE=+1 COLOR="+fColor+"> Payment Frequncy: " + Mortgage.Frequency + "  </li></UL>\n");
   text = (text +"<BR><CENTER><table border='0' width='350'>\n");
   text = (text +"<TR><TD ALIGN=CENTER class='tblTitle'><B>Year</B></FONT></TD><TD ALIGN=CENTER class='tblTitle'><B>Interest&nbsp;</B></FONT></TD><TD ALIGN=CENTER class='tblTitle'><B>Principal&nbsp;</B></FONT></TD><TD ALIGN=CENTER class='tblTitle'><B>Balance&nbsp;</B></FONT></TD></TR>\n");
     
   // create the Amortization table text by looping through a CONTAINER ARRAY 
   for (var q=1; q<oTable.length;q++) {
      text = (text +"<TR><TD ALIGN=CENTER class='tblCell'>"+ oTable[q].Year +"</TD><TD class='tblCell' ALIGN=RIGHT>"+ oTable[q].Interest +"&nbsp;</TD><TD class='tblCell' ALIGN=RIGHT>"+ oTable[q].Principle +"&nbsp;</TD><TD class='tblCell' ALIGN=RIGHT>"+ oTable[q].Balance +"&nbsp;</TD></TR>");
   }
   
   // create the footer  

   text = (text +"</TABLE></CENTER>");
   text = (text +"      </TD>\n");
   text = (text +"  </TR>\n");
   text = (text +"  <TR><FORM>\n");
   text = (text +"    <TD class='tblFoot' ALIGN='CENTER'><br>\n");
   text = (text +"    <INPUT TYPE='BUTTON' VALUE='Close Window' NAME='CloseWin'\n");
   text = (text +"    onClick=\"closewindow()\"><br><br></TD></FORM>\n");
   text = (text +"  </TR>\n");
   text = (text +"  <TR>\n");
   text = (text +"    <TD class='tblFoot' COLSPAN='2' ALIGN='CENTER'> Copyright ©\n");
   text = (text +"      2004 <B>YourOwnSite.com</B> All rights reserved.<br>\n");
   text = (text +"      Comments to</FONT><FONT FACE='ARIAL'SIZE='1' COLOR='#000000'>:</FONT><A\n");
   text = (text +"      HREF='MAILTO:Webmaster@YourOwnSite.com'><FONT FACE='ARIAL'SIZE='1'\n");
   text = (text +"      COLOR='#000000'> <b>Webmaster</B></FONT></A></TD>\n");
   text = (text +"  </TR>\n");
   text = (text +"  </TABLE>\n");
   text = (text +"</CENTER></DIV>\n");

   // Create a new window to display the results
   oWindow=window.open("","displayWindow","toolbar=no,width=400,height=350,directories=no,status=no,scrollbars=yes,resize=no,menubar=yes");
   oWindow.document.write(text);
   oWindow.document.close();

   return(true)
}

function Collection(item1, item2, item3, item4, item5, item6) {
   this.item1 = item1;
   this.item2 = item2;
   this.item3 = item3;
   this.item4 = item4;
   this.item5 = item5;
   this.item6 = item6;
}

function Loan(Amount, Rate, Term, Payment, Interest, Frequency, Periods ) {
   this.Amount = Amount;
   this.Rate = Rate;
   this.Term = Term;
   this.Payment = Payment;
   this.Interest = Interest;
   this.Frequency = Frequency;
   this.Periods = Periods;
   this.calcPeriods = calcPeriods;
   this.calcPayment = calcPayment;
   this.calcInterest = calcInterest;
}

function calcPayment() {
   this.Payment = (this.Amount*((this.Rate/(1200))/(1-(Math.pow(1+(this.Rate/(1200)),((this.Term*12)*-1))))));

  // handle bi-weekly 
  if ( this.Periods == 26 ){
      this.Payment = this.Payment / 2;
   }
}

function calcInterest() {
   this.Interest = ((this.Payment*(this.Term*this.Periods))-this.Amount);
}

function calcPeriods() {
   if (this.Frequency=="Monthly") { this.Periods=12 } else { this.Periods=26 }
}

function Show(oView) {
   document.MORTGAGE.PAYMENT.value = calcRound(Mortgage.Payment)
   document.MORTGAGE.INTEREST.value = calcRound(Mortgage.Interest)
}

function oRecord(Year, Interest, Principle, Balance){
   this.Year = Year;
   this.Interest = Interest;
   this.Principle = Principle;
   this.Balance = Balance;
}

function addRecord(Year, Interest, Principle, Balance){
   oTable[rec] = new oRecord(Year, Interest, Principle, Balance);
}

function select_item(name, value) {  
   this.name = name;
   this.value = value;
}

function get_selection(select_object) {   
   contents = new select_item();
   for(var i=0;i<select_object.options.length;i++)
      if(select_object.options[i].selected == true) {
        contents.name = select_object.options[i].text;
        contents.value = select_object.options[i].value;
      }      
   return(contents.name)
}

function calcRound(num) {
   result="$"+Math.floor(num)+"." ;
   n = result.length;
   if (num>1000 && num<999999) {  
     result="$"+result.substring(1,n-4)+","+result.substring(n-4,n);
   }
   if (num>1000000) {  
     result = "$"+result.substring(1,n-7)+","+result.substring(n-7,n-4)+","+result.substring(n-4,n);
   }
   var cents=100*(num-Math.floor(num))+0.5;
   result += Math.floor(cents/10);
   result += Math.floor(cents%10);
   return(result)
}

function setfocus() {   
   document.MORTGAGE.AMOUNT.focus();
   document.MORTGAGE.AMOUNT.select();
}

// unhide 
// -->
