/*  --------------- Login box SCROLLING functionality --------------- */
$(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();
  
  
  
    try{
        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");
  
  
            loginDropdown[0].style.display="none";
            headerRight[0].style.paddingRight="100px";
            $(document).on('scroll', function() {
                if($(this).scrollTop()>=(($(myLogin).position().top)+myLoginHeight)){
                    loginDropdown[0].style.display="flex";
                    headerRight[0].style.paddingRight="unset";
                }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 functionality error: " + error)
    }
  });
  
  /*  --------------- Login box LOGIN functionality --------------- */
  
  
  /******** Form Submission for Hero Logins ***********/
  function postOk() {
    var ok = document.getElementById('ok');
    ok.value = 'clicked';
    document.getElementById('login-form').submit();
    return false;
  }
  
  /******** Form Submission for Header Logins ***********/
  function postOkheader() {
    var ok = document.getElementById('okheader');
    ok.value = 'clicked';
    document.getElementById('login-form-header').submit();
    return false;
  }
  
  $(document).ready(function() {
  let loginSelection = 'emp';
  updateURL(loginSelection);
  updateURL2(loginSelection);
  });
  
  const loginApp = {
  dev: window.location.host=="employer-dev.bcbst.com" || window.location.host=="anwas65.bcbst.com:10042",
  test: window.location.host=="employer-test.bcbst.com" || window.location.host=="andxtst03:10062",
  prod: window.location.host=="employer.bcbst.com"||window.location.host=="bcbst.com",
  heroLoginID: "login-form",
  headerLoginID: "login-form-header",
  heroRegistrationID: "hero-registration-link",
  headerRegistrationID: "registration-link",
  devLogin: "https://sso2.bcbst.com/pf/adapter2adapter.ping",
  testLogin: "https://sso3.bcbst.com/pf/adapter2adapter.ping",
  prodLogin: "https://sso.bcbst.com/pf/adapter2adapter.ping",
  memberLogin: "?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest",
  brokerLogin: "?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=FormLoginBroker",
  employerLogin: "?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=FormLoginEmployer",
  }
  
  function updateURL(loginSelection) {
  if (loginSelection == "mem") {
    $('.username_section').addClass('d-none');
    if (document.getElementById(loginApp.headerRegistrationID)) {
      document.getElementById(loginApp.headerRegistrationID).setAttribute("href", "https://www.bcbst.com/register-member");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgot-password");
  }
    if (document.getElementById(loginApp.headerLoginID)) {
        if (loginApp.prod) {
            document.getElementById(loginApp.headerLoginID).action = "https://my.bcbst.com/login";
          } else if (loginApp.test) {
            document.getElementById(loginApp.headerLoginID).action = "https://portals-stge.bcbst.com/login";
          } else if (loginApp.dev) {
            document.getElementById(loginApp.headerLoginID).action = "https://portals-stge.bcbst.com/login";
          }
    }
  } else if (loginSelection == "bro") {
    $('.username_section').removeClass('d-none');
    if (document.getElementById(loginApp.headerRegistrationID)) {
      document.getElementById(loginApp.headerRegistrationID).setAttribute("href", "https://www.bcbst.com/register?reg=broker");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword?usage=forgot");
  }
    if (document.getElementById(loginApp.headerLoginID)) {
      if (loginApp.prod) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.prodLogin + loginApp.brokerLogin;
      } else if (loginApp.test) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.testLogin + loginApp.brokerLogin;
      } else if (loginApp.dev) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.devLogin + loginApp.brokerLogin;
      }
    }
  } else if (loginSelection == "emp") {
    $('.username_section').removeClass('d-none');
    if (document.getElementById(loginApp.headerRegistrationID)) {
      document.getElementById(loginApp.headerRegistrationID).setAttribute("href", "https://www.bcbst.com/register?reg=EMPV");
      document.getElementById("forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword?usage=forgot");  
  }
    if (document.getElementById(loginApp.headerLoginID)) {
      if(loginApp.prod) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.prodLogin + loginApp.employerLogin;
      } else if(loginApp.test) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.testLogin + loginApp.employerLogin;
      } else if(loginApp.dev) {
        document.getElementById(loginApp.headerLoginID).action = loginApp.devLogin + loginApp.employerLogin;
      }
    }
  } else if (loginSelection == "pro") {
    $('.username_section').removeClass('d-none');
      window.location.href = "https://provider.bcbst.com/";
  }
  }
  
  function updateURL2(loginSelection) {
  if (loginSelection == "mem") {
    $('.username_section').addClass('d-none');
    if (document.getElementById(loginApp.heroRegistrationID)) {
      document.getElementById(loginApp.heroRegistrationID).setAttribute("href", "https://www.bcbst.com/register-member");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgot-password");  
  }
    if (document.getElementById(loginApp.heroLoginID)) {
        if(loginApp.prod){
            document.getElementById(loginApp.heroLoginID).action = "https://my.bcbst.com/login";
          } else if(loginApp.test){
            document.getElementById(loginApp.heroLoginID).action = "https://portals-stge.bcbst.com/login";
          } else if(loginApp.dev){
            document.getElementById(loginApp.heroLoginID).action = "https://portals-stge.bcbst.com/login";
          }
    }
  } else if (loginSelection == "bro") {
    $('.username_section').removeClass('d-none');
    if (document.getElementById(loginApp.heroRegistrationID)) {
      document.getElementById(loginApp.heroRegistrationID).setAttribute("href", "https://www.bcbst.com/register?reg=broker");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword?usage=forgot");  
  }
    if (document.getElementById(loginApp.heroLoginID)) {
      if(loginApp.prod){
        document.getElementById(loginApp.heroLoginID).action = loginApp.prodLogin + loginApp.brokerLogin;
      } else if(loginApp.test){
        document.getElementById(loginApp.heroLoginID).action = loginApp.testLogin + loginApp.brokerLogin;
      } else if(loginApp.dev){
        document.getElementById(loginApp.heroLoginID).action = loginApp.devLogin + loginApp.brokerLogin;
      }
    }
  } else if (loginSelection == "emp") {
    $('.username_section').removeClass('d-none');
    if (document.getElementById(loginApp.heroRegistrationID)) {
      document.getElementById(loginApp.heroRegistrationID).setAttribute("href", "https://www.bcbst.com/register?reg=EMPV");
      document.getElementById("hero-forgot-link").setAttribute("href", "https://www.bcbst.com/forgotpassword?usage=forgot"); 
  }
    if (document.getElementById(loginApp.heroLoginID)) {
      if(loginApp.prod){
        document.getElementById(loginApp.heroLoginID).action = loginApp.prodLogin + loginApp.employerLogin;
      } else if(loginApp.test){
        document.getElementById(loginApp.heroLoginID).action = loginApp.testLogin + loginApp.employerLogin;
      } else if(loginApp.dev){
        document.getElementById(loginApp.heroLoginID).action = loginApp.devLogin + loginApp.employerLogin;
      }
    }
  } else if (loginSelection == "pro") {
    $('.username_section').removeClass('d-none');
      window.location.href = "https://provider.bcbst.com/";
  }
  }
  
  /*  --------------- 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);
  }
  });
  });
  
  /*  --------------- 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();
  
      $cardsWrapper.removeClass('expanded');
      $this.removeClass(expandedClass);
  
      $(this).off('click');
    });
  });
  });
  
  /*  --------------- 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");
  });
  
   /*******Userstory 485364 - Menu Nav Optimizations Changes by surya- Start******/
  const flyOutMenuButtons = document.getElementsByClassName("nav-item-title");
  var MobileTab = /Android|webOS|iPhone|BlackBerry/i.test(navigator.userAgent) ? true : false;
  var height = $(window).height();
  var width = $(window).width();
  var mappedObj = {
    "": "Employers Overview",
    "Calculator": "Effective Date Calculator",
    "Ancillary Employee Benefit Plans": "Other Coverage Plans",
    "Individual": "Individual Products",
    "Group": "Group Products",
    "Medicare": "Medicare Products",
    "Update Inforamtion": "Update Your Info Form",
    "Compliance And Ethics": "Compliance Ethics"
  }
  
  $(document).ready(function() {
    var submenu = sessionStorage.getItem('Navsubmenu');
    var myPath = window.location.pathname;
    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);
    }
  });
  
  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('Navsub'))) {
            var navElements = $('.nav-item-title.active ul li');
            navElements.each(function(navel, el) {
                var storedValue = sessionStorage.getItem('Navsub');
                var selectedValue = el.children[0].text.replace('&', '').split("  ").join(" ");
                    if (storedValue === selectedValue) {
                        isSubvalue = true;
                        if (isSubvalue === true) {
                            el.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;
                            }
                        }
                        /* el.classList.add("active");*/
                    }
                
                if (storedValue === null || storedValue === "Contact Us") {
                    storedValue = "Our Plans";
                    sessionStorage.removeItem('Navsubmenu');
                }
  
            });
        } 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) {
        $('.sub-nav-icon-link').css('border-left-color', '');
        $('.sub-nav-icon-link').css('color', '');
        var elementIsClicked = true;
        if ($(e.target).hasClass('nav-item-link') && elementIsClicked) {
            this.classList.remove("active")
            var Nav = $(e.target)[0].innerText;
            sessionStorage.setItem('Navsub', Nav);
            if ((document.body.clientWidth < 768) || (height > width)) {
                $('.sub-nav-icon-link a').css('color', '#008cc9');
                mobileSwitch = true;
            } else {
                $('.sub-nav-icon-link').css('border-left-color', '#008cc9');
                mobileSwitch = false;
            }
  
        }
        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 485364 - 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);
  });
  });
  
  
  
  
  /*-----------------------------------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 session = document.cookie.match(/TLTSID=([^;]+)/);
        if(session){
           session = document.cookie.match(/TLTSID=([^;]+)/)[1];
        }
        else{
        session = "undefined";
        }
  var userToken = document.cookie.match(/TLTUID=([^;]+)/);
        if(userToken){
        userToken = document.cookie.match(/TLTUID=([^;]+)/)[1];
        }
        else{
        userToken = "undefined";
        } 
  
  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",
        "source": "Employer Search",
        "applicationId": "Employer",
        "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": "173.223.74.189",
        "session": session,
        "userToken": userToken,
        "date": timestamp,
        "hourOfDay":  hours,
        "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 filterQuery = [];
  var filterSummary = [];
  var filterField = "";
  
  if (filter) {
    filterQuery = ["mime_type:(\"application/pdf\")"];
    filterSummary = ["mime_type/application/pdf"];
    filterField = "mime_type";
  }
  
  var payload = [
    {
      "type": "click",
      "timestamp": timestamp,
      "count_i": 1,
      "params": {
        "date_year": timestamp,
        "date_month": timestamp,
        "query": query,
        "date_day": timestamp,
        "flag_s": "event",
        "doc_id": docid,
        "query_orig_s": query,
        "platform": "BCBST",
        "source": "Public Search",
        "user_id": "Anonymous",
        "user_token": "Anonymous",
        "day_of_week": dow,
        "date": timestamp,
        "attr_date_": [
          timestamp
        ],
        "attr_timestamp_tdt_": [
          timestamp
        ],
        "hour_of_day": hours,
        "query_id": "",
        "browser_type": navigator.appName,
        "browser_version": fullVersion,
        "url_type": "absolute",
        "os_device": deviceType,
        "browser_name": browserName,
        "count_i": 1,
        "parent_s": "",
        "host": window.location.hostname,
        "app_id": "Public Search",
        "query_t": [
          query
        ],
        "ctype": "result",
        "owner_s": "",
        "session": "",
        "ctx_prev_uri": "",
        "ctx_prev_query": "",
        "os_manufacturer": navigator.userAgent,
        "group_s": "",
        "request_id_s": "",
        "fusion_query_id": "",
        "url_path": "",
        "os_group": OSName,
        "label": "",
        "url": docid,
        "ctx_prev_path": [
  
        ],
        "referrer": "",
        "url_domain": document.domain,
        "os_name": OSName,
        "ip_address": "",
        "page_title": document.title,
        "id": "",
        "os_id": 0,
        "res_offset": start,
        "res_pos": position,
        "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=employer" + "&type=EMPLOYER", 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 href="' + resultURL + '" target="_blank"' + displayTitle + ' ' + '<img src="https://test.bcbst.com/images/lockA.png" alt="secure icon">' + '</a></li>');
    }
    else{
     $('#liveSearchResults').append('<li><a 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;
  
  /*Query Method*/
  function queryFusion(query, start, rows, filter, order){
    currentStart = start;
    currentFilter = filter;
    currentQuery = query;
        currentOrder = order;
        var sortParameter = "";
    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=employer" + sortParameter, function (jsonObj){	
    var parseJson_2 = JSON.parse(jsonObj.data.inquiryResponse);	
    console.log(parseJson_2);
    $('#liveSearchResults').html('');
    $('#searchResults').html('');
    
    updatePagination(parseJson_2, start);
    var numR = parseJson_2.response.numFound;
    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";
    }
    
    
        /*Bruce Banner*/
    if (parseJson_2.fusion != null){
            console.log(parseJson_2.fusion.banner);
          /*  $("#banner").show();*/
        }
    
    
    
    /*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-->
  $(document).ready(function(){
  $('#search-input-dev').keyup(function(event){
    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");
    };
    
  });
  });
  
  
  
  <!--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, ' '));
  }


////////////////////////////////////
///  Dynamic Banner Display
/////////////////////////////////////
$(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) {
   $(".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*******/


////////////////////////////////////
///  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) {
                    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);
    });
});