let members = 0;
var resizeTimeoutFn = 0;
$(window).on('resize', function () {
    clearTimeout(resizeTimeoutFn);
    resizeTimeoutFn = setTimeout(function () {
        loadOpacityDots();
        if ($(window).width() < 768) {
            if ($('.transform-slick-slide-js').length > 0) {
                $('.transform-slick-slide-js').not('.slick-initialized').slick();
                $('.transform-slick-slide-js:not(.full-width-slide)').find('.slick-track').addClass('margin-n30-left');
            }
        }

        //remove tabindex on resize
        $('.focusableElementUnslick-js:not(slick-initialized)').find('[tabindex="-1"]').removeAttr('tabindex');

        forceSkipSameHeightMobile();

        mobileUnslickCountOne.reSize();

        //refresh slick on screen resize to reset its width accordingly
        setTimeout(function () {
            $('.responsive-slick-slider.slick-initialized').not('.opacityDots').slick('setPosition');
            initProductThumbnailModalSlick();
        }, 300)
        //remove display inline block style generated by slick each time it refresh
        setTimeout(function () {
            $('.slider-remove-prev').find('.slick-arrow.slick-disabled').removeAttr('style');
        }, 300);
        //accordionTabPanel thumb height refresh
        setTimeout(function () {
            thumbHeightResize();
        }, 330);
        reSizePlanRate();
        processModalSameHeight();

        bottomSticky();
    }, 200);

});

$(document).ready(function () {
    //set event handler for tooltip enter keypress
    tooltipKeypress();
});

//start offset slick track*
// use this function to offset the first anlast slides of a slider to a certain negative and positive margin left
let offsetSlickTrack = {
    initialize: function (slickInstance) {
        let thisObject = this;
        slickInstance.on('init', function (event, slick) {
            const $this = $(this);
            if (slick.slideCount != slick.options.slidesToShow) {
                let slickTrackOffset = JSON.parse($this.attr('data-slick-track-offset'));

                if (slickTrackOffset.xs && window.matchMedia("(max-width: 767.98px)").matches) {
                    thisObject.processOffset($this, slickTrackOffset.xs);
                }
                else if (slickTrackOffset.sm && window.matchMedia("(max-width: 991.98px)").matches && window.matchMedia("(min-width: 768px)").matches) {
                    thisObject.processOffset($this, slickTrackOffset.sm);
                }
            }
            else {
                if (window.matchMedia("(min-width: 992px)").matches) {
                    slick.$list.css('padding', '0 0');
                }
            }
        });
        slickInstance.on('breakpoint', function (event, slick) {
            const $this = $(this);
            if (slick.slideCount != slick.options.slidesToShow) {
                let slickTrackOffset = JSON.parse($this.attr('data-slick-track-offset'));
                if (slickTrackOffset.xs && window.matchMedia("(max-width: 767.98px)").matches) {
                    thisObject.processOffset($this, slickTrackOffset.xs, slick);
                    thisObject.reInitialize($this, slickTrackOffset.xs, slick);
                }
                else if (slickTrackOffset.sm && window.matchMedia("(max-width: 991.98px)").matches && window.matchMedia("(min-width: 768px)").matches) {
                    thisObject.processOffset($this, slickTrackOffset.sm, slick);
                    thisObject.reInitialize($this, slickTrackOffset.sm, slick);
                }
            }
            else {
                if (window.matchMedia("(min-width: 992px)").matches) {
                    slick.$list.css('padding', '0 0');
                }

                setTimeout(function () {
                    $this.slick('setPosition');
                }, 200)
            }
        });
        slickInstance.on('setPosition', function (event, slick) {
            const sameHeight = $(this).find('.same-height');
            sameHeight.each(function () {
                resetSameHeightElements($(this));
            })
            processSameHeightElements($(this));
        });

    },
    processOffset: function (slickInstance, offsetValue) {
        let slickTrack = slickInstance.find('.slick-track');
        slickTrack.css('margin-left', '-' + offsetValue);
        slickInstance.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
            if (nextSlide > 0 && nextSlide < (slick.slideCount - slick.options.slidesToShow)) { // if next slide is in the middle
                slickTrack.css("margin-left", "0");
            } else if (nextSlide >= (slick.slideCount - slick.options.slidesToShow)) { // if next slide is the last slide
                slickTrack.css("margin-left", offsetValue);
            } else if (nextSlide == 0) { // if next slide is the first slide
                slickTrack.css("margin-left", "-" + offsetValue);
            }
        });
    },
    reInitialize: function (slickInstance, offsetValue, slick) {
        let slickTrack = slickInstance.find('.slick-track');
        const currentSlide = slick.currentSlide;
        slickTrack.css('margin-left', '-' + offsetValue);
        if (currentSlide > 0 && currentSlide < (slick.slideCount - slick.options.slidesToShow)) { // if next slide is in the middle
            slickTrack.css("margin-left", "0");
        } else if (currentSlide >= (slick.slideCount - slick.options.slidesToShow)) { // if next slide is the last slide
            slickTrack.css("margin-left", offsetValue);
        } else if (currentSlide == 0) { // if next slide is the first slide
            slickTrack.css("margin-left", "-" + offsetValue);
        }
    }
}
offsetSlickTrack.initialize($('[data-slick-track-offset]'));
//End offset slick track

//Goes back to top when page reloads
$(window).on('unload', function () {
    $(window).scrollTop(0);
});


$(window).on('load', function () {
    //recall same-height function when load is finish
    processSameHeightElements();

    //Accordion Tab 
    accordionTab();
    reSizePlanRate();
});

function reSizePlanRate() {
    var el = $('.plan-rate-container-js');
    el.each(function (element) {
        var items = $(this).find('.plan-item');
        if (window.matchMedia("(max-width: 767px)").matches) {
            items.css('width', '100%');
        } else {
            if (items.length === 4) {
                items.css('width', '25%');
            } else {
                items.css('width', '33.33%');
            }
        }
    });
}

$('.transform-slick-slide-js').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
    var slickSlideCount = $(this).find('.slick-slide').length;
    var $slider = $(this);
    $slider.find('.slick-track').removeClass('margin-n30-left').removeClass('margin-n15-left');
    if (!$slider.hasClass('full-width-slide')) {
        if (nextSlide == 0) {
            $slider.find('.slick-track').addClass('margin-n30-left');
        } else if (nextSlide == (slickSlideCount - 1)) {
            $slider.find('.slick-track').addClass('margin-n15-left');
        }
    }
})

//InfoBlock slider
$('.infoblock-slider').on('beforeChange', function (event, slick, currentSlide, nextSlide) {
    if (window.matchMedia('(max-width: 767px)').matches) {
        var $slider = $(this);
        var slickSlideCount = $slider.find('.slick-slide').length;

        if (nextSlide > 0 && nextSlide < (slickSlideCount - 1)) {
            $slider.find('.slick-track').css("margin-left", "0");
        } else if (nextSlide == (slickSlideCount - 1)) {
            $slider.not(['.device-product', '.device-thumb-nav']).find('.slick-track').css("margin-left", "15px");
        } else {
            $slider.find('.slick-track').css("margin-left", "");
        }
    }
});


$('.related-accessories-js').on('init', function () {
    $(this).find('img.lazy').on('load', function () {
        processSameHeightElements();
    });
    lazyLoad($(this).find(".slick-slide:nth-child(2)"));
});

$('.infoblock-slider, .responsive-slick-slider').on('lazyLoaded', function () {
    processSameHeightElements();
});

// Start slick event handler to hide offsreen card slides on infoblock sliders

$('.hiddenInactive').on('init', function () {
    $(this).find('.slick-slide[aria-hidden="true"]').addClass('offscreen');
});

function setBrand() {
    var queryString = encodeURI(window.location.search);
    if (queryString !== "" && queryString.indexOf("?filter=") > -1 && queryString.toLowerCase().indexOf("_brand") > -1) {

        var brandNameStart = queryString.indexOf("?filter=") + "?filter=".length,
            brandNameEnd = queryString.toLowerCase().indexOf("_brand"),
            brand = queryString.substring(brandNameStart, brandNameEnd).toLowerCase();

        brand = `#${brand}`;
        if ($(brand).length == 0) {
            brand = brand.toUpperCase();
        }
        $(brand).trigger("change");
        $("#filter-controls").hide();
    }
}

function hideInactiveSlides() {
    $('.hiddenInactive').on('afterChange', function () {
        $(this).find('.slick-slide[aria-hidden="true"]').addClass('offscreen');
        $(this).removeClass('sliding');
    });
    $('.hiddenInactive').on('beforeChange', function () {
        $(this).find('.slick-slide[aria-hidden="true"]').removeClass('offscreen');
        $(this).addClass('sliding');
    });
    let mousedown = false;
    $('.hiddenInactive').on('mousedown', function () {
        mousedown = true;
    });
    $('.hiddenInactive').on('mouseup', function () {
        mousedown = false;
    });
    $('.hiddenInactive').on('mousemove', function () {
        if (mousedown) {
            $(this).find('.slick-slide[aria-hidden="true"]').removeClass('offscreen');
        }
    });
}
// End slick event handler to hide offsreen card slides on infoblock sliders

//Start disable tab on link slides to prioritize tab on link
$('.link-slide').on('afterChange', function () {
    let $this = $(this);
    setTimeout(function () {
        $this.find('.slick-slide').attr('tabindex', -1);
    }, 100);
});
$('.link-slide').on('init', function () {
    let $this = $(this);
    setTimeout(function () {
        $this.find('.slick-slide').attr('tabindex', -1);
    }, 100);
});
//End disable tab on link slides to prioritize tab on link

//Delegate slick click event to open tooltip modal
$('.link-slide').on('click', 'span[role="button"]', function (e) {
});
//delegate slick hover event to trigger show tooltip function
$('.link-slide').on('mouseenter mouseleave', '.tooltip-interactive, .tooltip-static', function (e) {
    $(this).tooltip('show');
});
//delegate slick focus event to trigger show tooltip function
$('.link-slide').on('focus', '.tooltip-interactive, .tooltip-static', function (e) {
    $(this).tooltip('show');
    setTimeout(function () {
        $(this).find('.tooltip').attr('tabindex', 0);
    }, 100);
});

// for tooltip circle trigger Mobility-Connected-Car-Landing-Plug-in-connectivity
$('.mobility-circle-icon.mobility-circle-icon').on('shown.bs.tooltip', function () {
    $('.mobility-circle-icon.mobility-circle-icon').removeClass('active');
    $(this).addClass('active');
})

$('.mobility-circle-icon.mobility-circle-icon').on('hidden.bs.tooltip', function () {
    $('.mobility-circle-icon.mobility-circle-icon').removeClass('active');
})
window.addEventListener("load", function () {
    var filterUrl = window.location.search;
    function filterScrollToTarget() {
        var queryString = encodeURI(window.location.search);
        queryString = sanitizeHTML(queryString);
        const otherBrandsFieldId = "addmore";
        if (queryString !== "" && queryString.indexOf("?filter=") > -1 && queryString.toLowerCase().indexOf("_brand") > -1) {

            var brandNameStart = queryString.indexOf("?filter=") + "?filter=".length,
                brandNameEnd = queryString.toLowerCase().indexOf("_brand"),
                brand = queryString.substring(brandNameStart, brandNameEnd).toLowerCase();

            brand = "#" + brand;

            var isAllBrandsSelected = brand.toLocaleLowerCase().includes("all");
            var isOtherBrandsSelected = brand.toLocaleLowerCase().includes("more");
            if (isOtherBrandsSelected) brand = `#${otherBrandsFieldId}`;
            var target_brand = isAllBrandsSelected ? $("#filter-controls") :
                $(`[data-category=${!isOtherBrandsSelected ? brand.replace("#", "") : otherBrandsFieldId}]`)
            return target_brand;
        }
        return "";
    }
    if (filterUrl.indexOf("filter") > 0) {
        console.log(filterScrollToTarget())
        $('html, body').animate({
            scrollTop: filterScrollToTarget().offset().top - 80
        }, 500);
    }

})
$('document').ready(function () {
    if ($(window).width() < 768) {
        resizeTimeoutFn = setTimeout(function () {
            $('.transform-slick-slide-js.slick-initialized:not(.full-width-slide)').find('.slick-track').addClass('margin-n30-left');
        }, 200);

    }

    forceSkipSameHeightMobile();
    $('.carousel-navigator-centered').each(function (e) {
        var $this = $(this);
        if ($this.children().length > 1) {
            if ($this.children().length < 3) $this.addClass('two-slides');
            $this.slick();
        }
    });

    var locationURL = $(encodeURI(location)).attr('href');
    if (locationURL.indexOf("#clone") > -1) {
        $('html, body').animate({ scrollTop: $(document).scrollTop() - 50 }, 200);
    }
    var filterUrl = window.location.search;
    if (filterUrl.indexOf("filter") > 0) {
        var divId = encodeURI(window.location.search.substring(1).split("=")[1]);
        $('html, body').animate({
            scrollTop: $("#" + divId).offset().top - 50
        }, 200);
    }

    $('[class*="tooltip-"]').tooltip();

    // for video player button
    $('.video-control-button').on('click', function (e) {
        const $this = $(this);
        const player = $this.parents('div').find('video');
        let currentLabel = $this.attr('aria-label');
        let spanBg = $this.find('span:not(.sr-only)');
        let currentSpanClass = spanBg.attr('class');
        let pressedStatus = $this.data('pressed') == true ? false : true;

        // video action
        currentSpanClass == 'play-bg' ? player.get(0).play() : player.get(0).pause();

        // html manipulation
        $this.attr('aria-label', currentLabel == $this.data('play-label') ? $this.data('pause-label') : $this.data('play-label'));
        $this.data('pressed', pressedStatus).attr('data-pressed', pressedStatus);
        spanBg.removeClass(currentSpanClass).addClass(currentSpanClass === 'play-bg' ? 'pause-bg' : 'play-bg');
    });
});

// Start HomePage Slider
//var ele = document.getElementById("slider-rotating-carousel-component");
let ele = document.querySelectorAll('.slider-rotating-carousel-component');

if (ele.length != 0) {

    (function (bell, $) {

        $.widget("rsx.BannerSliderCarousel", {
            version: "0.5",
            widgetEventPrefix: "BannerSliderCarousel",
            links: [],
            options: {
                slidesContainer: '',
                pauseOnFocus: true,
                pauseOnHover: true,
                infinite: true,
                autoplay: true,
                autoplaySpeedMobile: 10000,
                autoplaySpeed: 6000, //default speed for all carousel slides
                dots: true,
                arrows: false,
                customPaging: function (slider, i) {
                    return '<button class="slider-rotating-carousel-button" type="button">' + (i + 1) + '</button>';
                },
                dotsClass: 'slider-rotating-carousel-buttons',
                initialSlide: 0,
                omnitureShow_s_oAPT: '347-0-0',
                omnitureClick_s_oAPT: '348-0-0',
                track_omniture: false,
                adobeTargetCssClass: "at-element-marker"
            },

            _create: function () {
                var self, that;
                self = that = this;
                var canonical = $('link[rel=\'canonical\']').attr("href").split('/').pop(); // added element
                var alternate = $('link[rel=\'alternate\']').attr("href").split('/').pop(); // added element

                var pathArray = ['/', '/Accueil', '/Mobility', '/Mobilite', '/Mobility/', '/Mobilite/'];
                for (i = 0; i < pathArray.length; i++) {
                    if (window.location.pathname === pathArray[i]) {
                        self.options.track_omniture = true;
                        break;
                    }
                }
                //in order to save the tab state on browser back button, it saves tab index in this hidden input

                var progressInterval,
                    percentComplete,
                    progressStep = 50,
                    progressIndicatorLength,
                    progressIndicatorUnit,
                    progressIndicatorTotal,
                    progressIndicatorTotalRounded,
                    overrideMouseOverOut = false;

                this.autoplaySpeed = that.options.autoplaySpeed;

                if (navigator.userAgent.match(/Android/i)
                    || navigator.userAgent.match(/webOS/i)
                    || navigator.userAgent.match(/iPhone/i)
                    || navigator.userAgent.match(/iPad/i)
                    || navigator.userAgent.match(/iPod/i)
                    || navigator.userAgent.match(/BlackBerry/i)
                    || navigator.userAgent.match(/Windows Phone/i)) {
                    this.autoplaySpeed = that.options.autoplaySpeedMobile;
                }

                var playButtonLabel = "Pause rotation of banners";
                var pauseButtonLabel = "Resume rotation of banners";

                if (!alternate && !canonical)
                    canonical = "Accueil";
                this.$window = $(window);
                this.$slidesContainer = this.element.find(self.options.slidesContainer);
                this.$slides = this.$slidesContainer.children();
                this.$pauseButton = this.element.find(".slider-rotating-carousel-pause");

                var playButtonLabel = this.$pauseButton.data("play-label");
                var pauseButtonLabel = this.$pauseButton.data("pause-label");
                // this.$accessibilityLabel = this.$pauseButton.find(".sr-only");
                this.$progressIndicator = this.$pauseButton.find(".slider-rotating-carousel-progress > circle");

                progressIndicatorLength = typeof SVGElement.prototype.getTotalLength !== "undefined" ? Math.round(this.$progressIndicator.get(0).getTotalLength()) : 125;
                progressIndicatorUnit = progressIndicatorLength / 100;

                this.$progressIndicator.css({ "stroke-dasharray": progressIndicatorLength });

                this.pausedThroughButton = false;
                this.rotate = false;
                this.hasFocus = false;
                this.hasHover = false;

                resumeRotation();

                // this.$accessibilityLabel.text(playButtonLabel);

                function pauseRotation() {
                    if (self.rotate) {
                        if (Math.abs(progressIndicatorTotalRounded) < 1) {
                            self.$progressIndicator.addClass("slider-rotating-carousel-progress_initial");
                        }
                        self.$pauseButton.attr('aria-label', playButtonLabel);
                        self.rotate = false;
                    }
                }

                function resumeRotation() {
                    if (!self.rotate) {
                        // if user manually paused the slideshow through the button, do not restart it automatically
                        if (!self.pausedThroughButton && !self.hasFocus && !self.hasHover) {
                            self.$progressIndicator.removeClass("slider-rotating-carousel-progress_initial");
                            self.$pauseButton.attr('aria-label', pauseButtonLabel);
                            self.rotate = true;
                        }
                    }
                }

                this.$pauseButton.on("click tap", function () {

                    var isPaused = self.$pauseButton.attr("data-pressed") === "true";

                    if (typeof s_oTrackPage === "function") { // && isHomePage === "True"
                        s_oTrackPage({ s_oAPT: "647-0-0", s_oBTN: self.$pauseButton.attr('aria-label') });
                    }

                    if (isPaused) {
                        self.pausedThroughButton = false;
                        resumeRotation();
                        self.$pauseButton.attr("data-pressed", false);
                    } else {
                        self.pausedThroughButton = true;
                        pauseRotation();
                        self.$pauseButton.attr("data-pressed", true);
                    }
                });

                this.$slidesContainer.on("mouseenter", function () {

                    if (!!('ontouchstart' in window) === false) {

                        if (!overrideMouseOverOut) {
                            self.hasHover = true;
                            pauseRotation();
                        }
                    }
                }).on("mouseleave", function () {

                    if (!overrideMouseOverOut) {
                        self.hasHover = false;
                        resumeRotation();
                    }
                });

                $(document).on("visibilitychange", function () {
                    if (document.visibilityState === "hidden") {
                        pauseRotation();
                    } else {
                        resumeRotation();
                    }
                });

                var startAutoplay = function () {

                    percentComplete = 0;
                    progressIndicatorTotal = 0;
                    updateProgressIndicator();
                    progressInterval = setInterval(progressIntervalHandler, progressStep);
                };

                var updateProgressIndicator = function () {
                    percentComplete += progressStep / that.autoplaySpeed * 100;
                    progressIndicatorTotal = percentComplete * progressIndicatorUnit * -1 + 1;
                    progressIndicatorTotalRounded = Math.round(progressIndicatorTotal * 10) / 10;
                    self.$progressIndicator.css({ "stroke-dashoffset": progressIndicatorTotalRounded });
                };

                var progressIntervalHandler = function () {

                    if (self.rotate && !self.pausedThroughButton && self.$pauseButton.attr("data-pressed") === "false") {

                        updateProgressIndicator();

                        if (percentComplete >= 100) {
                            self.$slidesContainer.slick('slickNext');
                            resetAutoplayProgress();
                        }
                    }
                };

                var resetAutoplayProgress = function () {
                    clearInterval(progressInterval);
                    startAutoplay();
                };
                this.$slidesContainer.focusin(function () {
                    if (!!('ontouchstart' in window) === false) {
                        if (!overrideMouseOverOut) {
                            that.hasFocus = true;
                            pauseRotation();

                        }
                    }
                }).focusout(function () {
                    if (!overrideMouseOverOut) {
                        that.hasFocus = false;
                        resumeRotation();
                    }
                });

                this.$slider = this.$slidesContainer
                    .on("init", function (event, self) {

                        self.$slider.removeClass("slider-rotating-carousel-height");
                        self.options.initialSlide = self.currentSlide;
                        if (that.options.autoplay) {
                            startAutoplay();
                        }
                        $(this).find('.slider-rotating-carousel-button')
                            .focusin(function () {
                                if (!overrideMouseOverOut) {
                                    pauseRotation();

                                }
                            }).focusout(function () {
                                if (!overrideMouseOverOut) {
                                    resumeRotation();
                                }
                            }).on("keyup", function (e) {

                                if (e.type === "keyup" && (e.which === 37 || e.which === 39)) {
                                    overrideMouseOverOut = true;
                                    $(this).closest('.slider-rotating-carousel-buttons').find('.slick-active .slider-rotating-carousel-button').focus();
                                    progressIndicatorTotalRounded = 0;
                                    pauseRotation();
                                }
                            });

                        $("#slider-rotating-carousel-component .slider-rotating-carousel-button")
                            .on("click tap", function () {
                                if (typeof s_oTrackPage === "function") { // && isHomePage === "True"
                                    s_oTrackPage({ s_oAPT: "647-0-0", s_oBTN: $(this).attr("aria-label") });
                                }
                            });
                        that._syncAdobeTarget(self);
                        $(this).find('.slick-slide.slick-cloned').removeAttr('id');
                        that._setAccessibleDotsLabel(that.$slidesContainer);
                    }).slick({
                        pauseOnFocus: self.options.pauseOnFocus,
                        pauseOnHover: self.options.pauseOnHover,
                        slidesToShow: 1,
                        slidesToScroll: 1,
                        infinite: self.options.infinite,
                        adaptiveHeight: self.options.adaptiveHeight,
                        arrows: false,
                        useTransform: false,
                        autoplay: false, //relies on custom implementation
                        waitForAnimate: false,
                        dots: self.options.dots,
                        customPaging: self.options.customPaging,
                        dotsClass: self.options.dotsClass
                    }).on("afterChange", function (event, slick, currentSlide, nextSlide) {
                        that._resetCTARedirectOnTestEnvironment();
                        that._track(currentSlide);
                        slick.$slider.find('.slick-slide.slick-cloned').removeAttr('id');
                        that._setAccessibleDotsLabel(that.$slidesContainer);
                    }).on("beforeChange", function (event, slick, currentSlide, nextSlide) {
                        that._resetCTARedirectOnTestEnvironment();
                        resetAutoplayProgress();
                    });
                that._syncAdobeTarget(self);
                var CarouselImpressions = setInterval(function () {
                    if (typeof s_oTrackPage === "function" || typeof s_track === "function") {
                        that._track(self.options.initialSlide);
                        clearInterval(CarouselImpressions);
                    }
                }, 100);
            },

            _trackOmniture: function (code, id) {
                if (typeof s_oTrackPage === "function") {
                    s_oTrackPage({ s_oAPT: code, s_oBID: id });
                } else if (typeof s_track === "function") {
                    s_track({ s_oAPT: code, s_oBID: id });
                }
            },

            _track: function (currentSlide) {
                if (this.options.track_omniture && this.links[currentSlide] === undefined) {
                    var banner = $(this.$slides[currentSlide]).find(".js-omni-banner");
                    var omnitureVal = $(banner).data("omni-s_obid");
                    this._trackOmniture(this.options.omnitureShow_s_oAPT, omnitureVal);
                    this.links[currentSlide] = true;
                }
            },
            /**
             * synchronize banner with Adobe to prevent flickering issue or banner copy not complete
             *
             * @param {any} self the item to pass
             */
            _syncAdobeTarget: function (self) {
                if (this.options.infinite) {
                    let leftClonedSlide = self.$slider.find(".slick-slide.slick-cloned").first();
                    let rightClonedSlide = self.$slider.find(".slick-slide.slick-cloned").last();
                    let allSlides = self.$slider.find(".slick-slide");
                    var firstSlide, lastSlide = "";
                    /*mapping first slide and last slide with their cloned slides accordingly*/
                    $.each(allSlides, function (index, $slide) {
                        if ($(this).data("slickIndex") === leftClonedSlide.data("slickIndex") + 1) {
                            firstSlide = $(this);
                        }
                        if ($(this).data("slickIndex") === rightClonedSlide.data("slickIndex") - 1) {
                            lastSlide = $(this);
                        }
                    });
                    /*find adobe target slider and replace by order*/
                    if (lastSlide && lastSlide.find("div").hasClass(this.options.adobeTargetCssClass)) {
                        leftClonedSlide.html(lastSlide.html());
                    }
                    if (firstSlide && firstSlide.find("div").hasClass(this.options.adobeTargetCssClass)) {
                        rightClonedSlide.html(firstSlide.html());
                    }
                    if (leftClonedSlide && leftClonedSlide.find("div").hasClass(this.options.adobeTargetCssClass)) {
                        lastSlide.html(leftClonedSlide.html());
                    }
                    if (rightClonedSlide && rightClonedSlide.find("div").hasClass(this.options.adobeTargetCssClass)) {
                        firstSlide.html(rightClonedSlide.html());
                    }
                }
            },
            _resetCTARedirectOnTestEnvironment: function () {
                let isProdUrl = function () {
                    let currentUrl = window.location.hostname;
                    return currentUrl.indexOf("www.bell.ca") > -1 ? true : false;
                };
                if (!isProdUrl()) {
                    $("div[id*='carousel-banner-id-']").each(function () {
                        $(this).find(".js-omni-button").click(function () {
                            let targetUrl = $(this).attr("href");
                            window.location.href = targetUrl;
                        });
                    });
                }
            },
            _setAccessibleDotsLabel: function (slidesContainer) {
                setTimeout(function () {
                    let tabButtons = slidesContainer.find('.slider-rotating-carousel-button');
                    tabButtons.each(function () {
                        let $this = $(this);
                        let currentLabel = $this.attr('aria-label');
                        let slideHeading = $('#' + $this.attr('aria-controls')).find('h2').text().trim();
                        if (slideHeading) {
                            $this.attr('aria-label', currentLabel + ' property page ' + slideHeading);
                        }
                    });
                });
            }
        });
    })({}, jQuery);

    //$('#slider-rotating-carousel-component').BannerSliderCarousel({
    //    'slidesContainer': ".slider-rotating-carousel",
    //    'autoplay-speed': "6000",
    //    'autoplay-speed-mobile': "6000",
    //    'class': "init"
    //});
    $('.slider-rotating-carousel-component').each(function () {

        const $this = $(this);
        const slidesContainer = $this.find(".slider-rotating-carousel");
        const slides = slidesContainer.children();

        if (slides.length === 1) {
            $this.find(".slider-rotating-carousel-pause").hide();
            slidesContainer.css({
                "opacity": "1",
                "visibility": "visible",
                "max-height": "initial",
                "text-align": "center",
                "overflow": "hidden"
            });
        } else {
            $this.BannerSliderCarousel({
                'slidesContainer': ".slider-rotating-carousel",
                'autoplay-speed': "6000",
                'autoplay-speed-mobile': "6000",
                'class': "init"
            });
        }
    });
    $('.slider-rotating-carousel-component').on('beforeChange', function (e, slick, currentSlide, nextSlide) {
        const next = $(this).find('.slick-slide')[nextSlide + 1];
        const height = next.querySelector('div').clientHeight;
        $(this).find('.slick-list').css('height', height);
    });
}

// End HomePage Slider

// Accessibility fix for banner slider. Add aria-labeledby on each slide

$('.slider-rotating-carousel').each(function () {
    $(this).find('.slick-slide[role="tabpanel"]').each(function (index) {
        $(this).attr('aria-labelledby', 'slick-slide-control0' + index);
    });
});

// Start same-height trigger on modal
$('.same-height-modal-js').on('shown.bs.modal', function () {
    $(this).find('.same-height').each(function () {
        processSameHeightElements($(this));
    });
});


//Start Radio Button with border
$('.graphical_ctrl input').change(function () {
    var $this = $(this);
    if ($this.attr('type') == "radio") {
        //Remove border to radio button
        $this.parent().closest('[aria-labelledby]').find('.radio-container').removeClass('checked-border');

        if ($this.prop('checked')) {
            //Add border to radio button 
            $this.closest('.radio-container').addClass('checked-border');
        }
    }
});

$('.graphical_ctrl input').focus(function () {
    //Add focus class in radio button container
    $(this).closest('.radio-container').addClass('focused-element');
});
$('.graphical_ctrl input').blur(function () {
    //Remove focus class in radio button container
    $(this).closest('.radio-container').removeClass('focused-element');
});
$('.radio-container').click(function (e) {
    var $this = $(this);
    $this.find('.graphical_ctrl input').prop('checked', true);
    $this.find('.graphical_ctrl input').trigger('change');
    $this.find('.graphical_ctrl input').focus();
});

//Tab anchor same-height function
$('.same-height-tab-js').on("click", function () {
    $(".same-height-tabpanel-js").find('.same-height').each(function () {
        processSameHeightElements($(this));
    });
});

$(document).ready(function () {
    $(window).on('load', function () {
        processSameHeightElements();
    });

    //checked if there are checked properties in DOM
    if ($('input[type="radio"][name="radioDevices"]:checked').length > 0) {
        let targetValue = $('input[type="radio"][name="radioDevices"]:checked').attr('aria-controls');
        //find targetValue and add block class to show the content
        $("section").find("#" + targetValue).addClass("block");
        //add checked border class
        $('.radio-container input[type="radio"][name="radioDevices"]:checked').closest('.radio-container').addClass('checked-border');
    }

    // Radio button click event
    $('.radio-container input[type="radio"][name="radioDevices"]').change(function () {
        // Get value of clicked radio button
        inputValue = $(this).attr('aria-controls');
        //checked radio btn if checked  
        $(this).prop('checked', true);
        // Get the DOM id aria-controls
        let targetContainer = $('div[id="' + inputValue + '"]');
        // Hide all other that has no id
        $('.display-radio-container').not(targetContainer).removeClass("block");
        // Show targeted element
        $(targetContainer).addClass("block");
        processSameHeightElements();
    });
});
//End Radio Button with border


//start script for youtube iframe api - used for slick video with youtube player on top -- see mobility connected car page
//not working using document.ready
const slickVideoContainers = document.querySelectorAll('[data-slick-video="main-container"]');
const videoModal = document.querySelector('#video-modal');
window.videoPlayers = [];
window.initializeVideoPlayers = function () {
    for (var i = 0; i < slickVideoContainers.length; i++) {
        slickVideo(slickVideoContainers[i], i);
    }
}
if (slickVideoContainers.length > 0 || videoModal) {
    youTubeIframeApi();
}
function youTubeIframeApi() {
    var tag = document.createElement('script');
    var firstScriptTag = document.getElementsByTagName('script')[0];
    tag.src = 'https://www.youtube.com/iframe_api';
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    window.onYouTubeIframeAPIReady = function () {
        initializeVideoPlayers();
        videoModal ? modalVideoPlayer.initialize() : '';
    }
}
function createVideoPlayer(defaultVideo, index, videoPlayerContainer) {
    window.videoPlayers[index] = new YT.Player(videoPlayerContainer, {
        videoId: defaultVideo,
    });
}

// start video modal
// this initializes upon loading youtube iframe api
const modalVideoPlayer = {
    initialize: function () {
        const modal = $('#video-modal');
        const iframe = document.querySelector('#video-modal iframe');
        const videoPlayer = new YT.Player(iframe);
        const defaultSource = 'https://www.youtube.com/embed/';

        // set modal accessibility fixes
        modal.find('[data-dismiss="modal"]').attr('role', 'button').addClass('close');
        modal.attr('aria-label', 'Video Player');
        modal.find('.bce-modal-header').prepend('<h2 class="sr-only">Video Player</h2>');

        // configure iframe
        iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
        iframe.setAttribute('src', defaultSource);

        // set iframe source and play
        $(document).on('click', '[data-toggle="video-modal"]', function (e) {
            e.preventDefault();
            $("#video-modal").modal('show');
            const $this = $(this);
            const videoId = $this.data('video-id');
            const playerSettings = $this.data('video-settings');
            iframe.setAttribute('src', defaultSource + videoId + playerSettings);
            iframe.addEventListener('load', iframeEvent);
        });
        //upon closing modal, remove iframe event handler to avoid redundancies and set the source back to default
        $(document).on('hidden.bs.modal', '#video-modal', function () {
            iframe.removeEventListener('load', iframeEvent);
            iframe.setAttribute('src', defaultSource);
        })
        //iframe event callback
        const iframeEvent = function () {
            try {
                videoPlayer.playVideo();
            }
            catch (error) { }
        }

        // add a focusable span that serves as the last focusable element inside the modal. When this receives focus, the close button will quickly and automatically get the focus instead.
        // The purpose of this is to trap the focus inside the video modal. This is just a remedy because we can't access the focused element inside the youtube iframe.
        modal.find('.modal-body').append('<span tabindex="0" class="video-modal-focus-trapper"></span>');

        this.setTabbing();
    },
    // set tabbing inside the modal to trap focus
    setTabbing: function () {
        const videoModal = $('#video-modal');
        videoModal.on('keydown', function (e) {
            const tabPressed = e.key === 'Tab' || e.keyCode === 9;
            // proceed only to the remaining script if tab key is pressed
            if (!tabPressed) {
                return;
            }
            // if tab + shift key is pressed, set focus to iframe to prevent focus going outside the page.
            if (e.shiftKey) {
                $(this).find('iframe').focus();
            }
        });
        // set focus to close button when it reaches the last focusable element
        videoModal.on('focus', '.video-modal-focus-trapper', function (e) {
            videoModal.find('a.close').focus();
        });
    }
}
// end video modal


//start script for connected car slick video -- applied in mobility connected car page


window.slickVideo = function (slickVideoContainer, index) {
    var defaultVideo = slickVideoContainer.querySelector('.default-video').dataset.videoId;
    var videoPlayerContainer = slickVideoContainer.querySelector('[data-slick-video="video-player-container"]');
    createVideoPlayer(defaultVideo, index, videoPlayerContainer)
    //pause video when navigating through video items
    $(slickVideoContainer).on('click', '.play-btn-container', function (e) {
        $(this).closest('.video-switch').trigger('click');
    });

    //pause video when navigating through video items
    $(slickVideoContainer).on('focus', '.play-btn-container', function (e) {
        window.videoPlayers[index].pauseVideo();
    });

    //respond to space and enter keys on the keyboard for accessibility
    $(slickVideoContainer).on('keypress', '.play-btn-container', function (e) {
        e.preventDefault();
        let key = e.keyCode;
        if (key == 32 || key == 13) {
            $(this).closest('.video-switch').trigger('click');
        }
    })
    // on video item click event
    $(slickVideoContainer).on('click', '.video-switch', function () {

        //variables
        let youtube = 'https://www.youtube.com/embed/';
        let playerSettings = '?rel=0&modestbranding=1&showinfo=0&enablejsapi=1';
        let videoId = $(this).data('video-id');
        let videoPlayer = slickVideoContainer.querySelector('[data-slick-video="video-player-container"]');
        let image = $(this).find('img');
        //check video status. if playing then stop, if not then play
        if (image.hasClass('playing')) {
            window.videoPlayers[index].pauseVideo();
            image.removeClass('playing');
        }
        else {
            // set youtube source
            videoPlayer.src = youtube + videoId + playerSettings;
            videoPlayer.addEventListener('load', function () {
                window.videoPlayers[index].playVideo();
            });
            // mark item as active
            $('.car-video-slider img').removeClass('active playing');
            $(this).find('img').addClass('active playing');
            $('.video-title').removeClass('surtitle-black');
            $(this).find('.video-title').addClass('surtitle-black');
        }
    });
}

//end script for connected car slick video

//START selectDestination Funtion
function destinationAddOnTabsEventListener() {
    if ($('#selectDestination').length > 0) {
        $('#selectDestination').on('change', function () {
            var $el = $(this),
                siblingEl = $el.closest('.destination-selection').next();
            siblingEl.find('#no-value').removeClass('d-block');
            siblingEl.children().hide();
            siblingEl.find('#' + $el.val()).show();
            processSameHeightElements();
        });
    }

}
destinationAddOnTabsEventListener();
//END selectDestination Funtion

function initializeScrollableTable() {
    $('.scrollableContainer-js').on('scroll', function () {
        var $this = $(this);
        var scrollPos = $this.scrollLeft();
        var width = $this.width();
        var scrollWidth = $this.get(0).scrollWidth;
        var container = $this.closest('[class^=scrollableContainerShadow]');
        if (scrollWidth > $this.get(0).clientWidth + 1) {
            if (scrollPos === 0) {
                container.removeClass('left');
            } else {
                container.addClass('left');
            }
            if (scrollPos + width === scrollWidth) {
                container.removeClass('right');
            } else {
                container.addClass('right');
            }
        }
        else {
            $this.closest('[class^=scrollableContainerShadow]').removeClass('left').removeClass('right');
        }
    });
    $(window).resize(function () {
        if (window.matchMedia('(max-width: 991px)').matches) {
            //$('[class^=scrollableContainerShadow]').addClass('right');
            $('.scrollableContainer-js').trigger('scroll');
        }
        else {
            $('.same-height-modal [class^=scrollableContainerShadow]').removeClass('left').removeClass('right');
        }
    });
}

initializeScrollableTable();

//More or Less Accordion Function in mobile view
var displayAccordionMoreAndLess = {
    init: function () {
        var self = this;
        self.addEventListener();
        self.addAriaHidden();
        self.onMobileResize();
    },
    addEventListener: function () {
        $('.expander-description-control').on('click', function (e) {
            var $this = $(this);

            if ($this.attr('aria-expanded') == 'false') {
                $this.prev().css('max-height', '10000px').attr('aria-hidden', 'false');
                $this.attr('aria-expanded', 'true');

            }
            else {
                $this.prev().removeAttr('style').attr('aria-hidden', 'true');
                $this.attr('aria-expanded', 'false');
            }
            e.stopImmediatePropagation();

        });
    },
    onMobileResize: function () {
        var self = this;
        $(window).resize(function () {
            self.addAriaHidden();
        });
    },
    addAriaHidden: function () {
        if (window.matchMedia('(max-width: 767px)').matches) {
            if ($('.expander-description[aria-hidden]').length <= 0) {
                $('.expander-description').attr('aria-hidden', 'true');
            }
        }
        else {
            $('.expander-description').removeAttr('style').removeAttr('aria-hidden');
        }
    }

};
if ($('.expander-description-control').length > 0) {
    displayAccordionMoreAndLess.init();
}

//Window resize function for slick -- this is to make the slick slider responsive

$(function () {
    let isUnslick = function (screen, breakpoints) {
        let unslicked = false;
        breakpoints.every(function (breakpoint) {
            if (breakpoint.breakpoint == screen && breakpoint.settings == 'unslick') {
                unslicked = true
                return false;
            }
            else {
                return true;
            }
        });
        return unslicked;
    };
    $(window).resize(function () {
        let responsiveSlickSlider = $('.responsive-slick-slider').not('.slick-initialized');
        let screen = $(window).width() - 1;

        responsiveSlickSlider.each(function () {
            let slick = $(this);
            let breakpoints = $(this).data('slick').responsive;
            if (screen >= 991) {
                if (!isUnslick(991, breakpoints)) {
                    slick.slick();
                }
            }
            if (screen >= 767 && screen < 991) {
                if (!isUnslick(767, breakpoints)) {
                    slick.slick();
                }
            }
            if (screen >= 300 && screen < 767) {
                if (!isUnslick(300, breakpoints)) {
                    slick.slick();
                }
            }
        })
    });
});

// End Window resize function for slick


$(function () {
    // This is to automatically update expand / collapse icon on single expand accordion. Upon clicking other accordion item, this will update the currently active accordion's icon
    $(document).on('hide.bs.collapse', '.single-expand', function (e) {
        $(this).closest('.accordion-wrap').find('.icon').removeClass('icon-small_icon_collapse').addClass('icon-small_icon_expand');
    });
    $(document).on('hide.bs.collapse', '[data-expand-type="single"]', function (e) {
        // for all screen sizes
        let expandIcon = $(this).closest('.accordion-wrap').find('.collapse-trigger').data('icon-expand');
        let collapseIcon = $(this).closest('.accordion-wrap').find('.collapse-trigger').data('icon-collapse');
        $(this).closest('.accordion-wrap').find('.icon:not([data-icon="xs"])').first().removeClass(collapseIcon).addClass(expandIcon);
        //for custom mobile icon
        let expandIconXs = $(this).closest('.accordion-wrap').find('.collapse-trigger').data('icon-expand-xs');
        let collapseIconXs = $(this).closest('.accordion-wrap').find('.collapse-trigger').data('icon-collapse-xs');
        if (expandIconXs && collapseIconXs) {
            $(this).closest('.accordion-wrap').find('[data-icon="xs"]').addClass(expandIconXs).removeClass(collapseIconXs);
        }
    });
    let windowSize = $(window).width();
    $(window).resize(function () {
        windowSize = $(window).width();
    });
    // Accordion custom mobile icon
    $('.collapse-trigger').on('click', function (e) {
        if (windowSize < 760) {
            let accordion = $(this);
            let expandIconXs = $(this).data('icon-expand-xs');
            let collapseIconXs = $(this).data('icon-collapse-xs');
            if (expandIconXs && collapseIconXs) {
                if (accordion.attr('aria-expanded') !== "true") {
                    accordion.closest('.accordion-wrap').find('.icon[data-icon="xs"]').addClass(collapseIconXs).removeClass(expandIconXs);
                }
                else {
                    accordion.closest('.accordion-wrap').find('.icon[data-icon="xs"]').removeClass(collapseIconXs).addClass(expandIconXs);
                }
            }
        }
    });
});

//refresh slick slider inside accordion upon expand
$(document).on('show.bs.collapse', '.collapse-accordion-accessible-toggle', function (e) {
    $(this).find('.responsive-slick-slider.slick-initialized').slick('refresh');
});


// Switch between dynamic title of accordion
$(document).on('show.bs.collapse hide.bs.collapse', '[data-title-type="dynamic"]', function (e) {
    var title = $(this).closest('.accordion-wrap').find('.accordion-title');
    var toggleColor = title.closest('.toggle-title-color');

    var expandTitle = title.data('expand-title');
    var collapseTitle = title.data('collapse-title');
    var ariaLabel = $(this).closest('.accordion-wrap').find('a.collapse-trigger span.sr-only span').html();
    var screenReader = $(this).closest('.accordion-wrap').find('a.collapse-trigger span.sr-only');

    if (toggleColor.hasClass("toggle-text-grey")) {
        if (e.type === 'hide') {
            title.html(expandTitle);
            if (toggleColor.length) {
                title.toggleClass('txtDarkGrey');
                toggleColor.toggleClass('margin-neg-t-50 margin-neg-55-t-xs');
            }
            // empty the sr
            screenReader.html('');
            // add the text
            screenReader.prepend(expandTitle + ' <span>' + ariaLabel + '</span>');
        }
        else if (e.type === 'show') {
            title.html(collapseTitle);
            if (toggleColor.length) {
                title.toggleClass('txtDarkGrey');
                toggleColor.toggleClass('margin-neg-t-50 margin-neg-55-t-xs');
            }
            // empty the sr
            screenReader.html('');
            // add the text
            screenReader.prepend(collapseTitle + ' <span>' + ariaLabel + '</span>');
        }
    } else {
        if (e.type === 'hide') {
            title.html(expandTitle);
            if (toggleColor.length) {
                title.toggleClass('txtWhite');
                toggleColor.toggleClass('margin-neg-t-50 margin-neg-55-t-xs');
            }
            // empty the sr
            screenReader.html('');
            // add the text
            screenReader.prepend(expandTitle + ' <span>' + ariaLabel + '</span>');
        }
        else if (e.type === 'show') {
            title.html(collapseTitle);
            if (toggleColor.length) {
                title.toggleClass('txtWhite');
                toggleColor.toggleClass('margin-neg-t-50 margin-neg-55-t-xs');
            }
            // empty the sr
            screenReader.html('');
            // add the text
            screenReader.prepend(collapseTitle + ' <span>' + ariaLabel + '</span>');
        }
    }
});
$('.clickable-card').on('click', '[data-toggle="modal"]', function (e) {
    e.preventDefault();
});
$('.clickable-card').on('click', '.tooltip-interactive', function (e) {
    e.preventDefault();
});
$('.clickable-card').on('click', '.tooltip-static', function (e) {
    e.preventDefault();
});

// Tooltip modal keypress on mobile view
$(function () {
    var keypressTooltipModal = $('.tooltip-interactive[data-toggle="tooltip"]').siblings($('[data-toggle="modal"]'));
    var keypressTooltipModalStatic = $('.tooltip-static[data-toggle="tooltip"]').siblings($('[data-toggle="modal"]'));
    keypressTooltipModal.on('keypress', function (e) {
        if (e.keyCode == 13) {
            $(this).trigger('click');
        }
    });
    keypressTooltipModalStatic.on('keypress', function (e) {
        if (e.keyCode == 13) {
            $(this).trigger('click');
        }
    });
});

// Side Nav Start
var FloatingSubNav = {
    isMobile: false,
    activeSubNavIndex: 1,
    magicLine: '#magic-line',
    init: function (windowScroll) {

        this.addMagicLine('.subnavgroup');

        // Check if will desktop or not then if desktop apply the floating scroll function
        if (FloatingSubNav.checkIfNotMobile() === false) {
            FloatingSubNav.checkScrollPos(windowScroll);
            $('.subnav-scroll').removeClass('d-none');
            FloatingSubNav.checkScrollableActiveSection(windowScroll);
        } else {
            $('.subnav-scroll').removeClass('d-none');
            FloatingSubNav.positionToRelative('.subnav-scroll');
        }

        FloatingSubNav.bindEvents();

    },

    bindEvents: function () {
        var that = this;

        $('.subnavgroup li a').on('click', function () {
            var sectionToScroll = '#' + $(this).parent().attr('data-section');
            if (typeof scrollOmnitureBegin === 'function') {
                scrollOmnitureBegin();
            }
            that.animateToSection(sectionToScroll);
        });
    },

    addMagicLine: function (element) {
        $(element).append("<li class='listStyleNone' id='magic-line'></li>");

    },

    checkScrollPos: function (scrollPos) {
        scrollPos += 200;
        // Define variables
        var spaceBefore = 135; // space before scrollable area

        //var spaceAfter = 50; // space after scrollable area
        var scrollableArea = '.scrollable-area';
        var elementToPositon = '.subnav-scroll';

        //var endPosElement = 'footer';
        var totalSpacesBeforeScrollableArea = this.getScrollableAreaTopValue(scrollableArea, spaceBefore);
        //console.log(totalSpacesBeforeScrollableArea);

        // pass scrollable area element instead of always looking for the footer to support cases wherein there's content between the scrollable area and the footer
        // we don't need the hardcoded spaceAfter value anymore
        if (scrollPos >= totalSpacesBeforeScrollableArea && (scrollPos - 200) < this.getScrollableAreaEndValue(elementToPositon, scrollableArea, spaceBefore)) {
            this.positionToFix(elementToPositon, spaceBefore, $('.subnav-scroll').width());
        } else if (scrollPos >= this.getScrollableAreaEndValue(elementToPositon, scrollableArea, spaceBefore)) {
            this.positionToAbsolute(elementToPositon);
        } else {
            this.positionToRelative(elementToPositon);
        }

    },

    checkScrollableActiveSection: function (scrollPos) {
        var that = this;
        var scrollableContents = '.scrollable-contents';
        var subNav = '.subnav-scroll';
        var scrollableContentsLength = $(scrollableContents).find('> div').length;
        var currentIndex = 1;
        scrollPos = Math.ceil(scrollPos) + 100;

        //if (scrollPos === $(window).height()) {
        if ($(window).scrollTop() + $(window).height() === $(document).height()) {
            currentIndex = scrollableContentsLength;
        } else {
            for (var i = 1; i < scrollableContentsLength + 1; i++) {
                if (i === 1) {
                    if (scrollPos < FloatingSubNav.getSectionTopValue(scrollableContents, 1)) {
                        currentIndex = 1;
                        break;
                    }
                } else if (scrollPos >= FloatingSubNav.getSectionTopValue(scrollableContents, i - 1) && scrollPos < FloatingSubNav.getSectionTopValue(scrollableContents, i)) {
                    currentIndex = i;
                    break;
                } else if (scrollPos >= FloatingSubNav.getSectionTopValue(scrollableContents, scrollableContentsLength)) {
                    currentIndex = scrollableContentsLength;
                    break;
                }
            }
        }
        this.activeSubNavIndex = currentIndex;
        this.checkActiveSubNav(this.activeSubNavIndex, subNav);
    },

    getSectionTopValue: function (scrollableSection, ctr) {
        /*var addedViewSpace = 150;
        if ($(scrollableSection).length > 0) {
            return $(scrollableSection).find("#scrollable-content-" + ctr).offset().top + addedViewSpace;
        }*/

        var scrollables = $(scrollableSection), scrollable;
        if (scrollables.length > 0) {
            scrollable = scrollables.find("#scrollable-content-" + ctr);
            return Math.floor(scrollable.offset().top + scrollable.height());
        }
    },

    checkActiveSubNav: function (activeIndex, subNav) {
        $(subNav).find('.subnavgroup li').removeClass('subnav_active');
        $(subNav).find('.subnavgroup li:nth-child(' + activeIndex + ')').addClass('subnav_active');
        if (typeof scrollOmniture === 'function') {
            scrollOmniture($(subNav).find('.subnavgroup li:nth-child(' + activeIndex + ')'), activeIndex);
        }
        this.animateMagicLine(activeIndex, subNav);
    },

    animateMagicLine: function (activeIndex, subNav) {
        var that = this;
        if ($(subNav).length > 0) {
            var target = $(subNav).find('.subnavgroup li:nth-child(' + activeIndex + ') a');
            var topPos = target.position().top;
            var newHeight = target.parent().height();
        }

        $(that.magicLine).stop().animate({
            top: topPos,
            height: newHeight
        });
    },

    animateToSection: function (sectionToScroll) {
        var topPos = $(sectionToScroll).offset().top;

        $('html, body').animate(
            {
                scrollTop: topPos - 100
            },
            500,
            'linear',
            this.animateCallback
        );
    },

    animateCallback: function () {
        if (typeof scrollOmnitureEnd === 'function') {
            scrollOmnitureEnd();
        }
    },

    checkIfNotMobile: function () {

        var windowWidth = $(window).outerWidth();

        windowWidth > 767 ? isMobile = false : isMobile = true;

        return isMobile;
    },

    getScrollableAreaTopValue: function (scrollableArea, spaceBefore) {
        if ($(scrollableArea).length > 0) {
            return $(scrollableArea).position().top + spaceBefore;
        }

    },

    // ScrollableAreaEl compute height
    getScrollableAreaEndValue: function (subNavHeight, scrollableArea, spaceBefore) {
        var scrollableAreaEl = $(scrollableArea);

        return (scrollableAreaEl.outerHeight() + scrollableAreaEl.position().top) - ($(subNavHeight).innerHeight() + spaceBefore);
    },

    positionToFix: function (element, spaceBefore, width) {
        $(element).css({
            'position': 'fixed',
            'top': spaceBefore,
            'bottom': 'auto',
            'max-width': width + 'px'
        });
    },

    positionToRelative: function (element) {
        $(element).css({
            'position': 'relative',
            'top': 'auto',
            'bottom': 'auto',
            'max-width': ''
        });
    },

    positionToAbsolute: function (element) {
        $(element).css({
            'position': 'absolute',
            'top': 'auto',
            'bottom': 0
        });
    }
};


$(window).on('scroll', function () {
    checkScrollLocation();
    //hiding social floats on footer
}).on('resize', function () {
    var subNavScrollEl = $('.subnav-scroll');

    // need to recalculate on resize especially for magic line
    checkScrollLocation();
    // match subnavscroll width with its parent using js since position:fixed ignores the parent width
    subNavScrollEl.width(subNavScrollEl.parent().width());
});

// all function on document ready

$(function () {
    // FocusUntrapper();

    // call scrollable-area FloatingSubNav
    var windowScroll = document.documentElement.scrollTop;

    if ($('.scrollable-area').length > 0) {
        FloatingSubNav.init(windowScroll);
    }
    //FocusUntrapper();

    // Page loader trigger
    $("#show-loader-contained-mask").click(function () {
        // start showing the loader
        showLoaderWithMask('#brf-loader-contained-mask');
    });

    clickDragScroll_table();

    loadOpacityDots();

    //checkbox filter
    checkboxFilter();

    //option filter
    radioFilter.initialize();

    //mobile unslick count one, paramater limits the card shown in slick
    mobileUnslickCountOne.initialize(5);

    //Redirects to selected brand
    viewBrandItems();

    //set filters for brand filter
    setBrand();
	
    //hide inactive slick slide items
    hideInactiveSlides();

    //star rating
    starRating();

    //product slick with thumbnails
    initProductThumbnailModalSlick();

    //This is for click and enter event for color pallete selectors
    switchDeviceColor();

    verticalNav();

    //set province label for simplified header
    setProvinceLabel();

    //return focus on modal trigger upon closing modal
    modalTriggerReturnFocus();

    memberCountPicker();

    bottomSticky();
});

//reset the scrollable container location
function checkScrollLocation() {
    if ($('.scrollable-area').length > 0) {
        var windowScroll = window.pageYOffset || document.documentElement.scrollTop;

        // Check if will desktop or not then if desktop apply the floating scroll function
        if (FloatingSubNav.checkIfNotMobile() === false) {
            FloatingSubNav.checkScrollPos(windowScroll);
            FloatingSubNav.checkScrollableActiveSection(windowScroll);
        } else {
            FloatingSubNav.positionToRelative('.subnav-scroll');
        }
    }
}

// Side Nav end

// Click and Drag Scroll Funtions
function clickDragScroll_table() {
    const slider = document.querySelectorAll('.clickdragscroll');
    const sliderCount = slider.length;

    if (sliderCount > 0) {
        let isDown = false;
        let startX;
        let scrollLeft;

        // loop all .clickdragscroll classname
        for (let x = 0; x < sliderCount; x++) {
            let s = slider[x];
            s.addEventListener('mousedown', function (e) {
                isDown = true;
                s.classList.add('active');
                startX = e.pageX - s.offsetLeft;
                scrollLeft = s.scrollLeft;
            });
            s.addEventListener('mouseleave', function () {
                isDown = false;
                s.classList.remove('active');
            });
            s.addEventListener('mouseup', function () {
                isDown = false;
                s.classList.remove('active');
            });
            s.addEventListener('mousemove', function (e) {
                if (!isDown) return;
                e.preventDefault();
                const x = e.pageX - s.offsetLeft;
                const walk = (x - startX) * 3; //scroll-fast
                s.scrollLeft = scrollLeft - walk;
            });
        }
    }
}

//reusable checkbox filter combonent
function checkboxFilter() {
    // on checkbox status change
    $('.checkbox-filter').on('change', function () {
        let $this = $(this);
        let checkboxFilterInstance = $this.closest('.js-checkbox-filter-wrap');
        let partialCards = checkboxFilterInstance.data('partial');
        let cardsToShow = {};
        //add or remove .checked class on its label
        if ($this.prop('checked')) {
            $('label[for=' + $this.prop('id') + ']').addClass('checked');
        }
        else {
            $('label[for=' + $this.prop('id') + ']').removeClass('checked');
        }
        let checkedFilter = $('.checkbox-filter:checked');
        //show all cards if no checkbox is checked.
        //Hide all cards if one or more checkbox is selected then show only matched categories in the next lines of code
        if (checkedFilter.length == 0) {
            showAllCards(checkboxFilterInstance)
        } else {
            hideAllCards();
            let cards = checkboxFilterInstance.find('.card-content');
            //iterate through all cards
            cards.each(function (index) {
                let card = $(this);
                //convert data-category value to array separated by space
                let categories = card.data('category').split(" ");
                //iterate through categories on each card
                checkedFilter.each(function () {
                    let checkBoxValue = $(this).val();
                    if (categories.indexOf(checkBoxValue) > -1) {
                        if (!cardsToShow[index]) {
                            cardsToShow[index] = card;
                        }
                    }
                });
            });
            let showedCards;
            Object.keys(cardsToShow).forEach(function (key) {
                showedCards = checkboxFilterInstance.find('.card-content').not('.d-none');
                if (partialCards) {
                    if (showedCards.length < partialCards) {
                        cardsToShow[key].removeClass('d-none');
                    }
                }
                else {
                    cardsToShow[key].removeClass('d-none');
                }
            });
            let viewMoreWrap = checkboxFilterInstance.find('.js-view-more-wrap');
            //if cards is less than the defined partial cards then hide viewmore button and its wrapper otherwise show.
            Object.keys(cardsToShow).length <= partialCards ? viewMoreWrap.hide() : viewMoreWrap.show();
            //unbind view-more button event
            checkboxFilterInstance.find('.js-view-more').off('click');
            //set view-more button event to show all items in cardsToShow based on the filter
            checkboxFilterInstance.find('.js-view-more').on('click', function (e) {
                e.preventDefault();
                viewMore(cardsToShow);
                viewMoreWrap.hide();
            });
        }
    });
    //function to show all cards
    let showAllCards = function (checkboxFilter) {
        let partialCards = checkboxFilter.data('partial');
        let cards = checkboxFilter.find('.card-content');
        hideAllCards();
        //show cards but limit them to the defined number of partial cards
        cards.each(function (index) {
            let counter = index + 1;
            if (partialCards) {
                if (counter <= partialCards) {
                    $(this).removeClass('d-none');
                }
                let viewMoreWrap = checkboxFilter.find('.js-view-more-wrap');
                //if cards is less than the defined partial cards then hide viewmore button and its wrapper otherwise show.
                cards.length <= partialCards ? viewMoreWrap.hide() : viewMoreWrap.show();
                //unbind view-more button event
                checkboxFilter.find('.js-view-more').off('click');
                //set view-more button event to show all items in cardsToShow based on the filter
                checkboxFilter.find('.js-view-more').on('click', function (e) {
                    e.preventDefault();
                    let cardsToShow = [];
                    //store cards to cardsToShow for later access
                    cards.each(function () {
                        cardsToShow.push($(this));
                    });
                    viewMore(cardsToShow);
                    viewMoreWrap.hide();
                });
            }
            else {
                $(this).removeClass('d-none');
            }
        });
    }
    //function to hide all cards
    let hideAllCards = function () {
        $('.card-content').addClass('d-none');
    }
    //upon loading check for checkbox filter instances and show partial cards
    let checkboxFilters = $('.js-checkbox-filter-wrap');
    checkboxFilters.each(function () {
        showAllCards($(this));
    });
    //view more function
    let viewMore = function (cardsToShow) {
        Object.keys(cardsToShow).forEach(function (key) {
            cardsToShow[key].removeClass('d-none');
        });
    }
}

function viewBrandItems() {
    $(document).on("click", ".view-all-js", function (e) {
        $($(this).attr("data-id")).click();
    });
}

//slick tiles viewAll function
function tilesViewBrandItems() {

    setTimeout(function () {
        $('a.txtUnderline.clickable-card.view-all-js').each(function () {
            $(this).on('click', function () {
                $($(this).attr("data-id")).click();
            });
        });
    }, 1000);

}

let radioFilter = {
    initialize: function () {
        let that = this;
        $('.radio-slick').each(function () {
            let clone = $(this).clone();
            $(this).siblings('.slick-clone').html(clone.html());
            processSameHeightElements();
            $('.slick-clone').hide();
            $('.slick-clone .card-container').addClass(['col-md-4', 'col-sm-6', 'col-xs-12', 'margin-b-30', 'pad-h-15', 'pad-h-xs-0']);
            $('.slick-clone').find('.view-all-js').hide();
        });

        //This is to initially select all-brands radio after from back button
        $('input#All-brands').prop('checked', true);

        $(".slick-clone .tooltip-static").tooltip();
        //This added the id a prefix to cloned items
        this.modifyID();

        $('input.radio-filter').on('change', function () {

            tilesViewBrandItems();

            var $this = $(this);
            //add or remove .checked class on its label
            if ($this.is(':checked')) {
                // remove checked class for other labels
                $('label[for!=' + $this.prop('id') + ']').removeClass('checked');
                // add checked class for the selected value
                $('label[for=' + $this.prop('id') + ']').addClass('checked');
            }

            // hides all section
            $(".card-filter .card-section-js").hide();
            $("#bottom-banner-smartphones").hide();

            if ($this.attr('data-filters') == 'all-items') {

                that.allBrands($("#" + $this.attr('data-filters')));

                // this shows view all link
                $(".view-all-wrapper").show();

                // this show bottom banner 
                $("#bottom-banner-smartphones").show();

            } else {
                // this hides view all link
                $(".view-all-wrapper").hide();

                // show selected section
                $("#" + $this.attr('data-filters')).show();

                //this shows cloned cards
                that.filter($("#" + $this.attr('data-filters')));
                lazyLoad($("#" + $this.attr('data-filters')));
            }
            mobileUnslickCountOne.reSize();

            // this scrolls to top when VIEW ALL text link was clicked
            let filterControls = $("#filter-controls");
            let headerNav = $("header:nth-child(1)");
            let innerHeaderHeight = $('.global-navigation').innerHeight();

            if ($(window).width() <= 768) {
                $("html, body").animate({
                    scrollTop: $(filterControls).offset().top - innerHeaderHeight - 20
                }, "1000");
            } else {
                $("html, body").animate({
                    scrollTop: $(filterControls).offset().top - innerHeaderHeight / 1.4
                }, "1000");
            }

        });

        // putting/updating id and aria-describedby for items inside the accordion
        $('.collapse-accordion-accessible-toggle .card-container').each(function () {
            let title = $(this).find('.device-name');
            let currentId = title.attr('id');
            let details = title.parent().siblings();
            let ariaDescribedby = "";
            let textTag = $(this).find(".text-tag");

            if (textTag.length > 0) {
                textTag.attr('id', currentId + "-text-tag");
                ariaDescribedby += currentId + "-text-tag ";
            }

            details.each(function (index) {
                let detailsId = currentId + '-details-' + index;
                $(this).attr('id', detailsId);
                ariaDescribedby += detailsId + " ";

            });

            let cardLink = $(this).find('.card-link-js');
            cardLink.attr('aria-describedby', ariaDescribedby.trim());
        });

        $('.radio-slick .card-container').each(function () {
            let title = $(this).find('.device-name');
            let currentId = title.attr('id');
            let details = title.parent().siblings();
            let ariaDescribedby = "";
            let textTag = $(this).find(".text-tag");

            if (textTag.length > 0) {
                textTag.attr('id', currentId + "-text-tag");
                ariaDescribedby += currentId + "-text-tag ";
            }

            details.each(function (index) {
                let detailsId = currentId + '-details-' + index;
                $(this).attr('id', detailsId);
                ariaDescribedby += detailsId + " ";

            });

            let cardLink = $(this).find('.card-link-js');
            cardLink.attr('aria-describedby', ariaDescribedby.trim());
        });
    },
    filter: function (section) {
        section.find(".slick-clone").show();
        section.find(".radio-slick").hide();
    },
    modifyID: function () {
        $('.slick-clone').each(function () {
            $(this).find('.card-container').each(function () {
                let title = $(this).find('.device-name');
                let currentId = title.attr('id');
                let details = title.parent().siblings();
                let ariaDescribedby = "";
                let textTag = $(this).find(".text-tag");

                if (textTag.length > 0) {
                    textTag.attr('id', 'cloned-' + currentId + "-text-tag");
                    ariaDescribedby += 'cloned-';
                    ariaDescribedby += currentId + "-text-tag ";
                }

                details.each(function (index) {
                    let detailsId = 'cloned-' + currentId + '-details-' + index;
                    $(this).attr('id', detailsId);
                    ariaDescribedby += detailsId + " ";

                });

                let cardLink = $(this).find('.card-link-js');
                let currentCardLinkLabel = cardLink.attr('aria-labelledby');
                title.attr('id', 'cloned-' + currentCardLinkLabel);
                cardLink.attr('aria-labelledby', 'cloned-' + currentCardLinkLabel);
                cardLink.attr('aria-describedby', ariaDescribedby.trim());
            });
        });
    },
    allBrands: function (section) {
        $(".card-filter .card-section-js").show();
        section.find(".slick-clone").hide();
        section.find(".radio-slick").show();
    }
}


let mobileUnslickCountOne = {
    slickContainer: $('.mobileUnslickCountOne'),
    initialize: function (maxCard) {
        // for first load of the page
        this.slickContainer.on('init', function (event, slick) {
            // slideCount = count of slick slides
            if (slick.slideCount == 1 && $(window).width() < 768) {
                slick.destroy();
            } else {
                if (slick.slideCount > maxCard) {
                    let ctr = 1;
                    slick.slickFilter(function () {
                        if (ctr <= maxCard) {
                            ctr++;
                            return true;
                        } else {
                            if ($(this).find('.view-all-js').length > 0) {
                                ctr++;
                                return true;
                            }
                            ctr++;
                            return false;
                        }
                    });
                }
            }

            // for slider with same-height class 
            if ($(this).find('.same-height').length > 0) {
                $(this).find('.same-height').each(function () {
                    resetSameHeightElements($(this));
                    processSameHeightElements($(this));
                });
            }
        }).slick();
        $('.slider-remove-prev').find('.slick-arrow.slick-disabled').removeAttr('style');

    },
    // function for resize
    reSize: function () {
        let slickContainer = this.slickContainer;
        $.each(slickContainer, function () {
            let count = $(this).find('.slick-slide').length;

            if (count == 1 && $(window).width() < 768) {
                $(this).slick('unslick');
            } else {
                if (!$(this).hasClass('slick-initialized')) {
                    $(this).slick();
                }
                if ($(this).hasClass('slick-initialized')) {
                    if ($('.radio-filter.checked').siblings('input').val() == 'All brands') {
                        //this counterpart for slick refresh
                        $(this).slick('unslick');
                        $(this).slick();
                    }
                }
            }
        });
        $('.slider-remove-prev').find('.slick-arrow.slick-disabled').removeAttr('style');
        setTimeout(function () {
            processSameHeightElements();
        }, 100);

    }
};


// Slider Dots behavior (display only 7)
function loadOpacityDots() {
    $('.box-shadow-slick').each(function (i) {
        var $this = $(this);
        if ($(window).width() > 991) { //if slides <= 3
            var slideCount = $this.find('.slick-slide').length;
            if (slideCount <= 3) {
                if ($this.hasClass('slick-initialized')) {
                    $this.slick('unslick');
                }
            }
        } else if ($(window).width() < 768) {
            var totalCount = $this.find('.slick-dots li').length;
            if (totalCount > 7) { //if dots > 7
                $this.addClass('opacityDots');
                if ($this.find('.slickDots-container').length == 0) {
                    $this.find('ul.slick-dots').wrap("<div class='slickDots-container'></div>");

                }

                $this.find('ul.slick-dots li').each(function (index) {
                    var $list = $(this);
                    $list.addClass('dot-index-' + index);
                });

                $this.find('ul.slick-dots li').eq(5).addClass('opacity-50');
                $this.find('ul.slick-dots li').eq(6).addClass('opacity-20');
            }
        }
    });

    var dotOffset = 0;
    var transformXIntervalNext = -18;
    var transformXIntervalPrev = 18;
    $('.opacityDots').on("beforeChange", function (event, slick, currentSlide, nextSlide) {
        var $this = $(this);
        var totalCount = $this.find('.slick-dots li').length;
        if (nextSlide < 4) { // first 4 cards
            dotOffset = 0;
            // console.log('first card:', nextSlide+1);

            $this.find('ul.slick-dots').css('transform', 'translateX(0px)');
            $this.find('.slick-dots li').removeClass(['opacity-20', 'opacity-50']);
            $this.find('ul.slick-dots li:eq(5)').addClass('opacity-50');
            $this.find('ul.slick-dots li:gt(5)').addClass('opacity-20');
            if (nextSlide == 2) {
                $this.find('ul.slick-dots li:eq(0)').addClass('opacity-50');
            } else if (nextSlide == 3) {
                $this.find('ul.slick-dots li:eq(' + (nextSlide - 2) + ')').addClass('opacity-50');
                $this.find('ul.slick-dots li:eq(' + (nextSlide + 2) + ')').addClass('opacity-50');
                $this.find('ul.slick-dots li:lt(' + (nextSlide - 2) + ')').addClass('opacity-20');
                $this.find('ul.slick-dots li:gt(' + (nextSlide + 2) + ')').addClass('opacity-20');
            }

        } else if (nextSlide >= 3 && nextSlide <= totalCount - 4) { //middle cards
            // console.log('middle card:', nextSlide+1);

            if (nextSlide >= 4) {
                if (nextSlide > currentSlide) {
                    dotOffset = dotOffset + transformXIntervalNext;
                    if ($this.find('ul.slick-dots li.dot-index-' + nextSlide).hasClass('opacity-50')) {
                        dotOffset = dotOffset + (transformXIntervalNext);

                    } else if ($this.find('ul.slick-dots li.dot-index-' + nextSlide).hasClass('opacity-20')) {
                        dotOffset = dotOffset + (transformXIntervalNext * 2);
                    }
                } else {
                    if (nextSlide < totalCount - 4) {
                        dotOffset = dotOffset + transformXIntervalPrev;
                        if ($this.find('ul.slick-dots li.dot-index-' + nextSlide).hasClass('opacity-50')) {
                            dotOffset = dotOffset + (transformXIntervalPrev);

                        } else if ($this.find('ul.slick-dots li.dot-index-' + nextSlide).hasClass('opacity-20')) {
                            dotOffset = dotOffset + (transformXIntervalPrev * 2);
                        }
                    }
                }
                $this.find('ul.slick-dots').css('transform', 'translateX(' + dotOffset + 'px)');
            }
            $this.find('.slick-dots li').removeClass(['opacity-20', 'opacity-50']);

            $this.find('ul.slick-dots li:eq(' + (nextSlide - 2) + ')').addClass('opacity-50');
            $this.find('ul.slick-dots li:eq(' + (nextSlide + 2) + ')').addClass('opacity-50');
            $this.find('ul.slick-dots li:lt(' + (nextSlide - 2) + ')').addClass('opacity-20');
            $this.find('ul.slick-dots li:gt(' + (nextSlide + 2) + ')').addClass('opacity-20');

        } else if (nextSlide > totalCount - 4) { //last 3 cards
            // console.log('last card:', nextSlide+1);

            if (currentSlide < totalCount - 4) {
                var i = (totalCount - 1) - nextSlide;
                dotOffset = dotOffset + (transformXIntervalNext * i);
                $this.find('ul.slick-dots').css('transform', 'translateX(' + dotOffset + 'px)');
            }

            $this.find('.slick-dots li').removeClass(['opacity-20', 'opacity-50']);
            $this.find('ul.slick-dots li:eq(' + (totalCount - 6) + ')').addClass('opacity-50');
            $this.find('ul.slick-dots li:lt(' + (totalCount - 6) + ')').addClass('opacity-20');
            if (nextSlide == totalCount - 3) {
                $this.find('ul.slick-dots li:last-child').addClass('opacity-50');
            }
        }
    });
}

function forceSkipSameHeightMobile() {
    if (window.matchMedia("(max-width: 767px)").matches) {
        if ($('[data-same-height-skip-mobile]').length > 0) {
            setTimeout(function () {
                $('[data-same-height-skip-mobile]').each(function () {
                    $(this).find('[data-same-height-index]').css({ 'min-height': '' });
                });
            }, 300);

        }
    }
}

//for star rating
function starRating() {
    let starRatingContainer = $(".star-rating");
    starRatingContainer.each(function () { //to be able to have multiple star rating 
        starRatingEvent($(this));
    });
}

function starRatingEvent(value) {
    $(value).find('label').hover(function () {
        let label = $(value).find('label');
        $(value).find('label').removeClass("blue-star");
        label.each(function () {
            let $this = $(this);
            $this.addClass("blue-star");
            if ($this.is(":hover")) {
                return false;
            }
        });
    }, function () { //mouse out
        let label = $(value).find('label');
        label.each(function (key, value) {
            let $this = $(this);
            let rating = $(this).closest(".star-rating").attr("data-rating");
            if (key + 1 > rating) { //select star rating value to add class base on data-rating
                $this.removeClass("blue-star");
            } else {
                $this.addClass("blue-star");
            }
        });
    });
    $('.star-rating input').focus(function () { //focus
        let input = $('.star-rating input');
        let label = $('.star-rating label');
        $('.star-rating label').removeClass("blue-star");
        label.each(function () {
            let $this = $(this);
            let id = $this.attr("for");
            $this.addClass("blue-star");
            if ($('.star-rating input#' + id).is(":focus")) {
                return false;
            }
        });
    });
    $('.star-rating input').on("click", function () { //select data-rating star value
        let $this = $(this);
        let rating = $this.closest(".star-rating");
        rating.attr("data-rating", $this.val());
    });
}

$('.clearStarRating').on("click", function () { //reset star rating
    let rating = $(".star-rating");
    rating.attr("data-rating", "0");
    $('.star-rating label').removeClass("blue-star");
});


//refresh slick on accordion expand
$('.refresh-tabpanel-slick-js').on('click', function () {
    console.trace();
    let $this = $(this);
    let id = $this.attr('aria-controls');
    let tabpanel = $('#' + id);
    let slickContainer = tabpanel.find('.infoblock-slider.slick-initialized');

    tabpanel.attr('tabindex', '-1');
    slickContainer.slick('refresh');

    setTimeout(function () {
        processSameHeightElements();
    }, 0);
});



//Product Details page with thumbnail
function initProductThumbnailModalSlick() {
    $('.modal-Product-Details-js').each(function () {
        $(this).click(function () {
            if ($('.product-slider').hasClass('slick-initialized')) {
                var currentSlide = $('.product-slider').slick('slickCurrentSlide');
                var prodModalSlider = $('.product-modal-slider');
                setTimeout(function () {
                    prodModalSlider.slick('refresh');
                }, 0);
                prodModalSlider.slick('slickGoTo', currentSlide);

                prodModalSlider.on('init afterChange', function () {
                    let $this = $(this);
                    setTimeout(function () {
                        $this.find('.slick-slide.slick-active').attr('tabindex', 0);
                    }, 100);
                });
            }
        });
    });
}

//Accordion Tab Panel 
function accordionTab() {
    let tabActive = $('.accordionTab.show');
    let activePanel = $("#" + tabActive.data('panel'));
    let activeTabDetail = $(tabActive).find('.accordionTab-detail');

    activePanel.addClass("panelFadeIn");
    activeTabDetail.addClass("tabDescriptionFadeIn");
    accordionthumbHeight($(tabActive));
}

function accordionthumbHeight(e) {
    let tabTrackThumb = $('.tab-track-thumb');
    if (tabTrackThumb.length > 0) {
        setTimeout(function () {
            let position1 = e.position();
            $(tabTrackThumb).css('top', position1.top + 'px');
            $(tabTrackThumb).css('height', e.outerHeight() + 'px');
        }, 5);
        setTimeout(function () {
            let position2 = e.position();
            $(tabTrackThumb).css('height', e.outerHeight() + 'px');
            $(tabTrackThumb).css('top', position2.top + 'px');
        }, 90);
        setTimeout(function () {
            let position3 = e.position();
            $(tabTrackThumb).css('height', e.outerHeight() + 'px');
            $(tabTrackThumb).css('top', position3.top + 'px');
        }, 180);
        setTimeout(function () {
            let position4 = e.position();
            $(tabTrackThumb).css('top', position4.top + 'px');
            $(tabTrackThumb).css('height', e.outerHeight() + 'px');
        }, 330);
    }
}

function thumbHeightResize() {
    let accordionTabActive = $('.collapse-accordion-accessible-toggle.show');
    let tabParent = $(accordionTabActive).closest('.accordionTab');
    if (tabParent.length > 0) {
        accordionthumbHeight($(tabParent));
    }
}

$(function () {
    let accordionTab = $('.accordionTab a');

    $(accordionTab).each(function () {
        let $activeTab = $(this);
        $activeTab.on('click', function () {
            let target = $(this);
            let tabCount, tabPanel, accordionTab;
            let tabParent = $(target).closest('.accordionTab');
            let tabDetails = $(tabParent).find('.accordionTab-detail');
            let panel = $("#" + tabParent.data('panel'));

            tabPanel = document.getElementsByClassName("accordionTabPanel");

            let tabShow = $("#" + tabDetails[0].id);
            if (tabShow.hasClass("show")) {
                event.stopPropagation();
            }

            for (tabCount = 0; tabCount < tabPanel.length; tabCount++) {
                if (tabPanel[tabCount].id != panel[0].id) { //get unselected panel to hide element
                    document.getElementById(tabPanel[tabCount].id).classList.add("d-sm-none");
                    tabPanel[tabCount].className = tabPanel[tabCount].className.replace("d-sm-block", "");
                    tabPanel[tabCount].className = tabPanel[tabCount].className.replace("panelFadeIn", "");
                }
                else {
                    panel.removeClass("d-sm-none");
                    panel.addClass("d-sm-block");
                    panel.addClass("panelFadeIn");
                }
            }

            accordionTab = document.getElementsByClassName("accordionTab");
            for (tabCount = 0; tabCount < accordionTab.length; tabCount++) {
                if (accordionTab[tabCount].id == tabParent[0].id) { //Get selected Tab to show element
                    tabDetails.addClass("tabDescriptionFadeIn");
                } else {
                    let tabDetailCount;
                    let tablinkActive = document.getElementById(accordionTab[tabCount].id);
                    let tabPanelDetail = $(tablinkActive).find('.accordionTab-detail');
                    for (tabDetailCount = 0; tabDetailCount < tabPanelDetail.length; tabDetailCount++) {
                        tabPanelDetail[tabDetailCount].className = tabPanelDetail[tabDetailCount].className.replace("tabDescriptionFadeIn", "");
                    }
                }
            }
            accordionthumbHeight($(tabParent));
        });
    });
});

// Start fix for slick focus sequence
function updateSlickDots(activeDot, $this) {
    setTimeout(function () {
        activeDot.attr('tabindex', 0);
        $this.find('.slick-dots li:not(".slick-active") button').attr('tabindex', -1);
        $this.find('.slick-dots button').removeAttr('aria-selected');
        activeDot.attr('aria-selected', true);
    });
}
let slickTrigger;
let beforeChangeCurrentSlide;
$(".link-slide").on('afterChange', function (event, slick, currentSlide, nextSlide) {
    lazyLoad($(this));
    if (beforeChangeCurrentSlide != currentSlide) {
        var $this = $(this);
        if (slickTrigger.hasClass('slick-arrow')) {
            let firstActiveCard = $this.find('.slick-active').first();
            firstActiveCard.find('a').focus();
            let activeDot = $this.find('.slick-dots .slick-active button');
            updateSlickDots(activeDot, $this);
        }
        else {
            let activeDot = $this.find('.slick-dots .slick-active button');
            if ($('body').hasClass('is_tabbing')) {
                activeDot.focus();
            }
            updateSlickDots(activeDot, $this);
        }
    }
});
$(".link-slide").on('beforeChange', function (event, slick, currentSlide, nextSlide) {
    beforeChangeCurrentSlide = currentSlide;
    slickTrigger = $(document.activeElement);
});
// End fix for slick focus sequence

//start accessibility fix for slick tabpanel label
//change aria-describedby to aria-label as ibm accessibility checker suggested
function setSlickLabel(slick) {
    setTimeout(function () {
        let tabpanels = slick.find('.slick-slide[role="tabpanel"]');
        tabpanels.each(function () {
            let ariaDescribedBy = $(this).attr('aria-describedby');
            $(this).attr('aria-labelledby', ariaDescribedBy);
            $(this).removeAttr('aria-describedby');
        });
    });
}
$('.infoblock-slider, .responsive-slick-slider').on('init afterChange', function () {
    setSlickLabel($(this));
});
//End accessibility fix for slick tabpanel label

// START configurable-slider
$(document).on("init", ".configurable-slider", function (event, slick) {
    const slickInstance = $(this);
    let customConfig = slickInstance.data("custom-config");
    if (!customConfig) return;

    let customFunctions = {
        "centerContainer": function (value) {
            let slickTrack = slickInstance.find('.slick-track');
            if (value) {
                slickTrack.css('cssText', 'margin: 0 auto !important');
            }
        }
    }

    let iterateConfig = function (config) {
        for (var key in config) {
            const executeCustomFunctions = customFunctions[key];
            executeCustomFunctions(config[key]);
        }
    }

    if (window.matchMedia("(max-width: 767px)").matches && customConfig.mobile) {
        iterateConfig(customConfig.mobile);
    } else if (window.matchMedia("(max-width: 991.98px)").matches && window.matchMedia("(min-width: 768px)").matches && customConfig.tablet) {
        iterateConfig(customConfig.tablet);
    } else if (window.matchMedia("(min-width: 992px)").matches && customConfig.desktop) {
        iterateConfig(customConfig.desktop);
    }

    // for mobility apple slider
    let cardContainer = $(this).find('.card-container');
    if ($(this).find('.card-container').length > 0) {

        $(this).find('.card-container').each(function () {
            let title = $(this).find('.device-name');
            let currentId = title.attr('id');
            let details = title.parent().siblings();
            let ariaDescribedby = "";
            let textTag = $(this).find(".text-tag");

            if (textTag.length > 0) {
                textTag.attr('id', currentId + "-text-tag");
                ariaDescribedby += currentId + "-text-tag ";
            }

            details.each(function (index) {
                let detailsId = currentId + '-details-' + index;
                $(this).attr('id', detailsId);
                ariaDescribedby += detailsId + " ";

            });

            let cardLink = $(this).find('.card-link-js');
            cardLink.attr('aria-describedby', ariaDescribedby.trim());
        });
    }
});

function switchDeviceColor() {

    $("#maincontent").on("click", ".tile-color-round-2", function () {
        $(this).closest(".color-pallette-js").find(".selected-color-pallette").removeClass("selected-color-pallette");
        $(this).closest(".color-pallette-js").find(".tile-color-round-2").attr("aria-checked", "false");
        $(this).addClass("selected-color-pallette");
        $(this).attr("aria-checked", "true");
    });

    let ua = window.navigator.userAgent;
    let msie = ua.indexOf("MSIE ");
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
    {
        $("#maincontent").on("keydown", ".tile-color-round-2", function (e) {
            var keycode = (e.keyCode ? e.keyCode : e.which);
            if (keycode == 13) {
                $(this).closest(".color-pallette-js").find(".selected-color-pallette").removeClass("selected-color-pallette");
                $(this).closest(".color-pallette-js").find(".tile-color-round-2").attr("aria-checked", "false");
                $(this).addClass("selected-color-pallette");
                $(this).attr("aria-checked", "true");
            }
        });
    }
    else  // If another browser
    {
        $("#maincontent").on("keypress", ".tile-color-round-2", function (e) {
            var keycode = (e.keyCode ? e.keyCode : e.which);
            if (keycode == 13) {
                $(this).closest(".color-pallette-js").find(".selected-color-pallette").removeClass("selected-color-pallette");
                $(this).closest(".color-pallette-js").find(".tile-color-round-2").attr("aria-checked", "false");
                $(this).addClass("selected-color-pallette");
                $(this).attr("aria-checked", "true");
            }
        });
    }
}

function lazyLoad(container) {
    var modalEl = container;
    setTimeout(function () {
        var lazyImages;
        if (typeof jQuery.fn.Lazy === 'function') {
            lazyImages = modalEl.find("img.lazy");
            //if (lazyImages.length > 0) {
            lazyImages.Lazy({ effect: "fadeIn" });
            //}
        }
    }, 100);
}

$(document).on('click', '.actual-tabs-controller-js [role="tab"]', function () {
    lazyLoad($('#' + $(this).attr('aria-controls')));
});

$('.modal').on('show.bs.modal', function (e) {
    var $this = $(this);
    if ($this.find('.carousel-navigator-centered').hasClass('slick-initialized')) {
        $this.find('.carousel-navigator-centered').slick('unslick');
    }
    $this.find('.carousel-navigator-centered').each(function (e) {
        var $this = $(this);
        if ($this.children().length > 1) {
            if ($this.children().length < 3) $this.addClass('two-slides');
            $this.slick();
        }
    });
});

function verticalNav() {
    //Start vertical tab override for link mode
    //Disable tab function vertical tabs to allow link to function
    $('ul.tabs.link-mode li').off('click');

    //Disable tab function on mobile and simulate a click on a link that is set in option's value'
    $('.custom-selection.link-mode').off('change');
    $('.custom-selection.link-mode').on('change', function () {
        let link = $(this).val();
        window.location.href = link;
    });
    //End vertical tab override for link mode
}

//hide provinces popup 
$('.trigger-popup').focusout(function (e) {
    let $thisPopup = $(this);
    let hidePopUp = $('.federal-bar-select-provinces-popup');
    $('.js-current-language').focus(function (e) {
        if (hidePopUp.length > 0) {
            hidePopUp.hide();
            $thisPopup.attr('aria-expanded', 'false'); //expand indicator
        }
    })
    $('.connector-brand a').focus(function (e) {
        if (hidePopUp.length > 0) {
            hidePopUp.hide();
            $thisPopup.attr('aria-expanded', 'false'); //expand indicator
        }
    })
});

// simplified header province selector expanded/collapsed indicater
$('.federal-bar-select-provinces').find('.trigger-popup').on('click touch', function () {
    let $this = $(this);
    let collapsed = $this.attr('aria-expanded');
    if (collapsed) {
        $this.attr('aria-expanded', 'true');
    }
    else {
        $this.attr('aria-expanded', 'false');
    }
});
$(document).on('click touch', function (e) {
    if (!$(e.target).parents().addBack().is('.trigger-popup')) {
        $('.federal-bar-select-provinces').find('.trigger-popup').attr('aria-expanded', 'false');
    }
});
// Set currently selected label for simplified header province selector
function setProvinceLabel() {
    setFocusTimeout(function () {
        let provinces = $('.simplified_header .federal-bar-select-provinces-popup .checkboxes a');

        provinces.each(function () {
            let label = $.trim($(this).find('.label-text').text());
            let selected = " (currently selected region)";
            if ($(this).hasClass('active')) {
                $(this).attr('aria-label', label + selected);
            }
            else {
                $(this).attr('aria-label', label);
            }
        });
    });
}
// supports dismissing of region dropdown when ESC is pressed while trigger button is focused. 
function focusRegion(e) {
    var keyCode = e.keyCode, $el;
    if (27 === keyCode) {
        $('.trigger-popup').focus();
    }
}

//Set delay on processSameHeightElements in modals upon resizing
function processModalSameHeight() {
    setTimeout(function () {
        processSameHeightElements();
    }, 200);

}

//Set tab sequense for small-slick
$('.slick-small').on('init reInit', function () {
    let $this = $(this);
    let slickDots = $this.parent().find('.slick-dots');
    slickDots.appendTo($this.parent()).css('margin-top', '-8px');
    $(".slick-small").each(function (instance) {
        $this = $(this);
        let slickSlide = $this.find('.slick-slide:not(.slick-cloned)');
        slickSlide.each(function () {
            let $this = $(this);
            let index = $this.data('slick-index');
            $this.attr('aria-labelledby', 'slick-slide-control' + (instance + 1) + index);
        })
    });
    $('.slick-cloned').removeAttr('id');
});
$(".slick-small").on('afterChange', function (event, slick, currentSlide, nextSlide) {
    lazyLoad($(this));
    if (beforeChangeCurrentSlide != currentSlide) {
        let $this = $(this);
        if (!slickTrigger.hasClass('slick-arrow')) {
            let activeDot = $this.parent().find('.slick-dots .slick-active button');
            if ($('body').hasClass('is_tabbing')) {
                activeDot.focus();
            }
        }
    }
});
$(".slick-small").on('beforeChange', function (event, slick, currentSlide, nextSlide) {
    beforeChangeCurrentSlide = currentSlide;
    slickTrigger = $(document.activeElement);
});

// start fix slick accessibility
const fixSlickAccessibility = {
    beforeChangeCurrentSlide: null,
    slickTrigger: null,
    initialize: function (slickInstance) {
        const parentObject = this;
        slickInstance.on('init reInit', function () {
            parentObject.setTabpanelLabel($(this));
        });
        slickInstance.on('afterChange', function (event, slick, currentSlide, nextSlide) {
            parentObject.setTabpanelLabel($(this));
            //set slick dots focus
            if (parentObject.beforeChangeCurrentSlide != currentSlide) {
                if (!parentObject.slickTrigger.hasClass('slick-arrow')) {
                    if ($('body').hasClass('is_tabbing')) {
                        $(this).find('.slick-dots .slick-active button').focus();
                    }
                }
            }
        });
        slickInstance.on('beforeChange', function (event, slick, currentSlide, nextSlide) {
            parentObject.beforeChangeCurrentSlide = currentSlide;
            parentObject.slickTrigger = $(document.activeElement);
            const activeDot = $(this).find('.slick-dots .slick-active');
            const slickNext = $(this).find('.slick-next');
            const slickPrev = $(this).find('.slick-prev');
            if (nextSlide > currentSlide) {
                slickPrev.removeAttr('tabindex');
                if (activeDot.next().is(':last-child')) {
                    slickNext.attr('tabindex', -1);
                }
            }
            else {
                slickNext.removeAttr('tabindex');
                if (activeDot.prev().is(':first-child')) {
                    slickPrev.attr('tabindex', -1);
                }
            }
        });
        setTimeout(function () {
            slickInstance.find('.slick-arrow').on('click', function () {
                $(this).removeAttr('aria-disabled');
            });
        }, 100);
    },
    setTabpanelLabel: function (slick) {
        const slickCurrent = slick.find('.slick-current');
        const activeDot = slick.find('.slick-dots .slick-active button');
        slickCurrent.attr('aria-labelledby', activeDot.attr('id'));
        setTimeout(function () {
            slickCurrent.removeAttr('aria-describedby');
            activeDot.attr('tabindex', 0);
        }, 0);
        $('.slick-cloned').removeAttr('id');
        lazyLoad(slick);
    }
}

fixSlickAccessibility.initialize($('.infoblock-slider-no-shadow'));
//end fix slick accessibility

// Start fix for Modals that are triggered via js .modal('show');
// Returns focus on modal trigger upon closing modal [SPRINT 14.2 - BTC-8499]
function modalTriggerReturnFocus() {
    let modalTrigger;
    $(document).on('click', '[data-toggle="modal"], [data-toggle="video-modal"]', function () {
        modalTrigger = $(this);
    });
    $('body').on('hidden.bs.modal', '.modal ', function () {
        if (modalTrigger) {
            modalTrigger.focus();
            modalTrigger = "";
        }
    });
}
// End fix for Modals that are triggered via js .modal('show');

// Close tooltip when escape key is pressed
$('[data-toggle="tooltip"]').on('keydown', function (event) {
    if (event.key === "Escape") {
        $(this).tooltip('hide');
    }
});

$('.disabled-select[aria-disabled="true"]').on('keydown click', function (e) {
    if (e.type === "keydown" && (e.which === 32 || e.which === 13)) {
        e.preventDefault();
    }
});



// Start member picker for Unlimited Plans
$(document).on("click", ".minus-member-js", function () {
    members -= 1;
    memberCountPicker();
});

$(document).on("click", ".add-member-js", function () {
    members += 1;
    memberCountPicker();
});

function createIconName() {
    if (members == 1) {
        return "icon-o-1member"
    } else {
        return "icon-o-" + members + "members"
    }
}

function memberCountPicker() {
    let container = $("div[data-default-member-count]");
    var maxMember = container.data("max-member");
    if (container.length > 0) {
        if (members == 0) {
            members = container.data("default-member-count");
        }
        let iconName = createIconName();
        container.find('[class*="icon-o-"]').hide();
        container.find('.' + iconName).show();
        container.find('[class*="member-text-"]').hide();
        container.find('.member-text-' + members).show();

        var section = container.closest('section');
        section.find('[class*="savings-"]').hide();
        section.find('.savings-' + members).show();
        section.find(".minus-member-js").prop("disabled", false);
        section.find(".add-member-js").prop("disabled", false);

        if (members == 1) {
            section.find(".minus-member-js").prop("disabled", true);
        }
        else if (members == maxMember) {
            section.find(".add-member-js").prop("disabled", true);
        }
    }
}
// End member picker for Unlimited Plans

// Start slick tabpanel component
$('.tab-panels-container.slider-with-data-options').on('init', function () {
    let slick = $(this);
    let arrowTriggered = false;
    let tabContainer = $(slick.data('custom-tab-control'));
    slick.find('.slick-next').attr('aria-label', 'Next tab');
    slick.find('.slick-prev').attr('aria-label', 'Previous tab');
    function initializeTabs() {
        setTimeout(function () {
            let tabpanels = slick.find('.slick-slide');
            tabpanels.each(function () {
                let tabpanel = $(this);
                let tab = $('#' + tabpanel.find('[data-tab]').data('tab'));
                tab.attr('aria-controls', tabpanel.attr('id'));
                tabpanel.attr('aria-labelledby', tab.attr('id'));
            });
        });
    }
    function verticallyCenterControls() {
        let slickHeight = parseInt(slick.height());
        let dotsHeight = parseInt(slick.find('.slick-dots').height());
        let slideHeight = slickHeight - dotsHeight - 4;
        let slickControls = slick.find('.slick-arrow');
        slickControls.css({
            'transform': 'translateY(-50%)',
            'top': slideHeight / 2 + 'px',
            'margin-top': '0px',
            'transition': 'all .1s'
        });
    }
    function disableDots() {
        setTimeout(function () {
            let dotsContainer = slick.find('.slick-dots');
            let dots = dotsContainer.find('button')
            dotsContainer.attr('aria-hidden', true);
            dotsContainer.removeAttr('role');
            dots.removeAttr('role aria-controls aria-label aria-selected').attr('tabindex', '-1');
        });
        slick.find('.slick-dots button').css('cursor', 'default').on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();
        })
    }

    verticallyCenterControls();
    initializeTabs();
    disableDots();

    slick.find('img.lazy').on('load', function () {
        slick.slick('setPosition');
    });

    slick.on('afterChange', function (e) {
        setTimeout(function () {
            slick.slick('setPosition');
        }, 300);
        initializeTabs();
        disableDots();

        if (arrowTriggered) {
            let currentSlide = slick.find('.slick-current');
            let tab = $('#' + currentSlide.find('[data-tab]').data('tab'));
            tabContainer.find('.slick-announcer').html(tab.text());
            arrowTriggered = false;
        }
    });

    slick.on('setPosition', function () {
        verticallyCenterControls();
    });

    slick.find('.slick-slide').on('focus', function () {
        $(this).closest('.slick-list').css('box-shadow', '0 0 0 3px #fff, 0 0 2px 3px #fff, 0 0 4px 5px #5fb0fc, 0 0 2px 5px #8ec6fc')
    });

    slick.find('.slick-slide').on('focusout', function () {
        $(this).closest('.slick-list').css('box-shadow', 'none')
    });

    slick.find('.slick-arrow').on('click', function () {
        arrowTriggered = true;
    });

    tabContainer.on('keydown', function () {
        tabContainer.find('.slick-announcer').html('');
    });
});

// End slick tabpanel component

$(document).on('show.bs.tooltip', '[data-toggle="tooltip"]', function () {
    $('[data-toggle="tooltip"]').not(this).tooltip('hide');
});

//Bottom sticky element
function bottomSticky() {

    const bottomSticky = $(".bottom-sticky-js")
    if (bottomSticky.length > 0) {
        const height = bottomSticky.height();
        $("footer").css("margin-bottom", height + "px");
        if (window.matchMedia("(max-width: 767.98px)").matches) {

            $("*:not(.bottom-sticky-js *)").on("focus", function () {

                const windowHeight = $(window).height();
                // Element's position relative to Viewport
                const position = ($(this).offset().top - $(window).scrollTop()) + $(this).height();
                const limit = windowHeight - height;

                if (position > limit) {
                    $(window).scrollTop($(this).offset().top - (windowHeight - (height + $(this).height() * 2)));
                }
            });
        }
    }

}

// Start contact slideout component
(function ($) {
    $.fn.slideOut = function (options) {
        let settings = $.extend({
            // defaults.
        }, options);

        return this.each(function () {
            const container = $(this);
            const trigger = container.find('.slideout-trigger-js');
            const triggerOpen = container.find('.slideout-open').parents('div.bgBlue');
            const icon = trigger.find('.icon-o');
            const appearLeft = settings.leftSlide;

            if (!appearLeft) {

                trigger.on('click', function (e) {
                    e.preventDefault();
                    container.toggleClass('maximized');
                    const content = $('#' + trigger.attr('aria-controls'));

                    if (container.hasClass('maximized')) {
                        trigger.attr('aria-expanded', 'true');
                        icon.addClass(settings.maximizedIcon).removeClass(settings.minimizedIcon);
                        content.removeClass('d-none');
                        container.removeClass('closed minimized');
                    }
                    else {
                        trigger.attr('aria-expanded', 'false');
                        icon.addClass(settings.minimizedIcon).removeClass(settings.maximizedIcon);
                        content.addClass('d-none');
                        container.addClass("minimized").removeClass('closed maximized');
                    }
                });

                $(document).bind("scroll", function () {
                    if ($(document).scrollTop() >= settings.scrollTop) {
                        if (!container.hasClass('maximized')) {
                            container.addClass("minimized").removeClass("closed maximized");
                        }
                    }
                    else {
                        container.addClass("closed").removeClass('minimized maximized');
                        icon.addClass(settings.minimizedIcon).removeClass(settings.maximizedIcon);
                    }
                });
            } else { // for appearLeft only used in store-locator

                trigger.on('click', function (e) {
                    e.preventDefault();
                    const content = $('#' + trigger.attr('aria-controls'));

                    if (content.hasClass('d-none')) {
                        triggerOpen.addClass('d-none').removeClass('d-block');
                        trigger.attr('aria-expanded', 'true');
                        content.removeClass('d-none');
                        container.find('.slideout-close').focus();
                        // console.log(container.find('.slideout-open'));
                    }
                    else {
                        triggerOpen.addClass('d-block').removeClass('d-none');
                        trigger.attr('aria-expanded', 'false');
                        content.addClass('d-none');
                        container.find('.slideout-open').focus();
                        // console.log(container.find('.slideout-close'));

                    }
                });
            }
        });

    };
}(jQuery));

$('[data-slideout]').each(function () {
    $(this).slideOut($(this).data('slideout'));
});
// End contact slideout component

let initializeInteractiveTooltip = function () {
    let tooltipIsTabbing = false;

    let tooltipTrigger = $('.tooltip-interactive-manual-js');
    tooltipTrigger.tooltip();

    //Check tooltip focus if the body has is_tabbing class
    $(document).on("focus", ".tooltip a[data-toggle='modal']", function () {
        if ($("body").hasClass("is_tabbing") === true) {
            tooltipIsTabbing = true;
        }
    });

    //Add is_tabbing class if the modal is shown
    $(document).on('shown.bs.modal', function () {
        if (tooltipIsTabbing) {
            $("body").addClass("is_tabbing");
            tooltipIsTabbing = false;

        }
    });

    // Shop-SMB/device-details-anatomy.html mobile issue not removing modal-open
    $(window).on('hidden.bs.modal', function () {
        var openModal = $('.modal-backdrop').length;
        if (openModal == 0) {
            $('body').removeClass('modal-open');
        }
    });

    //Open tooltip if tooltipTrigger is focus
    tooltipTrigger.on('focus', function () {
        tooltipTrigger.tooltip("show");
    });

    $(document).on("mouseenter", ".tooltip-interactive-manual-js", function () {
        tooltipTrigger.tooltip("show");
    });

    let tooltipHasHover = false;
    $(document).on("mouseleave", ".tooltip-interactive-manual-js", function () {
        setTimeout(function () {
            let selectTooltipTrigger = document.querySelector(".tooltip-interactive-manual-js");

            if (!selectTooltipTrigger.contains(document.activeElement) && !tooltipHasHover) {
                tooltipTrigger.tooltip("hide");
            }
        });
    });

    $(document).on("mouseenter", ".tooltip", function () {
        tooltipHasHover = true;
    });

    $(document).on("mouseleave", ".tooltip", function () {
        tooltipHasHover = false;
        let tooltipHasFocus = false;
        let tooltip = document.querySelector(".tooltip");
        let selectTooltipTrigger = document.querySelector(".tooltip-interactive-manual-js");

        if (tooltip) {
            tooltipHasFocus = tooltip.contains(document.activeElement) ? true : false;
        }

        if (!selectTooltipTrigger.contains(document.activeElement) && !tooltipHasFocus) {
            tooltipTrigger.tooltip("hide");
        }
    });

    //Tooltip will close if the focus is not on tooltipTrigger
    tooltipTrigger.on('focusout', function () {
        let tooltip = document.querySelector(".tooltip");


        if (tooltip) {
            setTimeout(function () {
                if (!tooltip.contains(document.activeElement)) {
                    tooltipTrigger.tooltip("hide");
                }
            }, 0)
        }
    });

    //Open modal inside tooltip when press Enter/Space
    $(document).on("keypress", ".tooltip a[data-toggle='modal']", function (e) {
        if (e.keyCode == 13 || e.keyCode == 32) {
            e.preventDefault();
            $(this).trigger('click');
        }

    });

    //Close tooltip if Escape is press
    $(document).on('keydown', function (event) {
        if (event.key === "Escape") {
            tooltipTrigger.tooltip('hide');
        }
    });

    //Tooltip will close if the focus is not on achrog tag
    $(document).on("focusout", ".tooltip a[data-toggle='modal']", function () {
        let tooltip = document.querySelector(".tooltip");
        const modal = document.querySelector($(this).attr("data-target"));

        setTimeout(function () {
            if (!tooltip.contains(document.activeElement) && !modal.contains(document.activeElement)) {
                tooltipTrigger.tooltip("hide");
            }
        }, 0)
    })

    // for updating the placement in mobile
    // $(window).on('resize', function() {
    //     var pos = ($(window).width() < 768) ? 'top' : 'left';
    //     tooltipTrigger.data('bs.tooltip').config.placement = pos;// For dynamic position
    //     tooltipTrigger.data('bs.tooltip').config.boundary= pos; // Used for tooltip boundary range
    //     tooltipTrigger.tooltip('update');
    // });

}

initializeInteractiveTooltip();

// Start Product slider as tab component
$(function () {
    const productSlider = {
        'mainSlider': $('.product-slider'),
        'navSlider': $('.dro-product-thumbnail-nav'),
        'initialize': function () {
            this.navSlider.on('init', function (e, slick) {
                const slider = $(this);
                const asNavFor = slick.options.asNavFor;
                const slides = slick.$slides;
                const mainSlides = $(asNavFor);
                setTimeout(function () {
                    slides.each(function () {
                        const tab = $(this);
                        const index = tab.attr('data-slick-index');
                        const tabpanel = mainSlides.find('[data-slick-index="' + index + '"]');
                        const tabId = 'tab-' + index;
                        const tabpanelId = 'tabpanel-' + tabpanel.attr('data-slick-index');
                        const isCurrent = tab.hasClass('slick-current') ? true : false;
                        $(this).find('a').attr({
                            'role': 'tab',
                            'id': tabId,
                            'aria-controls': tabpanelId,
                            'aria-selected': isCurrent,
                            'tabindex': isCurrent ? '0' : '-1'
                        });
                        tabpanel.attr({
                            'role': 'tabpanel',
                            'id': tabpanelId,
                            'aria-labelledby': tabId,
                            'tabindex': isCurrent ? '0' : '-1'
                        });
                        $(this).removeAttr('aria-hidden');
                    });
                });
                slider.find('.slick-track').attr('role', 'tablist');
                slider.find('.slick-track').attr('aria-labelledby', slider.data('labelledby'));
                const slickSlideCount = slider.find('.slick-slide').length;
                const slideNum = slider.data("slider-count");

                if (slickSlideCount <= slideNum) { // data-slider-count for slide number
                    // this will add class with !important
                    slider.find('.slick-track').addClass("transform-none");
                    slider.find('.slick-track').addClass("w-auto");
                    slider.find('.slick-track').addClass("m-l-auto");
                    slider.find('.slick-track').addClass("r-l-auto");
                }

                slider.on('keydown', function (e) {
                    e = e || window.event;
                    if (e.keyCode == '37') {
                        mainSlides.slick('slickPrev');
                    }
                    else if (e.keyCode == '39') {
                        mainSlides.slick('slickNext');
                    }
                    slider.find('.slick-current').find('a').focus();
                });

                slider.on('afterChange', function (e, slick) {
                    setTimeout(function () {
                        slick.$slides.each(function () {
                            const slide = $(this);
                            if (slide.hasClass('slick-current')) {
                                slide.find('a').attr({
                                    'aria-selected': true,
                                    'tabindex': 0
                                });
                            }
                            else {
                                slide.find('a').attr({
                                    'aria-selected': false,
                                    'tabindex': -1
                                });
                            }
                            slide.removeAttr('aria-hidden');
                            slide.removeAttr('tabindex');
                        });
                    });
                });

                let mainSlideIsTriggered;
                mainSlides.on('beforeChange', function (e, slick, currentSlide) {
                    mainSlideIsTriggered = $(this).find('.slick-current').is(':focus');
                });

                mainSlides.on('afterChange', function (e, slick) {
                    slick.$slides.each(function () {
                        if ($(this).hasClass('slick-current')) {
                            const slide = $(this);
                            setTimeout(function () {
                                slide.attr('tabindex', '0');
                                if (mainSlideIsTriggered) {
                                    slide.focus();
                                }

                            });
                        }
                        else {
                            $(this).attr('tabindex', -1)
                        }
                    })
                })
            });

            this.mainSlider.slick();
            this.navSlider.slick();
        }
    }
    productSlider.initialize();
});
// End Product slider as tab component

$(document).on('beforeChange', ".responsive-slick-slider, .infoblock-slider", function (event, slick, currentSlide, nextSlide) {
    beforeChangeCurrentSlide = currentSlide;
    slickTrigger = $(document.activeElement);
});
// End fix for slick focus sequence

// dual modal
$(document).on('click', ".dual-modal [data-toggle='modal']", function () {
    if ($(".modal-backdrop").length > 1) {
        $($(".modal-backdrop")[1]).css('z-index', '2002');
    }
});

// for dual modal DRO - tabindex and aria hidden fix
// $(document).on('click', "a[data-target='#device-return-option']", function () {
//     let $this = $(this);
//     var parentModal = $this.parents('#deviceOptionWrap');

//     if(parentModal) {
//         revertTabIndexAndAriaHiddenDifferentHierarchy(parentModal);
//         overwriteTabIndexAndAriaHiddenDifferentHierarchy($this);
//     }
// });

$('.dual-modal').on('shown.bs.modal', function () {
    let $this = $(this);
    // console.log($this);
    // var parentModal = $this.parents('#deviceOptionWrap');
    // console.log($this.parents());
})

// Tooltip modal keypress on mobile view
function tooltipKeypress() {
    $('.tooltip-interactive').on('keypress', function (e) {
        if (e.keyCode == 13 || e.keyCode == 32) {
            $(this).trigger('click');
        }
    });
};

// Fixed accordion focus outline disappearing when using screen reader
$('.collapse-trigger[data-toggle="collapse"]').on('click', function () {
    $("body").addClass('is_tabbing');
    window.addEventListener('mousedown', focusMouseDownControlOnce);
});

// start custom in store-locator page search

$(".store-dropdown-menu").on("change", "input[type='checkbox']", function () {
    $(this).closest("li").toggleClass("active", this.checked);
});

//  stop closing the selectbox
$(document).on('click', '.allow-focus', function (e) {
    e.stopPropagation();
})

// hover mouse in and out and keypress accept enter and spacebar
let inputCheckBox = $('.store-dropdown-menu input[type="checkbox"]');

function checkboxIndexToggle(tabIndex) {
    inputCheckBox.each(function () {
        $(this).attr("tabindex", tabIndex);
    });
}

let initializeSearchFilterMenu = function () {

    let dropdownMenu = $('.store-form-control .dropdown, .store-form-control .dropdown .store-dropdown-menu');
    let dropdownMenuBtn = $('.store-form-control .dropdown, .store-form-control .btn.dropdown-toggle');
    let dropdownMenuTablet = $('.store-checkbox-btn');
    let chevron = dropdownMenu.find('.btn.dropdown-toggle span.icon');

    checkboxIndexToggle(-1);

    lazyLoad($('.store-list'));

    dropdownMenu.mouseover(function (e) {
        // show
        toggleVisibility(dropdownMenu);

    }).mouseout(function (e) {
        // hide
        toggleVisibility(dropdownMenu, 'hide');

    }).on('keypress', function (e) {
        // enter
        if (e.keyCode == 13 || e.key === 'Enter') {
            e.preventDefault();
        }

    }).on('keyup', function (e) {
        // space
        if (e.keyCode == 32) {
            e.preventDefault();
        }

    });

    dropdownMenuTablet.on('click', function () {

        if ($('.dropdownTablet').hasClass('show')) {
            $(this).attr('aria-expanded', false);
            $('#overlay').css("display", "none");
            // for screen reader and focus
            $('.dropdown-custom-toggle-js').not('.store-checkbox-btn').trigger('click').focus();
        } else {
            $(this).attr('aria-expanded', true);
        }

    }).on('keydown', function (e) {
        //shift was down when tab was pressed

        if (e.shiftKey && e.keyCode == 9) {
            // console.log('shift tab');
            $(this).trigger('click');
            e.preventDefault();
        } else if (e.key === "Escape") { //escape
            // console.log('escape');
            $(this).trigger('click');
        }
    });

    // $('.graphical_ctrl_checkbox input[type="checkbox"]:not(:last)').on('focus', function(e){
    //     toggleVisibility();
    //     console.log('focus in on checkbox');
    // });

    // $('.graphical_ctrl_checkbox input[type="checkbox"]:last').on('focusout', function(e){
    //     toggleVisibility('hide');
    //     console.log('focus out on last checkbox');
    // });

    // if press shift tab from button to input search
    // dropdownMenuBtn.on('keypress', function(e){
    //     if(e.shiftKey && e.keyCode == 9) { 
    //         //shift was down when tab was pressed
    //         toggleVisibility('hide');
    //     }
    // });

    function toggleVisibility(container, display = 'show') {

        if (display == 'show') {
            chevron.addClass('icon-chevron-down').removeClass('icon-chevron-up');
            // show
            checkboxIndexToggle(0);
            container.addClass('show');
        } else if (display == 'd-flex') {
            chevron.addClass('icon-chevron-down').removeClass('icon-chevron-up');
            // show
            checkboxIndexToggle(0);
            container.addClass('d-flex');
        } else {
            chevron.addClass('icon-chevron-up').removeClass('icon-chevron-down');
            //hide
            checkboxIndexToggle(-1);
            container.removeClass('show');
        }
    }

}

initializeSearchFilterMenu();

$(document).on('click', '.store-dropdown-menu input[type="checkbox"]', function () {
    var $this = $(this);
    var parent = $this.parents('.dropdown');
    var countDisplay = parent.find('button .dropdown-selected');
    var spanChevron = parent.find('span.icon');

    if ($this.attr('checked')) {
        $this.attr('checked', false); //css
        $this.prop('checked', false); //css

    } else {
        $this.attr('checked', true);
        $this.prop('checked', true); // css   
    }

    var selectedCount = $('.store-dropdown-menu input[type="checkbox"]:checked').length;
    searchFilterSelectedCount(selectedCount, countDisplay);

    spanChevron.addClass('icon-chevron-down').removeClass('icon-chevron-up');

});

//  sample output [1] if closetype is "bracket", default is parenthesis choices are ('curly-brace','bracket','parenthesis'(default))
function searchFilterSelectedCount(count, displaySpan, closetype) {
    var b1, b2;

    if (closetype == "curly-brace") {
        b1 = "{",
            b2 = "}";
    } else if (closetype == "bracket") {
        b1 = "[",
            b2 = "]";
    } else {
        b1 = "(",
            b2 = ")";
    }

    if (count < 1) {
        displaySpan.empty();
        displaySpan.attr('aria-hidden', true);
    } else {
        displaySpan.html(b1 + count + b2);
        displaySpan.attr('aria-hidden', false);
    }
}

function selectboxChevronToggle(selectbox) {

    if (spanChevron.hasClass('icon-chevron-up')) {
        spanChevron.removeClass('icon-chevron-up').addClass('icon-chevron-down');
    } else {
        spanChevron.removeClass('icon-chevron-down').addClass('icon-chevron-up');
    }
}

// end custom in store-locator page search

//  start store details button

$(document).on('click', 'button.store-schedule-toggle', function (e) {

    let $this = $(this),
        parentStoreItem = $this.parents('.store-item'),
        distance = parentStoreItem.find('.store-distance'),
        scheduleIcon = $this.find('span.icon'),
        scheduleIconOpen = scheduleIcon.data('icon-expand'),
        scheduleIconClose = scheduleIcon.data('icon-collapse'),
        schedulerContainer = parentStoreItem.find('.store-schedule');

    if (schedulerContainer.hasClass('hide')) {
        $this.attr('aria-label', 'Close Schedule');
        $this.attr('aria-expanded', true);
        schedulerContainer.removeClass('hide');
        distance.removeClass('hide');
        scheduleIcon.addClass(scheduleIconClose).removeClass(scheduleIconOpen);
    } else {
        $this.attr('aria-label', 'Open Schedule');
        $this.attr('aria-expanded', false);
        schedulerContainer.addClass('hide');
        distance.addClass('hide');
        scheduleIcon.addClass(scheduleIconOpen).removeClass(scheduleIconClose);
    }

});

//  end store details button

// for focusable checkbox in tablet store-locator filter
$('.dropdownTablet').on('show.bs.dropdown', function () {
    checkboxIndexToggle(0);
    $('#overlay').css("display", "block");

    setTimeout(function () {
        $('.store-dropdown-menu button.store-checkbox-btn').focus();
        $('.store-dropdown-menu button.store-checkbox-btn').attr('aria-expanded', true);
    }, 100);

}).on('hide.bs.dropdown', function () {
    checkboxIndexToggle(-1);
    $('#overlay').css("display", "none");
    $('.store-dropdown-menu button.store-checkbox-btn').attr('aria-expanded', false);
});

$('.toggle-button-map').on('click', function () {
    let iframeMap = $('#' + $(this).attr('aria-controls'));

    if (iframeMap.hasClass('d-block')) {
        $(this).html($(this).data('expand'));
        iframeMap.removeClass('d-block').addClass('d-none');
        $(this).attr('aria-expanded', false);
    } else {
        $(this).html($(this).data('collapse'));
        $(this).attr('aria-expanded', true);
        iframeMap.removeClass('d-none').addClass('d-block');
    }
});
// js for large device/desktop pin letters generator
$('#slideout-store-details-content').ready(function () {
    let pinLetterLargeDevice = $('#slideout-store-details-content .pin-letter');

    pinLetterLargeDevice.each(function (index) {
        if ((index + 1) > 26) { // add class pin-2-letters for 2 letters in pin logo
            $(this).addClass('pin-2-letters').text(convertToNumberingScheme(index + 1));
        } else {
            $(this).text(convertToNumberingScheme(index + 1));
        }
    });
});
// js for small device/tablet/mobile pin letters generator
$('.store-search-result').ready(function () {
    let pinLetterSmallDevice = $('.store-search-result .pin-letter');

    pinLetterSmallDevice.each(function (index) {
        if ((index + 1) > 26) { // add class pin-2-letters for 2 letters in pin logo
            $(this).addClass('pin-2-letters').text(convertToNumberingScheme(index + 1));
        } else {
            $(this).text(convertToNumberingScheme(index + 1));
        }
    });
});

function convertToNumberingScheme(number) {
    var baseChar = ("A").charCodeAt(0),
        letters = "";

    do {
        number -= 1;
        letters = String.fromCharCode(baseChar + (number % 26)) + letters;
        number = (number / 26) >> 0; // quick `floor`
    } while (number > 0);

    return letters;
}

//Header navigation log-in popup function
$('.nav-login-form-popup.popup').on('click touch', function (event) {
    event.stopPropagation();
});




