
$(document).ready(function () {


const div = document.getElementById("embedded-messaging");
 
        div.style.display = "block"; // Ensure the div is visible

});


/********* Dynamically setting iframe height - Justin ****/
//commenting out because registration is breaking
/*function iframeLoaded() {
    var iFrameID = document.getElementById('bcbst-frame');
    if (iFrameID) {
        // here you can make the height, I delete it first, then I make it again
        var myContHeight = iFrameID.contentWindow.document.body.scrollHeight+150;
        iFrameID.style.minHeight = "";
        iFrameID.style.minHeight = myContHeight + "px";
        console.log("iFrame Content: " + myContHeight + "px");
    }
}

});
*/
/********* Scrolling sneak peek added by Chetan ****/
/*
try {
//var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ? true : false;
    $(document).ready(function () {
 



        //if (isMobile) 

        //if (window.outerWidth <= 767) {
if (window.matchMedia("(max-width: 421px)").matches){
//if (isMobile) {
$(".carousel .item").each(function () {
                var next = $(this).next();
        if (!next.length) {
            next = $(this).siblings(':first');
        }
        next.children(':first-child').clone().appendTo($(this));
        if (next.next().length > 0) {
            next.next().children(':first-child').clone().appendTo($(this));
        } else {
            $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
        }
            })
            
        }


    });

} catch (error) {
    console.log("swipe sneak peek error: " + error)
}
*/
/******* End here*******/



/*  
$(document).ready(function () {
    function centralizedJavaScriptAddition() {
          const centralizedJavascript = document.createElement('script');
          let environment;
          if (app.prodEnvironments.indexOf(app.hostname) > -1) {
              environment = 'www';
          } else {
              environment = 'test';
          }
          centralizedJavascript.setAttribute('type', 'text/javascript');
          centralizedJavascript.setAttribute('src', `https:/www}.bcbst.com/wcm/connect/theme%20elements/themeelements(sa)?cmpntid=d59053f4-8329-416b-91a9-42bdfbf8d5fa&srv=cmpnt&source=library&WCM_Page.ResetAll=TRUE&CACHE=NONE&CONTENTCACHE=NONE&CONNECTORCACHE=NONE`);
          $('head').append(centralizedJavascript);
      }
      centralizedJavaScriptAddition();
        if (location.href.indexOf("bcbst.com/index") > -1) {
            var myLogin = document.getElementById("login-form");
            var myLoginHeight = myLogin.scrollHeight;
            var loginDropdown = document.getElementsByClassName("login-dropdown");
            var headerRight = document.getElementsByClassName("header-right-container");
            var heroForm = document.getElementsByClassName("hero-form");
      
            function loginDropHide() {
                try {
                    if (!($(this).scrollTop() >= (($(myLogin).position().top) + myLoginHeight))) {
                        loginDropdown[0].style.display = "none";
                        headerRight[0].style.paddingRight = "100px";
                    }
                    $(document).on('scroll', function () {
                        if (window.outerWidth < 992 || $(this).scrollTop() >= (($(myLogin).position().top) + myLoginHeight)) {
                            loginDropdown[0].style.display = "flex";
                            headerRight[0].style.paddingRight = "0px";
                        } else {
                            loginDropdown[0].style.display = "none";
                            headerRight[0].style.paddingRight = "100px";
                            document.getElementsByClassName("header-right-container")[0].classList.remove("open");
                        }
                    }); //-->
                } catch (error) {
                    console.log("login scroll function error: " + error)
                }
            }
            window.onresize = function () {
                if (window.outerWidth >= 992) {
                    loginDropHide();
                } else {
                    loginDropdown[0].style.display = "flex";
                    headerRight[0].style.paddingRight = "0px";
                }
            }
            loginDropHide();
        }
      
      
      });
      */
      
      /*  --------------- Login box LOGIN functionality --------------- */
      var brokerLoginURL;
      var employerLoginURL;
      var memberLoginURL;
      let hostEnvironment = "";
      if(window.location.host=="www.bcbst-medicare.com"||window.location.host=="bcbst-medicare.com"||window.location.host=="rlse.bcbst-medicare.com"){
        brokerLoginURL = "https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=FormLoginBroker";
        employerLoginURL ="https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=FormLoginEmployer";
        memberLoginURL ="https://my.bcbst.com/login";
         hostEnvironment = 'www';
      } else if(window.location.host=="test.bcbst-medicare.com" || window.location.host=="apdxwcm02:10042"){
        brokerLoginURL = "https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=LoginTestBroker";
        employerLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=LoginTestEmployer";
        memberLoginURL ="https://portals-stge.bcbst.com/login";
  hostEnvironment = 'test';
      } else if(window.location.host=="dev.bcbstmedicare.com" || window.location.host=="anwas65.bcbst.com"){
        brokerLoginURL = "https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=LoginTestBroker";
        employerLoginURL ="https://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=LoginTestEmployer";
        memberLoginURL ="https://portals-stge.bcbst.com/login";
  hostEnvironment = 'test';;
      }

/////////////////////////////////////
///  Login Global Function
/////////////////////////////////////
function member_login(){
   if(hostEnvironment === 'test'){window.location.href = 'https://portals-stge.bcbst.com/login'}
   else{window.location.href = 'https://my.bcbst.com/login.'}
 }
      
      /******** Form Submission for Hero Logins ***********/
      function postOk() {
        try {
            if (location.href.indexOf("bcbst.com/get-care/personalized-care/managing-chronic-conditions/diabetes") > -1||
               location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/heart-conditions") > -1||
               location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/respiratory-health") > -1||
               location.href.indexOf("/get-care/personalized-care/managing-chronic-conditions/behavioral-health") > -1) {
                window.location.href="https://members.bcbst.com/wps/myportal/member/home/managingyourhealth/caremanagement";
                return false;
            }
            var ok = document.getElementById('ok');
            ok.value = 'clicked';
            var myUser = document.getElementById('username').value;
            var myDropdown = document.getElementById('accountType');
      
            //If it isn't "undefined" and it isn't "null", then it exists.
            if (typeof (mydropdown) != 'undefined' && myDropdown != null) {
                cmCreateRegistrationTag(myUser, "", "", "", "", "", myDropdown.options[myDropdown.selectedIndex].text + "-_-" + window.location.href.split('!')[0]);
            } else {
                cmCreateRegistrationTag(myUser, "", "", "", "", "", "Member-_-" + window.location.href.split('!')[0]);
            }
            document.getElementById('login-form').submit();
            return false;
        } catch (error) {
            console.log("error " + error);
        }
      }
      
      /******** Form Submission for Header Logins ***********/
      function postOkheader() {
        try {
            var ok = document.getElementById('okheader');
            ok.value = 'clicked';
            var myUser = document.getElementById('usernameh').value;
            var myDropdown = document.getElementById('accountTypeh');
            cmCreateRegistrationTag(myUser, "", "", "", "", "", myDropdown.options[myDropdown.selectedIndex].text + '-_-' + window.location.href.split('!')[0]);
            document.getElementById('login-form-header').submit();
            return false;
        } catch (error) {
            console.log("error " + error);
        }
      }
      
       
      function updateURL(loginSelection) {
        if (loginSelection == "mem") {
            document.getElementById("login-form-header").action = memberLoginURL;
            document.getElementById("registration-link").setAttribute("href", "https://www.bcbst.com/register-member");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgot-password");
      $('.username_section').addClass('d-none');
        } else if (loginSelection == "bro") {
            document.getElementById("login-form-header").action = brokerLoginURL;
            document.getElementById("registration-link").setAttribute("href", "https://www.bcbst.com/register/?reg=broker");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword/?usage=forgot");
      $('.username_section').removeClass('d-none');
        } else if (loginSelection == "emp") {
            document.getElementById("login-form-header").action = employerLoginURL;
            document.getElementById("registration-link").setAttribute("href", "https://www.bcbst.com/register/?reg=EMPV");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword/?usage=forgot");
      $('.username_section').removeClass('d-none');	
        } else if (loginSelection == "pro") {
            window.location.href = "https://provider.bcbst.com/";
            $('.username_section').removeClass('d-none');
        }
      }
      
      function updateURL2(loginSelection) {
        if (loginSelection == "mem") {
            document.getElementById("login-form").action = memberLoginURL;
            document.getElementById("hero-registration-link").setAttribute("href", "https://www.bcbst.com/register-member");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgot-password");
      $('.username_section').addClass('d-none');
        } else if (loginSelection == "bro") {
            document.getElementById("login-form").action = brokerLoginURL;
            document.getElementById("hero-registration-link").setAttribute("href", "https://www.bcbst.com/register/?reg=broker");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword/?usage=forgot");
      $('.username_section').removeClass('d-none');
        } else if (loginSelection == "emp") {
            document.getElementById("login-form").action = employerLoginURL;
            document.getElementById("hero-registration-link").setAttribute("href", "https://www.bcbst.com/register/?reg=EMPV");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword/?usage=forgot");
      $('.username_section').removeClass('d-none');
        } else if (loginSelection == "pro") {
            window.location.href = "https://provider.bcbst.com/";
            $('.username_section').removeClass('d-none');
        }
      }
      
      
      /*  --------------- HTML5 Speech Recognition API --------------- */
      /*  ---------------     Future Implementation    ----------------*/
      /*function startDictation() {
            if (window.hasOwnProperty('webkitSpeechRecognition')) {
                var recognition = new webkitSpeechRecognition();
                recognition.continuous = false;
                recognition.interimResults = false;
                recognition.lang = "en-US";
                recognition.start();
                console.log(recognition);
                console.log("speech recognition initiated");
                recognition.onspeechend=function(){
                    console.log("speech has stopped being detected");
                }
                
                recognition.onresult = function(e) {
                    console.log("speech results received");
                    document.getElementById('search-input').value = e.results[0][0].transcript;
                    console.log(e.results[0][0].transcript);
                    recognition.stop();
                    document.getElementById('siteSearch').submit();
                };
                recognition.onerror = function(e) {
                    console.log("speech recognition error");
                    console.log(e);
                    recognition.stop();
                }
            }
        }
      
      */
      
      
      /*  --------------- Accordion JS --------------- */
      /*$(function () {
      var $card = $('.component-text-accordion-card');
      
      $card.on('click', function () {
          var $this = $(this);
          var className = 'open';
      
          $this.toggleClass(className)
      });
      });*/
      
      $(function () {
        var $back = $('.component-text-accordion-content-back-link');
        //var $card = $('.component-text-accordion-card');
        var $card = $('li.component-text-accordion-card'); //only highest level cards
      
        $back.on('click', function (e) {
            e.preventDefault();
      
            var $ul = $card.closest('.component-text-accordion-items');
            var $subMenu = $(this).closest('.component-text-accordion-submenu');
      
            $subMenu.removeClass('show');
            $ul.addClass('show');
        });
      
        $card.on('click', function () {
            var $this = $(this);
            var defaultClassName = 'default';
            var className = 'open';
      
            var $accordion = $this.closest('.component-text-accordion.forms');
            var $ul = $this.closest('.component-text-accordion-items');
      
            if ($ul.length) {
                //var $cards = $ul.find('.component-text-accordion-card');
                var $cards = $ul.find('li.component-text-accordion-card'); //only highest level cards
                var index = $cards.index(this);
                var $subMenus = $ul.siblings('.component-text-accordion-submenu');
                var $subMenu = $subMenus.eq(index);
      
                if ($subMenu.length) {
                    $accordion.find('.' + defaultClassName).removeClass(defaultClassName);
      
                    $ul.removeClass('show');
                    $cards.removeClass(className);
                    $subMenus.removeClass('show');
                    $subMenu.addClass('show');
                    $subMenu.addClass('default');
                }
            }
      
            $this.toggleClass(className)
        });
      
        //BEGIN toggle of lowest-level accordion cards
        $('.component-text-accordion-card-header').on('click', function () {
            var $this = $(this);
            var className = 'open';
            var elementStatus = "noOpen";
            if ($this.closest(".component-text-accordion-card").hasClass(className)) {
                elementStatus = "yesOpen";
            }
            $("div.component-text-accordion-card").removeClass('open'); //only lowest level cards
            if (elementStatus == "noOpen") {
                $this.closest(".component-text-accordion-card").addClass(className);
                var isMobile = /Android|webOS|iPhone|BlackBerry/i.test(navigator.userAgent) ? true : false;
                if(isMobile){
                 $("html, body").animate({ scrollTop: $this.closest(".component-text-accordion").offset().top }, 0);
                }
            }
        });
      });
      
      /*  --------------- Dropdown JS --------------- */
      /*$("#inlineFormCustomSelectPref-upper").change(dropdownSelection);
      
      function dropdownSelection() {
      var selection = $("#inlineFormCustomSelectPref-upper").val();
      if (selection == 0) {
        $(".sec__imageText.homepage .option-one").css("display", "block");
        $(".sec__imageText.homepage .option-two").css("display", "none");
      } else if (selection == 1) {
        $(".sec__imageText.homepage .option-one").css("display", "none");
        $(".sec__imageText.homepage .option-two").css("display", "block");
      } else {
        $(".sec__imageText.homepage .option-one").css("display", "none");
        $(".sec__imageText.homepage .option-two").css("display", "none");
      }
      }*/
      $(function () {
        var $dropdownButtonText = $('#component-dropdown-button-text');
        var $menuItems = $('.component-dropdown-menu-item');
      
        $menuItems.each(function () {
            var $this = $(this);
      
            $this.on('click', function () {
                $dropdownButtonText.text($this.text());
            });
        });
      });
      
      
      /* --------------------- Plan Cards ---------------------*/
      $(function () {
        var $planCards = $('.plan-card');
      
        $planCards.on('click', function () {
            var $this = $(this);
            var $cardsWrapper = $this.parents('#plan-cards');
            var expandedClass = 'plan-card-expanded';
      
            $cardsWrapper.find('.' + expandedClass).removeClass(expandedClass);
      
            $cardsWrapper.addClass('expanded');
            $this.addClass(expandedClass);
      
            $this.children('.plan-card-close').on('click', function (event) {
                event.stopPropagation();
                $("#content").css("overflow-y","auto");
                $('.carousel-item').addClass("item");
                $cardsWrapper.removeClass('expanded');
                $this.removeClass(expandedClass);
      
                $(this).off('click');
            });
            if (window.matchMedia("(max-width: 421px)").matches){
                    if ($('.plan-card').hasClass('plan-card-expanded')) {
                       $("#content").css("overflow-y","hidden");
                       $('.carousel-item').removeClass("item");
                   }
            }
      
           
        });
      });
      
    
      /*  --------------- Hero Homepage JS --------------- */
    //   $(function () {
    //     const $heroIcons = $('.hero-icons');
    //     const $heroSlide = $('.hero-slide');
      
    //     $heroIcons.on('click', '.hero-icon', function heroIconClickHandler(e) {
    //         const $this = $(this);
    //         const className = 'clicked';
      
    //         if (!$this.hasClass(className)) {
    //             const $heroIcon = $('.hero-icon', $heroIcons);
      
    //             $heroIcon.removeClass(className);
    //             $heroSlide.addClass('hide')
      
    //             $this.addClass(className);
      
    //             const selectedIndex = $heroIcon.index(this) + 1;
      
    //             $heroSlide.eq(selectedIndex).removeClass('hide');
    //         }
    //     });
    //   });
      /*  --------------- Menu JS --------------- */
      $(document).ready(function () {
        let cache = {
            closeBtn: $("#close-search"),
            closeBtnDk: $("#close-search-dk"),
            search: $("#do-search"),
            searchDk: $("#do-search-dk"),
            mobileNav: $("#mobile-nav"),
            desktopNav: $("#desktop-nav")
        };
      
        const mqMobile = window.matchMedia('(max-width: 767px)');
      
        const adjustMenu = function () {
            cache.closeBtn.on('click touchstart', function (e) {
                e.preventDefault();
                cache.mobileNav.find('.search-container').fadeOut('fast').removeClass('show');
            });
      
            cache.search.on('click touchstart', function (e) {
                e.preventDefault();
                cache.mobileNav.find('.search-container').addClass('show').fadeIn('fast');
            });
        };
      
        mqMobile.addListener = function () {
            if (mqMobile.matches) {
                adjustMenu();
            }
        };
      
        adjustMenu();
        //  listeners desktop
        cache.searchDk.on('click', function (e) {
            e.preventDefault();
            cache.desktopNav.find('.search-container').addClass('show').fadeIn('fast');
            $(this).hide();
        });
      
        cache.closeBtnDk.on('click', function (e) {
            e.preventDefault();
            cache.desktopNav.find('.search-container').fadeOut('fast').removeClass('show');
            cache.searchDk.show();
        });
      
      
      });
      
      /*  --------------- scrollspy JS --------------- */
      /*!
      * BCBST timeline Plugin
      * Author: Hangar Interactive
      * version: 1.0
      * Licensed under the MIT license
      */
      ;
      (function ($, window, document, undefined) {
        $.fn.extend({
            BCBSTScrollSpy: function (options) {
                let defaults = {
                    jumpToClass: '.jump-to',
                    animate: false,
                    containers: {}
                };
      
                // Add any overriden options to a new object
                options = $.extend({}, defaults, options);
      
                var setNavHeight = function (_navigation) {
                    return _navigation.getBoundingClientRect().height;
                };
      
                var animateOnScroll = function (_links, _nav) {
                    let distance = 0,
                        localNavHeight = setNavHeight(_nav);
      
                    _links.on('click', function (e) {
                        e.preventDefault();
      
                        const body = $('html, body'),
                            id = $(this).attr('href'),
                            queryId = id.substring(1, id.length);
      
                        if ($(id).length) {
                            distance = ($(_nav).length) ? (document.querySelector('[id="${queryId}"]').getBoundingClientRect().top - localNavHeight) : document.querySelector('[id="${queryId}"]').getBoundingClientRect().top;
      
                            body.animate({
                                scrollTop: distance + window.pageYOffset
                            }, 1000);
                        }
                    });
                }
      
                return this.each(function () {
                    const navId = $(this).attr('id'),
                        navigation = document.querySelector('#${navId}'),
                        jumpTo = $(navigation).find(options.jumpToClass);
      
                    let navheight = 0;
                    navheight = setNavHeight(navigation);
      
                    if (options.animate) {
                        animateOnScroll(jumpTo, navigation);
                    }
      
                    //  Attach year on scroll
                    if (options.containers.length > 0) {
                        $(window).on("scroll", function () {
                            options.containers.each(function (index, element) {
                                let $years = (options.isMobile) ? $(navigation).find('.dropdown-item') : $(navigation).find('li'),
                                    windowOffset = window.pageYOffset,
                                    elementOffset = element.getBoundingClientRect().top + window.pageYOffset - 120,
                                    elementHeight = elementOffset + element.offsetHeight + 30;
      
                                if (windowOffset >= elementOffset && windowOffset <= elementHeight) {
                                    $years.removeClass('active');
                                    $years.eq(index).addClass('active');
      
                                    //  Update year into the dropdown button
                                    if (options.isMobile) {
                                        options.dropdownBtn.text($years.eq(index).text());
                                    }
                                    return false;
                                } else {
                                    $years.removeClass('active');
                                }
                            });
                        });
                    }
                });
            }
        });
      })(jQuery, window, document, undefined);
      
      
      
      
      
      
      /*  --------------- MAIN JS --------------- */
      
      
      
      
      
      
      
      $(document).ready(function () {
      
      
        const sidebar = $(".row-offcanvas");
        const toggleSidebarBtn = $(".toggle-hamburger-menu");
        const parent = $(".on").closest("ul");
        const caret = $(".on")
            .closest(".parent-nav-item")
            .find(".caret");
        caret.addClass("close-caret");
      
        parent.addClass("in");
      
        toggleSidebarBtn.on("click", () => {
            sidebar.toggleClass("active");
            toggleSidebarBtn.toggleClass("open");
        });
      
        //new header
      //Adding function below to collapse nav by default on INITIAL VIEW for mobile
      /*******Userstory 484775 - Menu Nav Optimizations Changes by surya- Start******/
      const flyOutMenuButtons = document.getElementsByClassName("nav-item-title");
      var height = $(window).height();
      var width = $(window).width();
      var mappedObj1 = {
        "Our Plans": "Medicare Plans",
        "Use Insurance": "Documents Forms",
        "Blueadvantage" : "Documents Forms"
      }
      var mappedObj = {
        "Our Plans": "Our Plans",
        "Use Insurance": "Use Insurance",
        "": "Our Plans"
      }
      $(document).ready(function() { 
        
        var myPath = window.location.pathname;
        if(myPath === '/'){ 
            sessionStorage.setItem('Navsubmenu', 'Medicare Plans'); 
            sessionStorage.setItem('Navsub', 'Our Plans');
        }else{
        var submenu = sessionStorage.getItem('Navsubmenu');
        if (myPath.split('/' [1] !== "/")) {
            var text = myPath.split('/')[1].toLowerCase().replace(/-/g, " ")
            var Nav = text.replace(/(?:^|\s)\S/g, function(a) {
                return a.toUpperCase();
            });
        }
        if (myPath.split('/')[2]) {
            var text1 = myPath.split('/')[2].toLowerCase().replace(/-/g, " ");
            var submenu1 = text1.replace(/(?:^|\s)\S/g, function(a) {
                return a.toUpperCase();
            });
        
        }
        if (myPath.split('/')[3]) {
            var text2 = myPath.split('/')[3].toLowerCase().replace(/-/g, " ")
            var NavsubThird = text2.replace(/(?:^|\s)\S/g, function(a) {
                return a.toUpperCase();
            });
        }
        if (NavsubThird) {
            submenu1 = NavsubThird;
        }
        if (mappedObj[Nav]) {
            sessionStorage.setItem('Navsub', mappedObj[Nav]);
            if (!(myPath.split('/')[2]) && !(myPath.split('/')[3])) {
                submenu1 = Nav;
            }
        } else {
            sessionStorage.setItem('Navsub', Nav);
        }
      if (mappedObj1[submenu1]) {
            sessionStorage.setItem('Navsubmenu', mappedObj1[submenu1]);
        }  else if(submenu == null || submenu1){  
                sessionStorage.setItem('Navsubmenu', submenu1);
               }else{
                  sessionStorage.setItem('Navsubmenu', submenu); 
               }
      }
      });
      
      function alterClass() {
        var ww = document.body.clientWidth;
        var mobileSwitch = false; //This switch prevents the menu from auto-collapsing again on mobile when resizing the window
        var flyOutMenuButtons = document.getElementsByClassName("nav-item-title");
        var myURL = window.location.href;
        var myPath = window.location.pathname;
        var isSubvalue = false;
      
        if ((myURL.indexOf(".com/employers") < 0) && (myURL.indexOf(".com/brokers") < 0)) {
            if ((sessionStorage.getItem('Navsubmenu'))) {
                for (var i = 0; i < flyOutMenuButtons.length; i++) {
                    flyOutMenuButtons[i].classList.remove("active");
                }
                var navElements = $('.nav-item-title');
                navElements.each(function(navel, el) {
                    el.classList.remove("active");
                    var storedValue = sessionStorage.getItem('Navsub');
                    var selectedValue = el.children[0].text;
                    if (storedValue === null || storedValue === "Contact Us") {
                        storedValue = "Our Plans";
                        sessionStorage.removeItem('Navsubmenu');
                    } 
                    if (storedValue === selectedValue) {
                        el.classList.add("active");
                    }
                });
      
                var navsubElements = $('.nav-item-title.active ul li');
                navsubElements.each(function(subel, subEle) {
                    var storedSubValue = sessionStorage.getItem('Navsubmenu');
                    var selectedSubValue = subEle.children[0].text.replace('&', '').split("  ").join(" ");
                    if(selectedSubValue === "Medicare Plans" || selectedSubValue === "Documents Forms"){
                    if (storedSubValue === selectedSubValue) {
                        isSubvalue = true;
                        subEle.classList.add('newClassName');
                        if ((document.body.clientWidth < 768) || (height > width)) {
                            $('.newClassName a').css('color', '#008cc9');
                            mobileSwitch = true;
                        } else {
                            $('.newClassName').css('border-left-color', '#008cc9');
                            mobileSwitch = false;
                        }
                    }
                }
                });
            } else {
                if ((myPath == "/") && (!flyOutMenuButtons[0].classList.contains("active")) && (!flyOutMenuButtons[1].classList.contains("active")) && (!flyOutMenuButtons[2].classList.contains("active")) && (!flyOutMenuButtons[3].classList.contains("active"))) {
                    sessionStorage.removeItem('Navsubmenu');
                    sessionStorage.removeItem('Navsub');
                    flyOutMenuButtons[0].classList.add("active");
                }
            }
            if(isSubvalue === false) {
                for (var i = 0; i < flyOutMenuButtons.length; i++) {
                    flyOutMenuButtons[i].classList.remove("active");
                } 
                    flyOutMenuButtons[0].classList.add("active");
                
            }
        }
      }
      const headerHamburgerIcon = document.querySelector(".header-hamburger-menu");
      const headerMenu = document.querySelector(".main-nav");
      const headerMenuSubNav = document.querySelector(".sub-nav");
      headerHamburgerIcon.addEventListener("click", function() {
        headerHamburgerIcon.classList.toggle("open");
        headerMenu.classList.toggle("open");
        headerMenuSubNav.classList.toggle("open");
        alterClass();
      })
      
      
      $(window).resize(function() {
        alterClass();
      });
      
      
      //Toggle open menus for header fly out navigation
      var elementIsClicked = false;
      for (var i = 0; i < flyOutMenuButtons.length; i++) {
        flyOutMenuButtons[i].addEventListener("click", function(e) {
            var elementIsClicked = true;
            if (($(e.target).innerText == "Use Insurance" || $(e.target).innerText == "Our Plans") && (elementIsClicked)) {
                this.classList.remove("active")
                var Nav = $(e.target)[0].innerText;
                sessionStorage.setItem('Navsub', Nav);
            } else {
                var submenu = $(e.target)[0].innerText;
                submenu = submenu.replace('&', '').split("  ").join(" ");
                sessionStorage.setItem('Navsubmenu', submenu); 
            }
            if (this.classList.contains("active")) {
                if (document.body.clientWidth < 768) {
                    this.classList.toggle("active");
                }
            } else {
                for (var i = 0; i < flyOutMenuButtons.length; i++) {
                    flyOutMenuButtons[i].classList.remove("active");
                }
                this.classList.toggle("active");
            }
        })
      }
      /*******Userstory 484775 - Menu Nav Optimizations Changes by surya- End******/
      
        //removing the below because querySelectorAll doesn't seem to work in IE
      
        //Toggle open menus for header fly out navigation
        /*const flyOutMenuButtons = document.querySelectorAll(".nav-item-title");
        flyOutMenuButtons.forEach(function(el){
          el.addEventListener("click", function(){
            if(el.classList.contains('active')){
              el.classList.toggle("active");
            } else {
              document.querySelectorAll(".nav-item-title.active").forEach(function(elem) {
                elem.classList.remove("active");
              })
              el.classList.toggle("active");
            }
          })
        })*/
      
      
      
        const searchIcon = document.querySelector(".search-icon");
        searchIcon.addEventListener("click", function () {
            searchIcon.parentNode.parentNode.parentNode.classList.toggle("slide-out");
        })
      
        const closeIcon = document.querySelector(".close-icon")
        closeIcon.addEventListener("click", function () {
            searchIcon.parentNode.parentNode.parentNode.classList.remove("slide-out");
        })
      
      
      
        $(".nav-item").on("click", () => {
            $(this).find(".caret")
                .toggleClass("close-caret");
        });
      
      
        if ($('.component-edit-area').length) {
      
            $('.component-edit-area').each(function () {
      
                var $this = $(this),
                    contentBlockName = $this.attr('data-content-block'),
                    contentBlockHtml = $('#' + contentBlockName).html();
      
                $this.find('textarea').val(contentBlockHtml);
      
            });
      
            $('.btn-view-html').on("click", (e) => {
                e.preventDefault();
      
                var $this = $(this),
                    textHtml = $this.siblings('textarea');
      
                if (textHtml.is(':hidden')) {
                    textHtml.slideDown();
                    $this.text('Hide HTML');
                } else {
                    textHtml.slideUp();
                    $this.text('View HTML');
                }
      
            });
      
            $('.btn-download-html').on("click", (e) => {
                e.preventDefault();
      
                var $this = $(this),
                    contentBlockName = $this.parent('.component-edit-area').attr('data-content-block'),
                    textareaBlock = $this.parent('.component-edit-area').find('textarea');
                try {
                    var refId = textareaBlock.attr('id');
                    saveTextAsFile(contentBlockName, refId);
                } catch (error) {
                    throw error;
                }
            });
      
        }
      
        try {
            var cache = {
                'desktopNav': $("#history-timeline"),
                'mobileNav': $("#history-timeline-mobile"),
                'mqDesktop': window.matchMedia('(min-width: 1200px)'),
                'mqMobile': window.matchMedia('(max-width: 767px)'),
                'mqTablet': window.matchMedia('(min-device-width : 768px) and (max-device-width : 1024px)')
            };
      
            //  Apply when the timeline container exits
            if (cache.desktopNav && cache.mobileNav) {
                timeline({
                    'containers': '.year-details',
                    'main': '.timeline',
                    'global': cache
                });
            }
        } catch (error) {
            console.warn(error);
        }
      
      });
      
      function saveTextAsFile(filename, textId) {
        var textToWrite = document.getElementById(textId).value;
        var textFileAsBlob = new Blob([textToWrite], {
            type: 'text/plain;charset=utf-8'
        });
      
        var downloadLink = document.createElement('a');
        downloadLink.download = filename + "-html.txt";
        //downloadLink.innerHTML = 'Download File';
      
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = 'none';
        downloadLink.dataset.downloadurl = ['text/plain', downloadLink.download, downloadLink.href].join(':');
        document.body.appendChild(downloadLink);
      
      
        downloadLink.click();
      
        return false;
      }
      
      function destroyClickedElement(event) {
        document.body.removeChild(event.target);
      }
      
      /**
      * Build timeline functionality
      * @param {Object} _config (DOM elements linked with the timeline)
      */
      var timeline = function (_config) {
        let timelineContainer = (_config.global.mqMobile.matches) ? _config.global.mobileNav : _config.global.desktopNav;
      
        $(timelineContainer).BCBSTScrollSpy({
            animate: true,
            containers: $(".period-container"),
            dropdownBtn: $("#dropdownMenuButton"),
            isMobile: _config.global.mqMobile.matches
        });
      
        /* Check the location of each element */
        $(_config.main).find(_config.containers).each(function (i) {
      
            let bottom_of_object = $(this).offset().top + $(this).outerHeight()
            bottom_of_window = $(window).height();
      
            if (bottom_of_object > bottom_of_window) {
                $(this).addClass('hidden');
            }
        });
      
        $(window).scroll(function () {
      
            /* Check the location of each element hidden */
            $(_config.main).find('.hidden').each(function (i) {
      
                let bottom_of_object = $(this).offset().top + $(this).outerHeight(),
                    bottom_of_window = $(window).scrollTop() + $(window).height() + timelineContainer.height();
      
                /* If the object is completely visible in the window, fadeIn it */
                if (bottom_of_window > bottom_of_object) {
                    $(this).animate({
                        'opacity': '1'
                    }, 700);
                }
            });
        });
      };
      
      
      
      
      
      
      
      /*  --------------- Prism JS --------------- */
      
      
      
      
      
      
      /* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript */
      var _self = "undefined" != typeof window ? window : "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope ? self : {},
        Prism = function () {
            var e = /\blang(?:uage)?-(?!\*)(\w+)\b/i,
                t = _self.Prism = {
                    util: {
                        encode: function (e) {
                            return e instanceof n ? new n(e.type, t.util.encode(e.content), e.alias) : "Array" === t.util.type(e) ? e.map(t.util.encode) : e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ")
                        },
                        type: function (e) {
                            return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]
                        },
                        clone: function (e) {
                            var n = t.util.type(e);
                            switch (n) {
                                case "Object":
                                    var a = {};
                                    for (var r in e) e.hasOwnProperty(r) && (a[r] = t.util.clone(e[r]));
                                    return a;
                                case "Array":
                                    return e.map && e.map(function (e) {
                                        return t.util.clone(e)
                                    })
                            }
                            return e
                        }
                    },
                    languages: {
                        extend: function (e, n) {
                            var a = t.util.clone(t.languages[e]);
                            for (var r in n) a[r] = n[r];
                            return a
                        },
                        insertBefore: function (e, n, a, r) {
                            r = r || t.languages;
                            var i = r[e];
                            if (2 == arguments.length) {
                                a = arguments[1];
                                for (var l in a) a.hasOwnProperty(l) && (i[l] = a[l]);
                                return i
                            }
                            var o = {};
                            for (var s in i)
                                if (i.hasOwnProperty(s)) {
                                    if (s == n)
                                        for (var l in a) a.hasOwnProperty(l) && (o[l] = a[l]);
                                    o[s] = i[s]
                                } return t.languages.DFS(t.languages, function (t, n) {
                                n === r[e] && t != e && (this[t] = o)
                            }), r[e] = o
                        },
                        DFS: function (e, n, a) {
                            for (var r in e) e.hasOwnProperty(r) && (n.call(e, r, e[r], a || r), "Object" === t.util.type(e[r]) ? t.languages.DFS(e[r], n) : "Array" === t.util.type(e[r]) && t.languages.DFS(e[r], n, r))
                        }
                    },
                    highlightAll: function (e, n) {
                        for (var a, r = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'), i = 0; a = r[i++];) t.highlightElement(a, e === !0, n)
                    },
                    highlightElement: function (a, r, i) {
                        for (var l, o, s = a; s && !e.test(s.className);) s = s.parentNode;
                        s && (l = (s.className.match(e) || [, ""])[1], o = t.languages[l]), a.className = a.className.replace(e, "").replace(/\s+/g, " ") + " language-" + l, s = a.parentNode, /pre/i.test(s.nodeName) && (s.className = s.className.replace(e, "").replace(/\s+/g, " ") + " language-" + l);
                        var u = a.textContent,
                            g = {
                                element: a,
                                language: l,
                                grammar: o,
                                code: u
                            };
                        if (!u || !o) return t.hooks.run("complete", g), void 0;
                        if (t.hooks.run("before-highlight", g), r && _self.Worker) {
                            var c = new Worker(t.filename);
                            c.onmessage = function (e) {
                                g.highlightedCode = n.stringify(JSON.parse(e.data), l), t.hooks.run("before-insert", g), g.element.innerHTML = g.highlightedCode, i && i.call(g.element), t.hooks.run("after-highlight", g), t.hooks.run("complete", g)
                            }, c.postMessage(JSON.stringify({
                                language: g.language,
                                code: g.code
                            }))
                        } else g.highlightedCode = t.highlight(g.code, g.grammar, g.language), t.hooks.run("before-insert", g), g.element.innerHTML = g.highlightedCode, i && i.call(a), t.hooks.run("after-highlight", g), t.hooks.run("complete", g)
                    },
                    highlight: function (e, a, r) {
                        var i = t.tokenize(e, a);
                        return n.stringify(t.util.encode(i), r)
                    },
                    tokenize: function (e, n) {
                        var a = t.Token,
                            r = [e],
                            i = n.rest;
                        if (i) {
                            for (var l in i) n[l] = i[l];
                            delete n.rest
                        }
                        e: for (var l in n)
                            if (n.hasOwnProperty(l) && n[l]) {
                                var o = n[l];
                                o = "Array" === t.util.type(o) ? o : [o];
                                for (var s = 0; s < o.length; ++s) {
                                    var u = o[s],
                                        g = u.inside,
                                        c = !!u.lookbehind,
                                        f = 0,
                                        h = u.alias;
                                    u = u.pattern || u;
                                    for (var p = 0; p < r.length; p++) {
                                        var d = r[p];
                                        if (r.length > e.length) break e;
                                        if (!(d instanceof a)) {
                                            u.lastIndex = 0;
                                            var m = u.exec(d);
                                            if (m) {
                                                c && (f = m[1].length);
                                                var y = m.index - 1 + f,
                                                    m = m[0].slice(f),
                                                    v = m.length,
                                                    k = y + v,
                                                    b = d.slice(0, y + 1),
                                                    w = d.slice(k + 1),
                                                    N = [p, 1];
                                                b && N.push(b);
                                                var O = new a(l, g ? t.tokenize(m, g) : m, h);
                                                N.push(O), w && N.push(w), Array.prototype.splice.apply(r, N)
                                            }
                                        }
                                    }
                                }
                            }
                        return r
                    },
                    hooks: {
                        all: {},
                        add: function (e, n) {
                            var a = t.hooks.all;
                            a[e] = a[e] || [], a[e].push(n)
                        },
                        run: function (e, n) {
                            var a = t.hooks.all[e];
                            if (a && a.length)
                                for (var r, i = 0; r = a[i++];) r(n)
                        }
                    }
                },
                n = t.Token = function (e, t, n) {
                    this.type = e, this.content = t, this.alias = n
                };
            if (n.stringify = function (e, a, r) {
                    if ("string" == typeof e) return e;
                    if ("Array" === t.util.type(e)) return e.map(function (t) {
                        return n.stringify(t, a, e)
                    }).join("");
                    var i = {
                        type: e.type,
                        content: n.stringify(e.content, a, r),
                        tag: "span",
                        classes: ["token", e.type],
                        attributes: {},
                        language: a,
                        parent: r
                    };
                    if ("comment" == i.type && (i.attributes.spellcheck = "true"), e.alias) {
                        var l = "Array" === t.util.type(e.alias) ? e.alias : [e.alias];
                        Array.prototype.push.apply(i.classes, l)
                    }
                    t.hooks.run("wrap", i);
                    var o = "";
                    for (var s in i.attributes) o += s + '="' + (i.attributes[s] || "") + '"';
                    return "<" + i.tag + ' class="' + i.classes.join(" ") + '" ' + o + ">" + i.content + "</" + i.tag + ">"
                }, !_self.document) return _self.addEventListener ? (_self.addEventListener("message", function (e) {
                var n = JSON.parse(e.data),
                    a = n.language,
                    r = n.code;
                _self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r, t.languages[a])))), _self.close()
            }, !1), _self.Prism) : _self.Prism;
            var a = document.getElementsByTagName("script");
            return a = a[a.length - 1], a && (t.filename = a.src, document.addEventListener && !a.hasAttribute("data-manual") && document.addEventListener("DOMContentLoaded", t.highlightAll)), _self.Prism
        }();
      "undefined" != typeof module && module.exports && (module.exports = Prism);;
      Prism.languages.markup = {
        comment: /<!--[\w\W]*?-->/,
        prolog: /<\?[\w\W]+?\?>/,
        doctype: /<!DOCTYPE[\w\W]+?>/,
        cdata: /<!\[CDATA\[[\w\W]*?]]>/i,
        tag: {
            pattern: /<\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
            inside: {
                tag: {
                    pattern: /^<\/?[^\s>\/]+/i,
                    inside: {
                        punctuation: /^<\/?/,
                        namespace: /^[^\s>\/:]+:/
                    }
                },
                "attr-value": {
                    pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
                    inside: {
                        punctuation: /[=>"']/
                    }
                },
                punctuation: /\/?>/,
                "attr-name": {
                    pattern: /[^\s>\/]+/,
                    inside: {
                        namespace: /^[^\s>\/:]+:/
                    }
                }
            }
        },
        entity: /&#?[\da-z]{1,8};/i
      }, Prism.hooks.add("wrap", function (t) {
        "entity" === t.type && (t.attributes.title = t.content.replace(/&amp;/, "&"))
      });;
      Prism.languages.css = {
        comment: /\/\*[\w\W]*?\*\//,
        atrule: {
            pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
            inside: {
                rule: /@[\w-]+/
            }
        },
        url: /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
        selector: /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
        string: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
        property: /(\b|\B)[\w-]+(?=\s*:)/i,
        important: /\B!important\b/i,
        "function": /[-a-z0-9]+(?=\()/i,
        punctuation: /[(){};:]/
      }, Prism.languages.css.atrule.inside.rest = Prism.util.clone(Prism.languages.css), Prism.languages.markup && (Prism.languages.insertBefore("markup", "tag", {
        style: {
            pattern: /<style[\w\W]*?>[\w\W]*?<\/style>/i,
            inside: {
                tag: {
                    pattern: /<style[\w\W]*?>|<\/style>/i,
                    inside: Prism.languages.markup.tag.inside
                },
                rest: Prism.languages.css
            },
            alias: "language-css"
        }
      }), Prism.languages.insertBefore("inside", "attr-value", {
        "style-attr": {
            pattern: /\s*style=("|').*?\1/i,
            inside: {
                "attr-name": {
                    pattern: /^\s*style/i,
                    inside: Prism.languages.markup.tag.inside
                },
                punctuation: /^\s*=\s*['"]|['"]\s*$/,
                "attr-value": {
                    pattern: /.+/i,
                    inside: Prism.languages.css
                }
            },
            alias: "language-css"
        }
      }, Prism.languages.markup.tag));;
      Prism.languages.clike = {
        comment: [{
            pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
            lookbehind: !0
      }, {
            pattern: /(^|[^\\:])\/\/.*/,
            lookbehind: !0
      }],
        string: /("|')(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
        "class-name": {
            pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
            lookbehind: !0,
            inside: {
                punctuation: /(\.|\\)/
            }
        },
        keyword: /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
        "boolean": /\b(true|false)\b/,
        "function": /[a-z0-9_]+(?=\()/i,
        number: /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/,
        operator: /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
        punctuation: /[{}[\];(),.:]/
      };;
      Prism.languages.javascript = Prism.languages.extend("clike", {
        keyword: /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/,
        number: /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
        "function": /(?!\d)[a-z0-9_$]+(?=\()/i
      }), Prism.languages.insertBefore("javascript", "keyword", {
        regex: {
            pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
            lookbehind: !0
        }
      }), Prism.languages.insertBefore("javascript", "class-name", {
        "template-string": {
            pattern: /'(?:\\'|\\?[^'])*'/,
            inside: {
                interpolation: {
                    pattern: /\$\{[^}]+\}/,
                    inside: {
                        "interpolation-punctuation": {
                            pattern: /^\$\{|\}$/,
                            alias: "punctuation"
                        },
                        rest: Prism.languages.javascript
                    }
                },
                string: /[\s\S]+/
            }
        }
      }), Prism.languages.markup && Prism.languages.insertBefore("markup", "tag", {
        script: {
            pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/i,
            inside: {
                tag: {
                    pattern: /<script[\w\W]*?>|<\/script>/i,
                    inside: Prism.languages.markup.tag.inside
                },
                rest: Prism.languages.javascript
            },
            alias: "language-javascript"
        }
      });;
      
      
      
      
      
      
      /*  --------------- KSS JS --------------- */
      
      
      
      
      
      (function () {
        var KssStateGenerator;
      
        KssStateGenerator = (function () {
            var pseudo_selectors;
      
            pseudo_selectors = ['hover', 'enabled', 'disabled', 'active', 'visited', 'focus', 'target', 'checked', 'empty', 'first-of-type', 'last-of-type', 'first-child', 'last-child'];
      
            function KssStateGenerator() {
                var idx, idxs, pseudos, replaceRule, rule, stylesheet, _i, _len, _len2, _ref, _ref2;
                pseudos = new RegExp("(\\:" + (pseudo_selectors.join('|\\:')) + ")", "g");
                try {
                    _ref = document.styleSheets;
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        stylesheet = _ref[_i];
                        if (stylesheet.href && stylesheet.href.indexOf(document.domain) >= 0) {
                            idxs = [];
                            _ref2 = stylesheet.cssRules;
                            for (idx = 0, _len2 = _ref2.length; idx < _len2; idx++) {
                                rule = _ref2[idx];
                                if ((rule.type === CSSRule.STYLE_RULE) && pseudos.test(rule.selectorText)) {
                                    replaceRule = function (matched, stuff) {
                                        return matched.replace(/\:/g, '.pseudo-class-');
                                    };
                                    this.insertRule(rule.cssText.replace(pseudos, replaceRule));
                                }
                                pseudos.lastIndex = 0;
                            }
                        }
                    }
                } catch (_error) {}
            }
      
            KssStateGenerator.prototype.insertRule = function (rule) {
                var headEl, styleEl;
                headEl = document.getElementsByTagName('head')[0];
                styleEl = document.createElement('style');
                styleEl.type = 'text/css';
                if (styleEl.styleSheet) {
                    styleEl.styleSheet.cssText = rule;
                } else {
                    styleEl.appendChild(document.createTextNode(rule));
                }
                return headEl.appendChild(styleEl);
            };
      
            return KssStateGenerator;
      
        })();
      
        new KssStateGenerator;
      
      }).call(this);
      
      
      
      // custom code.
      (function () {
      
      
        // navigation.
        $('.kss-header__hamburger-trigger').on('click', function (e) {
            var kssNavigation = '.kss-navigation',
                kssDocumentation = '.kss-documentation',
                kssHamburger = '.kss-header__hamburger';
      
            if ($(kssNavigation).hasClass('kss-state-active')) {
                $(kssNavigation).removeClass('kss-state-active');
                $(kssDocumentation).removeClass('kss-state-active');
            } else {
                $(kssNavigation).addClass('kss-state-active');
                $(kssDocumentation).addClass('kss-state-active');
            }
      
            if ($(kssHamburger).hasClass('kss-state-active')) {
                $(kssHamburger).removeClass('kss-state-active');
            } else {
                $(kssHamburger).addClass('kss-state-active');
            }
        });
      
      
        // smooth scrolling.
        (function smoothScrolling() {
            $('.kss-nav__item > a[href*=section]').on('click', function (e) {
                if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                    var target = $(this.hash);
                    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      
                    if (target.length) {
                        $('html, body').animate({
                            scrollTop: target.offset().top
                        }, 1000);
      
                        return false;
                    }
                }
            });
        })();
      
      
        // colors.
        (function () {
            var parameters = $('.kss-parameters');
      
            if (parameters) {
                $('.kss-parameters__item').each(function (index) {
                    var description = $(this).find('.kss-parameters__description').text().trim().replace(/; +/g, ';');
                    var colorName = description.split(';')[1] ? description.split(';')[1] : '';
                    var colorVar = $(this).find('.kss-parameters__name').text().trim();
                    var colorCode = description.split(';')[0];
                    var isHexadecimal = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(colorCode);
                    var isRGB = /(rgba?\((?:\d{1,3}(, +|,|\))){3}(?:\d+\.\d+\))?)/i.test(colorCode);
                    var colorContent = '<span class="kss-color__name">' + colorName + '</span>' +
                        '<span class="kss-color__var">' + colorVar + '</span>' +
                        '<span class="kss-color__code">' + colorCode + '</span>';
      
                    if (isHexadecimal || isRGB) {
                        $(this).parent().addClass('kss-colors-container');
                        $(this).addClass('kss-color').css('background', colorCode);
                        $(this).find('.kss-parameters__description').html(colorContent);
                    }
                });
            }
        })();
      
      
      })();
      /*           Registration        */
      $(function () {
        // Modal functionality
        var $registrationSection = $('.registration-section');
      
        $registrationSection.each(function () {
            var $this = $(this);
            var $modalTriggerElement = $this.find('.registration-section-main-sample-link');
            var $modal = $this.find('.registration-section-modal');
            var $modalCloseButton = $modal.find('.registration-section-modal-close');
      
            function toggleModal() {
                $modal.toggleClass('registration-section-modal-visible');
            }
      
            $modalTriggerElement.on('click', toggleModal);
            $modalCloseButton.on('click', toggleModal);
        });
      });
      
      
      
      /*  --------------- Facebook Pixel Code for Medsupp --------------- */
      
      if (window.location.href.indexOf("/medsupp") > -1) {
      !function(f,b,e,v,n,t,s)
      
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      
      n.queue=[];t=b.createElement(e);t.async=!0;
      
      t.src=v;s=b.getElementsByTagName(e)[0];
      
      s.parentNode.insertBefore(t,s)}(window,document,'script',
      
      'https://connect.facebook.net/en_US/fbevents.js');
      
      
      fbq('init', '606929439853627'); 
      
      fbq('track', 'PageView');
      }
      
      /*  ---------------------------------------------------------------- */
      
      
      
      /*-----------------------------------Search JS--------------------------------*/
      
      /*Signals*/
      function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
      }
      
      function getLocalHour() {
      return new Date().getHours();
      } 
      
      var weekday = new Array(7);
      weekday[0] = "Sunday";
      weekday[1] = "Monday";
      weekday[2] = "Tuesday";
      weekday[3] = "Wednesday";
      weekday[4] = "Thursday";
      weekday[5] = "Friday";
      weekday[6] = "Saturday";
      
      function getDateISO() {
      var date = new Date(Date.now());
      return date.getUTCFullYear() +
        '-' + pad(date.getUTCMonth() + 1) +
        '-' + pad(date.getUTCDate()) +
        'T' + pad(date.getUTCHours()) +
        ':' + pad(date.getUTCMinutes()) +
        ':' + pad(date.getUTCSeconds()) +
        '.' + (date.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
      }
      var deviceType = "Computer";
      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
      deviceType = "Mobile";
      }
      // This script sets OSName variable as follows:
      // "Windows"    for all versions of Windows
      // "MacOS"      for all versions of Macintosh OS
      // "Linux"      for all versions of Linux
      // "UNIX"       for all other UNIX flavors 
      // "Unknown OS" indicates failure to detect the OS
      
      var OSName = "Unknown OS";
      if (navigator.appVersion.indexOf("Win") != -1) OSName = "Windows";
      if (navigator.appVersion.indexOf("Mac") != -1) OSName = "MacOS";
      if (navigator.appVersion.indexOf("X11") != -1) OSName = "UNIX";
      if (navigator.appVersion.indexOf("Linux") != -1) OSName = "Linux";
      
      var nVer = navigator.appVersion;
      var nAgt = navigator.userAgent;
      var browserName = navigator.appName;
      var fullVersion = '' + parseFloat(navigator.appVersion);
      var majorVersion = parseInt(navigator.appVersion, 10);
      var nameOffset, verOffset, ix;
      
      // In Opera, the true version is after "Opera" or after "Version"
      if ((verOffset = nAgt.indexOf("Opera")) != -1) {
      browserName = "Opera";
      fullVersion = nAgt.substring(verOffset + 6);
      if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
      }
      // In MSIE, the true version is after "MSIE" in userAgent
      else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
      browserName = "Microsoft Internet Explorer";
      fullVersion = nAgt.substring(verOffset + 5);
      }
      // In Chrome, the true version is after "Chrome" 
      else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
      browserName = "Chrome";
      fullVersion = nAgt.substring(verOffset + 7);
      }
      // In Safari, the true version is after "Safari" or after "Version" 
      else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
      browserName = "Safari";
      fullVersion = nAgt.substring(verOffset + 7);
      if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
      }
      // In Firefox, the true version is after "Firefox" 
      else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
      browserName = "Firefox";
      fullVersion = nAgt.substring(verOffset + 8);
      }
      // In most other browsers, "name/version" is at the end of userAgent 
      else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) <
      (verOffset = nAgt.lastIndexOf('/'))) {
      browserName = nAgt.substring(nameOffset, verOffset);
      fullVersion = nAgt.substring(verOffset + 1);
      if (browserName.toLowerCase() == browserName.toUpperCase()) {
        browserName = navigator.appName;
      }
      }
      // trim the fullVersion string at semicolon/space if present
      if ((ix = fullVersion.indexOf(";")) != -1)
      fullVersion = fullVersion.substring(0, ix);
      if ((ix = fullVersion.indexOf(" ")) != -1)
      fullVersion = fullVersion.substring(0, ix);
      
      majorVersion = parseInt('' + fullVersion, 10);
      if (isNaN(majorVersion)) {
      fullVersion = '' + parseFloat(navigator.appVersion);
      majorVersion = parseInt(navigator.appVersion, 10);
      }
      
      function getLocalDOW() {
      
      return weekday[new Date().getDay()];
      }
      
      function getOS(){
      var userAgent = window.navigator.userAgent,
          platform = window.navigator.platform,
          macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
          windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
          iosPlatforms = ['iPhone', 'iPad', 'iPod'],
          os = null;
       
      
      if (macosPlatforms.indexOf(platform) !== -1) {
        os = 'Mac OS';
      } else if (iosPlatforms.indexOf(platform) !== -1) {
        os = 'iOS'
      } else if (windowsPlatforms.indexOf(platform) !== -1) {
        os = 'Windows';
      } else if (/Android/.test(userAgent)) {
        os = 'Android';
      } else if (!os && /Linux/.test(platform)) {
        os = 'Linux';
      }
      return os
      }
      function isMobileOrTablet(){
        var check = false;
        (function(a){
            if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) 
                check = true;
        })(navigator.userAgent||navigator.vendor||window.opera);
        return check;
      }
      
      function buildQuerySignal(query, filter) {
      
      var timestamp = getDateISO();
      var hours = getLocalHour().toString(); //Getting the hour of day, because this is the hour from the user's perspective
      var dow = getLocalDOW(); //Getting the local day of week, because this is the day from the user's perspective
      var currentURL = window.location.href;
      var currentPath = window.location.pathname;
      var hostName = window.location.hostname;
      var currentTitle = document.title;
      var browserName = window.navigator.userAgent;
      var browserOS = getOS();
      console.log(browserOS);
      var isMobile = isMobileOrTablet();
      var cookieValidation = document.cookie;
      var session;
      var userToken;
      var matchesSession;
      var matchesUserToken;
      
      if (cookieValidation){
        matchesSession = cookieValidation.match(/TLTSID=([^;]+)/);
        matchesUserToken = cookieValidation.match(/TLTUID=([^;]+)/);
        if (matchesSession && matchesSession.length > 1) {
          session = matchesSession[1];
        }
        if (matchesUserToken && matchesUserToken.length > 1){
          userToken = matchesUserToken[1];
        }
      }
      else{
        session = "Null";
        userToken = "Null";
      }
      
      var filterQuery = [];
      var filterSummary = [];
      var filterField = "";
      
      if (filter) {
        filterQuery = ["mime_type:(\"application/pdf\")"];
        filterSummary = ["mime_type/application/pdf"];
        filterField = "mime_type";
      }
      
      var payload = [
        {
          "signalType": "request",
          "timestamp": timestamp,
          "parameters": {
            "dateYear": timestamp,
            "dateMonth": timestamp,
            "query": query,
            "dateDay": timestamp,
            "flag": "event",
            "queryOriginalSignal": query,
            "platform": "BCBST Medicare",
            "source": "BCBST Medicare Search",
            "applicationId": "BCBST Medicare.com",
            "userId": "Anonymous",
            "filterQueries": filterQuery,
            "filter": filterSummary,
                    "uniformResourceLocator": currentURL,
            "urlPath": currentPath,
            "hostName": hostName,
            "pageTitle": currentTitle,
            "filterField": filterField,
            "filter": filterSummary,
            "browserName": browserName,
            "operatingSystemName": browserOS,
            "OperatingSystemDevice" : isMobileOrTablet() ? "Touch" : "Desktop",
            "dayOfWeek": dow,
            "ipAddress": "",
            "session": session,
            "userToken": userToken,
            "date": timestamp,
            "hourOfDay":  hours,
            "fusionQueryId": "",
            "collection": "MAIN"
          }
        }
      ];
      return JSON.stringify(payload);
      }
      
      function buildClickSignal(query, filter, docid, start, position){
      
      var timestamp = getDateISO();
      var hours = getLocalHour(); //Getting the hour of day, because this is the hour from the user's perspective
      var dow = getLocalDOW(); //Getting the local day of week, because this is the day from the user's perspective
      var cookieValidation = document.cookie;
      var session;
      var userToken;
      var matchesSession;
      var matchesUserToken;
      var browserOS = getOS();
      console.log(browserOS);
      var isMobile = isMobileOrTablet();
      
      if (cookieValidation){
        matchesSession = cookieValidation.match(/TLTSID=([^;]+)/);
        matchesUserToken = cookieValidation.match(/TLTUID=([^;]+)/);
        if (matchesSession && matchesSession.length > 1) {
          session = matchesSession[1];
        }
        if (matchesUserToken && matchesUserToken.length > 1){
          userToken = matchesUserToken[1];
        }
      }
      else{
        session = "Null";
        userToken = "Null";
      }
      var filterQuery = [];
      var filterSummary = [];
      var filterField = "";
      
      if (filter) {
        filterQuery = ["mime_type:(\"application/pdf\")"];
        filterSummary = ["mime_type/application/pdf"];
        filterField = "mime_type";
      }
      
      var payload = [
        {
          "signalType": "click",
          "timestamp": timestamp,
          "count": 1,
          "parameters": {
            "date_year": timestamp,
            "date_month": timestamp,
            "query": query,
            "filter": filterSummary,
            "filterQueries": filterQuery,
            "filterField": filterField,
            "applicationId": "BCBST Medicare",
            "session": session,
            "userId": "Anonymous",
            "userToken": userToken,
            "hostName": window.location.hostname,
            "ipAddress": "",
            "platform": "BCBST Medicare",
            "source": "BCBST Medicare",
            "pageTitle": document.title,
            "uniformResourceLocator": window.location.href,
            "documentId": docid,
            "fusionQueryId": "",
            "resourcePosition": position,
            "callType": "result",
            "urlPath": window.location.pathname,
            "browserName": window.navigator.userAgent,
            "operatingSystemName": browserOS,
            "OperatingSystemDevice" : isMobileOrTablet() ? "Touch" : "Desktop",
            "fusionQueryId": "",
            "collection": "MAIN"
          }
        }
      ];
      
      return JSON.stringify(payload);
      }
      
      
      /*Get Fusion */
      function getFusion(url, callBack, retries){
      $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        
        success: callBack,
        error: function(){
         if (!retries){
          retries = 0;
         }
         else if (retries >= 3){
          console.log("Retries Exceeded for " + url);
          return
         }
         setTimeout(function(){getFusion(url, callBack, retries + 1)}, 1000);
        }
      });
      }
      
      /*Post Fusion */
      function postFusion(url, data, retries){
      $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(){},
        error: function(XMLHttpRequest, textStatus, errorThrown){
         if (!retries){
          retries = 0;
         }
         else if (retries >= 3){
          console.log("Retries Exceeded for " + url);
          return
         }
         setTimeout(function(){postFusion(url, data, retries + 1)}, 1000);
        }
      });
      }
      
      /*Post Query Signal */
      function postQuerySignal(query, filter){
      postFusion("/public-search/signal", buildQuerySignal(query, filter));
      }
      
      /*Post Click Signal */
      function postClickSignal(query, filter, docid, start, position){
      postFusion("/public-search/signal", buildClickSignal(query, filter, docid, start, position));
      }
      
      /*Result Click */
      function resultClick(index, docid){
      postClickSignal(currentQuery, currentFilter, docid, currentStart, index);
      }
      
      /*Suggest Method */
      function suggest(query){
      getFusion("/public-search/suggestion?inquiry=" + query + "*" + "&qpParams=medicare" + "&type=Medicare", function (jsonObj){	
      var parseJson = JSON.parse(jsonObj.data.suggestionResponse);	
      console.log(parseJson);
      $('#liveSearchResults').html('');
      var searchField = $('#search-input-dev').val();
      var rEXP = new RegExp(searchField, "i");
        parseJson.grouped.cleantitle_lc_s.doclist.docs.forEach(function(doc) {
        var displayTitle = doc.title;
        var resultURL = doc.id;
        if(parseJson.highlighting && doc.id && parseJson.highlighting[doc.id] && parseJson.highlighting[doc.id].title_t){
          displayTitle = (parseJson.highlighting[doc.id].title_t[0]);
        }
        if(doc.id && doc.id.indexOf("/myportal/") !=-1){
           $('#liveSearchResults').append('<li><a class="search-link" href="' + resultURL + '" target="_blank"' + displayTitle + ' ' + '<img src="https://test.bcbst.com/images/lockA.png" alt="secure icon">' + '</a></li>');
        }
        else{
         $('#liveSearchResults').append('<li><a class="search-link" href="' + resultURL + '" target="_blank"' + displayTitle + ' ' + '</a></li>');
        }
        
        });
          
        /*Select Text From List
        $('#liveSearchResults').on('click', 'li', function() {
        var resultsText = $(this).text();
        $('#search-input-dev').val(resultsText);
        $("#liveSearchResults").html('');
        submitSearch(0);
        });*/
      });
      };
      
      var currentStart;
      var currentFilter;
      var currentQuery;
      var currentOrder;
      let searchType = 'keyword search'
        
    function analyticsAdd(event, searchT, resultCount, searchStatus) {
        if(event == "search_result") {
            dataLayer.push({
                'event': event,
                'search_type': searchT,
                'result_count': resultCount,
                'search_status': searchStatus
            });
            console.log({
                'event': event,
                'search_type': searchT,
                'result_count': resultCount,
                'search_status': searchStatus
            });
        } else if(event == "search") {
            dataLayer.push({
                'event': event,
                'search_type': searchT,
            });
            console.log({
                'event': event,
                'search_type': searchT,
            });
        }
        
    }
    
      
      
      /*Query Method*/
      function queryFusion(query, start, rows, filter, order){
        currentStart = start;
        currentFilter = filter;
        currentQuery = query;
            currentOrder = order;
            var sortParameter = "";
        var radioSelection = "";
        var filterValue = "";
        pdfValue = "0";
        console.log("Total number of PDF files: " + pdfValue);
        postQuerySignal(query, filter);
            /*Dropdown Logic*/
        if (currentOrder == "Newest"){
          sortParameter = "&sortBy=lastModified_dt desc";
        }
        else if(currentOrder == "Oldest"){
          sortParameter = "&sortBy=lastModified_dt asc";
        } 
            console.log("Selected Sort: " + currentOrder);
        getFusion("/public-search/inquiry?inquiry=" + query + (filter ? "&filterQuery=mime_type:(%22application/pdf%22)" : "") + "&cursorValue=" + (start*rows) + "&numberOfRows=" + rows + "&qpParams=medicare" + sortParameter, function (jsonObj){	
        var parseJson_2 = JSON.parse(jsonObj.data.inquiryResponse);	
        console.log(parseJson_2);
    if(jsonObj == null){
            analyticsAdd('search_result', searchType, 0, 'unsuccessful')
            console.log(dataLayer)
        }
        else {
            analyticsAdd('search_result', searchType, parseJson_2.response.numFound, 'successful')
        }
        $('#liveSearchResults').html('');
        $('#searchResults').html('');
        
        updatePagination(parseJson_2, start);
        var numR = parseJson_2.response.numFound;
        fusionId = parseJson_2.responseHeader.params.fusionQueryId;
        function passId(){
          fusionId = parseJson_2.responseHeader.params.fusionQueryId;
          console.log("Pass ID: " + fusionId);
          return fusionId;
        }
        document.getElementById("returnedOutput").innerHTML = "";
        $("#returnedOutput").append("<h1>Showing" + " " + numR + " " + "results for" + " " + "'" + currentQuery + "'" + "</h1>");
        console.log("Number of returned results: " + numR);
        if (numR > 0){
          document.getElementById("results-pagination").style.display = "flex";
        }
        
         if (parseJson_2.fusion != null){
            const myObj = JSON.parse(parseJson_2.fusion.banner);
            var bannerTitle = myObj.url;
            if ($("#banner").html().length > 0){
                      // console.log("Content Already Exisits");	
            }
            else{
                    if(bannerTitle === "EOC_banner"){
                        $("#banner").append(`<p dir="ltr">Looking for an Evidence of Coverage for your plan?&nbsp;<a href="https://www.bcbst-medicare.com/use-insurance/documents-forms/blueadvantage" target="_blank"  class="button primary">Go here to find your Evidence of Coverage</a></p>
`);
                        $("#banner").show();
                    }
                    else if(bannerTitle === "OTC_Formulary_Banner"){
                        $("#banner").append(`<p dir="ltr">Looking for our Over-the-counter (OTC) catalog?<a href="https://www.bcbst-medicare.com/use-insurance/helpful-tools-resources/medicare" target="_blank"  class="button primary">Go here to learn more and shop online.</a></p>
`);
                        $("#banner").show();
                    }
                    else{
                        $("#banner").hide(); 
                    }
            }
            }
        
        
        
        /*Display Search Results*/
        parseJson_2.response.docs.forEach(function(doc, index){
          var displayTitle = doc.title;
          var displayDesc;
          var hrefID = doc.id;
          var pdfCheck = hrefID.substr(hrefID.lastIndexOf('.')).toLowerCase();
          if (pdfCheck  === '.pdf') {
            pdfValue++;
          }
                if(doc.description){
                    displayDesc = doc.description + "...";
                }
          if(parseJson_2.highlighting && doc.id && parseJson_2.highlighting[doc.id] && parseJson_2.highlighting[doc.id].title_t){
              displayTitle = (parseJson_2.highlighting[doc.id].title_t[0]);
          }
          if(parseJson_2.highlighting && doc.id && parseJson_2.highlighting[doc.id] && parseJson_2.highlighting[doc.id].description_t){
              displayDesc = (parseJson_2.highlighting[doc.id].description_t[0]) + "...";
          }
          if(!displayTitle){
            displayTitle = hrefID;
          }
          if(!displayDesc){
            displayDesc = "";
          }
          if(doc.id && doc.id.indexOf("/myportal/") !=-1){
            $("#searchResults").append("<li>" + hrefID + "<br><a onclick='resultClick("+ index +","+ JSON.stringify(hrefID).replace(/'/g, "\\'") + ")' href='"  + hrefID + "'>" + displayTitle + '<img src="https://test.bcbst.com/images/lockA.png" alt="secure icon">' + " " + "</a><br>" + displayDesc + "</li>" + "<br>");
          }
          else{
            $("#searchResults").append("<li>" + hrefID + "<br><a onclick='resultClick("+ index +","+ JSON.stringify(hrefID).replace(/'/g, "\\'") + ")' href='"  + hrefID + "'>" + displayTitle + "</a>" + "<br>" + displayDesc + "</li>" + "<br>");
          }
        });
        if(pdfValue > 0){
          document.getElementById("filterPdf").style.display = "block";
        }
      });
      }
      
      /*Submit Search */
      function submitSearch(start){
      var searchField = $('#search-input-dev').val();
      var pdfFilter = $('#pdfFilter').is(":checked");
      var orderSelect = $("#orderSelect option:selected").text();
      queryFusion(searchField, start, 10, pdfFilter, orderSelect);
      }
      
      /*Pagination*/
      function clickValue(value){
      submitSearch(value);
      }
        
      function updatePagination(parseJson_2, currentPage){
      document.getElementById("results-pagination").innerHTML = "";
      var totalReturned = parseJson_2.response.numFound; //Total found
      var rowsPerPage = 10;
      var maxPagesFirst = 5;
      var maxPagesSecond = 2;
      var pageThreshold = 5;
      var remaining;
      var totalPages = Math.ceil(totalReturned/rowsPerPage);    
      
      
      if(currentPage > 0){
      //enable prev (link w/currentPage-1)
      $('#results-pagination').append('<li class="page-item active"><span class="page-link" href="#" tabindex="-1" onclick="clickValue(' + (currentPage -1) + ')">Previous</span>');
      }else{
      //disable prev
      $('#results-pagination').append('<li class="page-item disabled"><span class="page-link" href="#" tabindex="-1">Previous</span>');
      }
      
      if(currentPage >= pageThreshold && currentPage  >= (totalPages - pageThreshold)){
        //Format 2 ... 5
        remaining = paginate(totalReturned, maxPagesSecond, rowsPerPage,0);
        $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
        remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage, totalPages - pageThreshold);
      }else  if(currentPage >= pageThreshold ){
        //Format 2 ... 5 ... 2
        remaining = paginate(totalReturned, maxPagesSecond, rowsPerPage,0);
        $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
        remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage,currentPage);
           //Format 5 ... 2
        if(remaining.pagesLeft > 0) {
          $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
          paginate(totalReturned, maxPagesSecond, rowsPerPage, remaining.pageCount - (remaining.pagesLeft-2 > 0  ? 2 : 1));
        }
      }else {
        //Format 5 ... 2
        remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage,currentPage);
        if(remaining.pagesLeft > 0) {
          $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
          paginate(totalReturned, maxPagesSecond, rowsPerPage, remaining.pageCount - (remaining.pagesLeft-2 > 0  ? 2 : 1));
        }
      }
      
      if(currentPage != (totalPages-1)){
        //enable next (Link with currentPage+1)
        $('#results-pagination').append('<li class="page-item active"><span class="page-link" onclick="clickValue(' + (currentPage + 1) + ')">Next</span>');
      }else{
        //disable next
        $('#results-pagination').append('<li class="page-item disabled"><span class="page-link">Next</span>');
      }
      }
      
      
      function paginate( totalResults, maxPages, rowsPerPage, startPage ){
      var total = Math.ceil(totalResults/rowsPerPage)*rowsPerPage;    
      var pageCount = Math.ceil(totalResults/rowsPerPage);    
      var remaining = {
        pageCount: pageCount,
        pagesConsumed: -1,
        pagesLeft: -1,
        rowsLeft: -1
      };
      
      pageCount = Math.min(pageCount,maxPages+startPage);
      remaining.pagesConsumed = pageCount;
      remaining.pagesLeft = remaining.pageCount - remaining.pagesConsumed;
      remaining.rowsLeft = totalResults - (remaining.pagesConsumed * rowsPerPage);
      
      for (let index = startPage; index < pageCount; index++) {
        var value = (index+1);
        $('#results-pagination').append('<li class="page-item"><span class="page-link" onclick="clickValue(' + index + ')">' + value + '</span></li>');	
      }
      
      return remaining;
      }
      
      
      // Live Search Part
      let searchAnalyticsTriggered = false;
      $(document).ready(function(){
      $('#search-input-dev').keyup(function(event){
        $('#search-input-dev').keydown(function(event){
            if(event.keyCode === 13 && searchAnalyticsTriggered === false){
                searchAnalyticsTriggered = true;            
                analyticsAdd('search', searchType);
            }
        })
        if (event.which === "/n"){
          submitSearch(0);
        }
        if($('#search-input-dev').val().length > 2){
            suggest($('#search-input-dev').val());
        };	
        if($('#search-input-dev').val().length === 0){
          suggest($('#search-input-dev').val());
          console.log("search is zero");
        };
setTimeout(() =>{
    $('#liveSearchResults li .search-link').on('click', function(){
        searchType = 'suggested search'
        analyticsAdd('search', searchType);
    });
}, 1500);
      });
      });
      
      
      
        //   Get Search Results
      $(document).ready(function(){
      var qString = window.location.search;
      var currentURL = window.location.href;
      var userInput = getParameterByName("q" , qString);
      $('#search-input-dev').val(userInput);
      if (userInput && userInput.length > 0){
      submitSearch(0);
      }
      /*Checkbox Filter*/	
       $('#pdfFilter').change(function(){
        submitSearch(0);
      });
        /*Order Change*/
       $('#orderSelect').change(function(){
        submitSearch(0);
      });
      });
      
      
      
      function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
      }
      
      $(document).ready(function(){
        const domain = window.location.pathname.split('/').reverse()[0];
        if (window.location.hostname.indexOf('anwas65') > -1) {
           $("a[href^='/']").each(function() {
             this.href = this.href.replace("https://anwas65.bcbst.com:10042/", "https://anwas65.bcbst.com:10042/publicsites/" + domain + "/");
           });
        } else if (window.location.hostname.indexOf('apdxwcm') > -1) {
           $("a[href^='/']").each(function() {
             this.href = this.href.replace("https://apdxwcm02:10042/", "https://apdxwcm02:10042/publicsites/" + domain + "/");
           });
        }
      });

///////////////////////////////////////////////
// Dynamic Mobile Functions
///////////////////////////////////////////////
let isMobile = false;
$(document).ready(() => {
    checkMobile();
    mobilePhoneLink();
    $(window).on("resize", () => {
        checkMobile();
        if (isMobile === true) mobilePhoneLink();
    });
});


///////////////////////////////////////////////
// Creation of Dynamic Phone links
///////////////////////////////////////////////
let mobileLinkCreated = false;
function mobilePhoneLink() {
    if(mobileLinkCreated === false && isMobile === true) {
        $('.dynamicPhone').each(function(ind) {
            const phoneLink = document.createElement('a');
            phoneLink.href = `tel:${$(this).text().replaceAll('-','')}`;
            phoneLink.innerHTML = $(this).text();
            if ($(this).hasClass('text-white')) phoneLink.classList = 'text-white';
            $(this).contents().filter(function(){ return this.nodeType != 1; }).remove();
            $(this).append(phoneLink);
        });
        mobileLinkCreated = true;
    };
}

///////////////////////////////////////////////
// Mobile Check Function
///////////////////////////////////////////////
function checkMobile() {
    const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if(width < 768) isMobile = true;
    else isMobile = false;
};


////////////////////////////////////
///  Dynamic Banner Display
/////////////////////////////////////
$(document).ready(function() {
    let loc_host;
    // Assigns host variable with proxy endpoint based on which environment is being loaded.
    if (window.location.host == "test.bcbst.com" || window.location.host == "andxtst03:10062" ||
        window.location.host == "test-bluecare.bcbst.com" || window.location.host == "test-bluecareplus.bcbst.com" ||
        window.location.host == "provider-test.bcbst.com" || window.location.host == "broker-test.bcbst.com" ||
        window.location.host == "employer-test.bcbst.com" || window.location.host == "medicare-test.bcbst.com") {
        loc_host = "https://api2.bcbst.com/api/proxyservice/bannerMessage";
    }else{
        loc_host = "https://api.bcbst.com/api/proxyservice/bannerMessage";
    }
    
    let domain_json = {
        "domain_map": {
                "bcbst": {
                    "dev":  "dev.bcbst.com",
                    "test": "test.bcbst.com",
                    "prod": "www.bcbst.com"
                },
                "medicare": {
                    "dev":  "dev.bcbstmedicare.com",
                    "test": "test.bcbst-medicare.com",
                    "prod": "www.bcbst-medicare.com"
                },
                "bluecare": {
                    "dev":  "dev-bluecare.bcbst.com",
                    "test": "bluecare-test.bcbst.com",
                    "prod": "bluecare.bcbst.com"
                },
                "bluecareplus": {
                    "dev":  "dev-bluecareplus.bcbst.com",
                    "test": "test-bluecareplus.bcbst.com",
                    "prod": "bluecareplus.bcbst.com"
                },
                "provider": {
                    "dev":  "provider-dev.bcbst.com/",
                    "test": "provider-test.bcbst.com",
                    "prod": "provider.bcbst.com"
                },
                "employer": {
                    "dev":  "employer-dev.bcbst.com",
                    "test": "employer-test.bcbst.com",
                    "prod": "employer.bcbst.com"
                },
                "broker": {
                    "dev":  "broker-dev.bcbst.com",
                    "test": "broker-test.bcbst.com",
                    "prod": "broker.bcbst.com"
                }
            }
        }

    $.get(loc_host, function(data) {
        //Fixed
        if (data.global_fixed) {
            const globalMsg = data.global_fixed.Banner_Message;
            const globalStart = data.global_fixed.Start;
            const globalEnd = data.global_fixed.End;
            const currentTime = new Date();
            const formattedCurrentTime = currentTime.getFullYear() + '-' +
                ('0' + (currentTime.getMonth() + 1)).slice(-2) + '-' +
                ('0' + currentTime.getDate()).slice(-2) + ' ' +
                ('0' + currentTime.getHours()).slice(-2) + ':' +
                ('0' + currentTime.getMinutes()).slice(-2) + ':' +
                ('0' + currentTime.getSeconds()).slice(-2);

            if (formattedCurrentTime >= globalStart && formattedCurrentTime <= globalEnd) {
                $('#alert-bar').html(globalMsg).show();
            } else {
                $('#alert-bar').hide();
            }
        }

        //Unique
        if (data.banner_Message && Array.isArray(data.banner_Message.unique)) {
            let showUnique = false;
            let uniqueMsg = '';
            const currentDomain = window.location.host.toLowerCase();
            const currentTime = new Date();
            const formattedCurrentTime = currentTime.getFullYear() + '-' +
                ('0' + (currentTime.getMonth() + 1)).slice(-2) + '-' +
                ('0' + currentTime.getDate()).slice(-2) + ' ' +
                ('0' + currentTime.getHours()).slice(-2) + ':' +
                ('0' + currentTime.getMinutes()).slice(-2) + ':' +
                ('0' + currentTime.getSeconds()).slice(-2);

            function getDomainProperty(currentDomain, domainMap) {
                currentDomain = currentDomain.toLowerCase();
                for (const prop in domainMap) {
                    const devDomain = domainMap[prop].dev.toLowerCase();
                    const testDomain = domainMap[prop].test.toLowerCase();
                    const prodDomain = domainMap[prop].prod.toLowerCase();
                    if (currentDomain === testDomain || currentDomain === prodDomain || currentDomain === devDomain) {
                        return prop;
                    }
                }
                return null;
            }
            const matchedProperty = getDomainProperty(currentDomain, domain_json.domain_map);
            data.banner_Message.unique.forEach(function(item) {
                if (item.domain && item.domain.toLowerCase() === matchedProperty) {
                    // Check force_override
                    if (item.force_override === true) {
                        showUnique = false;
                        return; 
                    }
                    if (item.Start && item.End &&
                        formattedCurrentTime >= item.Start &&
                        formattedCurrentTime <= item.End) {
                        if (item.Banner_Message && item.Banner_Message.trim() !== '') {
                            showUnique = true;
                            uniqueMsg += item.Banner_Message;
                        } else {
                            showUnique = false;
                        }
                    }
                }
            });
            if (showUnique && uniqueMsg) {
                $('#unique-alert-bar p').html(uniqueMsg).show();
            } else {
                $('#unique-alert-bar').hide();
            }
        }
    }).fail(function(error) {
        console.error("Error fetching JSON banner data: ", error);
    });
});