var amount, apr, n, payment, npy, tablebuilt=false;

function calculate(){
var d=document.f;
amount=d.amount.value;
apr=d.apr.value;
n=d.n.value;
npy=d.npy.value;
if( (amount!='') && (n!='') && (apr!='') && (npy!='') ){
tmp=Math.pow((1+(apr/100/npy)), (n*npy));
payment=(amount*tmp*(apr/100/npy))/(tmp-1);
if((!isNaN(payment))&&(payment!=Number.POSITIVE_INFINITY)&&(payment!=Number.NEGATIVE_INFINITY)){
d.payment.value=round(payment);
//d.totpaid.value=round(payment*n*npy);
//d.intpaid.value=round((payment*n*npy)-amount);
}else alert('Error:\nOne or more fields contain data\nwhich cannot be used in the\ncalculation.');
}else alert('Error:\nYou did not provide enough data.');
}

function round(val){
tmp=Math.round(val*100)/100+'';
if(tmp.indexOf('.')==-1)tmp+='.00';
else if(tmp.length-tmp.indexOf('.')==2)tmp+='0';
return tmp;
}

function resetall(){
var d=document.f;
d.amount.value='';
d.apr.value='';
d.n.value='';
d.npy.value=12;
d.payment.value='';
//d.totpaid.value='';
//d.intpaid.value='';
d.amount.focus();
}

function buildtable(){
tablebuilt=true;
txt='<html><head><title>Payment Schedule</title></head><body bgcolor="#00436e"><center><form>';
txt+='<input type="button" value="Close" onClick="self.close()"><br><br>';
txt+='<table bgcolor="white" border="1" cellpadding="4">';
txt+='<tr><td align="center">Payment<br>Number</td><td align="center">Payment<br>Amount</td><td align="center">Interest</td><td align="center">Principle</td><td align="center">Balance</td></tr>';
amount=eval(amount);
for(i=1;i<=n*npy;i++){
tbldata='<td bgcolor="'+((i%2!=0) ? 'lightgrey' : 'white')+'" align="right">';
interest=amount*apr/npy/100;
amount+=interest;
principle=payment-interest;
amount-=payment;
txt+='<tr>'+tbldata+i+':</td>'+tbldata+round(payment)+'</td>'+tbldata+round(interest)+'</td>'+tbldata+round(principle)+'</td>'+tbldata+round(amount)+'</td></tr>';
}
txt+='</table><br><br><input type="button" value="Close" onClick="self.close()"></center></form></body></html>';
var psch=window.open('', 'viewsch' ,'top=0,left=0,toolbar=no,scrollbars=yes,resizable=yes,width=500,height=450,menubar=no,status=no');
psch.document.write(txt);
}

window.onload=function(){
document.f.amount.focus();
}
