﻿/*************************************************************
    
    axa.wealth.common.js

    This file contains scripts that are for use in both the
    Exktron Web Forms site and the MVC site

    Requires jquery

**************************************************************/

/*
    Sets the style of the selected menu item
    This is determined from the path of the url.
*/
function setSelectedHeaderNavMenuItem() {
    $('.headerNavItem').each(function () {
        var $this = $(this);
        var link = $this.find(">:first-child");
        if (link.attr('href')) {
            // Remove any instances of ../ pre-pending the url
            var linkUrl = link.attr('href');
            while (linkUrl.indexOf('../') >= 0) {
                linkUrl = linkUrl.substring(linkUrl.indexOf('../') + '../'.length);
            }
            // If the current path starts with the link url, then highlight the link
            if (window.location.href.toLowerCase().indexOf(linkUrl.toLowerCase()) == 0 && linkUrl.length > 1) {            
                $this.addClass('active');
            }
        }
    });
}

var loaderHeight = 32;
var loaderWidth = 32;

$(function () {

    $('#uiChangePasswordForm').submit(
		function () {
		    $(this).ajaxSubmit({
		        beforeSubmit: function () {
		            $('#uiChangePasswordForm #uiChangePasswordButton').val("Please wait...");
		            $('#uiChangePasswordForm #uiChangePasswordButton').attr("disabled", "true");

		            var containerHeight = $('#uiChangePasswordForm #componentContainer').height();
		            var containerWidth = $('#uiChangePasswordForm #componentContainer').width();

		            $('#uiChangePasswordForm #loader').height(containerHeight);
		            $('#uiChangePasswordForm #loader').width(containerWidth);

		            $('#uiChangePasswordForm #loader').css("margin-top", (containerHeight / 2 - loaderHeight / 2) + "px");
		            $('#uiChangePasswordForm #loader').css("margin-left", (containerWidth / 2 - loaderWidth / 2) + "px");

		            $('#uiChangePasswordForm #componentContainer').addClass("loaderopacity");

		            $('#uiChangePasswordForm #loader').show();
		        },
		        dataType: "json",
		        error: function (error) {
		            // todo: temporarily hardcoding the general error page here. Need to store this in some way
		            window().location.href = "/adviser/general-login-error/";
		        },
		        success: function (jsonObject) {
		            if (jsonObject.error == "false") {
		                window.location.href = jsonObject.data;
		            }
		            else {
		                $('#uiChangePasswordForm #uiChangePasswordFormError').show();
		                $('#uiChangePasswordForm #uiChangePasswordFormError > ul').empty();
		                $('#uiChangePasswordForm #uiChangePasswordFormError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-errors");

		                $.each(jsonObject.data, function (key, value) {
		                    $('#uiChangePasswordForm #uiChangePasswordFormError > ul').append('<li> ' + value.ErrorMessage + '</li>');
		                });

		                $('#uiChangePasswordForm #loader').hide();

		                $('#uiChangePasswordForm #componentContainer').removeClass("loaderopacity");

		                $('#uiChangePasswordForm #uiChangePasswordButton').val("Change Password");
		                $('#uiChangePasswordForm #uiChangePasswordButton').removeAttr("disabled");

		                $('#uiChangePasswordForm #NewPassword').val("");
		                $('#uiChangePasswordForm #ConfirmNewPassword').val("");
		            }
		        }
		    });
		    return false;
		});

    $(".consultationRequestWrapper form").submit(function (e) {
        if ($(this).valid()) {
            $('.consultationRequestWrapper #uisubmitconsultation').val("Submit ...");
            $('.consultationRequestWrapper #uisubmitconsultation').attr("disabled", "disabled");
            $.post("/Plugins/ConsultationRequest/Home/DefaultPost",
                    $(this).serialize(),
                    function (data) {
                        $(".consultationRequestWrapper").html(data);
                    },
                    "html");
        }
        e.preventDefault();
    });

    $('#uiIncDDCalcForm #uiTaxFreeLumpSumRow').hide();
    $('#uiIncDDCalcForm #uiOutputPanel').hide();

    $("#uiIncDDCalcForm input[id='uiMaxTaxFreeReqRadioBtn']").click(
			function () {
			    if ($("#uiIncDDCalcForm input[id='uiMaxTaxFreeReqRadioBtn']:checked").val() == "No")
			        $('#uiIncDDCalcForm #uiTaxFreeLumpSumRow').show();
			    else
			        $('#uiIncDDCalcForm #uiTaxFreeLumpSumRow').hide();
			}
		);

    $('#uiIncDDCalcForm #uiPrint').click(function () {
        window.print();
    });

    $('#uiIncDDCalcForm #uiResetBtn').click(
			function () {
			    var now = new Date();
			    $("#uiIncDDCalcForm #Age").val("");
			    $("#uiIncDDCalcForm #InvestorsName").val("");
			    $("#uiIncDDCalcForm #TotalFundsAvailableDisplay").val("");
			    $("#uiIncDDCalcForm #TaxFreeAmountDisplay").val("");

			    $("#uiIncDDCalcForm #uiMaxTaxFreeReqRadioBtn[value='Yes']").attr('checked', true);
			    $("#uiIncDDCalcForm #uiMaxTaxFreeReqRadioBtn[value='No']").attr('checked', false);

			    $("#uiIncDDCalcForm #Sex[value='M']").attr('checked', true);
			    $("#uiIncDDCalcForm #Sex[value='F']").attr('checked', false);
			    $("#uiIncDDCalcForm #MaritalStatus").val('0');

			    $("#uiIncDDCalcForm #ReferenceDateDisplay").val(now.getDate() + "/" + now.getMonth() + "/" + now.getFullYear());

			    $('#uiIncDDCalcForm #uiIncDDCalcError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-valid");
			    $('#uiIncDDCalcForm #uiIncDDCalcError > ul > li').remove();
			    $('#uiIncDDCalcForm #uiTaxFreeLumpSumRow').hide();

			    $('#uiIncDDCalcForm #uiGiltIndexYieldResult').text("");
			    $('#uiIncDDCalcForm #uiTaxFreeLumpSumTakenResult').text("");
			    $('#uiIncDDCalcForm #uiGADFactorResult').text("");
			    $('#uiIncDDCalcForm #uiMaximumAnnualIncomeResult').text("");
			    $('#uiIncDDCalcForm #uiMaximumMonthlyIncomeResult').text("");
			    $('#uiIncDDCalcForm #uiOutputPanel').slideUp();
			}
		);

    $("#AgeDisplay").numeric({ decimal: false, negative: false });
    $("#TotalFundsAvailableDisplay").numeric({ decimal: false, negative: false });
    $("#TaxFreeAmountDisplay").numeric({ decimal: false, negative: false });

    $('#uiIncDDCalcForm').submit(
        function () {
            if ($('#uiIncDDCalcForm').valid()) {
                $(this).ajaxSubmit({
                    beforeSubmit: function () {
                        $('#uiIncDDCalcForm #uiCalculateBtn').val("Calculating ...");
                        $('#uiIncDDCalcForm p.componentCTA.button').addClass("disabled");
                        $('#uiIncDDCalcForm #uiCalculateBtn').attr("disabled", "disabled");
                        $('#uiIncDDCalcForm #uiResetBtn').attr("disabled", "disabled");
                    },
                    dataType: "json",
                    url: '/Plugins/IncDDCalculator/Home/Calculate',

                    error: function (error) {
                        $('#uiIncDDCalcForm #uiIncDDCalcError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-errors");
                        $('#uiIncDDCalcForm #uiIncDDCalcError > ul > li').remove();
                        $('#uiIncDDCalcForm #uiIncDDCalcError > ul').append('<li>Your request could not be processed due to an unexpected error.</li>');
                        $('#uiIncDDCalcForm #uiCalculateBtn').val("Calculate");
                    },
                    success: function (jsonObject) {
                        if (jsonObject.error == "false") {
                            $('#uiIncDDCalcForm #uiGiltIndexYieldResult').text(jsonObject.data.GiltIndexYield);
                            $('#uiIncDDCalcForm #uiTaxFreeLumpSumTakenResult').text(jsonObject.data.TaxFreeLumpSumTaken);
                            $('#uiIncDDCalcForm #uiGADFactorResult').text(jsonObject.data.GADFactor);
                            $('#uiIncDDCalcForm #uiMaximumAnnualIncomeResult').text(jsonObject.data.MaximumAnnualIncome);
                            $('#uiIncDDCalcForm #uiMaximumMonthlyIncomeResult').text(jsonObject.data.MaximumMonthlyIncome);
                            $('#uiIncDDCalcForm #uiOutputPanel').slideDown();
                            $('#uiIncDDCalcForm #uiIncDDCalcError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-valid");
                            $('#uiIncDDCalcForm #uiIncDDCalcError > ul > li').remove();
                        }
                        else {
                            $('#uiIncDDCalcForm #uiIncDDCalcError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-errors");
                            $('#uiIncDDCalcForm #uiIncDDCalcError > ul > li').remove();
                            $.each(jsonObject.data, function (key, value) {
                                $('#uiIncDDCalcForm #uiIncDDCalcError > ul').append('<li>' + value.ErrorMessage + '</li>');
                            });
                        }

                        $('#uiIncDDCalcForm p.componentCTA.button').removeClass("disabled");
                        $('#uiIncDDCalcForm #uiCalculateBtn').removeAttr("disabled");
                        $('#uiIncDDCalcForm #uiResetBtn').removeAttr("disabled");
                        $('#uiIncDDCalcForm #uiCalculateBtn').val("Calculate");
                    }
                });
            }
            return false;
        });

    $('#uiRegistrationForm').submit(
        function () {
            if (!($('#uiRegistrationForm').valid())) {
                $('html,body').scrollTop(0);
                return false;
            }
            return true;
        }
    );

    $('#uiLoginForm').submit(
		function () {
		    $(this).ajaxSubmit({
		        beforeSubmit: function () {
		            $('#uiLoginForm #uiLoginButton').val("Please wait...");
		            $('#uiLoginForm #uiLoginButton').attr("disabled", "true");

		            var containerHeight = $('#uiLoginForm #componentContainer').height();
		            var containerWidth = $('#uiLoginForm #componentContainer').width();

		            $('#uiLoginForm #loader').height(containerHeight);
		            $('#uiLoginForm #loader').width(containerWidth);

		            $('#uiLoginForm #loader').css("margin-top", (containerHeight / 2 - loaderHeight / 2) + "px");
		            $('#uiLoginForm #loader').css("margin-left", (containerWidth / 2 - loaderWidth / 2) + "px");

		            $('#uiLoginForm #componentContainer').addClass("loaderopacity");

		            $('#uiLoginForm #loader').show();
		        },
		        dataType: "json",
		        error: function (error) {
		            // todo: temporarily hardcoding the general error page here. Need to store this in some way
		            window().location.href = "/adviser/general-login-error/";
		        },
		        success: function (jsonObject) {
		            if (jsonObject.error == "false") {
		                window.location.href = jsonObject.data;
		            }
		            else {
		                $('#uiLoginForm #uiLoginFormError').show();
		                $('#uiLoginForm #uiLoginFormError > ul').empty();
		                $('#uiLoginForm #uiLoginFormError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-errors");
		                
		                $.each(jsonObject.data, function (key, value) {
		                    $('#uiLoginForm #uiLoginFormError > ul').append('<li> ' + value.ErrorMessage + '</li>');
		                });

		                $('#uiLoginForm #loader').hide();

		                $('#uiLoginForm #componentContainer').removeClass("loaderopacity");

		                $('#uiLoginForm #uiLoginButton').val("Login");
		                $('#uiLoginForm #uiLoginButton').removeAttr("disabled");

		                $('#uiLoginForm #Password').val("");
		            }
		        }
		    });
		    return false;
		});

    $('#uiAssociateUnipassForm').submit(
		function () {
		    $(this).ajaxSubmit({
		        beforeSubmit: function () {
		            $('#uiAssociateUnipassForm #uiAssociateUnipassButton').val("Please wait...");
		            $('#uiAssociateUnipassForm #uiAssociateUnipassButton').attr("disabled", "true");

		            var containerHeight = $('#uiAssociateUnipassForm #componentContainer').height();
		            var containerWidth = $('#uiAssociateUnipassForm #componentContainer').width();

		            $('#uiAssociateUnipassForm #loader').height(containerHeight);
		            $('#uiAssociateUnipassForm #loader').width(containerWidth);

		            $('#uiAssociateUnipassForm #loader').css("margin-top", (containerHeight / 2 - loaderHeight / 2) + "px");
		            $('#uiAssociateUnipassForm #loader').css("margin-left", (containerWidth / 2 - loaderWidth / 2) + "px");

		            $('#uiAssociateUnipassForm #componentContainer').addClass("loaderopacity");

		            $('#uiAssociateUnipassForm #loader').show();
		        },
		        dataType: "json",
		        error: function (error) {
		            // todo: temporarily hardcoding the general error page here. Need to store this in some way
		            window().location.href = "/adviser/general-login-error/";
		        },
		        success: function (jsonObject) {
		            if (jsonObject.error == "false") {
		                window.location.href = jsonObject.data;
		            }
		            else {
		                $('#uiAssociateUnipassForm #uiAssociateUnipassFormError').show();
		                $('#uiAssociateUnipassForm #uiAssociateUnipassFormError > ul').empty();
		                $('#uiAssociateUnipassForm #uiAssociateUnipassFormError').removeClass("validation-summary-valid validation-summary-errors").addClass("validation-summary-errors");
		                
		                $.each(jsonObject.data, function (key, value) {
		                    $('#uiAssociateUnipassForm #uiAssociateUnipassFormError > ul').append('<li> ' + value.ErrorMessage + '</li>');
		                });

		                $('#uiAssociateUnipassForm #loader').hide();

		                $('#uiAssociateUnipassForm #componentContainer').removeClass("loaderopacity");

		                $('#uiAssociateUnipassForm #uiAssociateUnipassButton').val("Associate Unipass certificate");
		                $('#uiAssociateUnipassForm #uiAssociateUnipassButton').removeAttr("disabled");

		                $('#uiAssociateUnipassForm #Password').val("");
		            }
		        }
		    });
		    return false;
		});

});

$(function () {
    var Axa;

    if (Axa === undefined) {
        Axa = {};
    }
    if (Axa.Wealth === undefined) {
        Axa.Wealth = {};
    }

    var setLiteratureLibrary = function (items, taxonomyParentId) {
        $('a[data-axawealth-taxonomyid]').nextAll().each(function () { $(this).remove(); });
        $('a[data-axawealth-taxonomyid=' + taxonomyParentId + ']')
        .after(items)
        .next() // the ul sibling.
        .find('li.headerLink > a')
        .each(function () {
            var that = this;
            $(this).click(function () {
                var library = Axa.Wealth.LiteratureLibrary;
                library.getLiterature($(that).attr('data-axawealth-taxonomyid'), function (data) {
                    library.setLiterature(data);
                    library.hideLiteratureLibrary($(that));
                });

                return false;
            });
        });
    };

    var setLiterature = function (data) {
        // if we have not used search then there will be a libraryTableWrapper
        var libraryTableWrapper = $('.libraryTableWrapper');
        if (libraryTableWrapper.length > 0) {
            libraryTableWrapper.replaceWith(data);
            return;
        }

        // If search has just been used then we will need to find the searchTableResults table.
        var searchTableResults = $('.searchTableResults');
        if (searchTableResults.length > 0) {
            searchTableResults.replaceWith(data);
            return;
        }

        // If search has just been used then we will need to find the searchTableResults table.
        var literatureLibrary = $('.literatureLibrary > .libraryList');
        if (literatureLibrary.length > 0) {
            literatureLibrary.after(data);
            return;
        }
    };

    // The purpose of this object is to retrieve literature data 
    // based on taxonomy ids or search criteria.
    Axa.Wealth.LiteratureLibrary = function () {
        var library = {};
        library.ajaxLibraryUrl = $('.libraryList').attr('data-ajax-libraryurl');
        library.ajaxLiteratureUrl = $('.libraryList').attr('data-ajax-literatureurl');
        library.getLiteratureLibrary = function (id, callback) {
            $.ajax({
                type: 'GET',
                url: this.ajaxLibraryUrl || '',
                data: { taxonomyId: id },
                error: function (error) {
                    // todo: temporarily hardcoding the general error page here. Need to store this in some way
                    window.location.href = '/adviser/general-login-error/';
                },
                success: function (jsonObject) { callback(jsonObject.libraryHtml); }
            });
        };
        library.getLiterature = function (id, callback) {
            $.ajax({
                type: 'GET',
                url: this.ajaxLiteratureUrl || '',
                data: { taxonomyId: id },
                error: function (error) {
                    // todo: temporarily hardcoding the general error page here. Need to store this in some way
                    window.location.href = '/adviser/general-login-error/';
                },
                success: function (jsonObject) { callback(jsonObject.literatureHtml); }
            });
        };
        library.hideLiteratureLibrary = function (selectedLibraryItem) {
            // The selected item is an anchor inside an li inside a ul. We need to hide the ul
            selectedLibraryItem.parent().parent().hide();

            // set parent anchor to be active, so we can change the color
            selectedLibraryItem.parent().parent().parent().find("a:first").addClass('active');
        };
        library.setLiterature = setLiterature;
        library.setLiteratureLibrary = setLiteratureLibrary;
        return library;
    } (); // Create object.

    $('#SearchForm').ajaxForm({
        beforeSubmit: function () {
            $('#SearchForm #SubmitText').attr("disabled", "true");
        },
        dataType: 'json',
        url: function () {
            return $('#SearchForm').attr('data-ajax-url');
        } (),
        error: function (error) {
            // todo: temporarily hardcoding the general error page here. Need to store this in some way
            window.location.href = '/adviser/general-login-error/';
        },
        success: function (jsonObject) {
            $('#SearchForm #SubmitText').removeAttr("disabled");
            Axa.Wealth.LiteratureLibrary.setLiterature(jsonObject.searchResultsHtml);
            // clear any selected library item heading
            $('.libraryList > ul > li.headerLink.active').removeClass('active');
        }
    });

    $('.libraryList > ul > li.headerLink > a')
        .each(function () {
            var that = this;

            $(this).click(function () {
                // Change the style of the selected headerLink.
                var headerLink = $(this).closest('.headerLink');
                $('.literatureLibrary .libraryList .headerLink').removeClass('active');
                $(headerLink, this).toggleClass('active');

                // Get the library html and set the callback function.
                var library = Axa.Wealth.LiteratureLibrary;
                library.getLiteratureLibrary($(that).attr('data-axawealth-taxonomyid'), function (data) {
                    library.setLiteratureLibrary(data, $(that).attr('data-axawealth-taxonomyid'));
                });

                return false;
            });
        });

});

