﻿/// <reference name="MicrosoftAjax.js"/>

//
// Load Window
//

window.onload = function() {
    
    Init();
    CalculateFinance();
}

//
// Load Document Elements
//

function LoadFormElements()
{
	// Array of document objects
	this.DocumentElements = new Array();

	this.LoadElements = function(sTagName)
	{
		var aTagElements = document.getElementsByTagName(sTagName);

		// Get tags by name in the document
		for (var iCounter = 0; iCounter < aTagElements.length; iCounter++)
		{
	
			if (aTagElements[iCounter].id && aTagElements[iCounter].id != '')
			{
				sObjectId = aTagElements[iCounter].id;
				
				this.DocumentElements[sObjectId] = document.getElementById(sObjectId);
				
				
			}
		}
	}
	
	this.LoadElements('input');
	this.LoadElements('select');
	this.LoadElements('textarea');
	this.LoadElements('checkbox');
	this.LoadElements('radio');
	this.LoadElements('span');
	this.LoadElements('div');
	
    this.SetCalculatorValues = function(oHiddenField, oDisplayLabel, sFieldValue, bWriteToLabel)
    {
        oHiddenField.value = sFieldValue;
        if (bWriteToLabel) oDisplayLabel.innerHTML = sFieldValue;
    }
}

//
// Set global form variables
//

var oCalculatorForm;

function Init()
{
    
	oCalculatorForm = new LoadFormElements();
	
	//
	// Non Wizard Control Fields
	//
	
	// Hidden Fields - Not Calculated
	oCalculatorForm.YearlyRegistration = oCalculatorForm.DocumentElements['YearlyRegistration'];
	oCalculatorForm.MonthlyRegistration = oCalculatorForm.DocumentElements['MonthlyRegistration'];
	oCalculatorForm.SelectedState = oCalculatorForm.DocumentElements['State'];
    oCalculatorForm.LeaseProtectionRate = oCalculatorForm.DocumentElements['LeaseProtectionRate'];
    oCalculatorForm.ResidualPercentageRate = oCalculatorForm.DocumentElements['ResidualPercentageRate'];
    oCalculatorForm.LuxuryCarTaxRate = oCalculatorForm.DocumentElements['LuxuryCarTaxRate'];
    // Hidden Fields - Calculated
    oCalculatorForm.OnRoadCost = oCalculatorForm.DocumentElements['OnRoadCost'];
	oCalculatorForm.GST = oCalculatorForm.DocumentElements['GST'];
	oCalculatorForm.LuxuryCarTax = oCalculatorForm.DocumentElements['LuxuryCarTax'];
	oCalculatorForm.StampDuty = oCalculatorForm.DocumentElements['StampDuty'];
	oCalculatorForm.Registration = oCalculatorForm.DocumentElements['Registration'];
	oCalculatorForm.LeaseProtection = oCalculatorForm.DocumentElements['LeaseProtection'];
	oCalculatorForm.Brokerage = oCalculatorForm.DocumentElements['Brokerage'];
	oCalculatorForm.FinanceAmount = oCalculatorForm.DocumentElements['FinanceAmount'];
	
	// Display Fields
	oCalculatorForm.GSTLabel = oCalculatorForm.DocumentElements['GSTLabel'];
	oCalculatorForm.OnRoadCostLabel = oCalculatorForm.DocumentElements['OnRoadCostLabel'];
	oCalculatorForm.LuxuryCarTaxLabel = oCalculatorForm.DocumentElements['LuxuryCarTaxLabel'];
	oCalculatorForm.StampDutyLabel = oCalculatorForm.DocumentElements['StampDutyLabel'];
	oCalculatorForm.RegistrationLabel = oCalculatorForm.DocumentElements['RegistrationLabel'];
	oCalculatorForm.LeaseProtectionLabel = oCalculatorForm.DocumentElements['LeaseProtectionLabel'];
	oCalculatorForm.BrokerageLabel = oCalculatorForm.DocumentElements['BrokerageLabel'];
	oCalculatorForm.FinanceAmountLabel = oCalculatorForm.DocumentElements['FinanceAmountLabel'];

	if (oCalculatorForm.DocumentElements['ControlPrefix']) 
	{
	    var sControlPrefix = oCalculatorForm.DocumentElements['ControlPrefix'].value;
	}
    
    //
	// Wizard Controls
	//
	
	// Standard Fields
    oCalculatorForm.PurchasePrice = oCalculatorForm.DocumentElements[sControlPrefix +'PurchasePriceTextBox'];
	oCalculatorForm.ResidualPercentage = oCalculatorForm.DocumentElements[sControlPrefix +'ResidualPercentageDropDownList'];
	oCalculatorForm.LeaseTerm = oCalculatorForm.DocumentElements[sControlPrefix +'LeaseTermDropDownList'];
	oCalculatorForm.ResidualPayment = oCalculatorForm.DocumentElements[sControlPrefix +'ResidualPaymentTextBox'];
	
	if (oCalculatorForm.LeaseTerm)
	{
	   //GetResidualPercentages(oCalculatorForm.LeaseTerm.value);  
	}
}

//
// Calculator
//

function CalculateFinance()
{
    
    if (oCalculatorForm.PurchasePrice)
	{
	   
    	var fPurchasePrice = parseFloat(GetNumericString(oCalculatorForm.PurchasePrice.value));
		var fLuxuryCarTaxRate = parseFloat(oCalculatorForm.LuxuryCarTaxRate.value);
		var fGST = parseFloat(0);
		var fYearlyRegistration = parseFloat(oCalculatorForm.YearlyRegistration.value);
		var fOnRoadCost = parseFloat(0);
		var fLeaseProtectionRate = parseFloat(oCalculatorForm.LeaseProtectionRate.value);
		var fLeaseProtection = parseFloat(0);
		var fResidualPercentage = oCalculatorForm.ResidualPercentageRate.value;
		var fResidualPayment = parseFloat(0);
		var sSelectedState = oCalculatorForm.SelectedState.value;
		
		if (oCalculatorForm.LeaseProtection.value != "")
		{
			fLeaseProtection= parseFloat(GetNumericString(oCalculatorForm.LeaseProtection.value));
		}

		if (!isNaN(fPurchasePrice))
		{
			// Get/Set the GST value
			if (fPurchasePrice < fLuxuryCarTaxRate)
			{
				fGST = GetRoundedNumber((fPurchasePrice / 11));
				oCalculatorForm.GST.value = GetCurrencyString(fGST);
			}
			else
			{
				fGST = GetRoundedNumber((fLuxuryCarTaxRate / 11));
				oCalculatorForm.GST.value = GetCurrencyString(fGST);
			}
			
			// Set the LCT
			var fAmountSubjectToLCT = fPurchasePrice - fLuxuryCarTaxRate;
			var fLuxuryCarTax = 0;

			if (fPurchasePrice > fLuxuryCarTaxRate)
			{
				fLuxuryCarTax = (fAmountSubjectToLCT / 11) * 0.25;

				oCalculatorForm.SetCalculatorValues(oCalculatorForm.LuxuryCarTax, oCalculatorForm.LuxuryCarTaxLabel, GetCurrencyString(GetRoundedNumber(fLuxuryCarTax)));
			}
			else oCalculatorForm.SetCalculatorValues(oCalculatorForm.LuxuryCarTax, oCalculatorForm.LuxuryCarTaxLabel, 0);
			
			// Set the stamp duty
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.StampDuty, oCalculatorForm.StampDutyLabel, GetCurrencyString(GetRoundedNumber(GetStampDuty(fPurchasePrice, sSelectedState))));
			
			// Set the registration
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.Registration, oCalculatorForm.RegistrationLabel, GetCurrencyString(GetRoundedNumber(fYearlyRegistration)));
			
		}
		fOnRoadCost += fPurchasePrice;
		fOnRoadCost += fYearlyRegistration;
		fOnRoadCost += fLuxuryCarTax;
		fOnRoadCost += GetStampDuty(fPurchasePrice, sSelectedState);
		
		if (!isNaN(fOnRoadCost))
		{
			// Show/Set the on road cost
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.OnRoadCost, oCalculatorForm.OnRoadCostLabel, GetCurrencyString(GetRoundedNumber(parseFloat(fOnRoadCost))), true);
			
			// Set the lease protection
			fLeaseProtection = parseFloat(Math.round(fOnRoadCost / 1000) * fLeaseProtectionRate);
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.LeaseProtection, oCalculatorForm.LeaseProtectionLabel, GetCurrencyString(GetRoundedNumber(fLeaseProtection)));
			
			// Set the brokerage
			fBrokerage= parseFloat(Math.round((fOnRoadCost - fGST) * 0.04));
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.Brokerage, oCalculatorForm.BrokerageLabel, GetCurrencyString(GetRoundedNumber(fBrokerage)));
			
			// Get/Set the finance amount to (fOnRoadCostt - fGST) + fLeaseProtection
			var fFinanceAmount = GetRoundedNumber(parseFloat(fOnRoadCost - fGST));
			oCalculatorForm.SetCalculatorValues(oCalculatorForm.FinanceAmount, oCalculatorForm.FinanceAmountLabel, GetCurrencyString(fFinanceAmount));
			
			fResidualPayment = parseFloat(fFinanceAmount * (fResidualPercentage / 100));

			// Show the residual payment
			oCalculatorForm.ResidualPayment.value = GetCurrencyString(GetRoundedNumber(fResidualPayment));
		}
	}
}

function GetNumericString(sInput)
{
	var sPurchasePrice = '';
	var sIntRegex = /[0-9\.]/;

	for (var iCounter = 0; iCounter < sInput.length; iCounter++)
	{
		if (sInput.charAt(iCounter).match(sIntRegex))
		{
			sPurchasePrice += sInput.charAt(iCounter);
		}
	}

	return sPurchasePrice;
}

function GetCurrencyString(sAmount)
{
	sInputAmount = new String(sAmount);

	aCurrency = sInputAmount.split('.');
	sCurrency1 = aCurrency[0];
	sCurrency2 = (aCurrency.length > 1)? '.' + aCurrency[1] : '';
	
	var sCurrencyRegex = /(\d+)(\d{3})/;

	while (sCurrencyRegex.test(sCurrency1))
	{
		sCurrency1 = sCurrency1.replace(sCurrencyRegex, '$1' + ',' + '$2');
	}
	
	return '$'+ sCurrency1 + sCurrency2;
}

function GetRoundedNumber(fNumberToRound)
{
	return fNumberToRound.toFixed(2);
}

function GetStampDuty(fPurchasePrice, sSelectedState)
{
	var fSampDuty = parseFloat(0);

	if (sSelectedState == "ACT" || sSelectedState == "NSW")
	{
		if (fPurchasePrice <= 45000)
		{
			fSampDuty = fPurchasePrice * 0.03;
		}
		else
		{
			fSampDuty += 45000 * 0.03;
			fSampDuty += (fPurchasePrice - 45000) * 0.05;
		}
	}
	else if (sSelectedState == "QLD" || sSelectedState == "NT")
	{
		fSampDuty = fPurchasePrice * 0.02;
	}
	else if (sSelectedState == "VIC")
	{
		if (fPurchasePrice <= 35000)
		{
			fSampDuty = fPurchasePrice * 0.025;
		}
		else if (fPurchasePrice > 35000 && fPurchasePrice <= 45000)
		{
			fSampDuty = fPurchasePrice * 0.04;
		}
		else
		{
			fSampDuty += fPurchasePrice * 0.05;
		}
	}
	else if (sSelectedState == "SA")
	{
		if (fPurchasePrice > 3000)
		{
			fSampDuty = 60;
			fSampDuty += (fPurchasePrice - 3000) * 0.04;
		}
		else
		{
			fSampDuty = 60;
		}
	}
	else if (sSelectedState == "TAS")
	{
		if (fPurchasePrice <= 35000)
		{
			fSampDuty = fPurchasePrice * 0.03;
		}
		else if (fPurchasePrice > 35000 && fPurchasePrice <= 45000)
		{
			fSampDuty = fPurchasePrice * 0.11;
		}
		else
		{
			fSampDuty += fPurchasePrice * 0.04;
		}
	}
	else if (sSelectedState == "WA")
	{
		if (fPurchasePrice <= 15000)
		{
			fSampDuty = fPurchasePrice * 0.0275;
		}
		else if (fPurchasePrice > 15000 && fPurchasePrice <= 40000)
		{
			fSampDuty = fPurchasePrice * 0.05;
		}
		else
		{
			fSampDuty += fPurchasePrice * 0.065;
		}
	}

	return fSampDuty;
}

//
// AJAX
//

function GetResidualPercentages(LeaseTerm)
{
	var iLeaseProtectionRate = 0;
    var iResidualPercentageRate = 0;
    
    for (var iCounter = 0; iCounter < Residuals.length; iCounter++)
    {
        var bSelected = false;
        var iSelectedIndex = 0;
        
        if (Residuals[iCounter][0] == LeaseTerm)
        {
            bSelected = true;
            iLeaseProtectionRate = Residuals[iCounter][1];
            iResidualPercentageRate = Residuals[iCounter][2];
            iSelectedIndex = iCounter;
        }
    }
	
	oCalculatorForm.ResidualPercentageRate.value = iResidualPercentageRate;
    oCalculatorForm.LeaseProtectionRate.value = iLeaseProtectionRate;
    // Calculate finance for new selected residual
	CalculateFinance();
}