﻿var homeLoanEnquiry = function() {
    var helpOptionSelected;
    var loanPurpose;
    var howSoon;
    var loanAmount;
    var title;
    var firstName;
    var lastName;
    var email;
    var contactNumber;
    var postCode;
    var contactTime;
    var termsAndConditions;
    var propertyValue;
    var totalIncome;
    var creditHistory;
    var fivePercentDeposit;

    var ShowErrorMessage = function(errorPanelId, errorMessage) {
        var isValid = errorMessage == "";

        var errorPanel = jQuery(errorPanelId).text(errorMessage);
        isValid ? errorPanel.hide() : errorPanel.show();

        return isValid;
    };

    var Validate = function() {
        var isValid = true;

        //isValid = ValidateHelpOption() && isValid;
        isValid = ValidateLoanPurpose() && isValid;
        isValid = ValidateHowSoon() && isValid;
        isValid = ValidateLoanAmount() && isValid;
        isValid = ValidateName() && isValid;
        isValid = ValidateEmail() && isValid;
        isValid = ValidateContactNumber() && isValid;
        isValid = ValidatePostCode() && isValid;
        isValid = ValidateContactTime() && isValid;
        isValid = ValidateTC() && isValid;
        isValid = ValidatePropertyValue() && isValid;
        isValid = ValidateTotalIncome() && isValid;
        isValid = ValidateCreditHistory() && isValid;
        isValid = ValidateFivePercentDeposit() && isValid;

        if (!isValid) {
            ShowInProgress(false);
        }
        return isValid;
    };

    var ValidateHelpOption = function() {
        var errorMessage = "";

        if (jQuery(".checkBoxSelect").length == 0) {
            eerrorMessage = "Please select one of the help options above";
        }

        return ShowErrorMessage(".errorHelpOption", errorMessage);
    };

    var ValidateLoanPurpose = function() {
        var errorMessage = "";

        if (loanPurpose.get(0).selectedIndex == 0) {
            errorMessage = "Loan purpose is required";
        }

        return ShowErrorMessage(".errorLoanPurpose", errorMessage);
    };

    var ValidateHowSoon = function() {
        var errorMessage = "";

        if (howSoon.get(0).selectedIndex == 0) {
            errorMessage = "How soon period is required";
        }

        return ShowErrorMessage(".errorHowSoon", errorMessage);
    };

    var ValidateLoanAmount = function() {
        var errorMessage = "";
        var amount = loanAmount.val().replace(/\$|,|\(|\)/g, "");

        if (amount == "") {
            errorMessage = "Loan amount is required";
        }

        amount = parseFloat(amount);

        if (isNaN(amount) || Math.abs(amount) == 0) {
            errorMessage = "Loan amount must be a positve amount";
        }

        return ShowErrorMessage(".errorLoanAmount", errorMessage);
    };

    var ValidateName = function() {
        var errorMessage = "";

        if (title.val() == "" || firstName.val() == "" || lastName.val() == "") {
            errorMessage = "Your full name is required - title, first name and last name";
        } else {
            title.val(Capitalise(title.val()));
            firstName.val(Capitalise(firstName.val()));
            lastName.val(Capitalise(lastName.val()));
        }

        return ShowErrorMessage(".errorName", errorMessage);
    };

    var ValidateEmail = function() {
        var emailRegex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", "i");
        var errorMessage = "";
        var emailAddress = email.val();

        if (email == "") {
            errorMessage = "Email address is required";
        } else if (!emailRegex.test(emailAddress)) {
            errorMessage = "Email must be in a valid format - e.g. me@mydomain.com.au";
        }

        return ShowErrorMessage(".errorEmail", errorMessage);
    };

    var ValidateContactNumber = function() {
        var errorMessage = "";

        var value = contactNumber.val().replace(/ |\(|\)/g, "");

        if (value == "") {
            errorMessage = "Best contact number is required";
        } else if (value.length != 10) {
            errorMessage = "Contact number must be a landline (inc area code) or a mobile number";
        }

        return ShowErrorMessage(".errorContactNumber", errorMessage);
    };

    var ValidatePostCode = function() {
        var errorMessage = "";
        var value = postCode.val();

        if (value == "") {
            errorMessage = "Post code is required";
        } else if (value.length != 4) {
            errorMessage = "Post code must be in a valid format - e.g. 2000";
        }

        return ShowErrorMessage(".errorPostCode", errorMessage);
    };

    var ValidateContactTime = function() {
        var errorMessage = "";

        if (contactTime.get(0).selectedIndex == 0) {
            errorMessage = "How preferred contact time is required";
        }

        return ShowErrorMessage(".errorContactTime", errorMessage);
    };

    var ValidateTC = function() {
        var errorMessage = "";

        if (!termsAndConditions.get(0).checked) {
            errorMessage = "The acceptance of the above agreement is required to proceed";
        }

        return ShowErrorMessage(".errorTC", errorMessage);
    };

    var ValidatePropertyValue = function() {
        var errorMessage = "";
        var amount = propertyValue.val().replace(/\$|,|\(|\)/g, "");

        if (amount == "") {
            errorMessage = "Property value is required";
        }

        amount = parseFloat(amount);

        if (isNaN(amount) || Math.abs(amount) == 0) {
            errorMessage = "Property value must be a positve amount";
        }

        return ShowErrorMessage(".errorPropertyValue", errorMessage);
    };

    var ValidateTotalIncome = function() {
        var errorMessage = "";
        var amount = totalIncome.val().replace(/\$|,|\(|\)/g, "");

        if (amount == "") {
            errorMessage = "Total income is required";
        }

        amount = parseFloat(amount);

        if (isNaN(amount) || Math.abs(amount) == 0) {
            errorMessage = "Total income must be a positve amount";
        }

        return ShowErrorMessage(".errorTotalIncome", errorMessage);
    };

    var ValidateCreditHistory = function() {
        var errorMessage = "";

        if (creditHistory.get(0).selectedIndex == 0) {
            errorMessage = "Credit history is required";
        }

        return ShowErrorMessage(".errorCreditHistory", errorMessage);
    };

    var ValidateFivePercentDeposit = function() {
        var errorMessage = "";

        if (fivePercentDeposit.get(0).selectedIndex == 0) {
            errorMessage = "Property deposit selection is required";
        }

        return ShowErrorMessage(".errorFivePercentDeposit", errorMessage);
    }


    var ShowInProgress = function(show) {
        var inProgress = jQuery(".inProgress");
        !show || false ? inProgress.hide() : inProgress.show();
    };

    var InitClickToSelect = function() {
        jQuery(".helpOption").hover(function() {
            jQuery(".clickToSelect", this).show();
        }, function() {
            jQuery(".clickToSelect", this).hide();
        }).click(OnHelpOptionClick);
    };

    var OnHelpOptionClick = function(event) {
        event.preventDefault();
        jQuery(".checkBox").removeClass("checkBoxSelect");
        jQuery(".checkBox", this).addClass("checkBoxSelect");
        helpOptionSelected.val(this.className);
        ValidateHelpOption();
    };

    var NumberOrSpace = function(e) {

        var isValid = true;

        //if the letter is not digit then reject it
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            isValid = false;
        }

        return isValid;
    };

    var FormatMoney = function() {
        var value = jQuery(this);

        if (value.val() != "") {
            value.formatCurrency({ dollarOnly: true, negativeFormat: "%s%n" })
        }
    };

    var ClearMoneyFormat = function() {
        var value = jQuery(this);
        value.val(value.val().replace(/\$|,|\(|\)/g, ""));
    };

    var FormatContactNumber = function() {
        var value = contactNumber.val();

        if (value.startsWith("04") && value.length == 10) {
            var mobilePart1 = value.substring(0, 4);
            var mobilePart2 = value.substring(4, 7);
            var mobilePart3 = value.substring(7, 10);
            value = mobilePart1 + " " + mobilePart2 + " " + mobilePart3;
        } else if (value.startsWith("0") && value.length > 1) {
            var postCode = value.substring(0, 2);
            var landlinePart1 = value.substring(2, 6);
            var landlinePart2 = value.substring(6, 10);
            value = "(" + postCode + ") " + landlinePart1 + " " + landlinePart2;
        }

        contactNumber.val(value);
    };

    var CleanContactNumber = function() {
        contactNumber.val(contactNumber.val().replace(/ |\(|\)/g, ""));
    };

    var Capitalise = function(inputString) {
        var outputString = "";
        var tmpStr, tmpChar, preString, postString, strlen;
        tmpStr = inputString.toLowerCase();
        stringLen = tmpStr.length;
        if (stringLen > 0) {
            for (i = 0; i < stringLen; i++) {
                if (i == 0) {
                    tmpChar = tmpStr.substring(0, 1).toUpperCase();
                    postString = tmpStr.substring(1, stringLen);
                    tmpStr = tmpChar + postString;
                }
                else {
                    tmpChar = tmpStr.substring(i, i + 1);
                    if (tmpChar == " " && i < (stringLen - 1)) {
                        tmpChar = tmpStr.substring(i + 1, i + 2).toUpperCase();
                        preString = tmpStr.substring(0, i + 1);
                        postString = tmpStr.substring(i + 2, stringLen);
                        tmpStr = preString + tmpChar + postString;
                    }
                }
            }
        }
        return tmpStr;
    }

    return {
        Init: function() {
            jQuery(".numeric").keypress(NumberOrSpace);
            helpOptionSelected = jQuery(".helpOptionSelected");
            loanAmount = jQuery(".loanAmountInput").watermark({ html: "e.g. 400,000", cls: "watermark" }).focus(ClearMoneyFormat).blur(FormatMoney).change(ValidateLoanAmount);
            title = jQuery(".title").watermark({ html: "Title", cls: "watermark" });
            firstName = jQuery(".firstName").watermark({ html: "First name", cls: "watermark" });
            lastName = jQuery(".lastName").watermark({ html: "Last name", cls: "watermark" }).change(ValidateName);
            jQuery(".myQuestionInput").watermark({ html: "Please type your question here", cls: "watermark" });
            email = jQuery(".email").watermark({ html: "e.g. me@mydomain.com.au", cls: "watermark" }).change(ValidateEmail);
            loanPurpose = jQuery(".loanPurposeInput").change(ValidateLoanPurpose);
            howSoon = jQuery(".howSoonInput").change(ValidateHowSoon);
            contactNumber = jQuery(".contactNumber").watermark({ html: "Landline (inc area code) / mobile", cls: "watermark" }).focus(CleanContactNumber).blur(FormatContactNumber).change(ValidateContactNumber);
            postCode = jQuery(".postCode").watermark({ html: "e.g. 2000", cls: "watermark" }).change(ValidatePostCode);
            contactTime = jQuery(".contactTime").change(ValidateContactTime);
            termsAndConditions = jQuery(".tcCheckbox input").change(ValidateTC);

            propertyValue = jQuery(".propertyValue").watermark({ html: "e.g. 600,000", cls: "watermark" }).focus(ClearMoneyFormat).blur(FormatMoney).change(ValidatePropertyValue);
            totalIncome = jQuery(".totalIncome").watermark({ html: "e.g. 100,000", cls: "watermark" }).focus(ClearMoneyFormat).blur(FormatMoney).change(ValidateTotalIncome);
            creditHistory = jQuery(".creditHistory").change(ValidateCreditHistory);
            fivePercentDeposit = jQuery(".fivePercentDeposit").change(ValidateFivePercentDeposit);

            InitClickToSelect();
        },
        OnSubmit: function() {
            ShowInProgress();
            return Validate();
        }
    }
} ();

jQuery(document).ready(function() {
    homeLoanEnquiry.Init();
});
