/************************************************************
* Estimate.js
* 29-Apr-2011
* MR
*
* Does the rental calculations based on the rates
*
************************************************************/

// Perform rounding to 2 decimal places
function RoundValue(pSource) {
    return (Math.round(pSource * 100) / 100).toFixed(2);
}

// Return the weekly instalment, given the monthly instalment
function ConvertMonthlyToWeekly(pMonthlyAmount) {
    return RoundValue(pMonthlyAmount * 12 / 52);
}

// Returns the ExGst monthly instalment from the Inc GST total invoice amount
function CalculateMonthlyInstalmentExGst(pInvoiceAmountIncGst, pTerm) {
    var monthlyInstalment = CalculateMonthlyInstalment(pInvoiceAmountIncGst, pTerm);

    if (IsValidValue(monthlyInstalment)) {
        monthlyInstalment = monthlyInstalment / (1 + (Rates.GSTRate / 100));
    }

    return monthlyInstalment;
}

// Returns the IncGst monthly instalment from the Inc GST total invoice amount
function CalculateMonthlyInstalmentIncGst(pInvoiceAmountIncGst, pTerm, EtrType) {
    var monthlyInstalment = null;

	var pInvoiceAmountExGst = pInvoiceAmountIncGst / (1 + (Rates.GSTRate / 100));

    if (IsValidValue(pInvoiceAmountExGst) && IsAmountInLimits(pInvoiceAmountIncGst)) {
        var rate = GetRate(pTerm, pInvoiceAmountExGst);

        monthlyInstalment = pInvoiceAmountExGst * (rate / 100);
		
		if (EtrType == "Primary") {
			monthlyInstalment -= GetMonthlyPrimaryETRValue(pInvoiceAmountIncGst, monthlyInstalment);
		}
		else if (EtrType == "Secondary") {
			monthlyInstalment -= GetMonthlySecondaryETRValue(pInvoiceAmountIncGst, monthlyInstalment);
		}
		
    }

    return monthlyInstalment;
}

// Checks if the invoice amount is in the limits for the specified term
function IsAmountInLimits(pInvoiceAmountIncGst){
	if (pInvoiceAmountIncGst >= GetLowerFundingLimit() && pInvoiceAmountIncGst <= GetUpperFundingLimit()){
		return true;
	}
	
	return false;
}

// Check whether the given variable has been defined
function IsValidValue(pValue) {
    if ((typeof pValue != 'undefined') && (pValue != null)) {
        return true;
    }

    return false;
}

function GetMonthlyPrimaryETRValue(invoiceAmountIncGST, monthlyInstalmentIncGst) {
	
	var value = 375;
	
	if (monthlyInstalmentIncGst*12 <= 750) {
		value = (Rates.ETRRate/100)*monthlyInstalmentIncGst*12;
	}
	
	return (value/12);
}

function GetMonthlySecondaryETRValue(invoiceAmountIncGST, monthlyInstalmentIncGst) {
	
	var value = 750;
	
	if (monthlyInstalmentIncGst*12 <= 1500) {
		value = (Rates.ETRRate/100)*monthlyInstalmentIncGst*12;
	}
	
	return (value/12);
}

