window.onerror=null
var bState = true;
var rec = 0;
var oTable = new Array();

var bColor = '#FFFFFF' // white
// var fColor = '#98D43F' //green
var fColor = '#3f3e73' //mauve

var ftColor = '#000000' //black
var gColor = '#000000' //red



// names for the collections (used for form validation)
oReq = new Collection("AMOUNT","RATE","","","","")
oVal = new Collection("AMOUNT","RATE","","","","")
oTst = new Collection("N","N","","","","")


//============================================================================
// Gets called when the user pressed one of the buttons.
// oForm: 		form elements
// oBtn:  		the name of the button that was pressed
// return value:	did we make it through?
//============================================================================

function controller(oForm, oBtn) {

  
  while (bState) {


      if (!Required(oForm))

         break;

      if (!Validate(oForm))

         break;

      if (!Create())

         break;

      if (!SetValue(oForm))

         break;
      if (oBtn.name == "cmdAmortize")
	  {
		Mortgage.amortize(oForm)
	  }
	  else
	  {
		Mortgage.calcPayment(oForm);
	  }
      //Show(oForm);
      if (bState) {

          bState = false

      }

   }

   bState = true

}



//============================================================================
// Check if a form element is required by comparing the all of the form
// elements against a collection of required form control names.
// oView: 		form elements
// oReq		required elements
// return value:	did it pass the test?
//============================================================================

function Required(oView) {

   for (i in oView ) {

      for (j in oReq) {

          if (i == oReq[j]) {

             if (isMissing(oView[i])) {

               return(false)

             }

          }

      }

  }

  return(true)

}



//============================================================================
// Check if a form control is required and missing
// oView: 		a form control
// Return value:	do we have a problem?
//============================================================================

function isMissing(oCtrl) {

   if (oCtrl.value == "") {

      if (document.MORTGAGE.langJS.value == "Francais")
	  {
	  	alert("On ne peut laisser un champ vide, entrez un nombre");
	  }
	  else
	  {
	  	alert("You have left a required value blank. Please type a number");
	  }
	  

      oCtrl.focus();

      oCtrl.select();

      return(true)

      }

   else

      {

      return(false)

   }

}



//============================================================================
// Check if a form element inputs need to be a certain type by
// comparing all of the form elements against a collection of
// form controls that need specific types of input data.
// oView: 		form elements
// oReq		required elements
// return value:	did it pass the test?
//============================================================================

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)

}



//============================================================================
// Check if a form control input is the right type
// oView: 		a form control
// Return value:	do we have a problem?
//============================================================================

function isTest(oCtrl, oTest) {

   if (oTest=="N" && !isNumber(oCtrl.value) ) {

      if (document.MORTGAGE.langJS.value == "Francais")
	  {
	  	alert(oCtrl.value+" contient des symboles invalides. Entrez un nombre");
	  }
	  else
	  {
	  	alert(oCtrl.value+" contains an invalid character. Please type a number");
	  }
	  

      oCtrl.focus();

      oCtrl.select();

      return(true)

      }

      else

      {

      return(false)

   }

}



//============================================================================
// Check if the result is a number
// input: 		a texbox value
// Return value:	true / 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)

}



//============================================================================
// Make a string input into a number
// input: 		a texbox value
// Return value:	a number
//============================================================================

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 && ch=="."){

          result = result + ch

       }

     }
  return(result)

}


//============================================================================
// Create a default instance of the object
// parm1:	Amount	- required
// parm2:	Rate		- required
// parm3:   	Term		- required
// parm4:	Payment
// parm5:	Interest
// parm6:	Frequency	- required
// parm7:	Periods
// return value:	did we create the oebject?
//============================================================================

function Create() {

   Mortgage = new Loan(50000, 8, 30, 0, 0, "Monthly", 0 );

   return(true)

}


//============================================================================
// Set the properties of the object based on form inputs
// oView: 		form elements
// return value:	did it get and set the properties?
//============================================================================

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();

  

  
   // update the form view
  // Show()

   return(true)

}


//============================================================================
// Amortize is called at the end of the controler loop and checks to see
// if the amortize button was pushed
// oForm: 		form elements
// oBtn:  		the name of the button that was pressed
// return value:	did we select the Amortize button?
//============================================================================

function amortize(oForm) {

 	var P; //Principal
    var I; //Interets
    var L; //Amortisation en annees
    var N; //nombre de paiements totaux (non acc)
    var M; //paiement périodique
    var H; //paiement hypothèque périodique
    var C; //capital
    var Q; //balance due
	var NP; //nombre de paiements
    var X;
	var H2=0;
	var C2=0;
	var Affiche;
	var nombrepaym;
	nombrepaym = this.Periods;
	//Mettre conteurs a zero
    X=0;
	Affiche=0;
	rec=0;
	oTable = new Array();
    //Principal
	P = this.Amount;
	P2 = this.Amount;
    //taux interet annuel
	I = this.Rate;
	TauxAnnu = this.Rate/100;
	
    //Amortisation en annees
	L = this.Term; 
	
	//nombre de paiements totaux
	NP = parseInt(this.Periods); // nombre de paiements
    N = L*NP; // periodestotales
	
    //Taux interet par paiement
	I = Math.pow((1+TauxAnnu/2),(2/NP)) - 1;
	//Taux interet de base
	var intcandebase = Math.pow((1+TauxAnnu/2),(2/12)) - 1;
	
	//Et maintenant... les gros calculs...
	//paiements périodiques
	var paymperiobase  = (P * intcandebase) / ( 1 - ( 1/ Math.pow((1+intcandebase),(L*12))));
	this.Payment = paymperiobase;
	var M = paymperiobase;
	if (nombrepaym == '52a' || nombrepaym == '26a') {
		M = paymperiobase / (NP/13) ;
		this.Payment = M;
		
		
	} 
	if ((nombrepaym == '52' || nombrepaym == '26'|| nombrepaym == '2'|| nombrepaym == '1' )) {
		M = (P * I) / ( 1 - ( 1/ Math.pow((1+I),N)));
		this.Payment = M;
	} 
	//trouver amortiss réel
	if (nombrepaym == '52a' || nombrepaym == '26a') {
		kk = 0;
		inttotcana2 = 0;
		balcana2 = P2;
		paymcana2 = M;
    for (var jj = 0; jj < N; jj++) {
		intcana2 = I * balcana2;
		inttotcana2 = inttotcana2 + intcana2;
		balcana2    = balcana2 - (paymcana2 - intcana2); 
		kk = jj;
		if (balcana2 < 0 ) { 
			balcana2 = 0;
			amortreelmois = ((kk+1)/NP)*12,0; //Decimales(((kk+1)/NP)*12,0);
			amortreelmois = Digits(amortreelmois,2);// amortissement reel annee
			amortreel = (kk+1)/NP,2;//Decimales((kk+1)/NP,2);
			amortreel = amortreel.toFixed(2);//amortreel.substring(0,amortreel.length-2);
			break;
			}
		}
	}
 
if (nombrepaym == '52' || nombrepaym == '26'|| nombrepaym == '2'|| nombrepaym == '1' || 			    nombrepaym == '12')
{
		var TP = parseInt(N);
		if (TP < parseFloat(N)){TP=TP+1;}
}
		


var montreAns=0;
var compteurPaiement;
if (TP<1561)
{
	if (nombrepaym == '52' || nombrepaym == '52a' || nombrepaym == '26' || nombrepaym ==        '26a')
	{ // trouver les montants périodiques 
	
	   var montreAns=1;
	}
} //fin TP<1561
if (TP>1560){
	if (nombrepaym == '52' || nombrepaym == '52a' || nombrepaym == '26' || nombrepaym == '26a') { // trouver les montants annuels 
	
	}
} //fin TP>1560
// trouver les montants annuels

// fin des en-têtes

// afficher le reste du tableau

var totalPaiementAnnuel;
var balanceAnnuelle;
var currStart;
if (nombrepaym=="52a")
{
	totalPaiementAnnuel = 52 * this.Payment;
}
else if (nombrepaym=="26a")
{
	totalPaiementAnnuel = 26 * this.Payment;
}
else
{
	totalPaiementAnnuel = nombrepaym * this.Payment;
}

balanceAnnuelle = this.Amount;
currStart = get_selection(document.MORTGAGE.START);
currStart = parseInt(currStart);
currStart += 1;
//alert("N "+N);
while (X < N)
{
var P3;
P3=P2-C2;
Hp=0;
Q2=0;

if (montreAns==1)
{
	var z=(Affiche)/NP
	var z2=parseInt(z)-parseFloat(z)
	if (z>0)
	{
		if (z2>=0)
		{
			var text = z; //Tb1+"&nbsp;Ann&eacute;e&nbsp;"+z+Tbf+Tb1+Tbf+Tb1+Tbf+Tb1+Tbf+Tb1+Tbf+Tb1+Tbf+Tbf2;
		}
	}
}


cycle=1;
	if (nombrepaym == '52' || nombrepaym == '52a' || nombrepaym == '26' || nombrepaym == '26a') { // trouver les montants annuels
	cycle=NP;
		if (TP<1561){cycle=1;}
	}
//alert("cycle "+cycle);
for (i = 1; i <= cycle; i++) // trouver les montants annuels
{
	H=P*I; // hypo payé par paiement
	H2=H2+H; // intérets accumulés
	Hp=Hp+H; // interets payés
	C=M-H; // capital
	C2=C2+C; // capital accumulé
	//alert("C2 "+C2);
	Q=P-C; // balance due
	Q2=Q2+C; // capital remboursé
	//alert("Q2 "+Q2);
	P=Q;
	if (P2-C2 <= 0 )
	{
	    C2 = P2;
	    Q2 = P3;
		break;
	}
}	


if (nombrepaym == "52a")
{
	compteurPaiment = X;

	mod = compteurPaiment % 52; 
	if (mod == 0)
	{
		rec++;
		if (H2 < 0)
		{
			H2=0;
			totalPrincipalAnnuel = 0;
			balanceAnnuelle = 0;
		}
		else if (balanceAnnuelle < totalPaiementAnnuel)
		{
			totalPrincipalAnnuel = balanceAnnuelle;
			balanceAnnuelle = 0;
		}
		else
		{
			totalPrincipalAnnuel = totalPaiementAnnuel - H2;
			balanceAnnuelle = balanceAnnuelle - totalPrincipalAnnuel;
		}
		addRecord(currStart, Digits(H2,2), Digits(totalPrincipalAnnuel,2), Digits(balanceAnnuelle,2));
		//currStart = parseInt(currStart);
		currStart += 1;
		H2 = 0;
		C2 = 0;
	}
		
}
else if (nombrepaym == "26a")
{
	compteurPaiment = X;

	mod = compteurPaiment % 26; 
	if (mod == 0)
	{
		rec++;
		if (H2 < 0)
		{
			H2=0;
			totalPrincipalAnnuel = 0;
			balanceAnnuelle = 0;
		}
		else if (balanceAnnuelle < totalPaiementAnnuel)
		{
			totalPrincipalAnnuel = balanceAnnuelle;
			balanceAnnuelle = 0;
		}
		else
		{
			totalPrincipalAnnuel = totalPaiementAnnuel - H2;
			balanceAnnuelle = balanceAnnuelle - totalPrincipalAnnuel;
		}
		addRecord(currStart, Digits(H2,2), Digits(totalPrincipalAnnuel,2), Digits(balanceAnnuelle,2));
		//currStart = parseInt(currStart);
		currStart += 1;
		H2 = 0;
		C2 = 0;
	}
		
}
else
{
	compteurPaiment = X + 1;

	mod = compteurPaiment % nombrepaym; 
	if (mod == 0 && compteurPaiment > 0)
	{
		
		rec++;
		totalPrincipalAnnuel = totalPaiementAnnuel - H2;
		balanceAnnuelle = balanceAnnuelle - totalPrincipalAnnuel;
		addRecord(currStart, Digits(H2,2), Digits(totalPrincipalAnnuel,2), Digits(balanceAnnuelle,2));
		//currStart = parseInt(currStart);
		currStart += 1;
		H2 = 0;
		C2 = 0;
		
	}
}
X=X+cycle; // ajuster compteur paiements
Affiche=Affiche+1; // ajuster compteur
if (P2-C2 <= 0 ) {break;}
}
   if (document.MORTGAGE.langJS.value == "Francais")
	  {
    	showAmortize(oForm);
	  }
	  else
	  {
		showAmortizeEng(oForm);
	  }

}



//============================================================================
// create Records computes the values associated with the Amortzation of a Mortgage Loan and
// adds those values to a record in the Amortization table container array
// return value:	did we calculate all values to display in the Amortization?
//============================================================================

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 = 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)

}

//============================================================================
// Build a text string with a header, the table and a footer in HTML then
// diplay the table in a new window with only the menu active.
// oForm: 		form elements
// return value:	did we display the Amortization?
//============================================================================

function showAmortize(oForm) {

   // create the header

   text = ("<HEAD><TITLE>Table d'amortissement</TITLE></HEAD>");

   text = (text +"<BODY BGCOLOR =  "+bColor+">");

   text = (text +"<FONT face=Arial COLOR="+gColor+"><B>Table d'amortissement</B></FONT>");

   text = (text +"<BR><BR><FONT face=Tahoma, Verdana style=font-size:10pt>www.prethypotheque.ca</FONT>");

   text = (text +"<BR><BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Montant de l'emprunt:</B> </FONT>" +calcRound(Mortgage.Amount));

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Taux d'int&eacute;r&ecirc;t:</B> </FONT>" + Mortgage.Rate + " %");

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Dur&eacute;e de l'emprunt:</B> </FONT>" + Mortgage.Term + "&nbsp;ann&eacute;es");

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Fr&eacute;quence des versements:</B> </FONT>" + Mortgage.Frequency + "");

   text = (text +"<br><BR><CENTER><table border='1' width='100%' cellpadding='3' cellspacing='0' noshade>");

   text = (text +"<TR><TD ALIGN=CENTER BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Ann&eacute;es&nbsp;</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Int&eacute;r&ecirc;t&nbsp;</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Principale&nbsp;</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><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><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Year +"</font></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Interest +"</FONT></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Principle +"</FONT></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Balance +"</FONT></TD></TR>");

   }



   // create the footer

   text = (text +"</TABLE></CENTER>");



   // Create a new window to display the results

   oWindow=window.open("","displayWindow","toolbar=no,width=500,height=600,directories=no,status=no,scrollbars=yes,resize=no,menubar=yes");

   oWindow.document.write(text);

   oWindow.document.close();



   return(true)

}


//============================================================================
// Build a text string with a header, the table and a footer in HTML then
// diplay the table in a new window with only the menu active.
// oForm: 		form elements
// return value:	did we display the Amortization?
//============================================================================

function showAmortizeEng(oForm) {

   // create the header

   text = ("<HEAD><TITLE>Amortization Table</TITLE></HEAD>");

   text = (text +"<BODY BGCOLOR =  "+bColor+">");

   text = (text +"<FONT face=Arial COLOR="+gColor+"><B>Amortization Table</B></FONT>");

   text = (text +"<BR><BR><FONT face=Tahoma, Verdana style=font-size:10pt>www.prethypotheque.ca</FONT>");

   text = (text +"<BR><BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Mortgage Amount:</B> </FONT>" +calcRound(Mortgage.Amount));

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Interest Rate:</B> </FONT>" + Mortgage.Rate + " %");

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Mortgage Length:</B> </FONT>" + Mortgage.Term + " Years");

   text = (text +"<BR><FONT face=Tahoma, Verdana style=font-size:10pt COLOR="+ftColor+"><b>Payment Frequncy:</B> </FONT>" + Mortgage.Frequency + "");

   text = (text +"<br><BR><CENTER><table border='1' width='100%' cellpadding='3' cellspacing='0' noshade>");

   text = (text +"<TR><TD ALIGN=CENTER BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Year</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Interest&nbsp;</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><B>Principal&nbsp;</B></FONT></TD><TD ALIGN=RIGHT BGCOLOR="+fColor+"><FONT face=Arial style=font-size:10pt COLOR="+bColor+"><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><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Year +"</font></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Interest +"</FONT></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Principle +"</FONT></TD><TD ALIGN=RIGHT><FONT face=Tahoma, Verdana style=font-size:8pt>"+ oTable[q].Balance +"</FONT></TD></TR>");

   }
  // create the footer

   text = (text +"</TABLE></CENTER>");



   // Create a new window to display the results

   oWindow=window.open("","displayWindow","toolbar=no,width=500,height=600,directories=no,status=no,scrollbars=yes,resize=no,menubar=yes");

   oWindow.document.write(text);

   oWindow.document.close();



   return(true)

}





//============================================================================
// Collection Constructor, a custom object to act as an array but provide
// more flexibility in the future.
//============================================================================

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;

}



//============================================================================
// Loan Constructor, defines what the Loan object will look like
// and how it will behave.
//============================================================================

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;
   
   this.amortize = amortize;

}

function Digits (input,dec) {
        input += "";                         // Make sure input is a string:
        var original_input = input;          // Keep original copy of input string:
        var amount = parseFloat(input);      // Get float value:
		var posval = "";
		var decval = "";
        if (isNaN (amount))                  // Return unmodified input if we weren't able to convert it:
                return original_input;
		if (dec == 2) {
	        amount = Math.round (100 * amount);  // Express amount in pennies, rounded to the nearest penny:
	        var string;

	        if (amount < 10) {
	                string = "00" + amount;      // Convert amount to string and pad with leading zeros if necessary:
	        } else if (amount < 100) {
	                string = "0" + amount;
			} else {
	                string = "" + amount;
			}
			posval = string.substring(0,string.length - 2);
			decval = string.substring(string.length - 2,string.length);
    	} else {
			posval  = "" + Math.round (amount);  // Express amount
		}

		var frontnums = "";
		var midnums   = "";

		if (posval.length > 6) {
			frontnums = posval.substring(0,(posval.length - (parseInt(posval.length / 3) * 3) ))+",";
		}
		if (posval.length > 3){
			midnums   = posval.substring(posval.length - 6,posval.length - 3)+",";
		}

		lastnums   = posval.substring(posval.length - 3, posval.length);

		newposval = "$"+frontnums+midnums+lastnums;
		if (dec == 2) {newposval = newposval+"."+decval;}
        return newposval;                      // Return formatted currency string:
}

function calcPayment(which) {

    
   var numpmts       = ""+document.MORTGAGE.FREQUENCY.options[document.MORTGAGE.FREQUENCY.selectedIndex].value;
	var termyears  = 5; //parseInt(document.calculator.term.options[document.calculator.term.selectedIndex].value);
	var termperiods   = termyears * parseInt(numpmts);
	var amortyears    = this.Term;
	var totperiods    = amortyears*parseInt(numpmts);
	var prinamt1   = this.Amount;
	var calcpmt    = this.Payment;
    var i          = parseFloat(this.Rate);
	var calcamt   = parseFloat(calcpmt);
	if (calcamt  != calcpmt && calcpmt > 0 ) {
		document.MORTGAGE.PAYMENT.value = " ERROR ";
		return;
	}

calcdiff = 99999;
	newpmt = 0;
	calcrate       = 0.09;
	if (which == "i" && calcpmt > 0 ) {
		while (Math.abs(calcdiff) > 0.1 ) {
			newpmt = (parseFloat(prinamt1) * calcrate) / ( 1 - ( 1/ Math.pow((1+calcrate),totperiods)));
			calcdiff = (calcpmt - newpmt);
			var sign = (calcdiff) / Math.abs(calcdiff)
			calcrate =  (0.01 * sign) * ( Math.abs(calcdiff) > 500 ) + (0.0001 * sign) * ( Math.abs(calcdiff) > 20 ) +  (0.00001 * sign) * ( Math.abs(calcdiff) > 10 ) + (0.000001 * sign) * ( Math.abs(calcdiff) > 1 ) +(0.0000001 * sign)  + calcrate;
		}
		i =  2 * ( Math.pow((1+calcrate),parseInt(numpmts)/2) - 1);  
		i = parseInt(i * 1000000)/10000;
	}

   if (i < 0.3) {
        i = i * 100.0;   
	}

    //document.calculator.interest.value = i+" %";
    i = i / 100.0;   

	var cani = Math.pow((1+i/2),(2/parseInt(numpmts))) - 1;  
	var canibase = Math.pow((1+i/2),(2/12)) - 1;  
	var usi  = i / parseInt(numpmts);
	var usibase  = i / 12;
 
	if (which == "p" && cani != 0 ) {
		

		calcbasepmt = calcpmt;
		calcperiods     = parseInt(numpmts);

		if ((numpmts == '52a' ||numpmts == '26a') && cani != 0 ) {
			var calcbasepmt = calcpmt * (parseInt(numpmts)/13) ;
			var prinamt1  = (calcbasepmt/canibase) * ( 1 - (1/(Math.pow((1+canibase),(amortyears*12))) ) ) ;
		} else {
			var prinamt1  = (calcpmt/cani) * ( 1 - (1/(Math.pow((1+cani),(totperiods))) ) ) ;
		}
		document.calculator.principal.value = Digits(prinamt1,0);

	} 
	
	if (which == "p" && cani == 0 ) {
		var prinamt1  = (calcpmt*totperiods) ;
		document.calculator.principal.value = Digits(prinamt1,0);
	} 

	var prinamt   = parseFloat(prinamt1);
	if (prinamt  != prinamt1) {

		document.calculator.principal.value = " ERROR ";
		return;
	}

	if ( cani == 0 ) {
		var canbasepmt  = prinamt/ (amortyears * 12) ;
		var usbasepmt   = canbasepmt;
	} else {
		var canbasepmt  = (prinamt * canibase) / ( 1 - ( 1/ Math.pow((1+canibase),(amortyears*12))));
		var usbasepmt   = (prinamt * usibase ) / ( 1 - ( 1/ Math.pow((1+ usibase),(amortyears*12))));
	}		

	var canpmt = canbasepmt;
	var uspmt  = usbasepmt;

	if ((numpmts == '52a' ||numpmts == '26a') && cani != 0 ) {
		var canpmt = canbasepmt / (parseInt(numpmts)/13) ;
		var uspmt  = usbasepmt /  (parseInt(numpmts)/13) ;
	} 

	if ((numpmts == '52' || numpmts == '26'|| numpmts == '2'|| numpmts == '1' ) && cani != 0 ) {
		var canpmt = (prinamt * cani) / ( 1 - ( 1/ Math.pow((1+cani),totperiods)));
		var uspmt  = (prinamt * usi ) / ( 1 - ( 1/ Math.pow((1+ usi),totperiods)));
	} 
	document.MORTGAGE.PAYMENT.value = Digits(canpmt,2);

	var canbal = prinamt1;
	var usbal  = canbal;
	var canint = 0;
	var usint = 0;
	var cantotint = 0;
	var ustotint = 0;
	

    for (var j = 0; j < termperiods ; j++) {
	 	canint    = cani * canbal;
		cantotint = cantotint + canint;
		canbal    = canbal - (canpmt - canint); 

	 	usint    = usi * usbal
		ustotint = ustotint + usint
		usbal    = usbal - (uspmt - usint); 
		if (usbal < 0  ) { 
			usbal = 0;
			break;
		}
		if (canbal < 0 ) { 
			canbal = 0 
			break;
		}
	}
	
	if (usbal < 0  ) { usbal = 0 };
	if (canbal < 0 ) { canbal = 0 };

	
	var k = j;
    for (var j = termperiods; j < totperiods; j++) {
	 	canint    = cani * canbal;
		cantotint = cantotint + canint;
		canbal    = canbal - (canpmt - canint); 

	 	usint    = usi * usbal
		ustotint = ustotint + usint
		usbal    = usbal - (uspmt - usint); 
		k = j;	
		if (usbal < 0  ) { 
			usbal = 0;
			break;
		}
		if (canbal < 0 ) { 
			canbal = 0 
			break;
		}
	}
	actyears = Digits((k+1)/parseInt(numpmts),2);
	if (cani == 0 ) {
		actyears = amortyears ;
	} else {
		actyears = actyears.substring(1,actyears.length);
	}
	document.MORTGAGE.INTEREST.value = Digits(cantotint,2);//Digits(parseInt(cantotint),0);
	
}



//============================================================================
// Loan object method that calculates the interest portion of a loan
//============================================================================

function calcInterest() {
   if (this.Periods == "26a")
   {
       this.Periods = 26;
   }
   else if (this.Periods == "52a")
   {	
      var p;
	  p = this.Payment.toFixed(2);

	  this.Interest = ((p*(1092.4072))-this.Amount);
   }
   else
   {
   	   this.Interest = ((this.Payment*(this.Term*this.Periods))-this.Amount);
   }

}



//============================================================================
// Loan object method that translates a selection drop down to a value
//============================================================================

function calcPeriods() {

   this.Periods = ""+document.MORTGAGE.FREQUENCY.options[document.MORTGAGE.FREQUENCY.selectedIndex].value;
   /*
   if (this.Frequency=="Monthly" || this.Frequency=="Mensuel")
   { 
        this.Periods=12
   }
   else if (this.Frequency=="Bi-Weekly" || this.Frequency=="2 semaines")
   {
	   this.Periods=26
   }
   else if (this.Frequency=="Bi-Weekly A" || this.Frequency=="2 semaines A")
   {
	   this.Periods="26a"
   }
   else if (this.Frequency=="Weekly A" || this.Frequency=="semaine A")
   {
	   this.Periods="52a"
   }
   else
   { 
   	    this.Periods=52
   }
   */

}



//============================================================================
// Loan object method that shows the calculated amounts
//============================================================================

function Show(oView) {

   window.document.MORTGAGE.PAYMENT.value = calcRound(Mortgage.Payment)

   window.document.MORTGAGE.INTEREST.value = calcRound(Mortgage.Interest)

}



//============================================================================
// oRecord Constructor, defines what the Amortzation record looks like
//============================================================================

function oRecord(Year, Interest, Principle, Balance){

   this.Year = Year;

   this.Interest = Interest;

   this.Principle = Principle;

   this.Balance = Balance;

}



//============================================================================
// addRecord defines how a record gets added to the container array
//============================================================================

function addRecord(Year, Interest, Principle, Balance){

   oTable[rec] = new oRecord(Year, Interest, Principle, Balance);
   //alert("rec + Year "+rec+" "+Year);

}



//============================================================================
// select_item Constructor, used to retrive the selected item from the dropdown
// control on a form.
// name: 		form element name
// value:  		the value of the options that was selected
// return value:	selected item
//============================================================================

function select_item(name, value) {

   this.name = name;

   this.value = value;

}



//============================================================================
// Common routine to retrieve the selected value from the drop down object
// select_object:	a drop down from control
// return value:	the selected objects name
//============================================================================

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)

}



//============================================================================
// Common routine for rounding that also formats the results into US currency
// num: 		a number
// return value:  result is rounded and formated for currency $999,999.00
//============================================================================

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)

}





//============================================================================
// A page specific routine to set the initial state when the page is reloaded.
//============================================================================

function setfocus() {

   document.MORTGAGE.AMOUNT.focus();

   document.MORTGAGE.AMOUNT.select();

}



// unhide
