//Version 1.0.1

//global variables
var anchorObj = null;

//Disable empty footer link
function DisableEmptyDiv() {
    $(".superFooter,.secNav").each(function () {
        if ($.trim($(this).text()).length <= 0 && $('img', this).length <= 0 && $('a', this).length <= 0) {
            $(this).attr("style", "display:none");
        }
    });
}

// Load Mini Dashboard
function InitMiniDashboard(sLoingQueryURL) {
    var seureURL = "https://secureq.bell.ca/mybell/loginquery.jsp";
    var cookie = $.cookies.get("bellcaregion");
    if (cookie != 'undefined' && cookie != null) {
        seureURL = "https://" + cookie + "/mybell/loginquery.jsp";
    }
    else {
        if (gomez != 'undefined' && gomez != null) {
            var sName = gomez.grpId;
            if (sName != null && sName.indexOf('TOROON') > -1) {
                seureURL = "https://secureo.bell.ca/mybell/loginquery.jsp";
            }
        }
    }

    $.ajax({
        type: "GET",
        url: seureURL,
        dataType: 'script',
        timeout:5000
    });
}
 
//e.g. setLanguageRegionCookieValue("EN", "ON")
//incase of supplying only one value i.e. province then other should be null
//e.g. setLanguageRegionCookieValue(null, "ON") //it will check cookie value first
function setLanguageRegionCookieValue(lang, region) {

    var geminiCookieName = "gemini";

    var cookieVal = $.cookies.get(geminiCookieName);

    var geminiCookieVal = getGeminiString(lang, region, cookieVal); ;

    //if we set domain ".bell.ca" in DIT/SIT or even localhost. it will not save cookie
    //we should add domain only on production 
    //set_cookie(geminiCookieName, geminiCookieVal, 90, ".bell.ca");
    var hostname = window.location.hostname;
    var domain = "";
    if (window.location.hostname != null && hostname.indexOf("bell.ca") > 0) {
        domain = ".bell.ca";
    }

    set_cookie(geminiCookieName, geminiCookieVal, 90, domain);

}

function IsGeminiCookieAvailable() {

    var geminiCookieName = "gemini";
    var cookV = $.cookies.get(geminiCookieName);

    return cookV;
}

function getGeminiString(lang, region, cval) {
    var retVal = "region=" + region + "|language=" + lang + "|province=" + region;

    if (cval != null) {
        var strSpl = cval.split('|');

        if (region == null || region.length == 0)
            strSpl[1] = "language=" + lang;

        if (lang == null || lang.length == 0)
            strSpl[2] = "province=" + region;

        retVal = strSpl[0] + "|" + strSpl[1] + "|" + strSpl[2];
    }

    return retVal;
}

function InitTopSearchBox(strSearchboxToolTip, strSearchURL) {
    $("#topNavSearch").keypress(function (event) {
        if (event.keyCode == '13') {
            ClickOnTopSearchGo(strSearchboxToolTip, strSearchURL);
            return false;
        }
    });

    $("#btnTopSearchGo").click(function () {
        ClickOnTopSearchGo(strSearchboxToolTip, strSearchURL);
        return false;
    });
}


function ClickOnTopSearchGo(searchTip, topSerachPage) {
    var topSearchPage = topSerachPage;
    var qBox = $("#topNavSearch").val();

    qBox = qBox.replace("/[%<>()*;:/|]/g", "\\");
    if (qBox.length == 0)
        qBox = searchTip;

    topSearchPage = topSearchPage.replace("#qbox#", qBox);
    window.location = topSearchPage;
}

function set_cookie(name, value, days, domain) {
    var expires = "", date;
    date = new Date();
    if (!days || isNaN(days)) {
        days = 365;
    }
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();

    var setCookieVal = name + "=" + value + expires + "; path=/";

    if (domain)
        setCookieVal += "; domain=" + domain;

    document.cookie = setCookieVal;
}


// Load Shopping Cart items
function InitCartItems() {
    //TODO
}

//Active Top Nav code
function SetActiveTopNavNode(activeLOB) {
    $('ul#primNav li').removeClass('active');
    var activeLob = activeLOB;
    if (activeLob != null && activeLob != '') {
        $('ul#primNav li.' + activeLob).addClass('active');
    }
}

///set active option for region dropdown
function SetRegionOption(region) {
    $('ul#provMenu li').removeClass('active');
    $("ul#provMenu li#" + region).addClass('active');
}

///toggle region in header control, and refresh page.
function toggleRegion(region) {
    setLanguageRegionCookieValue(null, region);
    //refresh page
    location.reload();
}

//Tab control
function SetActiveTab() {
    $('#tabNavigation > li > a.uiTabLink').each(function (i) {
        this.href = "#";
    });
    $("#tabNavigation").tabs();
}

function onSelectProvince(o, lang, referrer) {
    var region = o.value;
    setLanguageRegionCookieValue(null, region);
    location.href = referrer;
}


//*************************************************************************************************************
//                                             Send Email
//*************************************************************************************************************
function sendEmail() {
    var title = $("#email a").attr("title");
    if ($("#sendEmailLightBox").length == 0) {
        createEmailFrame(title);
    }
    var url = $("#email a").attr("href");
    var queryStr = $("#email a").attr("rev");
    if (queryStr != null && queryStr != "undefined" && queryStr != "") {
        url = url + queryStr;
    } else {
        url = url + "?pageUrl=" + String(window.location);
    }
    $("#emailiFrame").attr("src", url);
    window.myParentSendFriend = $.lightBox.showInPage('#sendEmailLightBox');
}

function createEmailFrame(title) {
    $eFrame = $("<div id=\"sendEmailLightBox\" class=\"hide\"><div class=\"lightBoxTitleJs\">" + title + "</div> <iframe id=\"emailiFrame\" src=\"\" frameborder=\"0\" width=\"680\" height=\"480\"></iframe></div>");
    $('body').append($eFrame);
}

//*************************************************************************************************************
//                                             Print And PDF
//*************************************************************************************************************
function saveAsPDF() {
    var documentType = "<!DOCTYPE HTML PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01\/\/EN\" \"http:\/\/www.w3.org\/TR\/html4\/strict.dtd\">";

    var $htmlObj = $("html");
    htmlContent = $htmlObj.html();
    htmlContent = removePricingDetails($htmlObj, htmlContent);
    htmlContent = documentType + "<html>" + htmlContent + "</html>";
    htmlContant = includeHeader(htmlContent);
    htmlContent = includePDFFooter(htmlContent);
    htmlContent = setPrintCss(htmlContent);
    htmlContent = removeSecNav(htmlContent);

    var currentTime = new Date().getTime();

    var fileName = $("title").html();

    if (fileName == '') {
        fileName = "Bell";
    }

    fileName = cleanTitle(fileName) + ".pdf";

    $.shop.convertToPDF.html(
						{ fields: {
						    htmlText: htmlContent,
						    pdfFileName: fileName
						}

						});
}

function removePricingDetails(contentObj, htmlContent) {
    var replace1 = "";
    var replace2 = "";
    if (contentObj.find("#pricing_link_holder") && contentObj.find("#pricing_link_holder").length > 0) {
        replace1 = contentObj.find("#pricing_link_holder").html();
    }
    if (contentObj.find("#detailTable") && contentObj.find("#detailTable").length > 0) {
        replace2 = contentObj.find("#detailTable").html();
    }
    htmlContent = textRemove(htmlContent, replace1);
    htmlContent = textRemove(htmlContent, replace2);

    return htmlContent;
}

function includeHeader(html) {
    var firstIndexOfOpenBody = html.indexOf('<body');

    if (firstIndexOfOpenBody == -1) {
        firstIndexOfOpenBody = html.indexOf('<BODY');
    }

    if (firstIndexOfOpenBody != -1) {
        var indexOfEndOfBodyTag = html.indexOf('>', firstIndexOfOpenBody);
        if (indexOfEndOfBodyTag != -1) {
            var beforeTag = html.substring(0, indexOfEndOfBodyTag + 1);
            var afterTag = html.substring(indexOfEndOfBodyTag + 1);

            var html2return =
				beforeTag +
				   "<div width='100%'class='toPrint'>" +
				   "<table width='100%'><tr><td align='right'><font size='2'>" + getFormatedTime() + "&nbsp;&nbsp;</font></td></tr></table></div>" +
				afterTag;
            return html2return;

        }
        return html;
    }
    return html;
}

function includePDFFooter(html) {
    var lastIndexOfCloseBody = html.lastIndexOf('</body>');

    if (lastIndexOfCloseBody == -1) {
        lastIndexOfCloseBody = html.lastIndexOf('</BODY>');
    }

    var html2print = "";
    if (lastIndexOfCloseBody != -1) {
        var beforeCloseBody = html.substring(0, lastIndexOfCloseBody);
        var afterCloseBody = html.substring(lastIndexOfCloseBody);

        var languageSelected = $("html").attr("lang");
        var copyRight = $('.footer').find('.unaccent').text();

        if ($.bell.isEmpty(copyRight)) {
            copyRight = "&#169; Bell Canada, 2011. All rights reserved";
        }

        //			var tableStyle = "width:100%; height:20px; cellpadding:0px;  border-width: 1px;padding: 0px; border-spacing: 0px;border-style: solid;border-color: black;border-collapse: collapse;";
        var tableStyle = "";
        var urlValue = location.href;
        var urlBreakPoint = 140;
        if (urlValue.length > urlBreakPoint) {
            urlValue = location.href.substring(0, urlBreakPoint) + "<br/>" + location.href.substring(urlBreakPoint);
        }

        html2print =
				beforeCloseBody +
				   "<style>body { padding: 32px 17px; }</style>" +
				   "<div width='100%'>" +
				   "<table width='100%' style='" + tableStyle + "'><tr>" +
				   "<td align='left'><font size='2'>" + copyRight + "</font></td>" +
				   "<td align='right'><font size='2'>" + getFormatedTime() + "</font></td></tr>" +
				   "<tr valign='top'><td align='left' colspan='2'><a href='" + location.href + "'><font size='2'>" + urlValue + "</font></a></td></tr></table></div>" +
				   afterCloseBody;
    }
    else {
        html2print = html;
    }

    return html2print;
}

function setPrintCss(html) {
    var firefoxOption = 'media="print"';
    var indexOfCssPrint = html.indexOf(firefoxOption);
    var replaceSize = firefoxOption.length;
    if (indexOfCssPrint == -1) {
        var ieOption = 'media=print';
        replaceSize = ieOption.length;
        indexOfCssPrint = html.indexOf(ieOption);
    }
    if (indexOfCssPrint != -1) {
        var before = html.substring(0, indexOfCssPrint);
        var after = html.substring(indexOfCssPrint + replaceSize);
        html = before + ' media="all" ' + after;

    }
    return html;
}

function removeSecNav(value) {
    var firstIndexOfSecNav = value.indexOf('secNav');
    if (firstIndexOfSecNav != -1) {
        var beforeTarget = value.substring(0, firstIndexOfSecNav);
        var afterTarget = value.substring(firstIndexOfSecNav);
        var returnValue = beforeTarget + 'error' + afterTarget;

        var firstIndexOfSecNavEndTag = returnValue.indexOf('>', firstIndexOfSecNav);
        beforeTarget = returnValue.substring(0, firstIndexOfSecNavEndTag);
        afterTarget = returnValue.substring(firstIndexOfSecNavEndTag);
        returnValue = beforeTarget + " style='display:none' " + afterTarget;

        return returnValue;
    }
    return value;
}

function textRemove(content, toRemove) {
    var index = content.indexOf(toRemove);
    if (index != -1) {
        var length = toRemove.length;
        var p1 = content.substring(0, index);
        var p2 = content.substring(index + length, content.length);
        content = p1 + p2;
    }
    return content;
}

function cleanTitle(sValue) {
    var ValidChars = "0123456789abcdefghijlmnopqrstuvxzwykABCDEFGHIJLMNOPQRSTUVXZKWY";
    var myChar = '';
    var returnValue = '';


    for (i = 0; i < sValue.length; i++) {
        myChar = sValue.charAt(i);
        if (ValidChars.indexOf(myChar) != -1) {
            returnValue = returnValue + myChar;
        }
    }
    return returnValue;
}

function get2DigitNumber(number2format) {
    if (number2format < 10) {
        return '0' + number2format;
    }
    return number2format
}

function getFormatedTime() {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth();
    curr_month++;
    var curr_year = d.getFullYear();
    var curr_hour = d.getHours();
    var curr_min = d.getMinutes();
    var curr_sec = d.getSeconds();
    var languageSelected = $("html").attr("lang");

    if (languageSelected == 'en') {
        return curr_month + "/" + get2DigitNumber(curr_date) + "/" + curr_year + " " + get2DigitNumber(curr_hour) + ":" + get2DigitNumber(curr_min) + ":" + get2DigitNumber(curr_sec);
    }
    else {
        return curr_date + "/" + get2DigitNumber(curr_month) + "/" + curr_year + " " + get2DigitNumber(curr_hour) + ":" + get2DigitNumber(curr_min) + ":" + get2DigitNumber(curr_sec);
    }
}

function printPdf() {
    if (frames["printIframe"]) {
        printOrGeneratePDF = "print";
        ajaxComponent('#print2pdfHtml').callAjaxAction('printToPdfAction');
    }
    else {
        window.print();
    }
}

function generatePdf() {
    if (frames["printIframe"]) {
        printOrGeneratePDF = "generate";

        var methodName = 'printToPdfAction'
        if (location.href.indexOf('Solution_Builder_Summary') != -1) {
            methodName = 'printToPdfSummaryAction';
        }

        ajaxComponent('#print2pdfHtml').callAjaxAction(methodName);
    }
    else {
        saveAsPDF();

    }
}

function printOrGenerate(html) {

    if (printOrGeneratePDF == "print") {

        frames["printIframe"].document.body.innerHTML = html;
        frames["printIframe"].focus();
        frames["printIframe"].print();
    }
    else
        if (printOrGeneratePDF == "generate") {
            var currentTime = new Date().getTime();
            //html = includeHeader(html);
            html = includePDFFooter(html);
            html = setPrintCss(html);

            $.shop.convertToPDF.html({
                fields: {
                    htmlText: html
                }
            });
        }
}




//**************************************************************************************
//  Legal Text
//
//legal text is displayed in DIV -  <div class="legalTextDiv"></div>
//**************************************************************************************
function rearrangeLegalTextWithTarget(lang, prov, cacheDivId) {
    var legals = {};
    var count = 0;
    $(".legaltext").each(function () {
        legalText = $(this).data("legal");
        if (legals[legalText] == undefined) {
            count += 1;
            legals[legalText] = count;
        }
    });
    $legalTextDiv = $(".legalTextDiv");
    if (count == 0) {
        $legalTextDiv.html('');
        return;
    }
    $(".legaltext").each(function () {
        $(this).text(legals[$(this).data("legal")]);
    });
    var totalKeys = "";
    for (var key in legals) {
        totalKeys += "|" + unescape(key);
    }
    var cacheDiv;
    var hasCache = false;
    var foundInCache = false;
    if (cacheDivId != undefined && $('#' + cacheDivId).length > 0) {
        hasCache = true;
        cacheDiv = $("#" + cacheDivId);
        if (cacheDiv.data('ids') == totalKeys) {
            foundInCache = true;
            $legalTextDiv.html(cacheDiv.html());
        }
    }

    if (foundInCache) {
        return;
    }

    var url = "/ajax/Home/LegalText?ids=" + totalKeys + "&ts=" + new Date().getTime();
    if (lang != undefined && lang != "")
        url = url + "&lang=" + lang;

    if (prov != undefined && prov != "")
        url = url + "&prov=" + prov;

    $.ajax({
        url: url,
        async: false,
        dataType: "html",
        success: function (data) {
            $legalTextDiv.html(data);
            if (hasCache) {
                cacheDiv.data('ids', totalKeys);
                cacheDiv.html(data);
            }
        },
        error: function () {
            var defErrorText = "Error";
            if ($.isFunction($.getText)) {
                $legalTextDiv.html($.getText("error"));
            } else {
                $legalTextDiv.html(defErrorText);
            }
        }
    })
}

function rearrangeLegalText(cacheDivId) {
    rearrangeLegalTextWithTarget("", "", cacheDivId);
}

(function ($) {
    if (typeof ($.shop) !== "object") { jQuery.shop = {}; }
    //*****************************************************
    //  function: $.convertToPDF()
    //
    //  usage:  1) $.convertToPDF.html(text, {params});  // params is optional
    //          2) $.convertToPDF.url(url, {params}); // url and params are optional
    //          3) $.convertToPDF.showError("My Title","Error Text"); 
    //
    //*****************************************************
    jQuery.shop.convertToPDF = {
        fieldHTML: "htmlText",
        fieldURL: "urlText",
        fieldPDFFileName: "pdfFileName",
        documentType: "<!DOCTYPE HTML PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01\/\/EN\" \"http:\/\/www.w3.org\/TR\/html4\/strict.dtd\">",

        html: function (HTMLStr, settings) {
            var i, textString, settingsObj;
            for (i = 0; i < arguments.length; i++) {
                if (typeof arguments[i] === "string") {
                    textString = arguments[i];
                } else if (typeof arguments[i] === "object") {
                    settingsObj = arguments[i];
                }
            }
            if (textString) {
                if (!settingsObj) { settingsObj = this.setParams({}); }
                settingsObj.fields[$.shop.convertToPDF.fieldHTML] = textString;
                settingsObj.fields = $.extend(false, this.setParams({}).fields, settingsObj.fields);
            }
            if (settingsObj) {
                settingsObj.fields = $.extend(false, this.setParams({}).fields, settingsObj.fields);
            } else { settingsObj = {}; }
            this.convert("html", this.setParams(settingsObj));
            return false;
        },
        url: function (urlStr, settings) {
            var i, urlString, settingsObj;
            for (i = 0; i < arguments.length; i++) {
                if (typeof arguments[i] === "string") {
                    urlString = arguments[i];
                } else if (typeof arguments[i] === "object") {
                    settingsObj = arguments[i];
                }
            }
            if (urlString) {
                if (!settingsObj) { settingsObj = this.setParams({}); }
                settingsObj.fields[$.shop.convertToPDF.fieldURL] = urlString;
                settingsObj.fields = $.extend(false, this.setParams({}).fields, settingsObj.fields);
            }
            if (settingsObj) {
                settingsObj.fields = $.extend(false, this.setParams({}).fields, settingsObj.fields);
            } else { settingsObj = {}; }
            this.convert("url", this.setParams(settingsObj));
            return false;
        },
        showError: function (title, message) {
            var $error = $("#convertErrorPDF");

            if ($error.length === 0) {
                $error = $("<div/>", {
                    id: "convertErrorPDF",
                    "class": "hide"
                });

                $error.append("<p class='lightBoxTitleJs'>" + title + "</p><div class='lbLining'><div class='lining'>" + message + "<\/div><\/div>").appendTo("body");
            }
            if (!$.isEmptyObject($.lightBox)) {
                $.lightBox.showInPage($error);
            }
        },
        setParams: function (settings) {
            var defaults = {
                form: {
                    id: "html2PDFForm",
                    action: "/_apps/PDF/GeneratePDF.aspx",
                    method: "post"
                },
                fields: {},
                iframe: {
                    id: "html2PDFFrame",
                    src: ""
                },
                docType: $.shop.convertToPDF.documentType
            };
            defaults.fields[$.shop.convertToPDF.fieldURL] = "";
            defaults.fields[$.shop.convertToPDF.fieldHTML] = "";
            defaults.fields[$.shop.convertToPDF.fieldPDFFileName] = "";

            settings = $.extend(false, defaults, settings);
            return settings;
        },
        convert: function (from, settings) {
            var $form, $iframe, hiddenFieldsHTML = "",
			$url, fileName = "", html = "";

            $form = $("#" + settings.form.id);

            if ($form.length === 0) {
                $form = $("<form/>", {
                    id: settings.form.id,
                    name: settings.form.id,
                    action: settings.form.action,
                    method: settings.form.method,
                    submit: function () {
                        this.target = settings.iframe.id;
                    }
                });
                $form.appendTo("body");

                $.each(settings.fields, function (field, val) {
                    hiddenFieldsHTML += '<input type="hidden" id="' + field + '" name="' + field + '" />';
                });
                $form.append(hiddenFieldsHTML);

                $.each(settings.fields, function (field, val) {
                    $("#" + field).val(val);
                });

                if (!$.isIE()) {
                    $iframe = $("<iframe/>", {
                        id: settings.iframe.id,
                        name: settings.iframe.id,
                        src: settings.iframe.src
                    }).appendTo("body");
                } else {
                    $("body").append('<iframe class="" name="' + settings.iframe.id + '" id="' + settings.iframe.id + '"></iframe>');
                }
            }

            // fileName
            if (settings.fields[$.shop.convertToPDF.fieldPDFFileName] === "") {
                fileName = $("title").html() + ".pdf";
                fileName = fileName.split(' ').join('_');
                $("#" + $.shop.convertToPDF.fieldPDFFileName).val(fileName);
            } else {
                fileName = settings.fields[$.shop.convertToPDF.fieldPDFFileName];
            }

            if (from === "html") {
                // reset url
                $("#" + $.shop.convertToPDF.fieldURL).val("");

                if (settings.fields[$.shop.convertToPDF.fieldHTML] !== "") {
                    // custom html 
                    html = settings.fields[$.shop.convertToPDF.fieldHTML];
                } else {
                    // current page html
                    html = settings.docType + "<html>" + $("html").html() + "</html>";
                }
                $("#" + $.shop.convertToPDF.fieldHTML).val(html);
            } else {
                // reset HTML
                $("#" + $.shop.convertToPDF.fieldHTML).val("");

                /*global location */
                $url = $("#" + $.shop.convertToPDF.fieldURL);
                $url.val($url.val() !== "" ? $url : $(window.location).attr("href"));
            }

            $("#" + $.shop.convertToPDF.fieldPDFFileName).val(fileName);
            $form.submit();
        }
    };

    //*************************************************************************************************************
    //                                             TV Reveiver Functions
    //*************************************************************************************************************
    jQuery.shop.tvReceiver = {
        setProductDetailsLink: function (paymentType) {

            $(".productDetailsLink").each(function () {
                var urls = $(this).attr("href").split("?payment=");
                var proUrl = urls[0] + "?payment=" + paymentType;
                $(this).attr("href", proUrl);
            });
        },

        //Selection changed in TV Listing
        selectPaymentTerm: function (paymentTerm) {
            if (paymentTerm == '' || paymentTerm == "undefined")
                return;
            var key = paymentTerm.toLowerCase();

            $('select[id^="list_tvOptionSelector_"] :selected').removeAttr('selected');
            $('select[id^="list_tvOptionSelector_"]').val(paymentTerm);
            $('span[id^="list_tv_optionSpan_"]').hide();
            var spanId = "list_tv_optionSpan_" + key + "_";
            $('span[id^=' + spanId + ']').show();

            var purchaseFootNotes = $('div[id^="purchaseFootNotes"]');
            var m2mFootNotes = $('div[id^="m2mFootNotes"]');
            var m2mHDPVRFootNotes = $('div[id^="m2mHDPVRFootNotes"]');

            if (key == "monthtomonth") {
                m2mFootNotes.show();
                purchaseFootNotes.hide();
                m2mHDPVRFootNotes.hide();
            }
            else if (key == "pvr_m2m") {
                m2mHDPVRFootNotes.show();
                m2mFootNotes.hide();
                purchaseFootNotes.hide();
            }
            else if (key == "purchase") {
                purchaseFootNotes.show();
                m2mFootNotes.hide();
                m2mHDPVRFootNotes.hide();
            }
            else {
                m2mHDPVRFootNotes.show();
                m2mFootNotes.hide();
                purchaseFootNotes.hide();
            }

            //set querystring of product details url
            this.setProductDetailsLink(paymentTerm);
        }
    };
    //*************************************************************************************************************
    //                                             Common
    //*************************************************************************************************************
    jQuery.shop.common = {
        displayLightBox: function (lightBoxName, defaultAction, altAction, options) {
            defaultOptions = { modal: false, minHeight: 100 };
            var finalOptions = $.extend({}, defaultOptions, options);
            $.lightBox.showInPage("#" + lightBoxName, finalOptions, function (boxObject) {
                if (boxObject.length) {
                    boxObject.find(".btnDftAct").unbind("click").click(function () {
                        if (typeof (defaultAction) == 'function') {
                            defaultAction();
                        }
                        $.lightBox.hide();
                        return false;
                    });

                    if (boxObject.find(".btnAltAct").length) {
                        boxObject.find(".btnAltAct").unbind("click").click(function () {
                            if (typeof (altAction) == 'function') {
                                altAction();
                            }
                            $.lightBox.hide();
                            return false;
                        });
                    }
                }
            });
            return false;
        },
        rearrangeShoppingCartLegalText: function (legalDiv) {
            var legals = {};
            var count = 1;
            var legalText;
            solutionDiv = legalDiv.prev();
            cacheDiv = legalDiv.find("legalTextCache");
            solutionDiv.find(".legaltext").each(function () {
                legalText = $(this).data("legal");
                if (legals[legalText] == undefined) {
                    legals[legalText] = count;
                    count += 1;
                }
            });

            solutionDiv.find(".legaltext").each(function () {
                $(this).text(legals[$(this).data("legal")]);
            });
            var totalKeys = "";
            for (var key in legals) {
                totalKeys += "|" + unescape(key);
            }
            $legalTextDiv = legalDiv.find(".legalTextDiv");
            var cacheDiv;
            var hasCache = false;
            var foundInCache = false;
            if (cacheDiv.data('ids') == totalKeys) {
                foundInCache = true;
                $legalTextDiv.html(cacheDiv.html());
            }
            if (count > 1)
                legalDiv.show();
            if (foundInCache) {
                return;
            }

            var url = "/ajax/Home/LegalText?ids=" + totalKeys + "&ts=" + new Date().getTime();
            $.ajax({
                url: url,
                async: false,
                dataType: "html",
                success: function (data) {
                    $legalTextDiv.html(data);
                    cacheDiv.data('ids', totalKeys);
                    cacheDiv.html(data);
                },
                error: function () {
                    var defErrorText = "Error";
                    if ($.isFunction($.getText)) {
                        $legalTextDiv.html($.getText("error"));
                    } else {
                        $legalTextDiv.html(defErrorText);
                    }
                }
            })
        },
        refreshPage: function () {
            url = $("link[rel='canonical']").attr('href');
            window.location = url;
        },

        replaceLegalTag: function(divId){
            var Div = $('#'+divId);
            htmlText = Div.html();
            legalRegex = /#{legal:[a-zA-Z]+}/gi;
            if (legalRegex.test(htmlText)){
                var legals = htmlText.match(legalRegex);
                for(var i in legals){
                    var legal = legals[i];
                    legalId = legal.replace("#{legal:", "").replace("}","")
                    legalSpan = "<span class='legaltext superscript' data-legal='"+legalId+"'></span>";
                    Div.html(htmlText.replace(legal, legalSpan));
                }
            }
        }

    };

    //*************************************************************************************************************
    //                                             Service Availability Check
    //*************************************************************************************************************

    jQuery.shop.serviceAvailability = {

        toggleSection: function (currentObject, sectionToShow, sectionToHide) {
            $.bell.setElementActive(currentObject, 'eqJs', 'capSelected');
            $(sectionToHide).hide();
            $(sectionToShow).show();
        },

        ServiceCheckBeforeSubmit: function () {
            if ($('#btnCheckPhone').data('submitting') == true)
                return false;
            $('#btnCheckPhone').data('submitting', true);

            $.ajaxLoader.show();
            if (typeof (lpServiceCheckHandler) == 'function') {
                lpServiceCheckHandler();
            }
        },

        ServiceCheckHotLeadsBeforeSubmit: function () {
            if ($('#btnHotLeadsSubmit').data('submitting') == true)
            return false;
            $('#btnHotLeadsSubmit').data('submitting', true);

            $.ajaxLoader.defaults.text= "";
            $.ajaxLoader.show();
            if (typeof (lpServiceCheckHandler) == 'function') {
            lpServiceCheckHandler();
            }
            },

        sacChangeProvince: function (ctl) {
            control = $(ctl);
            if (control.data('pageprovince') == control.val()) {
                return false;
            }
            var changeProvince = function () {
                toggleRegion(control.val());
            };

            var resetProvinceDropdown = function () {
                control.val(control.data('pageprovince'));
            };

            var submitForm = function () {
                control.closest('form').submit();
            }
            $.shop.common.displayLightBox('changeProvinceLB', submitForm, resetProvinceDropdown);
        },

        enableSelectAddress: function () {
            $("#addressList").removeAttr("disabled");
            $("#checkByIndicatedAddressSection").hide();
        },

        enableEnterAnotherAddress: function () {
            $("#addressList").attr("disabled", "disabled");
            $("#checkByIndicatedAddressSection").show();
        },
        enableEnterAnotherPostalCode: function(){
             var div1Class = $('#psqtCheckLink').attr('class');
             if(div1Class !=null)
             {
             if(div1Class.indexOf("toggleOpen") == -1)
             {
                $("#psqtCheckLink").click();
             }
             }
             $("input:radio[id='radioServiceCheckTypeAddress']").attr('checked',true);
             $("#checkByPhoneNumber").hide()
             $("optionAddress").show();
             $("#checkByAddress").show();
             $("#checkByIndicatedAddressSection").hide();
             $("#checkByAddressList").hide();
             $("#postalCode").val('');
        },
        enableEnterAnotherPhoneNumber: function(){
             var div1Class = $('#psqtCheckLink').attr('class');
             if(div1Class!=null)
             {
             if(div1Class.indexOf("toggleOpen") == -1)
             {
                $("#psqtCheckLink").click();
             }
             }
             $("input:radio[id='radioServiceCheckTypePhone']").attr('checked',true);
             $("#checkByAddress").hide();
             $("optionPhoneNumber").show();
             $("#checkByPhoneNumber").show();
             $("#checkByIndicatedAddressSection").hide();
             $("#checkByAddressList").hide();
             $("#phoneNumber").val('');
        },
        showChangeProvinceLightbox: function (newProvince) {
            $.lightBox.showInPage("#changeProvinceLB", { modal: true, minHeight: 100 }, function (boxObject) {
                if (boxObject.length) {
                    boxObject.find(".btnDftAct").unbind("click").click(function () {
                        toggleRegion(newProvince);
                        $.lightBox.hide();
                        return false;
                    });
                    boxObject.find(".btnAltAct").unbind("click").click(function () {
                        $.lightBox.hide();
                        return false;
                    });
                }
            });
        },

        changeAccount : function (){
            $.shop.common.displayLightBox("changeAccountLightBoxId", $.shop.serviceAvailability.selectAccount, null);
        },

        selectAccount : function(){
            $('#ChangeB1AccountTo').val($('input:radio[name=currentB1Account]:checked').val());
            $('#ChangeB1AccountTo').closest('form').submit();
        }
    };

    //*************************************************************************************************************
    //                                             Quickview Functions
    //*************************************************************************************************************

    jQuery.shop.quickview = {
        buyButtonClicked: function (control) {
            $detailPanel = $(control).closest(".detailPanel");
            $currentSelection = $detailPanel.find('select');
            if ($currentSelection != null) {
                var id = $currentSelection.val();
                if (id != null && id != "" && id != undefined) {
                    $detailPanel.find("#hdOfferId").val($currentSelection.val());
                }
            }
            $detailPanel.find('#SolutionBuildForm').submit();
        },

        qvFormSubmit: function (productId) {
            var qvPanelId = "#pDetailQVDiv" + productId;
            var $myQuickViewId = $(qvPanelId);
            var qvFormId = "#qvDetailForm" + productId;

            $.ajaxLoader.show();

            var url = $(qvFormId).attr("action");
            $myQuickViewId.load(url, $(qvFormId).serialize(), function (data, status) {
                if (status == "success") {
                    $.ajaxLoader.hide();
                    var $panel = $(data);
                    $myQuickViewId.before($panel).remove();
                  
                    $.pageRender($panel);
                } else if (status == "error") {
                    $.ajaxLoader.hide();
                }
            })
        },

        selectionChanged: function (controlName, productId) {
            var qvFormId = "#qvDetailForm" + productId;
            if (controlName == "SelectedColor") {
                $('#hdProductId', qvFormId).val($("input:radio[id='color_element']:checked", qvFormId).val());
            } else if (controlName == "SelectedMemory") {
                $('#hdProductId', qvFormId).val($("#memory_element option:selected", qvFormId).val());
            } else if (controlName == "SelectedTerm") {
                var productTermId = $("#contract_element option:selected", qvFormId).val();
                var termId = productTermId.split(',')[0];
                var handSetId = productTermId.split(',')[1];

                $('#hdSelectedTermId', qvFormId).val(termId);
                $('#hdProductId', qvFormId).val(handSetId);
            }
            $.shop.quickview.qvFormSubmit(productId);
        },

        initializeReelImage: function () {
            $('img.reelImage').each(function (ctl) {
                if ($(this).data("initialized"))
                    return;

                $(this).reel({
                    frames: 37,
                    saves: false,
                    speed: 0.5,
                    path: $(this).data("path"),
                    timeout: 1000,
                    images: $.shop.quickview.phone_frames(37),
                    preloader: 0,
                    throwable: false,
                    brake: 1
                });
                $(this).data("initialized", "true");

                //hack to set the rotation to stop image loop
                ctl = $(this);
                setTimeout(function () {
                    var interval = setInterval(function () {
                        if (ctl[0].src.split('img/').pop() === '01.jpg') {
                            ctl.trigger('stop');
                            clearInterval(interval);
                        }
                    }, 10);
                }, 3000);
            });
        },

      phone_frames:  function (frames) {
            var frames = 36, every = 1, stack = [];
            for (var i = 1; i <= frames; i += every) {
                var name = [i, '.jpg'].join('');
                while (name.length < 6) name = '0' + name;
                stack.push(name);
            }
            return stack;
        },

        resetReelImage: function () {
            $('img.jquery-reel').each(function () {
                $(this).trigger('teardown');
            });
        }

    };

    //*************************************************************************************************************
    //                                             Omniture
    //*************************************************************************************************************

    jQuery.shop.omniture = {
        psqtErrorcapture: function() {
            var objErrorlist = $("#checkResultMessage p");
            var oARS;
            var oAPT;
            try{

                    $("#checkResultMessage #psqterrorMsg").each(function () {
                    oARS = $(this).html();
                    oARS = oARS.replace(/<[^>]*>?/g, "");
                    });
                    $("#checkResultMessage #psqtCode").each(function () {
                    oAPT = $(this).html();
                    });
                    if ( typeof( s_oTrackPage) != 'undefined')
                    {
                            if(oAPT!="")
                            s_oTrackPage({ s_oAPT: oAPT, s_oARS: oARS});
                    }
            }
            catch(e)
            {;}
        }
    };


})(jQuery);

//*************************************************************************************************************
//                                            CMS Edit Link
//*************************************************************************************************************

function UpdateCMSPageEditLinkHref() {
    var editLink = $("#cmsPageEditLink");
    if (editLink.length) {
        var href = editLink.attr('href');
        if (href != null && href != "undefined") {
            href = href.replace("_xml", ".xml");
            editLink.attr('href', href);
        }
    }
}

//********************Mobility Accessories************************************************************************
var isBrandsLoaded = false;
function LoadMobilityBrand() {
    var dropdownList = $('#FILTER_BRAND');
    var length = $('#FILTER_BRAND option').size();

    if (length != 1 && isBrandsLoaded) return;

    $.ajaxLoader.show();

    //dropdownList.attr("disabled", "disabled");
    $.getJSON("/ajax/ProductList/BrandList", null, function (data) {
        for (i = 0; i < data.length; i++)
            dropdownList.append($('<option></option>').val(data[i].Value).html(data[i].Text));
        isBrandsLoaded = true;
        //dropdownList.removeAttr("disabled");
    });

    $.ajaxLoader.hide();
}

//Load product by brand
function LoadAccessProducts(brand) {
    var dropdownList = $('select#FILTER_MODEL');

    if (brand == '') {
        dropdownList.val(0);
    }
    else {
        $.ajaxLoader.show();
        //dropdownList.attr("disabled", "disabled");
        var imageType = $('#imageType').val();
        var url = "/ajax/ProductList/Products?brand=" + brand + "&imagetype=" + imageType;
        $.getJSON(url, null, function (data) {
            var defultOption = $("#FILTER_MODEL option:first-child");
            dropdownList.html("");
            dropdownList.append(defultOption);
            for (i = 0; i < data.length; i++)
                dropdownList.append($('<option></option>').val(data[i].Value).html(data[i].Text));
            //dropdownList.removeAttr("disabled");
        });

        $.ajaxLoader.hide();
    }
}

function ChangeMobilityBrand() {
    LoadAccessProducts($('#FILTER_BRAND').val());
    $('#selectedBrand').val($('#FILTER_BRAND').val());
}

function ChangeModel() {
    $('#selectedModel').val($('#FILTER_MODEL').val());
}

function ClickGetAccessories(pageIndex) {
    var link = $('a#btnGetAccessories');
    var selectProduct = $('#FILTER_MODEL').val();
    if (selectProduct.replace(" ", "") == "") {
        return;
    }
    var siteHierarchyCode = $('#SiteHierarchyCode').val();
    var zoneId = $('#ZoneId').val();
    if (selectProduct != '') {
        $.ajax({
            type: "GET",
            url: "/ajax/ProductList/GetAccessories?model=" + selectProduct + "&pageIndex=" + pageIndex + "&code=" + siteHierarchyCode + "&zone=" + zoneId,
            dataType: 'html',
            success: function (data) {
                $('#accList').html(data);
                $.pageRender('#accList');
            },
            error: function () {
            }
        });
    }
}

//*************** Product listing page ************************************************************************
function IsHideDIVByFeatures(prod, filterfeatures) {
    var features = prod.Features;
    var isHide = true;
    if (filterfeatures.length == 0) {
        isHide = false;
        return isHide;
    }
    for (var i = 0; i < filterfeatures.length; i++) {
        //incase value is price/amount filter
        if (filterfeatures[i].indexOf(">") != -1 || filterfeatures[i].indexOf("<=") != -1) {
            var opr1; var opr2; var isTrue;
            //greater then let say hundred
            if (filterfeatures[i].indexOf(">") != -1) {
                opr1 = filterfeatures[i].substr(filterfeatures[i].indexOf(">"));
                isTrue = eval(prod.productPricetoFilter + opr1);
            }
            //e.g. 0<=49 or 49<=100
            if (filterfeatures[i].indexOf("<") != -1) {

                opr2 = filterfeatures[i].substr(filterfeatures[i].indexOf("<"));
                opr1 = filterfeatures[i].substr(0, (filterfeatures[i].length - opr2.length));

                isTrue = eval(prod.productPricetoFilter + ">=" + opr1);

                if (isTrue) {
                    isTrue = eval(prod.productPricetoFilter + opr2);
                    //alert(thisProductList.DSource_Products[j].productPricetoFilter + opr2 + " result in =" + isTrue);
                }
            }

            if (isTrue) {
                isHide = false;
                return isHide;
            }
        }
        if (features.indexOf(filterfeatures[i]) != -1) {
            isHide = false;
            return isHide;
        }

    }
    return isHide;
}

//displaying products based on filter results
function UpdateProductListFilter(controlUniqueID) {
    var isHideDIV = false;
    //filter arrays
    var filterProductsfeatureM = new Array();
    var filterProductsfeaturePT = new Array();
    var filterProductsfeatureO = new Array();
    var filterProductsfeatureF = new Array();
    var filterProductsfeatureP = new Array();
    //check if user selected checkbox or dropdown to filter
    var isFilter = false;

    var hdncntrl = "#hdnControlID_" + controlUniqueID;
    //creating JSON
    if ($(hdncntrl).val() != "") {
        var thisProductList = eval('(' + $(hdncntrl).val() + ')');
    }

    //manufacturer
    $("#M_" + controlUniqueID + " option:selected").each(function () {
        if ($(this).val().length > 0) {
            isFilter = true;
            filterProductsfeatureM[filterProductsfeatureM.length] = $(this).val();
        }
    });
    //plan type
    $("#PT_" + controlUniqueID + " option:selected").each(function () {
        if ($(this).val().length > 0) {
            isFilter = true;
            filterProductsfeaturePT[filterProductsfeaturePT.length] = $(this).val();
        }
    });

    //OS
    $("input[id^=O_" + controlUniqueID + "]:checked").each(function () {
        isFilter = true;
        filterProductsfeatureO[filterProductsfeatureO.length] = $(this).attr('name');
    });


    //features
    $("input[id^=F_" + controlUniqueID + "]:checked").each(function () {
        isFilter = true;
        filterProductsfeatureF[filterProductsfeatureF.length] = $(this).attr('name');
    });

    //features
    $("input[id^=P_" + controlUniqueID + "]:checked").each(function () {
        isFilter = true;
        filterProductsfeatureP[filterProductsfeatureP.length] = $(this).attr('name');
    });

    for (var j = 0; j < thisProductList._Products.length; j++) {
        isHideDIV = false;
        var hideDIV = thisProductList._Products[j].ID;

        //unhide all divs before checking filters
        if ($("#" + hideDIV).hasClass("hide")) {
            $("#" + hideDIV).removeClass("hide");
        }
        isHideDIV = false;
        isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeatureM);
        //alert("1:"+ isHideDIV.toString());
        isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeaturePT);
        //alert("2:" + isHideDIV.toString());
        isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeatureO);
        //alert("3:" + isHideDIV.toString());
        isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeatureF);
        //alert("4:" + isHideDIV.toString());
        isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeatureP);

        var isLengthZero = false;
        $("#PT_" + controlUniqueID + " option:selected").each(function () {
            if ($(this).val().length == 0) {
                if ((thisProductList._Products[j].PlanType == "Prepaid") || (thisProductList._Products[j].PlanType == "GrabAndGo")) {
                    isHideDIV = true;
                    isLengthZero = true;
                    isFilter = true;
                }
            }
            else {
                isHideDIV = isHideDIV || IsHideDIVByFeatures(thisProductList._Products[j], filterProductsfeatureP);
                //alert("5:" + isHideDIV.toString());
            }
        });

        if (!isLengthZero) {
            if (!isHideDIV) {
                hideDIV = '';
            }
        }

        if (((isLengthZero) || (hideDIV.length > 0)) && (isFilter)) {
            $("#" + hideDIV).addClass("hide");
        }
    }

    var catid = "#cat_" + controlUniqueID;
    $(catid).closest(".hScrollBarJs").scroller({ fillSpace: false, toggle: true });
    return false;
}

//=========================== Reload Internext Service list =======================================

function GetInternetService(actionUrl, catId) {
    $.ajax({
        type: "Post",
        url: actionUrl + catId,
        dataType: 'html',
        success: function (data) {
            var listlId = "#psqtList_" + catId;
            var $listDiv = $(listlId);

            if ($listDiv.length) {
                var $panel = $(data);
                $listDiv.before($panel).remove();

                var $scroller = $(".hScrollBarJs");
                if ($scroller.length) {
                    $scroller.removeClass("scrollerInitializedJs");
                    $scroller.removeClass("hScrollBar");

                    $scroller.scroller({ fillSpace: false, toggle: true });
                }

                $.pageRender($scroller);
            }
        },
        error: function () {
        }
    });
}

//tvonline 
var baseUrl = "https://www.bell.ca/mybell/resources/login/invisibleLogin/loginSSO.jsp?action=idsp&SPID=urn:belltv:entityid&RelayState=";
function btvoForword(btvoUrl) {
    if (btvoLoggedIn) {
        var redirectUrlEncoded = baseUrl + escape(btvoUrl + "&useRelayState=Y");
        location.href = redirectUrlEncoded;
    }
    else {
        location.href = btvoUrl;
    }
}

function loginBtvoForword(btvoUrl) {
    var redirectUrlEncoded = baseUrl + escape(btvoUrl + "&useRelayState=Y");
    location.href = redirectUrlEncoded;
}


//bell.init.js
function BWS_Init_MasterPage()
{
	// We put here any script code that needs to run before DOM ready
	var head = document.getElementsByTagName('head')[0],
		style = document.createElement('style'),
		rules = document.createTextNode(".noJs h1, .noJs .txtRep, .noJs .buttonize, .noJs .labelOver, .noJs .labelOverAct {visibility: hidden;} .noJs .hScrollBarJs .refLine {height: 65px;visibility: hidden;} .noJs .filterBox {display: none;}");

	style.type = 'text/css';

	if (style.styleSheet) {
		style.styleSheet.cssText = rules.nodeValue;
	} else {
		style.appendChild(rules);
		head.appendChild(style);
	}
	document.body.className = document.body.className.replace(/noJs/, '');
}

//merged GOMEZ script 
var gomez = gomez ? gomez : {}; gomez.h3 = function (d, s) { for (var p in s) { d[p] = s[p]; } return d; }; gomez.h3(gomez, { b3: function (r) { if (r <= 0) return false; return Math.random() <= r && r; }, b0: function (n) { var c = document.cookie; var v = c.match(new RegExp(';[ ]*' + n + '=([^;]*)')); if (!v) v = c.match(new RegExp(n + '=([^;]*)')); if (v) return unescape(v[1]); return ''; }, c2: function (n, v, e, p, d, s) { try { var t = this, a = location.hostname; var c = n + '=' + escape(v) + (e ? ';expires=' + e.toGMTString() : '') + (p ? ';path=' + p : ';path=/') + (d ? ';domain=' + d : ';domain=' + a) + (s ? ';secure' : ''); document.cookie = c; } catch (e) { } }, z0: function (n) { var t = this; if (n) { var s = t.b0("__g_c"); if (!s) return ''; var v = s.match(new RegExp(n + ':([^\|]*)')); if (v) return unescape(v[1]); return ''; } else return ''; }, z1: function (n, m) { var t = this; if (n) { var s = t.b0("__g_c"); if (s) { if (s.indexOf(n + ':') != -1) s = s.replace(new RegExp('(' + n + ':[^\|]*)'), n + ':' + m); else s = s == ' ' ? n + ':' + m : s + '|' + n + ':' + m; t.c2("__g_c", s); } else t.c2("__g_c", n + ':' + m); }; } }); if (gomez.wrate) { gomez.i0 = gomez.z0('w'); if (gomez.i0) { gomez.runFlg = parseInt(gomez.i0) > 0 ? true : false; } else if (gomez.b3(parseFloat(gomez.wrate))) { gomez.runFlg = true; gomez.z1('w', 1); } else { gomez.runFlg = false; gomez.z1('w', 0); } } else if (gomez.wrate == undefined) { gomez.runFlg = true; gomez.z1('w', 1); } else { gomez.runFlg = false; gomez.z1('w', 0); }; if (gomez.runFlg) { gomez.h1 = function (v, d) { return v ? v : d }; gomez.gs = gomez.h1(gomez.gs, new Date().getTime()); gomez.acctId = gomez.h1(gomez.acctId, ''); gomez.pgId = gomez.h1(gomez.pgId, ''); gomez.grpId = gomez.h1(gomez.grpId, ''); gomez.E = function (c) { this.s = c; }; gomez.E.prototype = { g1: function (e) { var t = gomez, i = t.g6(e); if (i) i.e = t.b5(); } }; gomez.L = function (m) { this.a = m; }; gomez.L.prototype = { g2: function (m) { var t = gomez, n = t.b5(); var s = document.getElementsByTagName(m); var e = t.k; if (m == 'script') e = t.j; if (m == 'iframe') e = t.l; if (s) { var l = s.length; for (var i = 0; i < l; i++) { var u = s[i].src || s[i].href; if (u && !e[u]) { var r = new gomez.E(e); t.grm[u] = r; e[u] = new t.c7(u, n); if (t.gIE && m == 'script') t.e2(s[i], 'readystatechange', t.d2, false); else t.e2(s[i], 'load', r.g1, false); } } } } }; gomez.L.m = new Object; gomez.L.m['script'] = new gomez.L(); gomez.L.m['link'] = new gomez.L(); gomez.L.m['iframe'] = new gomez.L(); gomez.S = function () { var t = this, h = gomez.acctId + ".r.axf8.net"; t.x = location.protocol + '//' + h + '/mr/b.gif?'; t.y = location.protocol + '//' + h + '/mr/a.gif?'; }; gomez.h2 = function () { var t = this; t.gIE = false; t.f = new Object; t._h = 0; t.j = new Object; t.k = new Object; t.l = new Object; t.m = location.href; t.p = -1; t.q = -1; t.t = new Array; t.u = new Array; t._w = false; t.gSfr = /KHTML|WebKit/i.test(navigator.userAgent); t.gc = { 'n': 'c' }; t.grm = new Object; t.b; t.a = 0; t.d = false; t.x = false; t.s = new gomez.S; t._a = false; t.h6 = false; }; gomez.h3(gomez, { h5: function (u) { try { var s = document.createElement('script'); s.src = u; s.type = 'text/javascript'; if (document.body) document.body.appendChild(s); else if (document.documentElement.getElementsByTagName('head')[0]) document.documentElement.getElementsByTagName('head')[0].appendChild(s); } catch (e) { } }, a9: function () { var t = gomez, i = t.z0('a'), g = t.b0('__g_u'); t.gc.h = t.z0('b'); if (!t.gc.h) t.gc.h = 1; t.z1('b', parseInt(t.gc.h) + 1); if (i) { t.a = parseInt(i); if (t.a == 1) { t._w = true; } else if (t.a == 3) { t.x = true; t._w = true; }; t.d = true; t.gc.c = t.z0('c'); t.gc.d = t.z0('d'); t.gc.i = t.z0('e'); t.gc.j = t.z0('f'); if (t._w && !t._a) { t.h7(); t._a = true; }; } else { if (!t.gc.a) return; var s = 'v=1'; t.c2('__g_u', '1', new Date(t.gt() + 1000)); if (t.b0('__g_u') && g && g != '1' && g.indexOf('NaN') == -1 && g.indexOf('undefined') == -1) { s = 'v=0'; var r = g.split('_'); t.b2(parseInt(r[0]), parseInt(r[1]) + 1); if (r[4] && r[4] != '0' && t.gt() < parseInt(r[5]) && r[2] && r[2] != '0') { t.b1(parseFloat(r[2]), parseFloat(r[3]), parseFloat(r[4]), parseInt(r[5])); return; }; }; t.h6 = true; s = t.s.y + 'a=' + t.gc.a + '&' + s; if (t.gSfr) document.write("<scr" + "ipt src='" + s + "'" + "><\/scr" + "ipt>"); else t.h5(s); }; t.b = t.z0('g'); }, h7: function () { var t = gomez, u = t.tloc ? t.tloc : location.protocol + '//' + t.acctId + '.t.axf8.net/js/gtag4.js'; if (t.gSfr) document.write("<scr" + "ipt src='" + u + "'" + "><\/scr" + "ipt>"); else t.h5(u); }, b1: function (v, s, q, f) { var t = this; if (t._a) return; if (t.b3(v)) { t._w = true; t.a = 1; var p = parseFloat(s / v); if (t.b3(p)) { t.x = true; t.a = 3; }; }; t.d = true; t.z1('a', t.a); t.z1('e', v); t.z1('f', s); t.gc.i = v; t.gc.j = s; t.h4(v, s, q, f); if (t._w) { t.h7(); t._a = true; }; }, b2: function (v, s) { var t = this, f = new Date(t.gt() + 946080000000), g = '' + v + '_' + s; if (t._a) return; t.c2('__g_u', g, f); t.gc.c = v; t.gc.d = s; t.z1('c', v); t.z1('d', s); }, h4: function (o, p, q, d) { var t = this, f = new Date(t.gt() + 946080000000), g = t.b0('__g_u'); if (g && g != '1' && g.indexOf('NaN') == -1 && g.indexOf('undefined') == -1) { var r = g.split('_'), s; if (d) s = d; else if (q && q >= 0) s = new Date(t.gt() + parseInt(q * 86400000)).getTime(); else { q = 5; s = new Date(t.gt() + 432000000).getTime(); }; g = '' + r[0] + '_' + r[1] + '_' + o + '_' + p + '_' + q + '_' + s; t.c2('__g_u', g, f); }; }, gt: function () { return new Date().getTime() }, b5: function () { return new Date().getTime() - gomez.gs }, b6: function () { var t = gomez; t.p = t.b5(); }, f8: function () { var t = this; if (t.pollId1) clearInterval(t.pollId1); if (t.pollId2) clearInterval(t.pollId2); if (t.pollId3) clearInterval(t.pollId3); if (t.pollId4) clearInterval(t.pollId4); }, b7: function () { var t = gomez; t.f8(); t.q = t.b5(); }, c7: function (u, s) { var t = this; t.m = u; t.s = s; }, c8: function () { var t = gomez, n = t.b5(), l = document.images.length; if (l > t._h) { for (var i = t._h; i < l; ++i) { var u = document.images[i].src; if (u) { var r = new gomez.E(t.f); t.grm[u] = r; t.f[u] = new t.c7(u, n); t.e2(document.images[i], 'load', t.c4, false); t.e2(document.images[i], 'error', t.c5, false); t.e2(document.images[i], 'abort', t.c6, false); } } } t._h = l; }, c4: function (e) { var t = gomez, i = t.g6(e); if (i) i.e = t.b5(); }, c5: function (e) { var t = gomez, i = t.g6(e); if (i) { i.e = t.b5(); i.b = 1; } }, c6: function (e) { var t = gomez, i = t.g6(e); if (i) i.a = t.b5(); }, g6: function (e) { var t = gomez, e = window.event ? window.event : e, a = t.d8(e), i; if (t.grm[a.src || a.href] && t.grm[a.src || a.href].s) i = t.grm[a.src || a.href].s[a.src || a.href]; return i; }, d2: function () { var t = gomez; var e = window.event ? window.event : e, s = t.d8(e); if (s.readyState == 'loaded' || s.readyState == 'complete') { var o = t.j[s.src]; if (o) o.e = t.b5(); } }, setPair: function (name, value) { var t = this; t.t[t.t.length] = { 'n': 'p', 'a': name, 'b': value }; }, nameEvent: function (n) { var t = this; t.f6(n, 1); }, startInterval: function (n) { var t = this; t.f6(n, 2, 1); }, endInterval: function (n) { var t = this; t.f6(n, 2, 2); }, f6: function (n, p, b) { if (n && n.length > 20) n = n.substring(0, 20); var t = this, f = t.u; f[f.length] = { 'n': 'a', 'a': n, 'b': t.b5(), 'e': p, 'f': b }; }, d8: function (e) { if (gomez.gIE) return e.srcElement || {}; else return e.currentTarget || e.target || {}; }, e2: function (e, p, f, c) { var n = 'on' + p; if (e.addEventListener) e.addEventListener(p, f, c); else if (e.attachEvent) e.attachEvent(n, f); else { var x = e[n]; if (typeof e[n] != 'function') e[n] = f; else e[n] = function (a) { x(a); f(a); }; } }, i1: function () { var d = window.document, done = false, i2 = function () { if (!done) { done = true; gomez.b6(); gomez.a9(); } }; (function () { try { d.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } i2(); })(); d.onreadystatechange = function () { if (d.readyState == 'complete') { d.onreadystatechange = null; i2(); } }; }, g7: function () { try { var t = gomez; t.gc.a = t.acctId; /*@cc_ont.gIE = true; @*/if (t.gIE) { t.i1(); window.attachEvent('onload', t.b7); } else if (t.gSfr) { var m = setInterval(function () { if (/loaded|complete/.test(document.readyState)) { clearInterval(m); delete m; t.b6(); t.b7(); } }, 10); } else if (window.addEventListener) { window.addEventListener('DOMContentLoaded', t.b6, false); window.addEventListener('load', t.b7, false); } else return; t.c8(); t.pollId1 = setInterval(t.c8, 1); gomez.L.m['link'].g2('link'); t.pollId3 = setInterval("gomez.L.m['link'].g2('link')", 1); gomez.L.m['iframe'].g2('iframe'); t.pollId4 = setInterval("gomez.L.m['iframe'].g2('iframe')", 1); if (!t.gIE) t.a9(); } catch (e) { return; } } }); gomez.h2(); gomez.g7(); }

//Merged Opinion_Lab 
var custom_var, _sp = '%3A\\/\\/', _rp = '%3A//' + $.getPageLang() + '-CA.', _poE = 0.0, _poX = 0.0, _sH = screen.height, _d = document, _w = window, _ht = escape(_w.location.href), _hr = _d.referrer, _tm = (new Date()).getTime(), _kp = 0, _sW = screen.width; _d.onkeypress = _fK; function _fK(_e) { if (!_e) _e = _w.event; var _k = (typeof _e.which == 'number') ? _e.which : _e.keyCode; if ((_kp == 15 && _k == 12)) _w.open('http://www.opinionlab.com/ozone/24-7.asp?referer=' + _fC(_ht), 'Report', 'width=370,height=200,resizable=no,copyhistory=no,scrollbars=no'); _kp = _k }; function _fC(_u) { _aT = _sp + ',\\/,\\.,-,_,' + _rp + ',%2F,%2E,%2D,%5F'; _aA = _aT.split(','); for (i = 0; i < 5; i++) { eval('_u=_u.replace(/' + _aA[i] + '/g,_aA[i+5])') } return _u }; function O_LC() { _w.open('http://ccc01.opinionlab.com/comment_card.asp?time1=' + _tm + '&time2=' + (new Date()).getTime() + '&prev=' + _fC(escape(_hr)) + '&referer=' + _fC(_ht) + '&height=' + _sH + '&width=' + _sW + '&custom_var=' + custom_var, 'comments', 'width=535,height=192,screenX=' + ((_sW - 535) / 2) + ',screenY=' + ((_sH - 192) / 2) + ',top=' + ((_sH - 192) / 2) + ',left=' + ((_sW - 535) / 2) + ',resizable=yes,copyhistory=yes,scrollbars=no') }; function _fPe() { if (Math.random() >= 1.0 - _poE) { O_LC(); _poX = 0.0 } }; function _fPx() { if (Math.random() >= 1.0 - _poX) O_LC() }; window.onunload = _fPx; function O_GoT(_p) { _d.write('<a	href=\'javascript:O_LC()\'>' + _p + '</a>'); _fPe() }


//*************************************************************************************************************
//                                             Echelon
//*************************************************************************************************************
function compareAll(formID) {
    var submitFormID = "#" + formID;
    if ($(submitFormID).length)
    {
        $(submitFormID).submit();
    }
}

function userFunctionNavigateTo(linkObject, PanelId) {
    var $myQuickView = $("#" + PanelId);
    if ($myQuickView.length)
    {
        $myQuickView.load(linkObject.href, function (data) {
                var $data = $(data),
                $panel; $panel = $data.find(".detailPanel").removeClass("cBox");
                $myQuickView.before($panel).remove();
                $.quickView.resize();
                $.pageRender($panel);
      });
    }
    return false;
}

//=========================== Reload TV Package list after Service Availability Check Completed=======================================

function GetTVPackage(actionUrl, catId) {
    $.ajax({
        type: "Post",
        url: actionUrl + catId,
        dataType: 'html',
        success: function (data) {
            var listlId = "#tvpackList_" + catId;
            var $listDiv = $(listlId);
            if ($listDiv.length) {
                var $panel = $(data);
                $listDiv.before($panel).remove();
                var $scroller = $(".hScrollBarJs");
                if ($scroller.length) {
                    $scroller.removeClass("scrollerInitializedJs");
                    $scroller.removeClass("hScrollBar");

                    $scroller.scroller({ fillSpace: false, toggle: true });
                }

                $.pageRender($scroller);
                $.pageRender($scroller, "scroller"); 
                $package = $("[id$='_packages']");
                if ($package.length) {
                    $package.equalize({ similarItem: "unit" }); 
                }
            }
        },
        error: function () {
        }
    });
}

//=========================== Rate Plan =======================================
function RateplanMouseHover() {
        $("div[id^=rateplanSku]").hover(function () {
            $this = $(this);
            var id = $this.attr("id");
            var index = id.indexOf("--");
            var rateplanSku;
            if (index != -1) {
                rateplanSku = id.substring(index + 2, id.length);
                $("div[id*=" + rateplanSku + "]").each(function () {
                    var $this = $(this);
                    $this.children('div').addClass("capSelected");
                });

                var rateplanIndex = -1;
                $("div[id*=rateplanSku]").each(function (index) {
                    var $this = $(this);
                    if ($this.attr("id").indexOf(rateplanSku) >= 0)
                        rateplanIndex = index;
                });

                if (rateplanIndex == 0) {
                    $("div[id*=bonusfeatureL]").each(function () {
                        var $this = $(this);
                        $this.children('div').addClass("capSelected");
                    });
                }
                else if (rateplanIndex == 1) {
                    if (lpProvince.toUpperCase() == "PE" || lpProvince.toUpperCase() == "NS" || lpProvince.toUpperCase() == "NB" || lpProvince.toUpperCase() == "NL") {
                        $("div[id*=bonusfeatureL]").each(function () {
                            var $this = $(this);
                            $this.children('div').addClass("capSelected");
                        });
                    } else {
                        $("div[id*=bonusfeatureR]").each(function () {
                            var $this = $(this);
                            $this.children('div').addClass("capSelected");
                        });
                    }
                }
                else if (rateplanIndex == 2) {
                    $("div[id*=bonusfeatureR]").each(function () {
                        var $this = $(this);
                        $this.children('div').addClass("capSelected");
                    });
                }
                if ($("div[id*=bonusfeatureR]").length <= 0) {
                    $("div[id*=bonusfeatureL]").each(function () {
                        var $this = $(this);
                        $this.children('div').addClass("capSelected");
                    });
                }

                if ($("div[id*=bonusfeatureL]").length <= 0) {
                    $("div[id*=bonusfeatureR]").each(function () {
                        var $this = $(this);
                        $this.children('div').addClass("capSelected");
                    });
                }

                $("div[id*=divIncludedFeatures]").each(function () {
                    var $this = $(this);
                    $this.children('div').addClass("capSelected");
                });
                $("div[id*=divAdditionalFeatures]").each(function () {
                    var $this = $(this);
                    $this.children('div').addClass("capSelected");
                });

            }
        }, function () {
            $this = $(this);
            var id = $this.attr("id");
            var index = id.indexOf("--");
            var rateplanSku;
            if (index != -1) {
                rateplanSku = id.substring(index + 2, id.length);
                //                var rateplanIndex = 0;
                $("div[id*=--" + rateplanSku + "]").each(function () {
                    var $this = $(this);
                    $this.children('div').removeClass("capSelected");
                });

                var rateplanIndex = -1;
                $("div[id*=rateplanSku]").each(function (index) {
                    var $this = $(this);
                    if ($this.attr("id").indexOf(rateplanSku) >= 0)
                        rateplanIndex = index;
                });
                if (rateplanIndex == 0) {
                    $("div[id*=bonusfeatureL]").each(function () {
                        var $this = $(this);
                        $this.children('div').removeClass("capSelected");
                    });
                } else if (rateplanIndex == 1) {
                    if (lpProvince.toUpperCase() == "PE" || lpProvince.toUpperCase() == "NS" || lpProvince.toUpperCase() == "NB" || lpProvince.toUpperCase() == "NL") {
                        $("div[id*=bonusfeatureL]").each(function () {
                            var $this = $(this);
                            $this.children('div').removeClass("capSelected");
                        });
                    } else {
                        $("div[id*=bonusfeatureR]").each(function () {
                            var $this = $(this);
                            $this.children('div').removeClass("capSelected");
                        });
                    }
                } else if (rateplanIndex == 2) {
                    $("div[id*=bonusfeatureR]").each(function () {
                        var $this = $(this);
                        $this.children('div').removeClass("capSelected");
                    });
                }
                if ($("div[id*=bonusfeatureR]").length <= 0) {
                    $("div[id*=bonusfeatureL]").each(function () {
                        var $this = $(this);
                        $this.children('div').removeClass("capSelected");
                    });
                }

                if ($("div[id*=bonusfeatureL]").length <= 0) {
                    $("div[id*=bonusfeatureR]").each(function () {
                        var $this = $(this);
                        $this.children('div').removeClass("capSelected");
                    });
                }
                $("div[id*=divIncludedFeatures]").each(function () {
                    var $this = $(this);
                    $this.children('div').removeClass("capSelected");
                });
                $("div[id*=divAdditionalFeatures]").each(function () {
                    var $this = $(this);
                    $this.children('div').removeClass("capSelected");
                });
            }
        });
}

