// function for setting form values according to deposit type selected
// called automatically by changing deposit type
function spreadVals() { 
   var nVals = document.getElementById('chooser').options[document.getElementById('chooser').selectedIndex].value.split('|'); 
   document.getElementById('type').value = nVals[0];
   document.getElementById('minimum').value = formatCurrency(nVals[1]);
   document.getElementById('deposit').value = document.getElementById('minimum').value;
   document.getElementById('mths').value = nVals[2];
   document.getElementById('rate').value = nVals[3];
   document.getElementById('compounds').value = nVals[4];
} 

// functions for calculating maturity date
function makeArray() {
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i + 1] = makeArray.arguments[i];
}

var months = new makeArray('01','02','03','04',
                           '05','06','07','08','09',
                           '10','11','12');

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function calcMaturity(openDate, numMonths) {
	var openDate = openDate.toString().replace(/\//g,"")	// Remove slashes in openDate
	var openYear = parseInt(openDate.substr(4,4));			// Convert openDate year to integer
	var openMonth = parseInt(openDate.substr(0,2) - 1);		// Convert openDate month to integer
	var openDay = parseInt(openDate.substr(2,2));			// Convert openDate day to integer
	numMonths = parseInt(numMonths);						// Convert number of months to integer
	var mDate = new Date(openYear,openMonth,openDay);		// Create new date from openDate
	mDate.setTime(mDate.getTime() - 86400000);				// subtract one day
    // Create new date by adding number of months
	var date = new Date(y2k(mDate.getYear()),mDate.getMonth() + numMonths,mDate.getDate(),mDate.getHours(),mDate.getMinutes(),mDate.getSeconds());
    // Format maturity date as XX/XX/XXXX
	var maturityDate = months[date.getMonth() + 1] + '\/' + date.getDate() + '\/' + y2k(date.getYear());
	return maturityDate;
}

// function  for calculating the number of days
function daysBetween(openDate, maturityDate){
   if (
      openDate.indexOf("-") != -1) {
	  openDate = openDate.split("-");
   } else if (
      openDate.indexOf("/") != -1) {
      openDate = openDate.split("/");
   } else { return 0; }

   if (maturityDate.indexOf("-") != -1) {
      maturityDate = maturityDate.split("-");
   } else if (maturityDate.indexOf("/") != -1) {
      maturityDate = maturityDate.split("/");
   } else { return 0; }

   if (parseInt(openDate[0], 10) >= 1000) {
      var sDate = new Date(openDate[0]+"/"+openDate[1]+"/"+openDate[2]);
   } else if (parseInt(openDate[2], 10) >= 1000) {
      var sDate = new Date(openDate[2]+"/"+openDate[0]+"/"+openDate[1]);
   } else { return 0; }

   if (parseInt(maturityDate[0], 10) >= 1000) {
      var eDate = new Date(maturityDate[0]+"/"+maturityDate[1]+"/"+maturityDate[2]);
   } else if (parseInt(maturityDate[2], 10) >= 1000) {
      var eDate = new Date(maturityDate[2]+"/"+maturityDate[0]+"/"+maturityDate[1]);
   } else { return 0; }

   var one_day = 1000*60*60*24;
   var daysApart = Math.abs(Math.ceil((sDate.getTime()-eDate.getTime())/one_day));
   return daysApart;
}

// Function for formatting a currency field XXXXXXX.XX as X,XXX,XXX.XX
function formatCurrency(num) {
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num))
      num = "0";
      sign = (num == (num = Math.abs(num)));
      num = Math.floor(num*100+0.50000000001);
      cents = num%100;
      num = Math.floor(num/100).toString();
   if(cents<10)
      cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+','+
         num.substring(num.length-(4*i+3));
   return (((sign)?'':'-') + num + '.' + cents);
}

// function to autoformat open date as MM/DD/YYYY
// called by changing value of openDate in form
function jm_datemask(t) {
   var donepatt = /^(\d{2})\/(\d{2})\/(\d{4})$/;
   var patt = /(\d{2}).*(\d{2}).*(\d{4})/;
   var str = t.value;
   if (!str.match(donepatt)) {
      result = str.match(patt);
   if (result!= null) {
      t.value = t.value.replace(/[^\d]/gi,'');
      str = result[1] + '/' + result[2] + '/' + result[3];
      t.value = str;
   } else {
   if (t.value.match(/[^\d]/gi))
   t.value = t.value.replace(/[^\d]/gi,'');
   }
   }
}

// function autoformat deposit amount
// called by changing value of deposit in form
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 (whichCode == 13) return true;  // Enter
  if (whichCode == 8) return true;  // Delete
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  len = fld.value.length;
  for(i = 0; i < len; i++)
  if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
  aux = '';
  for(; i < len; i++)
  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len == 0) fld.value = '';
  if (len == 1) fld.value = '0'+ decSep + '0' + aux;
  if (len == 2) fld.value = '0'+ decSep + aux;
  if (len > 2) {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
        aux2 += milSep;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    fld.value += aux2.charAt(i);
    fld.value += decSep + aux.substr(len - 2, len);
  }
  return false;
}

// check for invalid number formats - used by computeForm()
function checkNumber(input, min, max, msg) {
	msg = msg + " field has invalid data: " + input;
    min = min - 1;
	var str = input;
    for (var i = 0; i < str.length; i++) {
        var ch = str.substring(i, i + 1)
        if ((ch < "0" || "9" < ch) && ch != '.') {
            alert(msg);
            return false;
        }
    }
    var num = 0 + str
    if (num < min || max < num) {
        alert(msg + " not in range [" + min + ".." + max + "]");
        return false;
    }
    input.value = str;
    return true;
}

// function that sets variable values and computes everything
// called by pressing compute button
function computeForm(form) {
	var openDate = form.openDate.value;									// set open date
	var numMonths = form.mths.value;									// set term in months
	var maturityDate = calcMaturity(openDate, numMonths);				// calculate maturiy date
	form.maturityDate.value = maturityDate;								// set maturity date form value
	var daysApart = daysBetween(openDate, maturityDate);				// calculate dividend days
	form.DaysBetween.value = daysApart;									// set dividend days form value
	var frequency = form.compounds.value;								// set frequency to compunding freq
	var vDeposit = form.deposit.value.toString().replace(/\$|\,/g,'');	// remove $ and commas from deposit
	var vMin = form.minimum.value.toString().replace(/\$|\,/g,'');		// remove $ and commas from minumum

if (form.chooser.value == "||||") {										// check that account type is selected
        alert("Please select an account type.");						// alert user about account type
		form.chooser.focus();											// put focus on account type
		form.div.value="";form.apy.value="";form.fv.value="";			// blank result variables
		form.maturityDate.value="";form.totalint.value="";				// continued
		form.DaysBetween.value="";										// continued
		return false;													// exit
    }
    if (!checkNumber(vDeposit, vMin, 100000000, "Deposit")) {			// verify the deposit is within range
		alert("Deposit amount must be greater than " + vMin + ".");		// alert user about deposit
		form.deposit.focus();											// put focus on deposit
		form.deposit.value = form.minimum.value;
		form.div.value="";form.apy.value="";form.fv.value="";			// blank result variables
		form.maturityDate.value="";form.totalint.value="";				// continued
		form.DaysBetween.value="";										// continued
		return false;													// exit
    }
	if (openDate == "") {												// check for blank open date
        alert("You must enter a start date.");							// alert user about start date
		form.openDate.focus();											// put focus on open date
		form.div.value="";form.apy.value="";form.fv.value="";			// blank result variables
		form.maturityDate.value="";form.totalint.value="";				// continued
		form.DaysBetween.value="";										// continued
		return false;													// exit
    }

	/*r=div rate, t=term, l=deposit, r=converted rate c=compounding*/
	var r, t, l, c
	r = (''+form.rate.value).toDecimal();
	t = parseInt((''+form.mths.value).toDecimal());
	l = (''+form.deposit.value).toDecimal();
	r = (parseFloat(r)>1)?(parseFloat(r)*.01):parseFloat(r);
	var APY_TERM=0;
   	if (frequency == "Quarterly") {
		APY_TERM = 4;
		c = 4;
		t = t/3;
    } else {
		APY_TERM = 12;
		c = 12;
	}
	/*p=principal, ar=annual rate, ct=compound term, t=terms */
	function CompoundInt(p,ar,ct,t) {
		return (p * Math.pow(1+(ar/ct), t)); }
	
	/* calc apy */
	var apy =( ( CompoundInt(1000,r,c,APY_TERM) - 1000 ) / 1000 );
	apy = Math.round(apy*100000);/* round to thousandth */
	var sapy = new String(apy);
	var lenapy = sapy.length;
	sapy=sapy.substr(0,lenapy-3)+"."+sapy.substr(lenapy-3,3);
	vFV = (''+CompoundInt(l,r,c,t)).toCurrency();
	form.fv.value = formatCurrency(vFV);
	form.div.value = formatCurrency(vFV.toString().replace(/\$|\,/g,'') - l);
    form.apy.value = sapy;
}

// Clear form values
function clearForm(form) {
		form.div.value="";form.apy.value="";form.fv.value="";			// blank result variables
		form.maturityDate.value="";form.DaysBetween.value="";			// continued
}

//
// loan calculator functions
//

function validateForm(){

// This function checks for empty required fields
// With Netscape focus is placed on empty fields
// Inputs are hard coded, nothing is passed to it
// It returns a true or false depending on validity 
	var amount = document.forms['cacl'].amount.value
	var payment = document.forms['cacl'].payment.value
	var rate = document.forms['cacl'].rate.value
	var months = document.forms['cacl'].months.value
	var comma = ","
	var temparry = new Array(10)

	temparray = amount.split(comma)
	amount = temparray.join("")
	temparray = payment.split(comma)
	payment = temparray.join("")
	temparray = rate.split(comma)
	rate = temparray.join("")
	temparray = months.split(comma)
	months = temparray.join("")


	if (isNaN(amount)) {
		alert("Amount must be a number!");
		document.forms['cacl'].amount.focus();
		return false;
	}
	if (isNaN(payment)) {
		alert("Payment must be a number!");
		document.forms['cacl'].payment.focus();
		return false;
	}
	if (isNaN(rate)) {
		alert("Rate must be a number!");
		document.forms['cacl'].rate.focus();
		return false;
	}
	if (isNaN(months)) {
		alert("Length of Loan must be a number!");
		document.forms['cacl'].months.focus();
		return false;
	}
	
	if(((amount != 0) && (amount != "")) &&
		((payment != 0) && (payment != ""))){ 
		alert("Please clear either the loan payment or the loan amount to continue.");
		document.forms['cacl'].amount.focus();
		return false;
	}
	if(((amount == 0) || (amount == "")) &&
		((payment == 0) || (payment == ""))){ 
		alert("You must select either the loan payment or the loan amount!");
		document.forms['cacl'].amount.focus();
		return false;
	}
	if((rate == 0) || (rate == "")){ 
		alert("You must select a loan rate!");
		document.forms['cacl'].rate.focus();
		return false;
		}
	else {
		rate = rate/1200;
	}

	if((months == 0) || (months == "")){
		alert("You must provide the term of the loan!");
		document.forms['cacl'].months.focus();
		return false;
		}
	else {
		if(document.forms['cacl'].frequency.options[document.forms['cacl'].frequency.selectedIndex].value == '1'){
			months = months * 12;
		}
	}

	if(payment == 0 || payment == ""){
		document.forms['cacl'].payment.value = parseInt(100 * ((amount * ( rate / (1 - (Math.pow(1 + rate, -months))))) + .005)) / 100;
	}
	else {
		document.forms['cacl'].amount.value = parseInt(100 * ((((Math.pow(1 + rate, -months)*(-payment + (Math.pow(1 + rate, months)* payment))))/rate) + .005)) / 100;
	}
	return false;
}
