var RentalCoveragePercent = 125;
var MinLoanAmount = 70000;
var MaxLoanAmount = 750000;
var MinLoanPeriod = 7;
var MaxLoanPeriod = 30;
var MinRentOnlyPeriod = 1;
var MaxRentOnlyPeriod = 2;
var AffordableAmount = 0.6;
var DiscountPeriodMonth = 6;
var DiscountPeriodYear = 2010;

function getLoanAmountField() { return document.getElementById("loanAmount"); }
function getLoanPeriodField() { return document.getElementById("loanPeriod"); }
function getRentOnlyPeriodField() { return document.getElementById("rentOnlyPeriod"); }
function getInterestRateField() { return document.getElementById("interestRate"); }
function getFirstIncomeField() { return document.getElementById("firstIncome"); }
function getSecondIncomeField() { return document.getElementById("secondIncome"); }
function getOutgoingsField() { return document.getElementById("outgoings"); }

function getRepaymentAmountField() { return document.getElementById("repaymentAmount"); }
function getInterestOnlyField() { return document.getElementById("interestOnlyAmount"); }
function getHppAffordablePaymentField() { return document.getElementById("hppAffordablePayment"); }

function getBTLAffordableLoanField() { return document.getElementById("btlAffordableLoan"); }
function getRentNeededAmountField() { return document.getElementById("rentNeededAmount"); }
function getRentalIncomeField() { return document.getElementById("rentalIncome"); }

//
//
//
//

function setFieldCorrectMessage(id) {
    var field = document.getElementById(id);
    
    if (!field)
        return;

    field.setAttribute("class", "fieldCorrect");
    field.setAttribute("className", "fieldCorrect");
    field.innerHTML = '';
}

function setFieldErrorMessage(id, msg) {
    var field = document.getElementById(id);

    if (!field)
        return;

    field.setAttribute("class", "errorBlock");
    field.setAttribute("className", "errorBlock");
    field.innerHTML = '<div class="fieldError"></div><div class="fieldValidate"><p><span class="required"><span class="errorIcon"></span> ' + msg + '</span></p></div>';
}

function repaymentBoundCheck() {
    var hasError = false;
    
    if (getLoanAmountField().value > MaxLoanAmount || getLoanAmountField().value < MinLoanAmount) {
        getLoanAmountField().setAttribute("class", "formField error autoWidth");
        getLoanAmountField().setAttribute("className", "formField error autoWidth");
        setFieldErrorMessage('loanAmountMessage', 'Finance amount must be between £' + MinLoanAmount + ' and £' + MaxLoanAmount);
        hasError = true;
    }
    else {
        getLoanAmountField().setAttribute("class", "formField correct autoWidth");
        getLoanAmountField().setAttribute("className", "formField correct autoWidth");
        setFieldCorrectMessage('loanAmountMessage');
    }

    if (getLoanPeriodField().value > MaxLoanPeriod || getLoanPeriodField().value < MinLoanPeriod) {
        getLoanPeriodField().setAttribute("class", "formField error autoWidth");
        getLoanPeriodField().setAttribute("className", "formField error autoWidth");
        setFieldErrorMessage('loanPeriodMessage', 'Finance period must be between ' + MinLoanPeriod + ' and ' + MaxLoanPeriod + ' years');
        hasError = true;
    }
    else {
        getLoanPeriodField().setAttribute("class", "formField correct autoWidth");
        getLoanPeriodField().setAttribute("className", "formField correct autoWidth");
        setFieldCorrectMessage('loanPeriodMessage');
    }

    if (getRentOnlyPeriodField().value != 0 && (getRentOnlyPeriodField().value > MaxRentOnlyPeriod || getRentOnlyPeriodField().value < MinRentOnlyPeriod)) {
        alert('Rent only period must be between ' + MinRentOnlyPeriod + ' and ' + MaxRentOnlyPeriod + ' years');
        getRentOnlyPeriodField().setAttribute("class", "formField error autoWidth");
        getRentOnlyPeriodField().setAttribute("className", "formField error autoWidth");
        hasError = true;
    }
    else {
        getRentOnlyPeriodField().setAttribute("class", "formField correct autoWidth");
        getRentOnlyPeriodField().setAttribute("className", "formField correct autoWidth");
    }

    if (getInterestRateField().value == '') {
        getInterestRateField().setAttribute("class", "formField error");
        getInterestRateField().setAttribute("className", "formField error");
        setFieldErrorMessage('interestRateMessage', 'You must select a product type');
        hasError = true;
    }
    else {
        getInterestRateField().setAttribute("class", "formField correct");
        getInterestRateField().setAttribute("className", "formField correct");
        setFieldCorrectMessage('interestRateMessage');
    }

    document.getElementById('formValidationMessage').style.display = hasError ? 'block' : 'none';

    return hasError;
}

function calculate_repayment() {
    getLoanAmountField().value = ForceNumeric(getLoanAmountField().value);
    getLoanPeriodField().value = ForceNumeric(getLoanPeriodField().value);

    if (repaymentBoundCheck())
        return;

    var selind = getInterestRateField().selectedIndex;
    var selval = getInterestRateField()[selind].value;

    if (selval.match(/\?/)) {
        // this is a rent only over the full term buy to let
        var finrate = ForceNumeric(selval.replace(/\?/, ""));
        var basicloanamount = getLoanAmountField().value;
        var loanamount = ForceNumeric(basicloanamount);
        getRepaymentAmountField().innerHTML = FormatNumber((loanamount * finrate) / (100 * 12));
        document.getElementById("discount").style.visibility = "hidden";
        return;
    }

    var basicloanamount = getLoanAmountField().value;
    var loanamount = Number(basicloanamount);
    var interestrate = selval;
    var loanperiod = getLoanPeriodField().value;
    var rentonlyperiod = 0;
    var discountRate = 0;

    if (interestrate.match("-")) {
        rentonlyperiod = 1;
        var myarray = interestrate.split("-");
        interestrate = myarray[1];
        discountRate = myarray[0];
        document.getElementById("discount").style.visibility = "visible";
    }

    else {
        document.getElementById("discount").style.visibility = "hidden";
    }



    if (rentonlyperiod == 0) {
        if (interestrate > 0 && loanperiod > 0) {
            var I = interestrate / 12;
            var X = 1 / (1 + I / 100);
            var N = loanperiod * 12;
            var L = loanamount;
            var P1 = 0;
            var P2 = loanamount;
            var A1 = FormatNumber((L - P1 * Math.pow(X, N)) * (X - 1) / (Math.pow(X, N + 1) - X))
            getRepaymentAmountField().innerHTML = A1;

            // rental amount for btl

            if (getRentNeededAmountField() != null)
            {
                getRentNeededAmountField().innerHTML = FormatNumber((FormatNumber((L - P1 * Math.pow(X, N)) * (X - 1) / (Math.pow(X, N + 1) - X)) / 100) * RentalCoveragePercent);
            }
        }
        else {
            getRepaymentAmountField().innerHTML = "*ERROR*";
            getInterestOnlyField().innerHTML = "*ERROR*";
        }
    }

    if (rentonlyperiod == 1)
    {
        if (interestrate > 0 && loanperiod > 0)
        {
            // discount period
            var I = discountRate / 12;
            var X = 1 / (1 + I / 100);
            var N = loanperiod * 12;
            var L = loanamount;
            var P1 = 0;
            var P2 = loanamount;
            var A1 = FormatNumber((L - P1 * Math.pow(X, N)) * (X - 1) / (Math.pow(X, N + 1) - X))
            getInterestOnlyField().innerHTML = A1;


            // main repayment period

            var basicfinanceamount = loanamount;
            var totalperiod = loanperiod * 12;
            var financeperiod = loanperiod * 12;
            var discountperiod = get_discount_period(DiscountPeriodMonth, DiscountPeriodYear);
            financeperiod = financeperiod - discountperiod;
            var financeamount = calculate_amount_at_discount_end(discountRate, basicfinanceamount, discountperiod, totalperiod);

            I = interestrate / 12;
            X = 1 / (1 + I / 100);
            N = financeperiod;
            L = financeamount;
            P1 = 0;
            P2 = financeamount;
            var A2 = FormatNumber((L - P1 * Math.pow(X, N)) * (X - 1) / (Math.pow(X, N + 1) - X))
            getRepaymentAmountField().innerHTML = A2;

            // rental amount for btl

            if (getRentNeededAmountField() != null)
            {
                getRentNeededAmountField().innerHTML = FormatNumber((FormatNumber((L - P1 * Math.pow(X, N)) * (X - 1) / (Math.pow(X, N + 1) - X)) / 100) * RentalCoveragePercent);
            }
        }
        else
        {
            getRepaymentAmountField().innerHTML = "*ERROR*";
            getInterestOnlyField().innerHTML = "*ERROR*";
        }
    }
}

function calculate_amount_at_discount_end(discountRate, originalAmount, termTaken, originalterm) {
    var oldRate = discountRate / 1200;
    var totalFinanceRemaining = originalAmount * Math.pow((oldRate + 1), termTaken);
    var temp = originalAmount * (oldRate / (1 - (1 / Math.pow((oldRate + 1), originalterm))));
    var amountPaid = temp * ((Math.pow((oldRate + 1), termTaken) - 1) / oldRate);
    var amountRemaining = totalFinanceRemaining - amountPaid;
    return amountRemaining;
}

function get_discount_period(endMonth, endYear) {
    var thedate = new Date();
    var thismonth = thedate.getMonth() + 1;
    var thisyear = thedate.getYear();
    if (thisyear < 1000) thisyear += 1900;
    var period = (12 * (endYear - parseInt(thisyear))) + endMonth - parseInt(thismonth);
    return period
}

//
//
//
//

function validateAffordableFields() {
    var hasError = false;

    if (getFirstIncomeField().value == 0) {
        setFieldErrorMessage('firstIncomeMessage', 'You must enter a first income value');
        getFirstIncomeField().setAttribute("class", "formField error autoWidth");
        getFirstIncomeField().setAttribute("className", "formField error autoWidth");
        hasError = true;
    }
    else {
        getFirstIncomeField().setAttribute("class", "formField correct autoWidth");
        getFirstIncomeField().setAttribute("className", "formField correct autoWidth");
        setFieldCorrectMessage('firstIncomeMessage');
    }

    getSecondIncomeField().setAttribute("class", "formField correct autoWidth");
    getSecondIncomeField().setAttribute("className", "formField correct autoWidth");
    setFieldCorrectMessage('secondIncomeMessage');

    getOutgoingsField().setAttribute("class", "formField correct autoWidth");
    getOutgoingsField().setAttribute("className", "formField correct autoWidth");
    setFieldCorrectMessage('outgoingsMessage');

    document.getElementById('formValidationMessage2').style.display = hasError ? 'block' : 'none';
}

function calculate_affordable() {
    getFirstIncomeField().value = ForceNumeric(getFirstIncomeField().value);
    getSecondIncomeField().value = ForceNumeric(getSecondIncomeField().value);
    getOutgoingsField().value = ForceNumeric(getOutgoingsField().value);
    validateAffordableFields();
    
    var firstincome = getFirstIncomeField().value;
    var secondincome = getSecondIncomeField().value;
    var outgoings = getOutgoingsField().value;
    if (firstincome > 0) {
        if (secondincome == 0) {
            averageloanamount = (firstincome - outgoings) * AffordableAmount;
        }
        else {
            var jointincome = Math.abs(firstincome) + Math.abs(secondincome);
            averageloanamount = (jointincome - outgoings) * AffordableAmount;
        }
        getHppAffordablePaymentField().innerHTML = FormatNumber(averageloanamount, 0);
    }
    else {
        getHppAffordablePaymentField().innerHTML = "*ERROR*";
    }
}

function validateAffordableBTLFields()
{
    var hasError = false;

    if (getRentalIncomeField().value == 0)
    {
        setFieldErrorMessage('rentalIncomeMessage', 'You must enter a rental income value');
        getRentalIncomeField().setAttribute("class", "formField error autoWidth");
        getRentalIncomeField().setAttribute("className", "formField error autoWidth");
        hasError = true;
    }
    else
    {
        getRentalIncomeField().setAttribute("class", "formField correct autoWidth");
        getRentalIncomeField().setAttribute("className", "formField correct autoWidth");
        setFieldCorrectMessage('rentalIncomeMessage');
    }

    document.getElementById('formValidationMessage2').style.display = hasError ? 'block' : 'none';
}

function calculate_affordable_btl()
{
    getRentalIncomeField().value = ForceNumeric(getRentalIncomeField().value);
    validateAffordableBTLFields();

    var rentalincome = getRentalIncomeField().value;

    if (rentalincome > 0)
    {
        var affordablePayment = (rentalincome / RentalCoveragePercent) * 100;
        getHppAffordablePaymentField().innerHTML = FormatNumber(affordablePayment, 0);

        //var affordableLoan = (affordablePayment * 12);
        //getBTLAffordableLoanField().innerHTML = FormatNumber(affordableLoan, 0);
    }
    else
    {
        getHppAffordablePaymentField().innerHTML = "*ERROR*";
        //getBTLAffordableLoanField().innerHTML = "*ERROR*";
    }
}

//
//
//
//

function FormatNumber(Number, Decimals, Separator) {
    Number += ""
    Decimals += ""
    Separator += ""
    if ((Separator == "") || (Separator.length > 1))
        Separator = "."
    if (Number.length == 0)
        Number = "0"
    var OriginalNumber = Number
    var Sign = 1
    var Pad = ""
    var Count = 0
    if (parseFloat(Number)) {
        Number = parseFloat(Number)
    } else {
        Number = 0
    }
    if ((parseInt(Decimals, 10)) || (parseInt(Decimals, 10) == 0)) {
        Decimals = parseInt(Decimals, 10)
    } else {
        Decimals = 2
    }
    if (Number < 0) {
        Sign = -1
        Number *= Sign
    }
    if (Decimals < 0)
        Decimals *= -1
    Number = "" + Math.floor(Number * Math.pow(10, Decimals + 1) + 5)
    if ((Number.substring(1, 2) == '.') || ((Number + '') == 'NaN'))
        return (OriginalNumber)
    if (Number.length < Decimals + 1) {
        for (Count = Number.length; Count <= Decimals; Count++)
            Pad += "0"
    }
    Number = Pad + Number
    if (Decimals == 0) {
        Number = Number.substring(0, Number.length - 1)
    } else {
        Number = Number.substring(0, Number.length - Decimals - 1) +
          Separator +
          Number.substring(Number.length - Decimals - 1,
          Number.length - 1)
    }
    if (Sign == -1)
        Number = "-" + Number
    if (Number.length == 0)
        Number = "0"
    return (Number)
}

function ForceNumeric(nValue) {
    validChars = "0123456789.";
    newValue = "";
    for (k = 0; k < nValue.length; k++) {
        thisChar = nValue.charAt(k);
        if (validChars.indexOf(thisChar) != -1) newValue += thisChar;
    }
    return newValue;
}
