/* cal.js
 * Author:	CJ july 18, 2001
*/

//pre-cache all 'up' images
var upImgs = new Array()
  upImgs["b0"]=new Image(26,26); upImgs["b1"]=new Image(26,26); 
  upImgs["b2"]=new Image(26,26); upImgs["b3"]=new Image(26,26); 
  upImgs["b4"]=new Image(26,26); upImgs["b5"]=new Image(26,26);
  upImgs["b6"]=new Image(26,26); upImgs["b7"]=new Image(26,26); 
  upImgs["b8"]=new Image(26,26); upImgs["b9"]=new Image(26,26); 
  upImgs["bpt"]=new Image(26,26); upImgs["bbksp"]=new Image(53,24);     
  upImgs["bclr"]=new Image(53,24); upImgs["bnext"]=new Image(83,24); 
  upImgs["bprev"] = new Image(83,24); upImgs["bshowans"] = new Image(94,24); 
  upImgs["bshowamort"] = new Image(165,24); upImgs["breset"] = new Image(65,24);
  upImgs["b0"].src = "images/b0_up.gif"; upImgs["b1"].src = "images/b1_up.gif"
  upImgs["b2"].src = "images/b2_up.gif"; upImgs["b3"].src ="images/b3_up.gif"
  upImgs["b4"].src ="images/b4_up.gif"; upImgs["b5"].src = "images/b5_up.gif"
  upImgs["b6"].src = "images/b6_up.gif"; upImgs["b7"].src = "images/b7_up.gif"
  upImgs["b8"].src = "images/b8_up.gif"; upImgs["b9"].src = "images/b9_up.gif"
  upImgs["bpt"].src = "images/bpt_up.gif"; upImgs["bbksp"].src = "images/bbksp_up.gif"
  upImgs["bclr"].src = "images/bclr_up.gif"; upImgs["bnext"].src = "images/bnext_up.gif"
  upImgs["bprev"].src = "images/bprev_up.gif"; upImgs["bshowans"].src = "images/bshowans_up.gif"
  upImgs["bshowamort"].src = "images/bshowamort_up.gif"; upImgs["breset"].src = "images/breset_up.gif"

//pre-cache all 'dn' images	
var dnImgs = new Array()
  dnImgs["b0"] = new Image(26,26); dnImgs["b1"] = new Image(26,26);
  dnImgs["b2"] = new Image(26,26); dnImgs["b3"] = new Image(26,26);
  dnImgs["b4"] = new Image(26,26); dnImgs["b5"] = new Image(26,26);
  dnImgs["b6"] = new Image(26,26); dnImgs["b7"] = new Image(26,26);
  dnImgs["b8"] = new Image(26,26); dnImgs["b9"] = new Image(26,26);
  dnImgs["bpt"] = new Image(26,26); dnImgs["bbksp"] = new Image(53,24);
  dnImgs["bclr"] = new Image(53,24); dnImgs["bnext"] = new Image(83,24);
  dnImgs["bprev"] = new Image(83,24); dnImgs["bshowans"] = new Image(94,24);
  dnImgs["bshowamort"] = new Image(165,24); dnImgs["breset"] = new Image(65,24);
  dnImgs["b0"].src = "images/b0_dn.gif"; dnImgs["b1"].src = "images/b1_dn.gif";
  dnImgs["b2"].src = "images/b2_dn.gif"; dnImgs["b3"].src ="images/b3_dn.gif";
  dnImgs["b4"].src ="images/b4_dn.gif"; dnImgs["b5"].src = "images/b5_dn.gif";
  dnImgs["b6"].src = "images/b6_dn.gif"; dnImgs["b7"].src = "images/b7_dn.gif";
  dnImgs["b8"].src = "images/b8_dn.gif"; dnImgs["b9"].src = "images/b9_dn.gif";
  dnImgs["bpt"].src = "images/bpt_dn.gif"; dnImgs["bbksp"].src = "images/bbksp_dn.gif";
  dnImgs["bclr"].src = "images/bclr_dn.gif"; dnImgs["bnext"].src = "images/bnext_dn.gif";
  dnImgs["bprev"].src = "images/bprev_dn.gif"; dnImgs["bshowans"].src = "images/bshowans_dn.gif";
  dnImgs["bshowamort"].src = "images/bshowamort_dn.gif"; dnImgs["breset"].src = "images/breset_dn.gif";
	
var lastInputField="" //stores name of last textBox in input Form which had focus 
var lastTdId //stores id of TD in which currently selected inputForm textBox lives
var popup

//------------------------------------------------------------
function upImg(img) {
  document.images[img].src = upImgs[img].src
}
//------------------------------------------------------------
function dnImg(img){
  document.images[img].src = dnImgs[img].src
}
//------------------------------------------------------------
function setMsg(msg) {
  window.status = msg
  return true
}
//------------------------------------------------------------
//doMsg(fName)
//purpose    : set value property of msgTxt text Box based
//            on value of str_fName
//parameters: fName - field name
function doMsg(fName) {
  var msgTBox = document.msg.msgTxt
  switch (fName) {
    case "m1p": msgTBox.value = "Please Enter the Total Loan Amount"; break
    case "m1r": msgTBox.value = "Please Enter the Annual Interest Rate (%)"; break
    case "m1y": msgTBox.value = "Please Enter the Number of Years (1 - 30)"; break
    case "m2p": msgTBox.value = "Please, Enter Monthly Income before taxes"; break
    case "m2r": msgTBox.value = "Please, Enter Interest Rate (%)"; break
    case "m2y": msgTBox.value = "Please, Enter Term of Loan (1 - 30 years)"; break
    case "l1p": msgTBox.value = "Please, Enter amount you wish to borrow"; break
    case "l1r": msgTBox.value = "Please, Enter Interest Rate (%)"; break
    case "l1y": msgTBox.value = "Please, Enter Term of Loan (1 - 5 years)"; break
    case "s1mC": msgTBox.value = "The amount that will be saved each month"; break
    case "s1r": msgTBox.value = "Please, Enter Annual Interest Rate (%)"; break
    case "s1y": msgTBox.value = "Please, Enter the length of time in months"; break
    case "i1a": msgTBox.value = "Please, Enter desired amount in the future"; break
    case "i1r": msgTBox.value = "Please, Enter Rate of Return (%)"; break
    case "i1y": msgTBox.value = "Please, Enter the length of time in years"; break
    case "f1a": msgTBox.value = "Please, Enter the amount you will invest each year"; break
    case "f1r": msgTBox.value = "Please, Enter Annual Rate of Interest (%)"; break
    case "f1y": msgTBox.value = "Please, Enter the length of time in years"; break
  }
}

//------------------------------------------------------------
function showPopup(w,h) {
  var window_left = (screen.width-w)/2;
  var window_top = (screen.height-h)/2;
  popup = window.open('','popup', 'toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+w+',height='+h+',top=' +window_top+',left='+window_left+ '');
	popup.focus();
}

//------------------------------------------------------------
//doCalDisplay(input)
//purpose    : concatenates the string value of calucator text
//             field with the new char entered by user and 
//             updates corresponding field in Input Form
//parameters : input - string; value of numeric button pushed
//calls      : updateInputForm()
function doCalDisplay(input) {
  var objCalTxt = document.cal.calTxt
  if (input == "." && (objCalTxt.value.indexOf(".")!=-1)) return //check for double decimal pt.
  objCalTxt.value = objCalTxt.value.toString() + input
  resetForm(document.resultForm,"$")
  updateInputForm()
}//doCalDisplay()

//------------------------------------------------------------
//doCalUpdate(field)
//purpose    : sets value of calucator text field to value of
//            current selected field and sets the global 
//            lastInputField to the currently
//            selected textBox
//parameters: field - object reference to field in form
//calls : doMsg(fName)
function doCalUpdate(field) {
  lastInputField = field
  if (field.value == null) document.cal.calTxt.value = ""
  else document.cal.calTxt.value = field.value
  doMsg(lastInputField.name)
  showFocus(lastInputField.name+"Td")
}//updateCal()

//------------------------------------------------------------
//doClr()
//purpose    : clears calculator text field and updates
//             corresponding input form field
//calls      : updateInputForm()
function doClr(){
  document.cal.calTxt.value=""
  updateInputForm()
}//doClr()

//------------------------------------------------------------
//doBksp()
//purpose    : deletes final char in calculator text field and
//             updates corresponding input form field
//calls      : updateInputForm()
function doBksp(){
  document.cal.calTxt.value = document.cal.calTxt.value.substring(0,document.cal.calTxt.value.length-1)
  updateInputForm()
}//doCalBksp()

//------------------------------------------------------------
//jump(where)
//purpose    : sets the value of (global)lastInputField to
//             advance from field-to-field in input form
//calls      : updateCal(field)
function jump(where){
  var objElements = document.inputForm.elements
  for (i=0; i < objElements.length; i++) {
    if (objElements[i].name == lastInputField.name) break
  }
  if (where=="next"){
    if (i==objElements.length-1) lastInputField = objElements[0]
    else lastInputField = objElements[i+1] 
  }
  else if (where=="prev"){
    if (i==0) lastInputField = objElements[objElements.length-1]
    else lastInputField = objElements[i-1] 
  }
  lastInputField.onfocus()
//  doCalUpdate(lastInputField) 
}//jump()


//------------------------------------------------------------
function initForm() {
  if (window.focus != null) window.focus();
  document.inputForm.elements[0].focus();
 document.inputForm.elements[0].onfocus();
}

//------------------------------------------------------------
//resetForm(formName, defStr)
//purpose    : sets all text fields in a form (FormName) to defStr
function resetForm(formName,defStr) {
  var i, curElem
  for (i=0; i < formName.elements.length; i++) {
    if (formName.elements[i].type == "text") formName.elements[i].value = defStr
  }
}

//------------------------------------------------------------
//resetAll()
//purpose    : resets the value of all fields (in inputForm,
//             resultForm and cal)
function resetAll(){
  resetForm(document.inputForm,"0")
  resetForm(document.resultForm,"$")
  document.cal.calTxt.value = ""
}

//------------------------------------------------------------
//updateInputForm()
//purpose    : sets value of last textBox in input Form which
//             had focus (denoted by global lastInputField) 
//            to current value of calculator textBox
function updateInputForm() {
  lastInputField.value = document.cal.calTxt.value
  lastInputField.onchange()
}//updateInputForm()

//------------------------------------------------------------
//checkIt(field,e)
//purpose    : checks whether chars input by user are numeric.
//             alerts user of error if non-numeric keys entered.
//             updates calculator display with user input.
//parameters : field - object reference of current (input) field 
//                     with focus
//             e - keypressed event
function checkIt(field,e){
  var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode
  status = charCode //see ASCII character value!
  if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode!=46)) {
 	  //alert("Please make sure entries are numbers only.")
	  return false
  }
    if (charCode == 46 && (field.value.indexOf(".")!=-1)) return false //check for double decimal pt.
	if (field.form == document.inputForm) resetForm(document.resultForm,"$")
	document.cal.calTxt.value = numval(parseFloat((field.value+String.fromCharCode(charCode))),2,0)
  return (true)
}//doCheckIt()

//------------------------------------------------------------
//showFocus(tdId)
//purpose    : DHTML effect for TD
function showFocus(tdId) {
  if (navigator.appName != "Netscape") {
    if (lastTdId != null) lastTdId.backgroundColor = "#ffffff";
    tdId = document.all[tdId].style; tdId.backgroundColor = "#eeeeee";
    lastTdId = tdId
  }
}

//------------------------------------------------------------
//zeroBlanks(formName)
//purpose    : sets all empty text fields to zero
//calls      : formName - form object reference
function zeroBlanks(formName) {
  var i, curElem
  for (i=0; i < formName.elements.length; i++) {
    curElem = formName.elements[i]
    if (curElem.type == "text") {
	  if (curElem.value=="" || isNaN(curElem.value))
	    curElem.value = "0"
	}
  }
}//zeroBlanks()

//------------------------------------------------------------
function numval(val,digits,minval,maxval) {
  if (val == "" || isNaN(val)) val = 0;
  val = parseFloat(val);
  if (digits == null) digits = 0;
  var dec = Math.pow(10,digits);
  val = (Math.round(val * dec))/dec;
  if (minval != null && val < minval) val = minval;
  if (maxval != null && val > maxval) val = maxval;
  return parseFloat(val);
}
//------------------------------------------------------------
function futureValue(p,r,y){
  return p*Math.pow(1+r,y);
}
//------------------------------------------------------------
function geomSeries(z,m,n) {
  var amt;
  if (z == 1.0) amt = n + 1;
  else amt = (Math.pow(z,n + 1) - 1)/(z - 1);
  if (m >= 1) amt -= geomSeries(z,0,m-1);
  return amt;
}

//------------------------------------------------------------
function mortgagePayment(p,r,y){
  return futureValue(p,r,y)/geomSeries(1+r,0,y-1);
}

//------------------------------------------------------------
function mortgageInt(mPy,curP,r,y) {
  var p=curP,pP=0,iP=0,tI=0
  for(var i=0; i < (12*y); i++){
    iP = (p*r)/12; tI = tI + iP; pP = mPy - iP;
	p = p -pP;
  } 
 return tI
}

//------------------------------------------------------------
function mortgageQual(p,r,y) {
 var t,b
 t = .35 * p * (Math.pow(1+(r/1200), y*12)-1);
 b = (r/1200) * Math.pow(1+(r/1200), y*12);
 return Math.round((t/b)*100)/100;
}

//------------------------------------------------------------
function saveEarn(mC,r,y) {
    return Math.round((mC*(Math.pow(1+(r/(12*100)),y)-1)/(r/(12*100)))*100)/100;
}

//------------------------------------------------------------
function installPay(p,r,y) {
  p1 = p*y; p2 = r/100; p3 = p1*p2; p4 = (p3*1)+(p*1); p5 = y*12;
  return numval((p4/p5),2)
}

//------------------------------------------------------------
function invest(a,r,y) {
  return Math.round((a*(1/(Math.pow(1+(r/100),y))))*100)/100;
}
//------------------------------------------------------------
function fEarn(a,r,y) {
  return Math.round((a*((Math.pow((1*1)+(1*(r/100)),y)-1)/(r/100)))*100)/100;
}

//------------------------------------------------------------
function showResult(formName) {
  zeroBlanks(document.inputForm)
  if (formName == "m1") { //monthly payments, total interest cost
    var p = parseFloat(document.inputForm.m1p.value);
    var r = parseFloat(document.inputForm.m1r.value)/100;
    var y = parseFloat(document.inputForm.m1y.value)
    var mPy = numval(mortgagePayment(p,r/12,y*12),2)
    document.resultForm.payments.value = "$ "+mPy;
    document.resultForm.totalInterest.value = "$ "+numval(mortgageInt(mPy,p,r,y),2)
  }
  if (formName == "s1") { //future value of savings
	var mC =  parseFloat(document.inputForm.s1mC.value);
	var r  = parseFloat(document.inputForm.s1r.value);
	var y  = parseFloat(document.inputForm.s1y.value);
    document.resultForm.earn.value = "$ "+saveEarn(mC,r,y)
  }
  if (formName == "m2") {// qualify for a mortgage of
    var p = parseFloat(document.inputForm.m2p.value);
	var r = parseFloat(document.inputForm.m2r.value);
	var y = parseFloat(document.inputForm.m2y.value);
    document.resultForm.fVal.value = "$ "+mortgageQual(p,r,y)
  }
  if (formName == "l1") { //monthly payment on loan
    var p = parseFloat(document.inputForm.l1p.value);
	var r = parseFloat(document.inputForm.l1r.value);
	var y = parseFloat(document.inputForm.l1y.value);
    document.resultForm.mP.value = "$ "+installPay(p,r,y)
  }
  if (formName == "i1") { //required investment today 
    var a = parseFloat(document.inputForm.i1a.value);
	var r = parseFloat(document.inputForm.i1r.value);
	var y = parseFloat(document.inputForm.i1y.value);
    document.resultForm.ivest.value = "$ "+invest(a,r,y)
  }
  if (formName == "f1") { //future value investment  
    var a = parseFloat(document.inputForm.f1a.value);
	var r = parseFloat(document.inputForm.f1r.value);
	var y = parseFloat(document.inputForm.f1y.value);
    document.resultForm.earn.value = "$ "+fEarn(a,r,y)
  }
}

//------------------------------------------------------------
function showAmort() {
  zeroBlanks(document.inputForm)
  var p = parseFloat(document.inputForm.m1p.value);
  var r = parseFloat(document.inputForm.m1r.value)/100;
  var y = parseFloat(document.inputForm.m1y.value)
  var mPy = numval(mortgagePayment(p,r/12,y*12),2)
  showPopup(500,300)
  writeAmortHtml(p,r,y,mPy)
}//showAmort()

//------------------------------------------------------------
function writeAmortHtml(p,r,y,mPy){
  var html =""
  html +="<html>\n<head>\n<title>Amortization Schedule</title>\n"
  html +="<link rel=\"stylesheet\" href=\"http://ncbdominica.com/styles.css\" type=\"text/css\">"

  if (navigator.appName != "Netscape") html +="<script language=\"JavaScript\" type=\"text/javascript\">window.status=\"Loading...(Please wait)\";</script>"

  html +="</head>\n"
  html +="<body bgcolor=\"#ffffff\" text=\"#000000\">\n"
  html +="<p class=\"hdr3\">Amortization Schedule</p>\n"
  html +="<div align=\"center\">\n"

  if (navigator.appName == "Netscape")  html +="<table style=\"border : 3px solid #eeeeee;\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"
  else   html +="<table class=\"logoBg\" style=\"border : 3px solid #eeeeee;\" width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n"

  html +="<tr>\n"
  html +="<td bgcolor=\"#006633\"><span class=\"tdHdr\">Year</span></td>\n"
  html +="<td bgcolor=\"#006633\"><span class=\"tdHdr\">Month</span></td>\n"
  html +="<td bgcolor=\"#006633\"><span class=\"tdHdr\">Total Principle Paid</span></td>\n"
  html +="<td bgcolor=\"#006633\"><span class=\"tdHdr\">Total Interest Paid</span></td>\n"
  html +="<td bgcolor=\"#006633\"><span class=\"tdHdr\">Outstanding Balance</span></td>\n"
  html +="</tr>\n"
  popup.document.write(html)
  var pP=0,iP=0
  for(var i=0; i < y; i++){
    tPp=0; tIp=0
    for (var j=0; j<12;j++) {
      popup.document.write("<tr>\n<td>&nbsp;</td>\n")
	  iP = (p*r)/12; tIp = tIp + iP;
	  pP = mPy-iP; tPp = tPp + pP;
	  p = p-pP;
	  popup.document.write("<td>"+(j+1)+"</td>\n")
	  popup.document.write("<td>"+numval(pP,2)+"</td>\n")
	  popup.document.write("<td>"+numval(iP,2)+"</td>\n")
	  popup.document.write("<td>"+numval(p,2)+"</td>\n")
	  popup.document.write("</tr>\n")
    }
    popup.document.write("<tr>\n")
    popup.document.write("<td bgcolor=\"#eeeeee\">Year "+(i+1)+"</td>")
    popup.document.write("<td bgcolor=\"#eeeeee\">-</td>")
    popup.document.write("<td bgcolor=\"#eeeeee\">"+numval(tPp,2)+"</td>")
    popup.document.write("<td bgcolor=\"#eeeeee\">"+numval(tIp,2)+"</td>")
    popup.document.write("<td bgcolor=\"#eeeeee\">"+numval(p,2)+"</td>")
    popup.document.write("</tr>\n")
  } 
  popup.document.write("</table>\n")
  popup.document.write("<p><a href=\"javascript:window.close()\">Close window</a></p>")
  popup.document.write("</div>\n</body>\n</html>")
  popup.document.close()
  popup.status="NCBDominica.com -- Amortization Schedule"
}