// JavaScript Document - Loan Calculator Functions

//Build an array to keep the last calculated value.
anchor = new Array(0,0,0,0);

function compute()
{	

	//Retrieve incoming values
	var amt = GetValueOf('amountTxt');
	var term = GetValueOf('termTxt');
	var iRate = GetValueOf('interestTxt');
	var pymt = GetValueOf('paymentTxt');
	
	//Store incoming values in an array
	
    var	tmpInValues = new Array(amt, term, iRate, pymt);
	
	var x;
	var blankCount=0;
	var blankIndex;
	for(x=0;x<tmpInValues.length;x++) 
        {
		if(tmpInValues[x] == 0) 
		{
			blankCount++;
			blankIndex = x;
		}
	}
	if(blankCount > 1)
	{
		alert('Please fill in all but one entry');
	} 
	else 
	{
		if(!(blankIndex >= 0)) 
		{
			//find the last value calculated from anchor
			var y;
			for(y=0;y<anchor.length;y++) 
			{
				if(anchor[y] == 1) 
				{
					blankIndex = y;
				}
			}
		}
	
		for(x=0;x<anchor.length;x++) 
		{
			anchor[x] = 0;
			if(x==blankIndex) 
			{
				anchor[x] = 1;
			}		
		}


// Perform the function based on the missing field

      switch(blankIndex.toString()) 
      {
        case "0":
			document.LoanCalc.amountTxt.value = amount();
			break;
        case "1":
			document.LoanCalc.termTxt.value = Term();
			break;
        case "2":
			document.LoanCalc.interestTxt.value = interest();
			break;
        case "3":
			document.LoanCalc.paymentTxt.value = payment();
			break;
      }
   }
}

function payment()
{

//Calculate the payment amount

  var principal = GetValueOf('amountTxt');
  var nr = GetValueOf('interestTxt');
  var termtype = document.LoanCalc.termSel.options[document.LoanCalc.termSel.selectedIndex].value;
  
  var money = 0;
  	
  nr = nr / 100.0;
  
  nr /= 12;

  var pow = 1;
 
  pow = Math.pow(pow * (1 + nr), GetValueOf('termTxt') * termtype);
  
  money = (principal * pow * nr) / (pow - 1); 

  return twoDecimals(RoundToHundreths(money));
}

function paymentcalc(interest)
{
//Payment calc used to get the interest rate

  var principal = GetValueOf('amountTxt');
  var nr = interest;   
  var money = 0;
  var termtype = document.LoanCalc.termSel.options[document.LoanCalc.termSel.selectedIndex].value;
  nr = nr / 100.0 / 12;
  var pow = 1;

  pow = Math.pow(pow * (1 + nr), GetValueOf('termTxt') * termtype);
	 
  money = (principal * pow * nr) / (pow - 1); 

  return money;
}

function amount ( )
{
//Calculates the Loan Principal
  var amount;
  var payment = GetValueOf('paymentTxt');
  var termtype = document.LoanCalc.termSel.options[document.LoanCalc.termSel.selectedIndex].value;
  var nr = GetValueOf('interestTxt')/ 12 / 100;
  var n = GetValueOf('termTxt') * termtype;
  amount = payment * (1 - Math.pow(1/(1 +nr), n)) / ((1 + nr) -1);

  return twoDecimals(RoundToHundreths(amount));
}

function Term ( )
{
//Calculates the Loan Term
	var bool = MinimumPaymentRequired();
    var termtype = document.LoanCalc.termSel.options[document.LoanCalc.termSel.selectedIndex].value;
	if(bool) 
        {
        var Principal = GetValueOf('amountTxt');
        var Payment = GetValueOf('paymentTxt');
        var Interest = GetValueOf('interestTxt');
        if (Interest > 1.0) {
            Interest = Interest / 100.0;
        }
        var r = Number(Number(1) + (Number(Interest)/Number(12)));
        var NumofPayments =0.0;
        NumofPayments =  (Math.log(Payment/(Payment+Principal*(1-r))))/ Math.log(r);

		if (parseInt(termtype) == 12)
        {
            NumofPayments = NumofPayments/12;
        }
        return twoDecimals(RoundToHundreths(NumofPayments));

	} 
	else 
	{
		return ('Error');
	}
}

function interest() {
//Calculates the interest rate
	var initialInterest = 100;
	var high = 9999;
	var low = 0;
	var realPayment = RoundToHundreths(GetValueOf("paymentTxt"));
	var paymentTmp = 0;
	var termtype = document.LoanCalc.termSel.options[document.LoanCalc.termSel.selectedIndex].value;
  	var numberofpayments = GetValueOf('termTxt') * termtype;
	var stepOne = GetValueOf('amountTxt') / numberofpayments;     

    if (realPayment < stepOne) 
	{
		alert('Payment is insufficient to pay the principal on the loan within the given timeframe.  The minimum value is '+twoDecimals(RoundToHundreths(stepOne))+'.');
		return ('Error');
	}

	for( i = 0; i < 500; i++) 
	{
	    paymentTmp = RoundToHundreths(paymentcalc(initialInterest));
		if ( paymentTmp < realPayment) {
			low = initialInterest
		} else if(paymentTmp > realPayment) {
			high = initialInterest;
		} else {
			break;
		}
		initialInterest = low + ((high - low) / 2);
	}

	return twoDecimals(RoundToHundreths(initialInterest));	
}

function MinimumPaymentRequired() {
//When doing a term calculation, the payment must be sufficient to cover the interest.  This function 
//validates the payment amount.
	if (GetField("termTxt") == ""  || GetField("termTxt") == "0") {
	  	var interest = GetValueOf('interestTxt') / 1200;
        var stepOne = GetValueOf('amountTxt') * interest;     
        if (GetValueOf("paymentTxt") < stepOne) {
			alert('Payment is insufficient to pay the interest on loan.  The minimum value is '+twoDecimals(RoundToHundreths(stepOne))+'.');
			return false;
		}
	}
	return true;
}


function RoundToHundreths(iValue) {
	// Round the value to Hundreths
	iValue = Math.round(iValue*100);
	iValue = iValue / 100;
	return iValue;
	
}

function twoDecimals(iAmount) {

	var Amount = ""+iAmount;
	var length = Amount.length;
	var posDecimalPoint=  Amount.indexOf('.');
	if (posDecimalPoint == -1) {
		Amount += ".00";
	} else if ( length - posDecimalPoint == 2) {
		Amount += "0";
	} else if (length - posDecimalPoint == 1) {
		Amount += "00";
	} 

	return Amount;
}

function ValidateNumericInput(sInputName, FieldName)
   //  check for valid numeric strings	
{

   if (isNumeric(GetField(sInputName)) == false)

      alert (FieldName + " is not numeric.");

   return;
}

function isNumeric(strString)
   //  check for valid numeric strings	
{
   var strValidChars = "0123456789.-,";
   var strChar;
   var blnResult = true;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

function GetValueOf(InputName) {
	var value = parseFloat(GetField(InputName));
	if (""+value == "NaN") {
		value = 0;
	}
    return value;
    
}

function GetField(InputName) {
    FieldReference = 'document.LoanCalc.' + InputName + '.value';
    return eval(FieldReference);
}

function Clear() {
	document.LoanCalc.amountTxt.value =  "";
	document.LoanCalc.interestTxt.value =  "";
	document.LoanCalc.termTxt.value =  "";
	document.LoanCalc.paymentTxt.value =  "";
}