﻿/*************************************************************************
  This code is from Dynamic Web Coding 
  at http://www.dyn-web.com/
  Copyright 2003 by Sharon Paine 
  See Terms of Use at http://www.dyn-web.com/bus/terms.html
  Permission granted to use this code 
  as long as this entire notice is included.
*************************************************************************/

// leave in page for way to customize layout of tooltip 
// and avoid errors if onmouseovers/outs before page completely loaded
function doTooltip(e, msg) {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.show(e, msg);
	}

function hideTip() {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.hide();
	}

// variables for tooltip content 
var Instructions = "<p>Instructions:</p><p>1.  Select how you want to <strong>Calculate</strong>";
Instructions += " a loan by choosing <strong>Amount of Loan</strong>, <strong>Loan Term</strong> or";
Instructions += " <strong>Payment Amount</strong>. You are required to enter an <strong>Interest Rate</strong>";
Instructions += " and 2 of either <strong>Amount of Loan</strong>, <strong>Loan Term</strong> or <strong>";
Instructions += "Payment Amount</strong> depending on the method of calculation chosen. The field to be calculated";
Instructions += " will be disabled.</p><p>2. Select the <strong>Payment Frequency</strong> and the <strong>First";
Instructions += " Payment Due</strong> date, then click the <strong>Calculate</strong> button.</p>";
Instructions += "<p>3. Once you have calculated the loan you can view an amortization schedule showing a breakdown";
Instructions += " of payments by choosing the type of <strong>Amortization Schedule</strong> and clicking the";
Instructions += " <strong>View Amortization Schedule</strong> button. </p><p>4. You can also use the option to";
Instructions += " add extra payments by selecting <strong>Extra Payments</strong>, selecting the frequency, entering";
Instructions += " the amount and starting date.</p>";

// onMouseUp() event of radio button triggers this function and button value determines which textfield to make readOnly
// When one is made readOnly, the others are not readOnly. Background color is toggled based on readOnly being true or false
function switchReadOnly(rb){
	prin = document.getElementById('prin');
	term = document.getElementById('term');
	pmt = document.getElementById('pmt');
	if (rb.value=="prin"){
		prin.readOnly = true;                                                // readOnly true makes field not changeable by user
		prin.value = "";                                                     // clear field value
		prin.style.backgroundColor = !prin.readOnly ? "#FFFFFF" : "#CCCCCC"; // readOnly true makes color grey (#CCCCCC)
		term.readOnly = false;
		term.style.backgroundColor = !term.readOnly ? "#FFFFFF" : "#CCCCCC";
		pmt.readOnly = false;
		pmt.style.backgroundColor = !pmt.readOnly ? "#FFFFFF" : "#CCCCCC";
		}
	if (rb.value=="term"){
		prin.readOnly = false;
		prin.style.backgroundColor = !prin.readOnly ? "#FFFFFF" : "#CCCCCC";
		term.readOnly = true;
		term.value = "";
		term.style.backgroundColor = !term.readOnly ? "#FFFFFF" : "#CCCCCC";
		pmt.readOnly = false;
		pmt.style.backgroundColor = !pmt.readOnly ? "#FFFFFF" : "#CCCCCC";
		}
	if (rb.value=="pmt"){
		prin.readOnly = false;
		prin.style.backgroundColor = !prin.readOnly ? "#FFFFFF" : "#CCCCCC";
		term.readOnly = false;
		term.style.backgroundColor = !term.readOnly ? "#FFFFFF" : "#CCCCCC";
		pmt.readOnly = true;
		pmt.value = "";
		pmt.style.backgroundColor = !pmt.readOnly ? "#FFFFFF" : "#CCCCCC";
		}
	}

// onClick event of checkbox triggers this function
// Extra payment form elements are toggled on or off depending on if the checkbox is checked or unchecked
function switchDisabled(ep){
	xtraFreq = document.getElementById('xtraFreq');
	xtraAmt = document.getElementById('xtraAmt');
	xtraMo = document.getElementById('mxp');
	xtraYr = document.getElementById('xpy');
	if (ep){		
		xtraFreq.disabled = !ep.checked ? true : false;                      // true if checked, false if unchecked
		xtraMo.disabled = !ep.checked ? true : false;
		xtraYr.disabled = !ep.checked ? true : false;
		xtraAmt.readOnly = !ep.checked ? true : false;
		xtraAmt.style.backgroundColor = !ep.checked ? "#CCCCCC" : "#FFFFFF"; // grey if checked, white if unchecked
		document.getElementById('sa').style.visibility = !ep.checked ? 'visible' : 'hidden';
		document.calculator.aip[1].checked = !ep.checked ? false : true;
		document.calculator.aip[0].checked = !ep.checked ? true : false;
		}
	}

// called by keypress event in term field, allows only numbers
function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
	return true;
	}

// autoformat loan amount and payment amount with commas and decimal
// called by keypress in loan amount or payment amount, ignores keypress when readonly
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (fld.readOnly) return false;                                             // - Ignore keys if disabled
	if (whichCode == 13) return true;                                           // - Allow Enter key
	if (whichCode == 8) return true;                                            // - Allow Delete key
	key = String.fromCharCode(whichCode);                                       // - Get value from key code, assign to var key
	if (strCheck.indexOf(key) == -1) return false;                              // - Ignore invalid key
	len = fld.value.length;                                                     // - Assign length of field to var len
	for(i = 0; i < len; i++)                                                    // - Loop through each character in field
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; // - Starting character is not zero or a period
	aux = '';                                                                   // - Assign null to aux
	for(; i < len; i++)                                                         // - Loop through each character in field again
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);  // - Check for a negative sign and append to aux
	aux += key;                                                                 // - Append key value to aux 
	len = aux.length;                                                           // - Assign length of aux to len
	if (len == 0) fld.value = '';                                               // - If length is 0, assign null value to fld
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;                          // - If length is 1, assign value 0.0 + aux
	if (len == 2) fld.value = '0'+ decSep + aux;                                // - If length is 2, assign value 0. + aux
	if (len > 2) {                                                              // - If length is greater than 2
		aux2 = '';                                                              // - Assign aux2 as null
		for (j = 0, i = len - 3; i >= 0; i--) {                                 // - Loop through characters before decimal
			if (j == 3) {                                                       // - When j has incremented to 3
				aux2 += milSep;                                                 // - Assign comma to aux2
				j = 0;                                                          // - Reset j to 0 and break out of loop
				}
			aux2 += aux.charAt(i);                                              // - Append current character to aux2 if j is not at 3
			j++;                                                                // - Increment j
			}
		fld.value = '';                                                         // - Clear value for fld
		len2 = aux2.length;                                                     // - Assign length of aux2 to len2
		for (i = len2 - 1; i >= 0; i--)                                         // - Loop through length of len2
		fld.value += aux2.charAt(i);                                            // - Append each character of aux2 to fld value 
		fld.value += decSep + aux.substr(len - 2, len);                         // - Append decimal point and last 2 characters to fld
		}
	return false;
	}

// auto format interest rate as XX.XXX
// function called by keypress in interest field
function percentFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (fld.disabled == true) return false;                                     // - Ignore keys if disabled
	if (whichCode == 13) return true;                                           // - Allow Enter key
	if (whichCode == 8) return true;                                            // - Allow Backspace key
	key = String.fromCharCode(whichCode);                                       // - Get value from key code, assign to var key
	if (strCheck.indexOf(key) == -1) return false;                              // - Ignore invalid key
	len = fld.value.length;                                                     // - Assign length of field to var len
	for(i = 0; i < len; i++)                                                    // - Loop through each character in field
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; // - if current character is zero or period, skip
	aux = '';                                                                   // - Assign null to aux
	for(; i < len; i++)                                                         // - Loop through each character in field again
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);  // - Not sure what this does
	aux += key;                                                                 // - Append key value to aux 
	len = aux.length;                                                           // - Assign length of aux to len
	if (len == 0) fld.value = '';                                               // - If length is 0, assign null value to fld
	if (len == 1) fld.value = '0'+ decSep + '00' + aux;                         // - If length is 1, assign value 0.00 + aux
	if (len == 2) fld.value = '0'+ decSep + '0' + aux;                          // - If length is 2, assign value 0.0 + aux
	if (len == 3) fld.value = '0'+ decSep + aux;                                // - If length is 3, assign value 0. + aux
	if (len > 3 && len < 6) {                                                   // - If length is greater than 3 but less than 6
		aux2 = '';                                                              // - Assign aux2 as null
		for (i = len - 4; i >= 0; i--) {                                        // - Loop through characters left of decimal
			aux2 += aux.charAt(i);                                              // - Append current character to aux2
			}
    fld.value = '';                                                             // - Clear value for fld
    len2 = aux2.length;                                                         // - Assign length of aux2 to len2
    for (i = len2 - 1; i >= 0; i--)                                             // - Loop through length of len2
    fld.value += aux2.charAt(i);                                                // - Append each character of aux2 to fld value 
    fld.value += decSep + aux.substr(len - 3, len);                             // - Append decimal point and last 2 characters to fld
 	}
	return false;
	}

// Changes term type when frequency is changed
function switchFreqText(Sel){
	if (Sel.value<3){
		if (document.getElementById) { // DOM3 = IE5, NS6  
			document.getElementById('termText').innerHTML = "\(Weeks\) ";
			} 
			else { 
				if (document.layers) { // Netscape 4 
					document.termText.innerHTML = "\(Weeks\) "; 
					} 
			else { // IE 4  
				document.all.termText.innerHTML = "\(Weeks\) "; 
				} 
			}
		}
	if (Sel.value>=3){
		if (document.getElementById) { // DOM3 = IE5, NS6 
			document.getElementById('termText').innerHTML = "\(Months\) ";
			} 
			else { 
				if (document.layers) { // Netscape 4 
					document.termText.innerHTML = "\(Months\) ";
					} 
			else { // IE 4 
				document.all.termText.innerHTML = "\(Months\) "; 
				} 
			}
		}
	}

// format 2 digit year as 4 digit year, not valid for years prior to 1000
function y2k(number){
	return (number < 1000) ? number + 1900 : number;
	}

mns=new Array('Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec');
today=new Date();
tyear=y2k(today.getYear());

// complete
function gMonth(){
	mnth='<SELECT name="zeb">';
	for(i=0;i<12;i++){
		mnth+='<OPTION VALUE="'+i+'"';
		if(i==today.getMonth())mnth+='SELECTED';
		mnth+='>'+mns[i]+'</OPTION>';
		}
	mnth+='</SELECT>';
	return mnth;
	}

function gYear(){
	mYear=tyear+10;
	ryr='<SELECT name="syear">';
	for(i=tyear;i<=mYear;i++){
		ryr+='<OPTION VALUE="'+i+'"';
		if(i==tyear)ryr+='SELECTED';
		ryr+='>'+i+'</OPTION>';
		}
	ryr+='</SELECT>';
	return ryr;
	}

function gMo(){
	mnth='<SELECT name="mxp" disabled>';
	for(i=0;i<12;i++){
		mnth+='<OPTION VALUE="'+i+'"';
		if(i==today.getMonth())mnth+='SELECTED';
		mnth+='>'+mns[i]+'</OPTION>';
		}
	mnth+='</SELECT>';
	return mnth;
	}

function gYr(){
	mYear=tyear+10;
	ryr='<SELECT name="xpy" disabled>';
	for(i=tyear;i<=mYear;i++){
		ryr+='<OPTION VALUE="'+i+'"';
		if(i==tyear)ryr+='SELECTED';
		ryr+='>'+i+'</OPTION>';
		}
	ryr+='</SELECT>';
	return ryr;
	}

function checkIrt(r){
	pow7=Math.pow(1+guess,pys);
	test=(pow7*pm-pm+guess*pow7*prc)/guess;
	return(r);
	}

function removeCommas(b){
	newnum="";
	numbs="- .,1234567890";
	for(i=0;i<b.length;i++){
		ch=b.charAt(i);
		if(ch!=",")newnum+=ch;
		if(numbs.indexOf(ch)==-1){
			i=b.length;
			newnum=NaN;
			}
		}
	b=newnum;
	return parseFloat(b);
	}

function formatIt(num){
	num=Math.round(num*100);
	strx=""+num;
	if(num<10&&num>0)strx="0"+num;
	if(num>-10&&num<0){
		num=-num;
		strx="-0"+num;
		}
	zeros=strx.length;
	num=strx.substring(0,zeros-2)+"."+strx.substring(zeros-2,zeros);
	neg="";
	num1="";
	if(num.indexOf(".")>=0){
		num1=num.substring(num.indexOf(".")+1,num.length)+"";
		num=num.substring(0,num.indexOf("."))+"";
		num1="."+num1;
		}
	if(num.charAt(0)=="-"){
		num=num.substring(1,num.length);
		neg="-";
		}
	if(num.length>=4){
		str=num.length;
		str1=num.length;
		while(str>=4){
			num=num.substring(0,str-3)+","+num.substring(str-3,str1);
			str-=3;str1++;
			}
		}
	num=neg+num+num1;
	return(num);
	}

function compTotal(total){
	x=1;
	princ1=Math.round(prc*100)/100;
	py=Math.round(pm*100)/100;
	pys=term*ap/12;
	while(x<pys){
		int2=princ1*itr;
		prin=py-int2;
		total+=py;
		princ1-=prin;
		x++;
		}
	int2=princ1*itr;
	prin=princ1;
	paylast=prin+int2;
	total+=paylast;
	total=formatIt(total);
	return(total);
	}

/* The formula used by the interest calculator is as follows:
   Debt times the interest rate times the number of days late divided by 365  

   The daily rate is calculated as follows:
   Debt times the interest rate divided by 365 */

function compLoan(form){
	/* Assign variable values for calculations */
	var radioLength = form.calctype.length; 				// compute number of radio buttons as an array
	for(var i = 0; i < radioLength; i++) { 					// loop through each button
		if(form.calctype[i].checked) { 						// look for selected button
			calcType=form.calctype[i].value; 				// assign selected button value to calcType
			}
		}
	if(form.aip[0]){
		nn=form.aip[0].checked; 							// nn = simple amortization
		}
	mt=form.aip[1].checked; 								// mt = dates and annual totals
	an=form.aip[2].checked; 								// an = annual totals only
	cp=12;
	prc=removeCommas(form.prin.value); 						// prc = principal amount
	syear=removeCommas(form.syear.value); 					// syear = start year
	sy=removeCommas(form.syear.value); 						// sy is working year on amortization totals, changes value
	z=form.zeb.selectedIndex; 								// z = starting month
	aip=form.aip.checked; 									// assign aip value of true if 
	term=removeCommas(form.term.value);
	pm=Math.round(removeCommas(form.pmt.value)*100)/100;
	total=0;
	ir=removeCommas(form.int.value)/100;
	itr=Math.pow(1+ir/cp,cp);
	itr=Math.pow(itr,1/12)-1;
	ap=12; 													// annual payments
	pys=term*ap/12; 										// term times annual payments divided by 12
	if(form.xtra.checked){
		xpy=removeCommas(form.xpy.value); 					// xpy = extra payment start year
		xz=form.mxp.selectedIndex; 							// xz = extra payment start month
		xpa=removeCommas(form.xtraAmt.value);				// extra amount		
		if(form.xtraFreq.selectedIndex==0){
			xp=1;
			wh='monthly';
			}
		if(form.xtraFreq.selectedIndex==1){
			xp=3;
			wh='quarterly';
			}
		if(form.xtraFreq.selectedIndex==2){
			xp=6;
			wh='semiannual';
			}
		if(form.xtraFreq.selectedIndex==3){
			xp=12;
			wh='annual';
			}
		if(form.xtraFreq.selectedIndex==4){
			xp=20;
			wh='one time only';
			}
		if(xpa==''||xpa==0||isNaN(xpa))xp=0; // if extra amount is null or 0 or not a number, frequency is code 0
		}
	else{
		xp=0;
		wh='';
		}
	
	/* Validation section */
	cv='';
	if(isNaN(prc)&&calcType!='prin')cv+='Amount of Loan\n';	// check for invalid loan amount if not calculating principal
	if(isNaN(term)&&calcType!='term')cv+='Loan Term\n'; 	// check for invalid term if not calculating term
	if(isNaN(pm)&&calcType!='pmt')cv+='Payment Amount\n'; 	// check for invalid payment amount if not calculating payment amount
	if(isNaN(itr))cv+='Interest Rate\n'; 					// check for invalid interest rate
	if(z<today.getMonth()&&syear==tyear){ 					// check that a prior month has not been selected if current year is selected
		alert('You cannot select a First Payment Due prior to the current month.');
		form.zeb.focus();
		return;
		}
	if(prc<pm){ 											// check for payment amount greater than loan amount
		alert('Payment Amount cannot exceed Amount of Loan.');
		form.pmt.focus();
		return;
	}
	if(form.xtra.checked){
		if(xz<z&&syear==xpy){ 								// check for extra start date before first payment date
			alert('Extra Payment Starting date cannot be before First Payment date.');
			form.mxp.focus();
			return;
			}
		if(xpa>prc){ 										// check for extra payment amount greater than loan amount
			alert('Extra Payment Amount cannot exceed Amount of Loan.');
			form.xtraAmt.focus();
			return;
			}
		}
	/* End validation section */
	
	if(cv){ // if an error was found and cv is assigned a value, alert user to errors
		alert('You must complete the following field(s):\n\n'+cv);
		return;
		}
	else{ // no errors, proceed with calculations
		if(calcType=='prin'){ // user has selected principal calculation
			if(itr==0){
				prc=pm*pys;
			}
			else{
				pow1=Math.pow(1+itr,-pys);
				pow2=Math.pow(1+itr,pys);
				prc=(pow1*(pow2*pm-pm))/itr;
				}
			}
		if(calcType=='term'){
			if(itr==0){
				if(pm!=0){
					term=prc/pm;
					}
				else{
					alert("You must enter a payment amount.");
					}
				}
			else{
				term=Math.log(pm/(pm-itr*prc))/Math.log(1+itr);
				}
			if(term<=0||isNaN(term)){
				alert("Can't compute # of Months using the current values.");
				}
			else{
				term=Math.round(term*100)/100;
				term=Math.round(term);
				form.term.value=Math.ceil(term*100)/100;
				}
			}
		if(calcType=='pmt'){
			if(itr==0){
				if(term!=0){
					pm=prc/pys;
					}
				else{
					alert("You must enter the number of months.");
					}
				}
			else{
				pow1=Math.pow(1+itr,pys);
				pm=Math.round((itr*pow1*prc)/(pow1-1)*100)/100;
				}
			}
		form.pmt.value=formatIt(pm);
		form.prin.value=formatIt(prc);
		form.totalPrin.value=formatIt(prc);

		/* Results computations */
		/* Assign variable values for calculations */
		x=1; 										// assign 1 to x, used in loop for payments and payment number
		g=0; 										// assign 0 to g
		y=1; 										// assign 1 to y
		trp=0; 										// assign 0 to trp, used to indicate one time payment
		
		/* xp is payment frequency: 0 = no extra payment, 1 = monthly, 3 = quarterly, 
		   6 = semiannual, 12 = annual, 20 = one time only - constant variable*/
		
		t=xp; 										// assign frequency to t
		intadd=0; 									// assign 0 to intadd, the running total of interest paid
		yrint=0; 									// assign 0 to yrint, the yearly interest paid
		ypr=0; 										// assign 0 to ypr, the yearly principal paid
		princadd=0; 								// assign 0 to princadd, the running total of principal paid
		payadd=0; 									// assign 0 to payadd, the total of principal and interest paid
		months=Math.round(term*100)/100; 			// round term, assign to months
		months=Math.ceil(months); 					// ceiling months
		p=Math.round(prc*100)/100; 					// round principal and assign to p
		l=p; 										// assign principal to l
		sy=syear; 									// assign starting year to sy
		pay1=Math.round(pm*100)/100; 				// round payment and assign to payl
		pay=pay1; 									// assign payment to pay
		p7=pay; 									// assign payment to P7
		ipw=Math.pow(1+ir,ap); 						// 
		rate=Math.round(ir*1000000)/10000; 			// convert rounded interest rate to decimal
		i=itr; 										// assign interest rate to i
		/* End variable section */
	
		/* Start calculation loop */
		while(p>=p7&&x<months){						// while current principal >= to payment amount and x < months
			int2=p*i; 								// calculate interest due
			it=formatIt(int2); 						// format interest2 and assign to it, NOT NEEDED
			/* check for extra payments */
			if(xp!=0){ 								// if there are extra payments
				if(xpa>0&&xz==z&&xpy==sy)trp=1; 	// if extra payment amt > 0 and begin month = extra start month and
													// begin yr = extra payment start year
				if(t==xp&&trp==1){ 					// if t = frequency number and it is one time payment
					princ=pay-int2+xpa; 			// principal = payment - (interest + extra payment)
					if(xpa>l){ 						// if extra payment amount > principal
						xpa=0; 						// set extra payment amount to zero
						princ=l; 					// assign principal to princ
						pay=princ+int2; 			// total payment = principal + interest
						}
					p7=pay+xpa; 					// p7 = payment + plus extra payment amount (total payment)
					paid=formatIt(p7); 				// assign total payment to paid amount
					}
				}
			/* if there are no extra payments */
			else{
				princ=pay-int2; 					// subtract interest from payment and assign to principal paid
				paid=formatIt(pay); 				// assign total payment to paid amount
				}
			/* tracking loop for one time payment */
			if(trp==1){ 							// if extra payments
				if(xp==20)t=10; 					// if extra pmt frequency one time only, assign 10 to t
				t--; 								// decrement t
				if(t==0)t=xp; 						// if t reduced to 0, assign frequency to t
				}
			pv=formatIt(princ); 					// format principal paid and assign to pv, NOT NEEDED!
			l=p-princ; 								// subtract principal paid from principal
			/* start of amortization details */		
			if(mt||an||nn){
				yrint+=int2; 						// add interest to year total interest
				ypr+=princ; 						// add principal to year total principal
				if(z==11){ 							// if this is the last payment of the year
					sy++; 							// increment current year
					z=-1; 							// reset month
					yrint=0; 						// reset year total interest
					ypr=0; 							// reset year total principal
					}
				z++; 								// increment current month
				}
			p-=princ; 								// subtract principal paid from principal
			intadd+=int2; 							// add current interest to total interest paid
			if(xp==0)payadd+=pay1; 					// if no extra payments, add payment to payadd
			princadd+=princ; 						// add principal paid to total principal paid
			x++; 									// increment x
			p7=pay; 								// assign payment to P7 again
			if(xp!=0){ 								// if extra payments
				if(t==xp&&trp==1)p7=pay+xpa; 		// if 
				}
			}
		/* end of loop */
		
		if(l>0){ 									// if there is a remainder of principal
			int2=l*i; 								// calculate interest
			princ=p; 								// assign remaining principal to princ
			pay=princ+int2; 						// calculate payment
			pay2=pay; 								// assign payment to pay2
			it=formatIt(int2); 						// format interest and assign to it
			pv=formatIt(princ); 					// format remaining principal
			paid=formatIt(pay); 					// format payment and assign to paid
			l=0; 									// assign 0 to l
			yrint+=int2; 							// add interest paid to year interest paid
			ypr+=princ; 							// add principal paid to year principal paid
			intadd+=int2; 							// add interest paid to total interest paid
			princadd+=princ; 						// add principal paid to total principal paid
			}
		if(xp!=0)payadd=intadd+princadd; 				// if extra payments, add total int and principal, assign to total pmt amount
		if(xp==0)payadd+=pay2; 							// if no extra payments, add current payment to total payment amount
		}
		/* start filling in form values */
		form.numPmts.value=x; 										// results - number of payments (term)
		form.totalInt.value=formatIt(intadd);						// results - total interest
		form.lastAmt.value=paid; 									// results - last payment amount
		form.lastDate.value=mns[z]+" "+sy; 							// results - string last payment month name to last payment year
		form.totalAmt.value=formatIt(Math.round(payadd*100)/100);	// results - total principal + interest paid
		sy=removeCommas(form.syear.value); 							// reset sy
		z=form.zeb.selectedIndex; 									// reset z
	}
						
function samortLoan(form){
	/* Assign variable values for calculations */
	x=1;
	g=0;
	y=1;
	trp=0;
	if(xp!=0){
		me=mns[xz];
		}
	else { me=''; }
	t=xp;
	intadd=0;
	yrint=0;
	ypr=0;
	output="";
	princadd=0;
	payadd=0;
	months=Math.round(term*100)/100;
	months=Math.ceil(months);
	p=Math.round(prc*100)/100;
	l=p;
	sy=syear;
	pay1=Math.round(pm*100)/100;
	pay=pay1;
	p7=pay;
	ipw=Math.pow(1+ir,ap);
	rate=Math.round(ir*1000000)/10000;
	i=itr;
	/* End variable section */
	
	/* start page output */
	output+="<table width=93% align=center><tr><td align=center colspan=6><font face='arial'><font color=red size=+2><b><i>Amortization Schedule</i></b></font><br>";
	/* do this if annual totals only */
	if(an){
		output+="<font color=blue><b>$ "+formatIt(p)+" Loan<br>" +rate+"% Interest Rate <br>$"+paid+" Payment <font size=-2>(12 times per year)</font><br>"+Math.round(pys*1000)/1000+" Payments</b>";
		}
	/* do this if dates and interest included */
	if(!an)output+="<font color=blue><b>$ "+formatIt(p)+" Loan<br>" +rate+"% Interest Rate <br>"+months+" Months</b></font><br>";
	/* do this if there are extra payments other than one time only */
	if(xp!=0&&xp<20){
		output+="<br>Make extra "+wh+" principal payments of $"+formatIt(xpa)+", beginning with the "+me+" "+xpy+" payment";
		}
	/* do this if there is a one time payment */
	else if(xp!=0&&xp==20){
		output+="<br>Make an extra "+wh+" principal payment of $"+formatIt(xpa)+" with the "+me+" "+xpy+" payment";
		}
	/* do this if there are no extra payments */
	output+="<br><br></td></tr>";
	/* do this if dates and interest included */
	if(!an)output+="<TR><TD colspan=2><font size=-1><b><u>Month</u></b></font></TD><TD align=right><font size=-1><b><u>Payment</u></b></font></TD><TD align=right><font size=-1><b><u>Principal Paid</u></b></font></TD><TD align=right><font size=-1><b><u>Interest Paid</u></b></font></TD><TD align=right><font size=-1><b><u>Remaining Balance</u></b></font></TD></TR>";
	/* do this if annual totals only */
	if(an)output+="<TR><TD colspan=3><font size=-1><b><u>Totals<br>Paid in Year</u></b></font></TD><TD align=right><font size=-1><b><u>Principal Paid</u></b></font></TD><TD align=right><font size=-1><b><u>Interest Paid</u></b></font></TD><TD align=right><font size=-1><b><u>Remaining Balance</u></b></font></TD></TR>";
	/* start of loop for payment schedule */
	while(p>=p7&&x<months){		
		int2=p*i;
		it=formatIt(int2);
		/* check for extra payments */
		if(xp!=0){
			if(xpa>0&&xz==z&&xpy==sy)trp=1;
			if(t==xp&&trp==1){
				princ=pay-int2+xpa;
				if(xpa>l){
					xpa=0;
					princ=l;
					pay=princ+int2;
					}
				p7=pay+xpa;
				paid=formatIt(p7);
				}
			}
		/* no extra payments */
		else{
			princ=pay-int2;
			paid=formatIt(pay);
			}
		/* not sure yet */
		if(trp==1){
			if(xp==20)t=10;
			t--;
			if(t==0)t=xp;
			}
		pv=formatIt(princ);
		l=p-princ;
		/* start of amortization details */		
		if(mt||an||nn){
			if(!an){
			output+="<TR><TD nowrap><font size=-1 color=blue>"+x+"</font></td>";
				if(mt)output+="<td><font size=-1>"+mns[z]+"</font></TD>";
				else output+="<td></td>";
				output+="<TD align=right><font size=-1>"+paid+"</font></TD><TD align=right><font size=-1 color=navy>"+pv+"</font></TD><TD align=right><font size=-1 color=red>"+it+"</font></TD><TD align=right><font size=-1>"+formatIt(l)+"</font></TD></TR>";
			}
			yrint+=int2;
			ypr+=princ;
			if(z==11&&!nn){
				if(mt)output+="<TR><TD colspan=3 nowrap><font color=green size=-1><b>Totals Paid in "+sy+"</b></font></TD>";
				if(an)output+="<TD colspan=3 nowrap><font color=green size=-1><b>"+sy+"</b></font></TD>";
				output+="<TD align=right><b><font color=navy size=-1>$"+formatIt(ypr)+"</font></b></TD><TD align=right><b><font color=red size=-1>$"+formatIt(yrint)+"</font></b></TD>";
				if(an)output+="<TD align=right><font size=-1>"+formatIt(l)+"</font></TD></TR>";
				if(!an)output+="<tr><td colspan=6><hr></td></tr>";
				sy++;
				z=-1;
				yrint=0;
				ypr=0;
				}
			z++;
			}
		p-=princ;
		intadd+=int2;
		if(xp==0)payadd+=pay1;
		princadd+=princ;
		x++;
		p7=pay;
		if(xp!=0){
			if(t==xp&&trp==1)p7=pay+xpa;
			}
		}
	/* end of loop */
	
	if(l>0){
		int2=l*i;
		princ=p;
		pay=princ+int2;
		pay2=pay;
		it=formatIt(int2);
		pv=formatIt(princ);
		paid=formatIt(pay);
		l=0;
		if(mt||an||nn){
			yrint+=int2;
			ypr+=princ;
			if(!an){
				output+="<TR><TD nowrap><font size=-1 color=blue>"+x+"</font></td>";
				if(mt)output+="<td><font size=-1>"+mns[z]+"</font></TD>";
				if(nn)output+="<td></td>";
				output+="<TD align=right><font size=-1>"+paid+"</font></TD><TD align=right><font size=-1 color=navy>"+pv+"</font></TD><TD align=right><font size=-1 color=red>"+it+"</font></TD><TD align=right><font size=-1>"+formatIt(l)+"</font></TD></TR>";
				if(mt)output+="<TR><TD colspan=3 nowrap><font color=green size=-1><b>Totals Paid in "+sy+"</b></font></TD>";
				}
		if(an)output+="<TD colspan=3 nowrap><font color=green size=-1><b>"+sy+"</b></font></TD>";
		if(!nn)output+="<TD align=right><b><font color=navy size=-1>$"+formatIt(ypr)+"</font></b></TD><TD align=right><font color=red size=-1><b>$" +formatIt(yrint)+"</font></b></TD>";
		if(an)output+="<TD align=right><font size=-1>0</font></TD>";
		intadd+=int2;
		princadd+=princ;
		}
	if(xp!=0)payadd=intadd+princadd;
	if(xp==0)payadd+=pay2;
	output+="<tr><td colspan=6><hr></td></tr><TR><TD nowrap><font color=green size=-2><b><u>Totals</u></b></font></TD><td></td><TD align=right><font size=-1><b>$"+formatIt(payadd)+"</b></font></TD><TD align=right><font color=navy size=-1><b>$"+formatIt(princadd)+"</b></font></TD><TD align=right><font color=red size=-1><b>$"+formatIt(intadd)+"</font></b></TD><TD align=right></TD></TR></TABLE>";
	output+="</font><br><form><center><input type='button' value='Print' onClick='window.print()'>&nbsp; ";
	}
	if(!window.open){
		output+="<input type='button' value='Back to Calculator' onClick='window.history.back()'>";
		self.document.open();
		self.document.write(''+output+'');
		self.document.close();
		}
	else{
		output+="<input type='button' value='Close' onClick='window.close()'></form>";
		nW=window.open("loan_pop.html","loanit","width=600,height=360,top=0,left=0,menuBar=1,scrollBars=1,resizable=1");
		nW.focus();
		}
	}

// Function called by clicking Reset button
function clearForm(form) {
	form.xtra.checked = false;
	form.xtraFreq.disabled = true;
	form.mxp.disabled = true;
	form.xpy.disabled = true;
	form.xtraAmt.readOnly = true;
	form.xtraAmt.style.backgroundColor = "#CCCCCC";
	prin = document.getElementById('prin');
	term = document.getElementById('term');
	pmt = document.getElementById('pmt');
	prin.readOnly = false;
	prin.style.backgroundColor = !prin.readOnly ? "#FFFFFF" : "#CCCCCC";
	term.readOnly = false;
	term.style.backgroundColor = !term.readOnly ? "#FFFFFF" : "#CCCCCC";
	pmt.readOnly = true;
	pmt.style.backgroundColor = !pmt.readOnly ? "#FFFFFF" : "#CCCCCC";
	document.getElementById('sa').style.visibility = 'visible';
	document.calculator.aip[0].checked = true;
	form.xtra.checked = false;
	if (document.getElementById) { // DOM3 = IE5, NS6 
		document.getElementById('termText').innerHTML = "\(Months\) ";
		} 
	else { 
		if (document.layers) { // Netscape 4 
			document.termText.innerHTML = "\(Months\) ";
			} 
		else { // IE 4 
			document.all.termText.innerHTML = "\(Months\) "; 
			} 
		}
	}
