/*
--------------------------------------------------------------------------------
Date: 23/10/2004

This file is a javascript implementation of financial calculations.  It is not
guaranteed to be correct and is NOT financially/legally or otherwise binding.

--------------------------------------------------------------------------------

The following values are self-describing and may be altered at a future
date by non-technical uses.

--------------------------------------------------------------------------------
*/

//Defines percentage tax for assumed tax bracket
var AVG_TAX_BRACKET_DIVISOR = 0.65; //CORRESPONDS TO 35% TAX BRACKET


//This toggle may be set to "false" which will disable user input validation
//(in case there is a need a.k.a. Foreign language use.
var ENFORCE_INPUT = true;


//Used internally by script to determine which element to mark as active.
var CurrentActiveElement = 1;


//Used to track which elements have a valid value
var blnBalanceAtPurchase = false;
var blnPresentBalance = false;
var blnPaymentAmount = false;
var blnAmortization = false;
var blnYearsLeft = false;
var blnYearsLivedAtHome = false;

/*
Function to read the value of an input field, verify the content
and force user to input correct values if not done already.

Enforces format only, prompts, clears, and focuses on violation
*/
function validateInput(element, value){

	//if ENFORCE_INPUT is disabled, even "alpha characters will be permitted and may
	//interfere with calculations in unpredicatable ways.
	if(element.id == "PaymentFrequency"){
		TallyMortgageInfo();
		return false;
	}
	
	if (ENFORCE_INPUT) {
		if(value.length <= 0){
			MarkCurrentInputAsInvalid(element);
			ClearOutPuts();
			return false;
		}else{
			//Disallow the '$' symbol as it will interfere with calculations
			if(value.indexOf("$") > -1){
				alert("Please enter the value again without commas, or $ symbols");
				clearAndReset(element);
				MarkCurrentInputAsInvalid(element);
				ClearOutPuts();
				return false;
			}
			//Be sure 
			if (isNaN(value)){
				alert("Please enter a valid number");
				clearAndReset(element);
				MarkCurrentInputAsInvalid(element);
				ClearOutPuts();
				return false;
			}
		}
	}	
		//value is valid, continue with calculations if possible
		MarkCurrentInputAsValid(element);
		TallyMortgageInfo();
}


//This defines and performs actions on elements whose values could not be validated
function clearAndReset(element){
	element.focus();
    element.select();
    element.value = "";

}

//This function performs the main financial calculations once all input fields are completed
function TallyMortgageInfo(){
	var valBalanceAtPurchase;
	var valPresentBalance;
	var valPaymentAmount;
	var valAmortization;
	var valYearsLeft;
	var valYearsLivedAtHome;
	//Check to see that all inputs are completed
	var AllCorrect = blnBalanceAtPurchase &&  blnPresentBalance && blnPaymentAmount && blnAmortization && blnYearsLeft && blnYearsLivedAtHome
	//alert("Values all valid?: " + AllCorrect);

	if (AllCorrect){
		//gather input values
		valBalanceAtPurchase = parseFloat(document.InputForm.BalanceAtPurchase.value);
		valPresentBalance = parseFloat(document.InputForm.PresentBalance.value);
		valPaymentFrequency = parseFloat(document.InputForm.PaymentFrequency.value);
		valPaymentAmount = parseFloat(document.InputForm.PaymentAmount.value);
		valAmortization = parseFloat(document.InputForm.Amortization.value);
		valYearsLeft = parseFloat(document.InputForm.YearsLeft.value);
		valYearsLivedAtHome = 	parseFloat(document.InputForm.YearsLivedAtHome.value);		
		
		//perform main calculations
		valAnnualPayment = valPaymentAmount * valPaymentFrequency;		
		valTotalPandICost = valAnnualPayment *  valAmortization;
		valInterestCost = valTotalPandICost - valBalanceAtPurchase;
		valHowMuchToEarn1 = "";
		valHowMuchToEarn2 = valTotalPandICost / AVG_TAX_BRACKET_DIVISOR;
		valHowMuchToEarn3 = valHowMuchToEarn2 - valBalanceAtPurchase;
		valTotalCostToDate = valAnnualPayment * valYearsLivedAtHome;
		valPrincipalPaidToDate = valBalanceAtPurchase - valPresentBalance;
		valInterestPaidToDate = valTotalCostToDate - valPrincipalPaidToDate;
		valAmountRequiredToEarnToDate = valTotalCostToDate / AVG_TAX_BRACKET_DIVISOR;
		valCurrentBorrowingCosts = valAmountRequiredToEarnToDate - valPrincipalPaidToDate;
		
		document.InputForm.AnnualPayment.value = FormatCurrency(valAnnualPayment);
		document.InputForm.TotalPandICost.value = FormatCurrency(valTotalPandICost);
		document.InputForm.InterestCost.value = FormatCurrency(valInterestCost);
		//document.InputForm.valHowMuchToEarn1
		document.InputForm.HowMuchToEarn2.value = FormatCurrency(valHowMuchToEarn2);
		document.InputForm.HowMuchToEarn3.value = FormatCurrency(valHowMuchToEarn3);
		document.InputForm.TotalCostToDate.value = FormatCurrency(valTotalCostToDate); 
		document.InputForm.PrincipalPaidToDate.value = FormatCurrency(valPrincipalPaidToDate);
		document.InputForm.InterestPaidToDate.value = FormatCurrency(valInterestPaidToDate);
		document.InputForm.AmountRequiredToEarnToDate.value = FormatCurrency(valAmountRequiredToEarnToDate);
		document.InputForm.CurrentBorrowingCosts.value = FormatCurrency(valCurrentBorrowingCosts);
	}else{
		ClearOutPuts();
	}
	
}

function ClearOutPuts(){
	document.InputForm.AnnualPayment.value = "";
	document.InputForm.TotalPandICost.value = "";
	document.InputForm.InterestCost.value =  "";
	//document.InputForm.valHowMuchToEarn1
	document.InputForm.HowMuchToEarn2.value =  "";
	document.InputForm.HowMuchToEarn3.value =  "";
	document.InputForm.TotalCostToDate.value =  "";
	document.InputForm.PrincipalPaidToDate.value =  "";
	document.InputForm.InterestPaidToDate.value =  "";
	document.InputForm.AmountRequiredToEarnToDate.value =  "";
	document.InputForm.CurrentBorrowingCosts.value =  "";
}
//Toggle tracking of fields which are valid or not

function MarkCurrentInputAsInvalid(element){
	if(element.id == "BalanceAtPurchase"){
		blnBalanceAtPurchase = false;
	}
	if(element.id == "PresentBalance"){
		blnPresentBalance = false;
	}
	if(element.id == "PaymentAmount"){
		blnPaymentAmount = false;
	}
	if(element.id == "Amortization"){
		blnAmortization = false;
	}
	if(element.id == "YearsLeft"){
		blnYearsLeft = false;
	}
	if(element.id == "YearsLivedAtHome"){
		blnYearsLivedAtHome = false;
	}
	
}

function MarkCurrentInputAsValid(element){
	if(element.id == "BalanceAtPurchase"){
		blnBalanceAtPurchase = true;
	}
	if(element.id == "PresentBalance"){
		blnPresentBalance = true;
	}
	if(element.id == "PaymentAmount"){
		blnPaymentAmount = true;
	}
	if(element.id == "Amortization"){
		blnAmortization = true;
	}
	if(element.id == "YearsLeft"){
		blnYearsLeft = true;
	}
	if(element.id == "YearsLivedAtHome"){
		blnYearsLivedAtHome = true;
	}
}


function FormatCurrency(integer){

	var value = CommaFormatted(new String(parseInt(integer) + ".00"));

return "$" + value;

}

function CommaFormatted(amount)
{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
// end of function CommaFormatted()


