﻿/// <reference path="jquery-1.4.4.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

var Address = function () {
    var that = {};

    function PerformSearchAndReplaceContent(url, p) {

        $("#addressLookupAjaxLoader").addClass("show");

        $.post(url, { postCode: p }, function (d) {
            $('#newAddress').replaceWith(d);
            //Refocus back to the postcode field.
            $("#Address_PostcodeSearched").focus();

            Page.ReparseValidation($("form"));
        });

        return true;
    }

    that.NotInList = function (url) {
        var p = $('#Address_PostcodeSearched').val();

        $.post(url, { postcode: p }, function (d) {
            $('#newAddress').replaceWith(d);
            //Refocus back to the postcode field.
            $("#Address_PostcodeSearched").focus();

            Page.ReparseValidation($("form"));
        });
        
        return false;
    }

    that.LookupPostcodeIfMatch = function (url, e) {

        //If the user has tabbed into here, ignore.
        if (e.which === 9 || e.which === 37 || e.which === 38 || e.which === 39 || e.which === 40) {
            return false;
        }

        var regex = /[A-Za-z]{1,2}[0-9]{1,2}[a-zA-Z]?\s?[0-9][A-Za-z]{2}/i;
        var postcode = $('#Address_PostcodeSearched').val();

        //If the postcode matches, call the lookup.
        if (regex.test(postcode.replace(" ", ""))) {
            PerformSearchAndReplaceContent(url, postcode);
        }

        return false;
    }

    that.lookupPostCode = function (url) {
        var postcode = $('#Address_PostcodeSearched').val();

        PerformSearchAndReplaceContent(url, postcode);

        return false;
    };

    that.setAddress = function (url) {
        //Find the selected item.
        var selectedID = $("#addressLookupSearchResults select option:selected").val();
        var p = $('#Address_PostcodeSearched').val();

        if (selectedID && selectedID !== -1 && p && p.length > 0) {
            $("#addressSearchAjaxLoader").addClass("show");

            $.post(url, { addressLookupID: selectedID, postcode: p }, function (d) {
                $('#newAddress').replaceWith(d);
            });
        }

        return false;
    }

    return that;

} ();

var LoanRate = function () {

    var that = {};

    that.UpdateLoanRateDisplay = function (url) {

        var rate = $("#LoanDetails_LoanRate").val();
        var term = $("#LoanDetails_LoanTerm").val();
        var repayment = $("#LoanDetails_RepaymentDate").val();

        $.post(url, { loanRate: rate, loanTerm: term, repaymentDate: repayment }, function (d) {
            $("#loanDetails").replaceWith(d);
        });

        return false;
    }

    that.ChangeLoanRate = function (url) {
        $("#loanRateAjaxLoader").addClass("show");

        that.UpdateLoanRateDisplay(url);

        return false;
    }

    that.ChangeLoanTerm = function (url) {
        $("#loanTermAjaxLoader").addClass("show");

        that.UpdateLoanRateDisplay(url);

        return false;
    }

    return that;

} ();

var Page = function () {

    var that = {};

    that.ScrollFirst = function (element) {
        var first = $(element).first();

        if (first.length == 1) {
            var x = first.offset().left;
            var y = first.offset().top;

            window.scroll(x, y);
        }

        return false;
    }

    that.ToggleDefaultTextForElement = function (element, toggleText, isFocus) {
        var content = $.trim($(element).val());

        if (toggleText.length == 0) {
            toggleText = "Click here";
        }

        toggleText = $.trim(toggleText);

        if (isFocus) {

            if (content == toggleText) {
                $(element).val("");
            }
        }
        else {
            if (content === "") {
                $(element).val(toggleText);
            }
        }

        return false;
    }

    that.SubmitOnEnter = function (element, event, submitIfNotEmpty) {
        var content = $(element).val().trim();
        var form = $(element).closest("form");

        if (event.which === 13 && content.length > 0) {
            form.submit();
        }
    }

    that.ReparseValidation = function (element) {
        //Unbind existing validation
        element.unbind();
        element.data("validator", null);

        //Check document for changes
        $.validator.unobtrusive.parse(document);

        //Re add validation with changes
        element.validate(element.data("unobtrusiveValidation").options);

        $("form").submit(function () {
            // Only display if 0 client side errors. It's ok to do this as the client side validation kicks off first.
            if ($(".input-validation-error").length === 0) {
                $(this).find("input[type=submit]").attr("disabled", "disabled");
                $(this).find("#ajaxLoaderFormSubmit, #ajaxLoaderFormSubmitSmallButton").addClass("show");
            }
        });
    }

    that.Defibrillation = function () {
        $.post("/Defibrillation/", {}, function (d) { });
        window.setTimeout("Page.Defibrillation()", 720000);
        return true;
    }

    that.RemoveRadioGroupValidation = function (element) {
        $(element).closest(".radioButtonGroupError").removeClass("radioButtonGroupError").addClass("radioButtonGroupValid");
    }

    return that;

} ();

$(document).ready(function () {
    $('.focus').focus();

    $("#AnswerCentreQuestion_Question").val($("#AnswerCentreQuestion_QuestionDefaultText").val());
    $("#homePage .allowHover").hover(function () {
        $(this).addClass("hover pointer");
    }, function () {
        $(this).removeClass("hover pointer");
    });

    $("#homePage .allowHover").click(function () {
        var link = $(this).find("a").first().attr("href");

        //Redirect.
        window.location.href = link;
    });

    if ($("form").length > 0) {
        $("form").submit(function () {
            // Only display if 0 client side errors. It's ok to do this as the client side validation kicks off first.
            if ($(".input-validation-error").length === 0) {
                $(this).find("input[type=submit]").attr("disabled", "disabled");
                $(this).find("#ajaxLoaderFormSubmit, #ajaxLoaderFormSubmitSmallButton").addClass("show");
                
            } else {
                //Check to see if radio button groups have errors (e.g. no option in a group has been selected). If so enable the radio button group error class.
                $(".radioButtonGroupValid input.input-validation-error").closest(".radioButtonGroupValid").removeClass("radioButtonGroupValid").addClass("radioButtonGroupError");  
            }
        });

        var settngs = $.data($('form')[0], 'validator').settings;
        settngs.onchange = function (element) { $(element).valid(); };
    }

    window.setTimeout("Page.Defibrillation()", 720000);
});

