﻿
"use strict";
var BELL = (function (bell, $) {

    bell.shop = bell.shop || {};

    bell.shop.addaline = {
        init: function () {
            var self = this;
            var SBratePlan = null;
            var SBhandset = null;
            var SBTabID = null;

            this.today = new Date($.now());
            this.expires = new Date($.now() + (90 * 86400000));
            this.modalTriggerButton = $("#add-a-line-mybell-login-trigger");
            this.addDevice = false;
            var $errors = $('#js-login-errors');
            var $alertMessage = $('#js-login-alert-msg');
            this.selectAccountModal = $('#add-a-line-select-account-modal');
            this.warningModal = $('#add-a-line-warning-modal');
            var mobilityAccounts = new Array();
            var selectedMobilityAccount = new Array();
            this.minDataPlaninMB = parseInt($("#minDataPlaninMB").val());
            
            $(".page-code_prsshpwls-family-sharing .rsx-offer-details-add-a-line").hide();

           if ($('body').hasClass("page-code_prsshpwls-family-sharing")) {
                $(document).on('click', ("#ratePlansDeviceTypes .js-shop-rp-devicetype"), function () {
                    (typeof s_oTrackPage === "function") && s_oTrackPage({
                        s_oAPT: "647-0-0",
                        s_oBTN: "step 1:" + $(this).find(".js-shop-rp-devicetype-title").attr("omnituretitle").trim()
                    });
                  });

                $(document).on('click', ("#ratePlans .js-shop-rp-plan"), function () {
                    var elementAttr = $(this).find(".add-a-line-js-omni-button").attr("omnituretitle");
                    var omnituretitleValue = "";
                    if (typeof (elementAttr) != "undefined" && elementAttr != false) {
                        omnituretitleValue = elementAttr.trim();
                    } else {
                        omnituretitleValue = $(this).find(".rsx-plan-name").clone().children().remove().end().text().trim();
                    }

                    (typeof s_oTrackPage === "function") && s_oTrackPage({
                        s_oAPT: "647-0-0",
                        s_oBTN: "step 2:" + omnituretitleValue
                    });
                });
            }

            if ($(".minDataRequired").length > 0) {
                $(".minDataRequired").each(function (index) {
                    var minData = parseInt($(this).val());
                    var label = $(this).closest("label");
                    if (self.minDataPlaninMB < minData) {
                        $(label).find("input").attr("disabled", true);
                        $(label).addClass("insufficient-data-addline");
                    }
                })
            }

            $("label.insufficient-data-addline").on("click", function () {
                var minData = parseInt($(this).find(".minDataRequired").val());
                //$("#add-a-line-min-data-modal").find("#data-in-mb").text(self.minDataPlaninMB / 1024);
                $("#add-a-line-min-data-modal").find("#insufficient-data #plan-name-option").text($(this).find(".planName").val());
                var minDataMessage = (minData / 1024 < 1 ? minData + $("#UnitOfMeasureMB").val() : minData / 1024 + $("#UnitOfMeasureGB").val());
                $("#add-a-line-min-data-modal").find("#insufficient-data #min-data-amount").text(minDataMessage);
                setTimeout(function () {
                    $("#add-a-line-min-data-modal").modal("open");
                    (typeof s_oTrackPage === "function") && s_oTrackPage({
                        s_oAPT: "104-2-2",
                        s_oPRM: "open minimum data warning modal",
                        s_oLBC: $(".min-data-warning-omniture").text().trim().slice(0, 99),
                        s_oPLE: $(".min-data-warning-omniture").text().trim().slice(0, 49)+ ":W"
                    })
                }, 500);
            });

            BELL.rsx.login.toggleLogin({
                $login: $("#loginForm_ec,#loginForm_ec_Footer"),
                $fullname: $(".js-connector-customer-name"),
                url: $("#loginForm_ec").closest(".rsx-connector-login-modal").data("user-src"),
                cookie: bell.shop.rateplans.getCookieValue("UserSession"),
                field: "MyBellUserFullName"
            });

            BELL.rsx.login.toggleLogin({
                $login: $("#loginForm_ec__MyAccount,#loginForm_ec__MyAccount_Footer"),
                $fullname: $(".js-connector-aliant-customer-name"),
                url: $("#loginForm_ec__MyAccount").closest(".rsx-connector-login-modal").data("myaccount-user-src"),
                cookie: bell.shop.rateplans.getCookieValue("MyAccountUserFullName"),
                field: "MyAccountUserFullName"
            });

            BELL.rsx.login.loginButtonText();

            $(this.modalTriggerButton).click(function () {
                bell.shop.rateplans.resetError();
            });
            if ($("#AddALine_isSelected").val() === "True") {
                    $("#selectingDeviceType").addClass("hidden");
                    $("#add-a-line-tabs-container").addClass("hidden");
                }

                $('#select-a-different-account-link').click(function () {
                    bell.shop.addaline.openSelectAccountModal();
                });

                $('#add-a-line-button').click(function () {
                    bell.shop.addaline.addALine();
                });
                
                $("#add-a-line-selecte-account-trigger").click(function () {
                    if (typeof ($("#add-a-line-select-account-modal").html()) == "undefined") {
                        self.openWarningModal();
                    }
                    else {
                        self.openSelectAccountModal();
                    }
                    
                });
                if ($("#AddALine_backFromSB").val() == "true") {
                    $("body").loadingIndicator();
                    $("body").loadingIndicator("show");
                $(window).load(function () {
                        $.ajax({
                            url: "/ajax/Mobility/getselectedvalues",
                            async: true,
                            dataType: "json",
                            success: function (data) {
                                self.SBratePlan = data.SelectedRatePlanID;
                                self.SBhandset = data.selectedHandsetID;
                                self.SBTabID = data.SelectedTabID;                                
                                bell.shop.addaline.addALine();
                            },
                            error: function (data) {
                                console.error("Error loading view: ", data);
                                $("body").loadingIndicator("hide");
                            }
                        });
                 });
             }
                if ($("#AddALine_backFromSBCD").val() == "true") {
                    $("body").loadingIndicator();
                    $("body").loadingIndicator("show");
                    $(window).load(function () {
                        bell.shop.addaline.addALine();
                        $("body").loadingIndicator("hide");
                    });
                    
                }

                $('#test-link').click(function () {
                    bell.shop.addaline.getMobilityAccounts();
                });
        },

        addALine: function () {
			if (typeof s_oTrackPage === "function") { 
				s_oTrackPage({
					s_oAPT: "647-0-0",
					s_oBTN: "add a line"
				});
			}
            
            $("#selectingDeviceType").removeClass("hidden");
            $("#add-a-line-tabs-container").removeClass("hidden");
            $(bell.shop.rateplans.summary.container).removeClass("hidden");
            

            if (bell.shop.addaline.SBTabID != null) {
                $("#ratePlansDeviceTypes").radios("setProperties", "label[data-rate-plan-details-modal-index='" + bell.shop.addaline.SBTabID + "'] input", "checked", true);
                bell.shop.addaline.SBTabID = null;
            }
            bell.shop.rateplans.navigateToSelector("#add-a-line-tabs-container");
            $(".page-code_prsshpwls-family-sharing .rsx-offer-details-add-a-line").show();
        },
        cacheSelection: function (handset_id, handset_alias) {
            if (bell.shop.addaline.SBratePlan == null) {
                var data = $("#ratePlans label.rsx-active").data("planGuid");
                $.ajax({
                    url: "/ajax/Mobility/SelectRatePlan",
                    data: { rateplanid: data },
                    async: true,
                    type: 'post',
                    dataType: "json"
                });
            }            

            if (bell.shop.addaline.SBhandset == null) {
                $.ajax({
                    url: "/ajax/Mobility/SelectDevice",
                    data: {
                        deviceID: handset_id,
                        productAlias: handset_alias
                    },
                    async: true,
                    type: 'post',
                    dataType: "json"
                });
            }
           
        },
        completeDataSelection: function (obj) {
            var deviceName = $(obj).find(".rsx-product-name").text();
            $("#selectingDataStep").find(".rsx-dock-rp-option-name").text(deviceName);
            if ($(obj).hasClass("rsx-product-list-lightbox-tablet")) {
                var contractSelected = $("label.js-shop-rp-plan.rsx-active");
                if (!contractSelected.data("contractNoTerm")) {
                
                var planPrice = $(contractSelected).find(".rsx-price").data("listedPrice");
                var devicePrice = $(obj).find(".rsx-pricing-model.rsx-active").find(".rsx-price-group-installment-monthly").data("priceValue");
                var monthlyPrice = (planPrice + devicePrice).toFixed(2);
                var html = bell.shop.rateplans.formatPrice(monthlyPrice);

                $(bell.shop.rateplans.summary.container).find("#addaline-monthly-price-total").html(html);
                }

            }
            if (!this.addDevice) {
                bell.shop.rateplans.summary.completedData();
                this.addDevice = true;
            }
            if (bell.shop.addaline.SBhandset != null) {
                bell.shop.addaline.SBhandset = null;
            }
        },

        openSelectAccountModal: function () {
            $(this.selectAccountModal).modal('open');
        },

        openWarningModal: function () {
            $('#add-a-line-warning-modal .warning-modal-heading').show();
            $('#add-a-line-warning-modal .warning-modal-body-container').show();
            $(this.warningModal).modal('open');
        },

        getMobilityAccounts: function () {
            $.ajax({
                url: "/ajax/Mobility/GetAddaLineEligibleAccounts",
                data: { addLineFlow: 1 },
                async: true,
                type: 'post',
                dataType: "json",
                success: function (data) {
                    console.log("getMobilityAccounts success");
                    if (data.length > 0) {
                        console.log(data);
                    }
                },
                error: function (data) {
                    console.log(data);
                    //bell.shop.addaline.openWarningModal(data);
                    defer.reject();
                },
                complete: function () {
                }
            });
        },

        Cookie: function (document, name, hours, path, domain, secure) {
            // All the predefined properties of this object begin with 'jQuery'
            // to distinguish them from other properties which are the values to
            // be stored in the cookie.
            this.jQuerydocument = document;
            this.jQueryname = name;
            if (hours)
                this.jQueryexpiration = new Date((new Date()).getTime() + hours * 3600000);
            else this.jQueryexpiration = null;
            if (path) this.jQuerypath = path; else this.jQuerypath = null;
            if (domain) this.jQuerydomain = domain; else this.jQuerydomain = null;
            if (secure) this.jQuerysecure = true; else this.jQuerysecure = false;
        },

        //
        // This function is the store() method of the Cookie object.
        //
        _Cookie_store: function () {
            // First, loop through the properties of the Cookie object and
            // put together the value of the cookie. Since cookies use the
            // equals sign and semicolons as separators, we'll use colons
            // and ampersands for the individual state variables we store
            // within a single cookie value. Note that we escape the value
            // of each state variable, in case it contains punctuation or other
            // illegal characters.
            var cookieval = "";

            if (this.jQueryisSingleValue) {
                cookieval = this.jQueryvalue;
            }
            else {
                for (var prop in this) {
                    // Ignore properties with names that begin with 'jQuery' and also methods.
                    if ((prop.charAt(0) === 'jQuery') || ((typeof this[prop]) == 'function'))
                        continue;
                    if (cookieval !== "") cookieval += '&';
                    cookieval += prop + ':' + escape(this[prop]);
                }
            }

            // Now that we have the value of the cookie, put together the
            // complete cookie string, which includes the name and the various
            // attributes specified when the Cookie object was created.
            var cookie = this.jQueryname + '=' + cookieval;
            if (this.jQueryexpiration)
                cookie += '; expires=' + this.jQueryexpiration.toGMTString();

            if (this.jQuerypath) cookie += '; path=' + this.jQuerypath;

            if (this.jQuerydomain) cookie += '; domain=' + this.jQuerydomain;

            //    alert('domain: ' + this.jQuerydomain);
            if (this.jQuerysecure) cookie += '; secure';

            //    alert('cookie to be written: ' + cookie);
            // Now store the cookie by setting the magic Document.cookie property.
            this.jQuerydocument.cookie = cookie;
        },
        _Cookie_load: function () {
            // First, get a list of all cookies that pertain to this document.
            // We do this by reading the magic Document.cookie property.
            var allcookies = this.jQuerydocument.cookie;
            if (allcookies === "") return false;

            // Now extract just the named cookie from that list.
            var start = allcookies.indexOf(this.jQueryname + '=');
            if (start === -1) return false;   // Cookie not defined for this page.
            start += this.jQueryname.length + 1;  // Skip name and equals sign.
            var end = allcookies.indexOf(';', start);
            if (end === -1) end = allcookies.length;
            var cookieval = allcookies.substring(start, end);

            this.jQueryvalue = cookieval;   // Set the complete string to a variable that can be used later.


            // Now that we've extracted the value of the named cookie, we've
            // got to break that value down into individual state variable
            // names and values. The name/value pairs are separated from each
            // other by ampersands, and the individual names and values are
            // separated from each other by colons. We use the split method
            // to parse everything.
            var a = cookieval.split('&');    // Break it into array of name/value pairs.
            for (var i = 0; i < a.length; i++)  // Break each pair into an array.
                a[i] = a[i].split(':');

            // Now that we've parsed the cookie value, set all the names and values
            // of the state variables in this Cookie object. Note that we unescape()
            // the property value, because we called escape() when we stored it.
            for (var j = 0; j < a.length; j++) {
                this[a[j][0]] = unescape(a[j][1]);
            }

            // We're done, so return the success code.
            return true;
        },
        _Cookie_remove: function () {
            var cookie;
            cookie = this.jQueryname + '=';
            if (this.jQuerypath) cookie += '; path=' + this.jQuerypath;
            if (this.jQuerydomain) cookie += '; domain=' + this.jQuerydomain;
            cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

            this.jQuerydocument.cookie = cookie;
        },
        loginButtonText: function () {
            var button = $("#rsx-login-register-button");

            var bellCookie = this.getCookieValue("UserSession");
            var isAuthenticated = bellCookie != null && bellCookie.length > 0;

            var myAccountCookie = this.getCookieValue("MyAccountUserFullName");
            var isMyAccountAuthenticated = myAccountCookie != null && myAccountCookie.length > 0;

            if (isAuthenticated && isMyAccountAuthenticated) {
                button.text(button.data("text-logout"));
            } else if (!isAuthenticated && !isMyAccountAuthenticated) {
                button.text(button.data("text-login"));
            } else {
                button.text(button.data("text-login-logout"));
            }
        }
          };

    return bell;

})(BELL || {}, jQRSX);


