﻿/// <reference path="../JQueryCore/jquery-latest.js" />
/// <reference path="../JQueryCore/jquery-latest-vsdoc.js" />

var ShoppingCartResultStatus = {
  NONE: 0,
  SUCCESS: 1,
  FAILURE: 2,
  INFORMATIONAL: 3,
  DATEFAILURE: 4
};

var DisplayModes = {
  SHOPPING: 'Shopping',
  APPCAPTURE: 'AppCapture',
  GENERAL: 'General'
};

(function($) {
    // Post logon action types
    var PostLogonActionType = {
        None: 0,
        SaveForLater: 1,
        SaveToCart: 2,
        EnrollNow: 3,
        RetrieveSettings: 4,
        ContinueAsGuest: 5
    };

    /* Shopping cart functionality variables */
    var ShoppingCartWidgetService = "UserCartShoppingService.asmx/";
    var AddPlanToCartWebMethod = "AddPlanToCart";
    var RemovePlanFromCartWebMethod = "RemoveFromShoppingCart";
    var EnrollPlanWebMethod = "EnrollPlan";
    var appCaptureURL = null; // to be loaded from a hidden field on page ready
    var shoppingCartURL = '/Shop/ShoppingCart';

    /* Login Redirection handling variables */
    var serviceEntryPoint = 'QuoteWizard.asmx';
    var shoppingCartURL = '/Shop/ShoppingCart';

    /* Variables for synchronising riders modal ajax callbacks */
    var incompatiblePlanDetectedInRidersModal = false;
    var enrollAjaxReturned = false;

    var workingPlanId = null;
    var callingDivSelector = null;
    var numberOfItemsInCart = null;

    var acceptedmessagetypes = 'CartContentsModified;SaveToCart;EnrollNow;EnrollmentComplete;QuoteUpdate;CartWidgetDisplayContext;UpdateShoppingCartPrice';

    /*****************************************************************
    When the document is ready we trigger initialization of the
    Shopping Cart Service Controller and the User Cart Widget Controller.
    ******************************************************************/
    $(document).ready(function() {
        pageobserver.subscribe(HandlePageobserverMessage, acceptedmessagetypes, "CartWidget");
        appCaptureURL = $('#appCaptureURL').val();
        numberOfItemsInCart = $('input[id$=cartItemsCount]').val();

        $('button#removeInactiveQuote').live('click', RemovePlanClick);

        // Override the "Enroll" breadcrumb
        $("a[id='breadcrumbLink_2']").live('click', function() {
            pageobserver.fire('{ "messagetype" : "EnrollNow", "planID" : "any" , "Callee" : "#pageSpecific" }');
            return false;
        });

        InitializeCartWidget();

        $.InitHelpControls('.helpbutton');

        // handle redirections following a cold state 'Enroll Now' click for an incompatible plan
        var value = $('input[id$=activeCartResult]').first().val();
        if (value !== "") {
            var activeCartResult = JSON.parse(value);
            workingPlanId = activeCartResult.Entity;
            HandleEnrollPlanResponse(activeCartResult);
        } else {
            // handle redirections following a cold state 'Enroll Now' click for a plan with riders
            var id = GetQueryString("enrollPlanId");
            if (id) {
                if (CheckForRiders(id)) {
                    workingPlanId = id;
                    DisplayRidersModal(id);
                }
            }
        }
    });

    /*******************************************************
    Handler for Shopping Cart Service messages.
    The method parses the json response. It also retrives
    the current persistance key if there is one. In the case
    where there is not one the server will assign one on the
    first call.
    ********************************************************/
    var HandlePageobserverMessage = function(message) {
        var jsonMessage = JSON.parse(message);
        var request = '{"planID" : "' + jsonMessage.planID + '"}';

        if (jsonMessage.Callee != undefined) {
            callingDivSelector = jsonMessage.Callee;
        }

        if (jsonMessage.planID != undefined) {
            workingPlanId = jsonMessage.planID;
        }
        switch (jsonMessage.messagetype) {
            case "SaveToCart":
                if (callingDivSelector !== null) {
                    AjaxWorkingStart($(callingDivSelector), 'Saving to Cart...');
                }
                CallWCFModel('POST', ShoppingCartWidgetService + AddPlanToCartWebMethod, request, AddPlanToCartAjaxCallback);
                break;
            case "EnrollNow":
                if (callingDivSelector !== null) {
                    AjaxWorkingStart($(callingDivSelector), 'Beginning Enrollment...');
                }
                EnrollApplicationNow();
                break;
            case "CartWidgetDisplayContext":
                HandleCartWidgetDisplayContext(message);
                break;
            case "QuoteUpdate":
                UpdateFromServer();
                break;
            case "CartContentsModified":
                UpdateFromServer(true);
                break;
            case 'EnrollmentComplete':
                $("span[id$='_enrollWidgetTitle']").text("Enrollment Complete");
                $("#UserCartWidgetFooter").hide();
                break;
            case 'UpdateShoppingCartPrice':
                UpdatePriceForPlan(JSON.parse(message));
                break;
            default:
                if (bDebug) {
                    trace('Message type received (' + m.messagetype + ') but there is no event handler for this message type!.');
                }
                break;
        }
    };

    function DisplayCartWidgetModal(Title, text, YesText, YesCallback, CancelText, CancelCallback) {
        ///<summary>Returns a string of Hello plus passed names</summary>
        ///<param name="Title" type="string">Title of message</param>
        ///<param name="text" type="string">Main body of message</param>
        ///<param name="YesText" type="string">Text for Yes button</param>
        ///<param name="YesFunction" type="string">Callback for yes button</param>
        ///<param name="YesFunctionParameter1" type="string">Argument for yes button</param>
        ///<param name="CancelText" type="string">Text for cancel button</param>

        var bttns = {};
        bttns[YesText] = function() {
            if (YesCallback) {
                YesCallback();
            }
            $(this).dialog("close");
        };

        if (CancelText) {
            bttns[CancelText] = function() {
                if (CancelCallback) {
                    CancelCallback();
                }
                $(this).dialog("close");
            };
        }

        $('#cartWidgetDialog').html(text).dialog({
            modal: true,
            draggable: false,
            dialogClass: 'olsmodal',
            title: Title,
            buttons: bttns,
            beforeclose: function() {
                AjaxWorkingDone($(callingDivSelector));
            }
        });
    }

    function DisplayRidersModal(planId) {

        var request = '{"planID" : "' + planId + '"}';

        incompatiblePlanDetectedInRidersModal = false;
        enrollAjaxReturned = false;
        CallWCFModel('POST', ShoppingCartWidgetService + EnrollPlanWebMethod, request, HandleIncompatiblePlansForModalAjaxCallback);
    }

    function RaidersModal(planId) {
        var title = 'This plan contains additional options.';
        var message = '<div>This plan contains additional options. Select those options you are interested in or continue without selections.</div>';

        LoadASCXViaAjax(
        '~/controls/quote/UserCartPlanControl.ascx',
        '%26ridersplanid=' + planId + "%26enroll=1",
        false,
        function(response) {
            // Ajax Success callback
            if (!incompatiblePlanDetectedInRidersModal) {
                var control = response;

                var bttns = {
                    'Continue to Enroll': function() {
                        var destURL = appCaptureURL + '&ProductCode=' + planId;
                        NavigateWithReferrer(destURL);
                    },
                    'Cancel': function() {

                        // if the plan documents content (random field on legal & benfit summary modal) is visible then we know we're on app capture track, otherwise we're in shop & quote
                        if ($('#plan-documents-content').length > 0) {

                            // if the modal is opened within appcapture then return to the cart page
                            NavigateWithReferrer(shoppingCartURL);

                        }
                        else {
                            // close the dialog
                            $(this).dialog("close");
                        }
                    }
                };

                var dlg = $('#cartWidgetDialog');

                dlg.html(message + control).dialog({
                    modal: true,
                    width: 753,
                    draggable: false,
                    dialogClass: 'olsmodal',
                    resizable: true,
                    title: title,
                    buttons: bttns,
                    close: function(event, ui) {
                        if (callingDivSelector !== null) {
                            var request = '{"planId": ' + planId + '}';
                            CallWCFModel('POST', ShoppingCartWidgetService + RemovePlanFromCartWebMethod, request);
                            AjaxWorkingDone($(callingDivSelector));
                            callingDivSelector = null;
                            $(this).dialog("close");
                        }
                    }
                });

                dlg.find("input[id$='_PlanNameCheckBox']").attr('checked', true);
                pageobserver.fire('{ "messagetype" : "BindCartControls" }');
                dlg.find("button[id$='RemoveFromCartLink']").hide();
                dlg.find("a[id$='_ViewPlanDetailsLink']").hide();
                dlg.find("a[id$='EditEffectiveButton']").hide();
                dlg.find("input[id$='PlanNameCheckBox']").attr('disabled', true);

                $.InitHelpControls('.helpbutton');

                if (!enrollAjaxReturned) {
                    AjaxWorkingStart(dlg.find('#ctl00_planContainer'), "Loading Options...");
                }
            }
        });
    }

    /*************************************************************
    Updates the price on the plan when a discount has been applied
    **************************************************************/
    function UpdatePriceForPlan(message) {
        var price = message.price;
        var planID = message.planid;
        var currentPlanDollarAmount = 0;
        var currentPlanCentAmount = 0;
        var currentTotalDollarAmount = 0;
        var currentTotalCentAmount = 0;
        var newTotal = 0;

        // call all the relevant selectors
        var planDiv = $('#widgetPlanId' + planID);
        var priceSections = planDiv.find('.planPrice span');
        var totalsDiv = $('#UserCartWidgetTotals span');

        // get the current plan price values
        currentPlanDollarAmount = $(priceSections[1]).text();
        currentPlanCentAmount = $(priceSections[2]).text();

        // get the total price values
        currentTotalDollarAmount = $(totalsDiv[1]).text();
        currentTotalCentAmount = $(totalsDiv[2]).text();

        // convert the two price values to a decimal number respectively
        var totalFloatValue = parseFloat(currentTotalDollarAmount + currentTotalCentAmount);
        var planFloatValue = parseFloat(currentPlanDollarAmount + currentPlanCentAmount);

        // calculate the new total
        newTotal = (totalFloatValue - planFloatValue).toFixed(2);
        newTotal = (parseFloat(newTotal) + parseFloat(price)).toFixed(2);

        var newTotalString = newTotal + '';

        if (newTotalString.indexOf('.') == -1) {
            newTotalString = newTotalString + '.00';
        }

        var totalCentFigure = newTotalString.substring(newTotalString.indexOf('.') + 1);

        if (totalCentFigure.length == 1) {
            newTotalString = newTotalString + '0';
        }

        // split the new prices
        var priceArray = price.split('.');
        var totalArray = newTotalString.split('.');

        // correct any NaN numbers
        if (isNaN(totalArray[0])) {
            totalArray[0] = '0';
        }

        if (isNaN(totalArray[1])) {
            totalArray[1] = '00';
        }

        if (isNaN(priceArray[0])) {
            priceArray[0] = '0';
        }

        if (isNaN(priceArray[1])) {
            priceArray[1] = '00';
        }

        // update this plans price
        $(priceSections[1]).text(priceArray[0]);
        $(priceSections[2]).text('.' + priceArray[1]);

        // update the total price
        $(totalsDiv[1]).text(totalArray[0]);
        $(totalsDiv[2]).text('.' + totalArray[1]);
    }

    function CheckForRiders(planId) {
        var riderIdList = $('input[id$=plansWithRiders]').val();
        return riderIdList.match(planId + ',');
    }

    function GetQueryString(key, default_) {
        if (default_ === null) default_ = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs === null)
            return default_;
        else
            return qs[1];
    }

    function EnrollApplicationNow() {
        if (IsUserLoggedOn()) {
            if ((!InShoppingCart()) && (CheckForRiders(workingPlanId))) {
                DisplayRidersModal(workingPlanId);
            }
            else {
                var request = '{"planID": "' + workingPlanId + '" }';
                CallWCFModel('POST', ShoppingCartWidgetService + EnrollPlanWebMethod, request, HandleEnrollPlanResponse);
            }
        } else {
            var postLogOnAction;
            if (CheckForRiders(workingPlanId)) {
                var redirectURL;
                if (window.location.href.indexOf('productcode') <= 0) {
                    redirectURL = window.location + '&enrollPlanId=' + workingPlanId + '&ProductCode=' + workingPlanId;
                }
                else {
                    redirectURL = window.location + '&enrollPlanId=' + workingPlanId;
                }
                postLogOnAction = '{ "request" : { "RedirectUrl" : "' + redirectURL + '", "ActionType" : "EnrollNow" } }';
            }
            else {
                postLogOnAction = '{ "request" : { "RedirectUrl" : "' + appCaptureURL + '&enrollPlanId=' + workingPlanId + '&ProductCode=' + workingPlanId + '", "ActionType" : "EnrollNow" } }';
            }
            ShowLogonPage(postLogOnAction);
        }
    }

    function InShoppingCart() {
        return DisplayMode == DisplayModes.SHOPPING;
    }

    function CartContainsPlans() {
        return numberOfItemsInCart > 0;
    }

    function RemovePlanClick(e) {
        var id = e.target.value;
        var request = '{"planId": ' + id + '}';
        CallWCFModel('POST', ShoppingCartWidgetService + RemovePlanFromCartWebMethod, request, RemovePlanFromCartAjaxCallback);
        return false;
    }

    function RemovePlanFromCartAjaxCallback(response) {
        $("span[id$='numberOfItemsInCart']").text(response.Entity);
        RefreshPage();
    }

    function AddPlanToCartAjaxCallback(response) {
        $("span[id$='numberOfItemsInCart']").text(response.Entity);
        if (IsUserLoggedOn()) {
            NavigateWithReferrer(shoppingCartURL);
        }
        else {
            GetProfileIdentityContext(function(result) {
                context = JSON.parse(result);
                // Double check if the user is logged in.
                if (context.Credentials.IsLoggedOn) {
                    // Redirect to shopping cart if logged in.
                    NavigateWithReferrer(shoppingCartURL);
                }
                else if (context.PostLogonAction !== null &&
        (context.PostLogonAction.ActionType == PostLogonActionType.ContinueAsGuest || context.PostLogonAction.ActionType == PostLogonActionType.EnrollNow || IsContinueAsGuestSet())) {
                    // Redirect to shopping cart if they have clicked "Continue as guest"
                    NavigateWithReferrer(shoppingCartURL);
                }
                else {
                    // The user is not logged on so redirect him to the log on page.
                    // The current Url is stored so that the log on page can return to it.
                    var postLogOnAction = '{ "request" : { "RedirectUrl" : "' + shoppingCartURL + '", "ActionType" : ' + '"SaveToCart"' + ' } }';
                    ShowLogonPage(postLogOnAction);
                }
            });
        }
    }

    function HandleEnrollPlanResponse(response) {
        switch (response.Status) {
            case ShoppingCartResultStatus.INFORMATIONAL:
                if (CartContainsPlans()) {
                    DisplayCartWidgetModal('There are no plans selected',
          response.Message,
          'Continue',
          function() {
              if (!InShoppingCart()) {
                  NavigateWithReferrer(shoppingCartURL);
              }
          });
                }
                else {
                    DisplayCartWidgetModal('There are no plans in the cart',
          'Please choose a plan to enroll in.',
          'Continue');
                }
                if (callingDivSelector !== null) {
                    AjaxWorkingDone($(callingDivSelector));
                    callingDivSelector = null;
                }
                break;

            case ShoppingCartResultStatus.SUCCESS:
                NavigateWithReferrer(appCaptureURL + '&ProductCode=' + response.PlanID);
                break;

            case ShoppingCartResultStatus.FAILURE:
            case ShoppingCartResultStatus.DATEFAILURE:
                var modalHeader = response.Status === ShoppingCartResultStatus.DATEFAILURE ? "Invalid Effective Date" : "Incompatible Plans";
                if (InShoppingCart()) {
                    DisplayCartWidgetModal(modalHeader,
          response.Message,
          'Continue', function() { RefreshPage(true); });
                }
                else {
                    // Any other page
                    DisplayCartWidgetModal(modalHeader,
         response.Message,
         'Save to Cart',
         function() {
             pageobserver.fire(JSON.stringify({ messagetype: "SaveToCart", planID: workingPlanId }));
         },
         'Cancel');
                }
                if (callingDivSelector !== null) {
                    AjaxWorkingDone($(callingDivSelector));
                    callingDivSelector = null;
                }
                break;
            default:
                break;
        }
    }

    function HandleIncompatiblePlansForModalAjaxCallback(response) {
        enrollAjaxReturned = true;
        AjaxWorkingDone($('#ctl00_planContainer'));

        switch (response.Status) {
            case ShoppingCartResultStatus.FAILURE:
            case ShoppingCartResultStatus.DATEFAILURE:
                var modalHeader = response.Status === ShoppingCartResultStatus.DATEFAILURE ? "Invalid Effective Date" : "Incompatible Plans";
                incompatiblePlanDetectedInRidersModal = true;
                DisplayCartWidgetModal(modalHeader,
         response.Message,
         'Save to Cart',
         function() {
             pageobserver.fire('{ "messagetype" : "SaveToCart", "planID" : ' + workingPlanId + ' }');
         },
         'Cancel');
                break;
            default:
                RaidersModal(workingPlanId);
                break;
        }
    }

    var DisplayMode = DisplayModes.GENERAL;

    /*****************************************************************
    Initializes the UserCartWidget.
    Subscribes for pageobserver events that the widget is interested in.
    Hooks up click events for widget buttons.
    ******************************************************************/
    function InitializeCartWidget() {
        ApplyStyles();

        $("a[id$='userCartWidgetButton']").live('click', function(e) {
            e.preventDefault();
            if (DisplayMode == DisplayModes.APPCAPTURE) {
                NavigateWithReferrer(shoppingCartURL);
            } else {
                pageobserver.fire('{ "messagetype" : "EnrollNow", "planID" : "any" , "Callee" : "#cartpage" }');
            }
        });

        //hook up the plan details modal dialog
        $('.plandetailsredirect').live('click', function(event) {

            var modalDivs = $('.olsmodal');

            var customDivs = $('#urlclicked.jqueryselectorclass');

            for (var i = 0; i < modalDivs.length; i++) {
                $(modalDivs[i]).remove();
            }

            for (var i = 0; i < customDivs.length; i++) {
                $(customDivs[i]).remove();
            }

            var url = this.href;
            $("<div id='urlclicked' class='jqueryselectorclass' url='" + url + "'></div>").
        load(url).
        dialog({
            width: 760,
            modal: true,
            resizable: true,
            draggable: false,
            position: 'top',
            dialogClass: 'olsmodal',
            title: "Plan Detail",
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                }
            },
            beforeclose: function() {
                pageobserver.fire('{ "messagetype" : "refreshbreadcrumb", "servicePoint" : "' + serviceEntryPoint + '", "breadCrumbIndex" : 1 }');
            }
        });

            event.preventDefault();
        });
    }

    /********************************************************
    asynchronously updates the contents of the UserCartWidget
    from the server using the LoadView.asmx service.
    *********************************************************/
    function UpdateFromServer(forceReload) {
        var args = '';
        if (forceReload) {
            args = '%26reloadCart=true';
        }
        var WidgetBusySelector = "div[id=UserCartWidgetBody]";
        AjaxWorkingStart($(WidgetBusySelector), "");
        $("#UserCartWidgetInnerContainer").stop(); //.animate({ "opacity": 0.5 }, 'slow', 'linear', function() {
        // load the user cart widget control via ajax
        LoadASCXViaAjax(
        '~/controls/quote/UserCartWidget.ascx',
        args,
        false,
        // success method
        function(response) {
            var outerDiv = $("#UserCartWidgetContainer");
            outerDiv.css({ "height": outerDiv.height() });
            var div = $("#UserCartWidgetInnerContainer");

            var newDivHtml = response.split('<script ')[0] + response.split('</script>')[1];
            div.html(newDivHtml);
            if ($().registerGlossaryTerms) {
                div.registerGlossaryTerms();
            }
            AjaxWorkingDone($(WidgetBusySelector));
            ApplyStyles();
            outerDiv.animate({ "height": div.height() + 'px' }, 200);
            div.stop(); //.animate({ "opacity": 1 }, 1000);
            $.InitHelpControls('.helpbutton');
        },
        // complete method
        function() {
            AjaxWorkingDone($(WidgetBusySelector));
        }
      );
        // });
    }

    /********************************************
    Handles cart widget display context messages.
    This allows us to determin wether we are in a
    shopping cart view or elsewhere on the site.
    *********************************************/
    function HandleCartWidgetDisplayContext(message) {
        var msg = JSON.parse(message);
        DisplayMode = msg.Mode;
        if (msg.planId !== undefined) {
            workingPlanId = msg.planId;
        }
        ApplyStyles();
    }

    /*******************************************************
    Sets the visibility of various divs based on the display
    mode that is currently active - see SetDisplayMode()
    ********************************************************/
    function ApplyStyles() {
        var $widget = $('div#UserCartWidget');
        if (DisplayMode == DisplayModes.APPCAPTURE) {
            $widget.find('div[id=widgetPlanId' + workingPlanId + ']').addClass('UserCartEnrolling');
            $widget.find('span[id=widgetEnrollPlanMessage' + workingPlanId + ']').removeAttr('style');
            $widget.find('a[id=userCartWidgetButton] span').text('Change Plans');
        }
        if (DisplayMode == DisplayModes.SHOPPING ||
      (!IsUserLoggedOn() && numberOfItemsInCart == 0)) {
            $widget.unbind();
        } else {
            $widget.click(function() { NavigateWithReferrer(shoppingCartURL); });
            $widget.hover(function() { $(this).css('cursor', 'pointer'); });
        }
        if (numberOfItemsInCart == '0' || DisplayMode == DisplayModes.GENERAL) {
            // Ensure the summary panel is not displayed
            $widget.find('div[id$=summaryPanel]').css('display', 'none');
            // Unhide the message for the small cart
            if (numberOfItemsInCart != '0') {
                $widget.find('#UserCartWidgetBody').removeAttr('style').addClass('UserCartNoBG').css('clear', 'none');
                $widget.find('span[id$=cartWidgetTitle]').css('display', 'none');
                $widget.find('#UserCartWidgetEnrollMessage').removeAttr('style');
                $widget.find('#smallCartWidgetMessage').removeAttr('style').css('float', 'left');
            }
        }
        else {
            // Need to show this on normal loads because two the method gets called twice - once General and once not
            $widget.find('div[id$=summaryPanel]').css('display', 'block');
            // Hide the default view
            $widget.find('span[id$=cartWidgetTitle]').css('display', 'none');
            $widget.find('#smallCartWidgetMessage').css('display', 'none');

            // Unhide the shopping cart related divs
            $widget.find('span[id$=enrollWidgetTitle]').removeAttr('style');
            $widget.find('#UserCartWidgetBody').removeAttr('style').removeClass('UserCartNoBG');
            $widget.find('#UserCartWidgetEnrollMessage').removeAttr('style');
            $widget.find('#UserCartWidgetCoverageContainter').removeAttr('style');
            $widget.find('#UserCartWidgetFooter').removeAttr('style');
            $widget.find('#largeCartWidgetMessage').removeAttr('style');
        }
    }

    function ShowLogonPage(postLogOnAction) {
        CallWCFModel('POST', serviceEntryPoint + '/PersistPostLogOnAction', postLogOnAction, function(response) {
            NavigateWithReferrer($("#uiLogonUrlHdn").val());
        });
    }
})(jQuery);

