////////////////////////////
// Anchor Linking - Function Call
////////////////////////////
$(document).ready(() => {
    if (location.hash !== '' || location.hash !== undefined) {
        anchor(location.hash);
    }
});

function anchor(hash) {
    let anchor = hash.substring(1, hash.length);
    try {
        switch (true) {
            case (anchor === 'bluecore'):
                $('.accordion_single_item').removeClass('active');
                $(`#${anchor}`).addClass('active');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Docs & Forms > bluecare & tenncareselect > member handbooks accordion 
            case (anchor === 'bluecare-member-handbook' || anchor === 'tenncare-select-handbook'):
                anchor = 'pharmacies-prescriptions';
                $('div[name$="ThroughYourEmployer-Billing"]').addClass('open');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Docs & Forms > coverkids > member handbooks accordion 
            case (anchor === 'coverkids-handbook'):
                anchor = 'individualContent';
                $('#throughContent, #ThroughYourEmployer').removeClass('default');
                $('#individualContent, #individual-family').addClass('default');
                $('div[name$="MedicareAdvantage-Billing"]').addClass('open');
                animate(anchor, 0);
                break;
            // Anchor to: BlueCare Docs & Forms > coverkids > member handbooks accordion 
            case (anchor === 'select-community'):
                anchor = 'enrollAvaility';
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Manuals, Policies & Guidelines > Provider Administartion Manual
            case (anchor === 'pam'):
                anchor = 'provider-administartion-manual';
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Contact Us > Transportation 
            case (anchor === 'transportation'):
                anchor = 'transportation';
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__10, #accordion_lvl_2__10').addClass('active');
                if (isMobile === true) $('.accordion_lvl_1').addClass('hidden');
                animate(anchor, 60);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > Long Term Supports and Services > ECF Choices dropdown 
            case (anchor === 'ecf-choices'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__8, #accordion_lvl_2__8, #ecf-choices').addClass('active');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > News & Updates 
            case (anchor === 'news'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__13, #accordion_lvl_2__13').addClass('active');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Get Care > Pregannacy Support
            case (anchor === 'get-help-meet'):
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > Long Term Supports and Services > Choices dropdown 
            case (anchor === 'choices'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__8, #accordion_lvl_2__8, #choices').addClass('active');
                animate(anchor, 60);
                break;
            // Anchor to: BlueCare Provider Digital Resources > Online Support
            case (anchor === 'online-support'):
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > Lab Policies
            case (anchor === 'lab-policies'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__6, #accordion_lvl_2__6').addClass('active');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > Tenncare
            case (anchor === 'tenncare'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__12, #accordion_lvl_2__12').addClass('active');
                animate(anchor, 120);
                break;
            // Anchor to: BlueCare Provider Docs & Forms > Required Training & Health Equity
            case (anchor === 'training'):
                $('.accordion_lvl_1_item, .accordion_lvl_2_container').removeClass('active');
                $('#accordion_lvl_1__11, #accordion_lvl_2__11').addClass('active');
                animate(anchor, 120);
                break;
        }
    } catch (error) {
        console.log("redirect error: " + error);
    }
}

function animate(hash, scroll) {
    $('html, body').animate({
        scrollTop: $(`#${hash}`).offset().top-scroll
    }, 1000);
};

/********* 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) 
  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 (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*******/



/* 
$(document).ready(function () {
  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=="blucare.bcbst.com" || window.location.host=="bluecare.bcbst.com"|| window.location.host=="rlse-bluecare.bcbst.com" || window.location.host=="apdxpubb01:10062"){
  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-bluecare.bcbst.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-bluecare.bcbst.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');
      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');
      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", "/register/?reg=MEMV");
      $('.username_section').addClass('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", "/register/?reg=MEMV");
      $('.username_section').addClass('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');
              
var isMobile = /Android|webOS|iPhone/i.test(navigator.userAgent) ? true : false;
if(isMobile){
// jayanthi
//$("html, body").scrollTop(0);
}
          }
      }

      $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") {
      var appeals = $(this).parents('span').attr('id');
      var appealsDiv = $(this).parents('div').attr('id');
      var sectionid = $(this).parents('section').attr('id');
    if( appeals == "review-services"){
     //if( appeals == "review-services" || sectionid == "our_plan_accordion"){
       var position = $('.sectionMainContent').offset().top;
       $('HTML, BODY').animate({scrollTop: position }, 0);
}




          $this.closest(".component-text-accordion-card").addClass(className);


/*jayanthi*/
var memberrights = $('.component-text-accordion-card'); 
if((memberrights).hasClass("open")){
 // var position = $('.gaj.dnf .component-text-accordion-submenu .component-text-accordion-card.open').offset().top-200;
var position = $('.component-text-accordion-submenu .component-text-accordion-card.open').offset().top-180;
  $('HTML, BODY').animate({scrollTop: position }, 1000);
}




      }

  });
});

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

  
//new header
//Adding function below to collapse nav by default on INITIAL VIEW for mobile
/*******Userstory 481722 - 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;
$(document).ready(function() {
if(window.location.pathname === '/contact-us'){
  sessionStorage.setItem('Navsub','Plans');
  sessionStorage.setItem('Navsubmenu','');
}
});
var height = $(window).height();
var width = $(window).width();
        
var mappedObj1 = {
  "getting started" : "getting started",
  "bluecare" : "bluecare",
  "tenncareselect" : 'tenncareselect',
  "coverkids" : "coverkids",
  "selectkids" : "selectkids",
  "selectcommunity" : "selectcommunity",
  "choices" : "choices",
  "employment community first choices" : "employment and community first choices",
  "your health" : "your health",
  "one on one help" : "one-on-one help",
  "pregnancy support" : "pregnancy support",
  "behavioral health" : "behavioral health",
  "katie beckett program" : "katie beckett program",
  "foster parents" : "foster parents support",
  "idd support" : "idd resource toolkit",
  "faqs" : "frequently asked questions",
  "understanding your rights" : "understanding your rights",
  "documents forms" : "documents and forms",
  "who we are" : "who we are",
  "vendors" : "vendor resources",
  "bluecaretn" : "bluecare",
  "member rights" : "understanding your rights",
  "katiebeckett"  : "katie beckett program",
  "one on one" : "one-on-one help"
}
var mappedObj = {
  "" : "plans",
  "plans programs" : "plans",
  "programs" : "programs",
  "get care" : "get care",
  "about us" : "about us",
  "katiebeckett" : "get care"
}
$(document).ready(function() {
  var submenu = sessionStorage.getItem('Navsubmenu');
  var myPath = window.location.href;
  if (myPath.split('/' [3] !== "/")) {
      var text = myPath.split('/')[3].toLowerCase().replace(/-/g, " ")
      var Nav = text.replace(/(?:^|\s)\S/g, function(a) {
          return a.toLowerCase();
      });
      if(Nav === "katiebeckett"){
          mappedObj1["submenu1"] = "katie beckett program";
      }
     
  }
  if ((myPath.split('/')[4] && myPath.indexOf('?') != -1) || (myPath.indexOf('#') != -1)) {
      if(myPath.indexOf('#') != -1){
          if (myPath.split('/')[4]) {
              var text1 = myPath.split('?')[0].split('/')[4].toLowerCase().replace(/-/g, " ");
              var submenu1 = text1.replace(/(?:^|\s)\S/g, function(a) {
                  return a.toLowerCase();
              });
          } 
      }else{
      var text1 = myPath.split('?',[4])[1].split('-').pop().toLowerCase().replace(/_/g, " ");
      if(myPath.endsWith("-footer-_-plans") || myPath.endsWith("-footer-_-programs")){
            text1 = "bluecare"
      }else if(myPath.endsWith("-footer-_-get_care")){
          text1 = "your health"
      }else if(myPath.endsWith("-footer-_-about_us")){
           text1 = "who we are"
      }if(text1 === "katie beckett program"){
          Nav = "programs"
      }
      var submenu1 = text1.replace(/(?:^|\s)\S/g, function(a) {
          return a.toLowerCase();
      });
  }
  }else{
      if (myPath.split('/')[4] && myPath.indexOf('#') == -1) {
          var text1 = myPath.split('/')[4].toLowerCase().replace(/-/g, " ");
          var submenu1 = text1.replace(/(?:^|\s)\S/g, function(a) {
              return a.toLowerCase();
          });
      }
  }
  if (myPath.split('/')[5]) {
      var text2 = myPath.split('/')[4].toLowerCase().replace(/-/g, " ")
      var NavsubThird = text2.replace(/(?:^|\s)\S/g, function(a) {
          return a.toLowerCase();
      });
  }
  if (NavsubThird) {
      submenu1 = NavsubThird;
  }
  if(submenu1 === 'selectkids' || submenu1 === 'selectcommunity' || submenu1 === 'choices' || submenu1 === 'employment community first choices'){
      mappedObj["plans programs"] = "plans";
      submenu1 = "bluecaretn";
  }
  if (mappedObj[Nav]) {
      sessionStorage.setItem('Navsub', mappedObj[Nav]);
      if (!(myPath.split('?')[3]) && !(myPath.split('/')[4])) {
          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;
          var isValue = false;
      
          if ((myURL.indexOf(".com/employers") < 0) && (myURL.indexOf(".com/brokers") < 0) && (myPath != '/')) {
              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.toLowerCase();
                      if (storedValue === "About") {
                          storedValue = "About Us";
                      } else if (storedValue === null || storedValue === "Contact Us") {
                          storedValue = "Plans";   
                          sessionStorage.removeItem('Navsubmenu');            
                      } 
                      if (storedValue === selectedValue) {
                          isValue = true;
                          el.classList.add("active");
                      }
                  });
      
                  var navsubElements = $('.nav-item-title .sub-items-list li');
                  navsubElements.each(function(subel, subEle) {
                      var storedSubValue = sessionStorage.getItem('Navsubmenu');
                      var selectedSubValue = subEle.children[0].text.replace('&', '').split("  ").join(" ").toLowerCase();
                      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.clear();
                      flyOutMenuButtons[0].classList.add("active");
                  }
              }
              if(isSubvalue === false && isValue === 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).className === 'nav-section-link' && elementIsClicked) {
                  this.classList.remove("active")
                  var Nav = $(e.target)[0].innerText.toLowerCase();
                  sessionStorage.setItem('Navsub', Nav);
              } else {
                  var submenu = $(e.target)[0].parentElement.innerText;
                  submenu = submenu.replace('&', '').split("  ").join(" ").toLowerCase();
                  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 481722 - Menu Nav Optimizations Changes by surya- End******/
                               
                              
  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, "&").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(/&/, "&"))
});;
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);
  });
});

$(document).ready(function () {
  let isMobileblue = /Android|webOS|iPhone|BlackBerry/i.test(navigator.userAgent) ? true : false;
  let isMobileblue1 = /iPad|iPod/i.test(navigator.userAgent) ? true : false;
  let url1 = window.location.href;
  let bchashes = url1.split("#")[1]; 
  let splitUrl = url1.split("?")[1]; 
  console.log(bchashes);
  anchorDown(bchashes, isMobileblue);
  $('nav#bcbst-header ul.sub-items-list a').on('click', (event) => {
    let element = event.target;
    console.log(element);
    console.log(element.nodeName);
    if (element.nodeName === 'I') {
      element = $(event.target).parent();
    }
    console.log(element);
    elementTitle = $(element).attr('title');
    console.log(elementTitle);
    bchashes = elementTitle.replace(/\s+/g, '-').toLowerCase();
    console.log(bchashes);
    anchorDown(bchashes, isMobileblue, element);
  });
  if (bchashes == "qualityimprovement") {
    let desktopPositionQIM = $("#questionflag").offset().top-90;
    let mobilePositionQIM = $("#questionflag").offset().top-70;
    let ipodPositionQIM = $("#questionflag").offset().top-70;
    if (isMobileblue) {
          $('html, body').animate({
          scrollTop: mobilePositionQIM
        }, 1000);
    } else if (isMobileblue1) {
          $('html, body').animate({
          scrollTop: ipodPositionQIM
        }, 1000);
    } else {
          $('html, body').animate({
          scrollTop: desktopPositionQIM
        }, 1000);
    }

}else if(bchashes == "bluecare" || bchashes == "tenncareselect" || bchashes == "tenncareselect"){
   var mobilePositioncard = $("#TennCareEligible").offset().top-30;
   var tenncarebluecare = $("#TennCareEligible").offset().top-90;
  if (isMobileblue) {
     $('html, body').animate({
        scrollTop: $("#TennCareEligible")
      }, 1000);
  }else{
     $('html, body').animate({
        scrollTop: $("#TennCareEligible")
      }, 1000);
   }      
}else  if(bchashes == "referralcomp"){

 $("#specialtypharm .card.component-text-accordion-card").removeClass("open");
 $('#referralAcc').addClass('open');
    
$('html, body').animate({
        scrollTop: $("body").find("#getARide").offset().top+100
      }, 200);

}else if(bchashes == "choices"){
var choicesmobilePosition = $("#ChoicesBCTN").offset().top-70;
   var choices = $("#ChoicesBCTN").offset().top-190;
  if (isMobileblue) {
     $('html, body').animate({
        scrollTop: choicesmobilePosition 
      }, 1000);
  }else{
     $('html, body').animate({
        scrollTop: choices
      }, 1000);
}
}else if(bchashes == "coverkidsgs-handbook" || bchashes == "coverkidshandbook" || bchashes == "coverkidshandbook"){
var coverkids_handbookCKmobile = $("#Your-member-handbook").offset().top-70;
   var coverkids_handbookCKdesktop = $("#Your-member-handbook").offset().top-130;
var coverkids_handbookCKdesktopwin = $("#Your-member-handbook").offset().top-70;
  if (isMobileblue) {
     $('html, body').animate({
        scrollTop: coverkids_handbookCKmobile
      }, 1000);
  }else{
     if(window.innerWidth <992){
       $('html, body').animate({
        scrollTop: coverkids_handbookCKdesktopwin
       }, 1000);
     }else{
      $('html, body').animate({
        scrollTop: coverkids_handbookCKdesktop
      }, 1000);
   }
}
}else if(bchashes == "choices"){
   var choicesmobilePositionchoice = $("#ChoicesBCTN").offset().top-70;
   var choicesdesk = $("#ChoicesBCTN").offset().top-170;
  if (isMobileblue) {
     $('html, body').animate({
        scrollTop: choicesmobilePositionchoice
      }, 1000);
  }else{
     $('html, body').animate({
        scrollTop: choicesdesk
      }, 1000);
}
   }else if(bchashes == "employmentcommunity"){
        var selectcommunitycommon= $(".emp-comm-gray").offset().top-90;
  
        $('html, body').animate({
        scrollTop: selectcommunitycommon
      }, 1000);
}else if(bchashes == "morelocalhelp" || bchashes == "morelocalhelp"){
        var morelocalhelpDiv = $("#morelocal-help").offset().top-150;
        var morelocalhelpDivwindow = $("#morelocal-help").offset().top-90;
        var morelocalhelpMobile = $("#morelocal-help").offset().top-110;
  if (isMobileblue) {
        $('html, body').animate({
          scrollTop: morelocalhelpMobile
        }, 1000);
      }else{
        if(window.innerWidth <992){
            $('html, body').animate({
        scrollTop: morelocalhelpDivwindow
      }, 1000);
      }else{
        $('html, body').animate({
        scrollTop: morelocalhelpDiv
      }, 1000);
       }
      }
}else if(bchashes == "healthhistory"){
      var healthhistorySec = $("#healthhistorySec").offset().top-170;
  
        $('html, body').animate({
        scrollTop: healthhistorySec
      }, 1000);
}else if(bchashes == "selectkids"){
      var selectKidsdeskmobile = $("#tellus").offset().top-70;
  
        $('html, body').animate({
        scrollTop: selectKidsdeskmobile
      }, 1000);
}else if(bchashes == "getaride"){
    var desktopPositiongetride = $("#enroll").offset().top-120;

        $('html, body').animate({
        scrollTop: desktopPositiongetride
      }, 1000);
}else if(bchashes == "BlueCareTennesseebenefitsoverview"){
var BlueCareTennesseebenefitsoverviewPos = $("#info_medical_networks").offset().top-130;
var BlueCareTennesseebenefitsoverviewMob = $("#info_medical_networks").offset().top-90;
if (isMobileblue) {
        $('html, body').animate({
        scrollTop: BlueCareTennesseebenefitsoverviewMob
      }, 1000);
}else{
 $('html, body').animate({
        scrollTop: BlueCareTennesseebenefitsoverviewPos
      }, 1000);
}
}else if(bchashes == "health_history_needs_survey"){
    var healthhistoryneedssurvey = $("#healthhistory_needssurvey").offset().top-230;
   var healthhistoryneedssurveymobile = $("#healthhistory_needssurvey").offset().top-70;
if (isMobileblue) {
        $('html, body').animate({
        scrollTop: healthhistoryneedssurveymobile
      }, 1000);
    }else{
      $('html, body').animate({
        scrollTop: healthhistoryneedssurvey
      }, 1000);
   }
}else if(bchashes == "selectcommunity"){
      var selectKidscommunitdiv = $("#selectCommunity").offset().top-90;
  
        $('html, body').animate({
        scrollTop: selectKidscommunitdiv
      }, 1000);
} else if(splitUrl=="cm_sp=cta-_-body_link-_-member_handbook"){
var desktopPositionhandbook_desk = $("#Your-member-handbook").offset().top-130;
var mobilePositionhandbook_mobile = $("#Your-member-handbook").offset().top-70;
   if (isMobileblue) {
        $('html, body').animate({
        scrollTop: mobilePositionhandbook_mobile
      }, 1000);
  } else{
        $('html, body').animate({
        scrollTop: desktopPositionhandbook_desk
      }, 1000);
}

}else if(bchashes =="wellcare"){
var desktopPositionhandbookdeskwel = $("#Well-care-visits-section").offset().top-90;
var desktopPositionhandbookdeskwelwin = $("#Well-care-visits-section").offset().top-40;
var mobilePositionhandbookwel = $("#Well-care-visits-section").offset().top-70;
   if (isMobileblue) {
        $('html, body').animate({
        scrollTop: mobilePositionhandbookwel
      }, 1000);
  } else{
  if(window.innerWidth <992){
      $('html, body').animate({
        scrollTop: desktopPositionhandbookdeskwelwin
      }, 1000);
     }else{
        $('html, body').animate({
        scrollTop: desktopPositionhandbookdeskwel
      }, 1000);
     }
 }

}
else if(bchashes == "moreLocalHelp"){
        var moreLocalHelpVar = $("#title-copy-accordions").offset().top-120;
  
        $('html, body').animate({
        scrollTop: moreLocalHelpVar
      }, 1000);
}else if(bchashes == "signuptext"){
/*JREDDY*/
        var signupVar = $("#signDiv").offset().top-170;
  
        $('html, body').animate({
        scrollTop: signupVar
      }, 1000);
}else if(bchashes == "Well-care-visits-men"){

        $("#Well-care-visits-section .component-text-accordion-items #ThroughYourEmployer").removeClass("default");
$("#Well-care-visits-content .component-text-accordion-submenu#throughContent").removeClass("default");
$("#Well-care-visits-section .component-text-accordion-items #blueadvantage").addClass("open");
$("#Well-care-visits-content .component-text-accordion-submenu#blueadvantage").addClass("show");
var desktopPositionwelmen = $("#Well-care-visits-section").offset().top-130;
        $('html, body').animate({
        scrollTop: desktopPositionwelmen
      }, 1000);
}

else if(bchashes == "getARide"){
        var getARideVarposition = $("#specialtypharm ").offset().top-120;
  
        $('html, body').animate({
        scrollTop: getARideVarposition
      }, 1000);
}
else  if(bchashes == "Using-your-Member"){
var desktopPositioncard_mem = $("#Sample-ID-Card").offset().top-120;
var mobilePositioncard_mem = $("#Sample-ID-Card").offset().top-50;
var ipodPositioncard_mem = $("#Sample-ID-Card").offset().top-70;
   if (isMobileblue) {
        $('html, body').animate({
        scrollTop: mobilePositioncard_mem
      }, 1000);
  } else if (isMobileblue1) {
        $('html, body').animate({
        scrollTop: ipodPositioncard_mem
      }, 1000);
  }else{

        $('html, body').animate({
        scrollTop: desktopPositioncard_mem
      }, 1000);
}

}else if(bchashes == "servicesrequire"){
var desktopPositionhandbook_require = $("#Sample-ID-Card").offset().top-130;
var mobilePositionhandbook_require = $("#Sample-ID-Card").offset().top-70;
   if (isMobileblue) {
        $('html, body').animate({
        scrollTop: mobilePositionhandbook_require
      }, 1000);
  } else {
        $('html, body').animate({
        scrollTop: desktopPositionhandbook_require
      }, 1000);
}
}

/*Quality improvment Ambati code end*/

$("a[href^='#']").on("click", (e) => {
e.preventDefault();
if($(this).attr('href')=== "#talktous")
{
staffNumbers();
}else if($(this).attr('href')=== "#referral")
 {

$('html, body').animate({
        scrollTop: $("body").find(this.hash).offset().top
      }, 200);
$("#specialtypharm .card.component-text-accordion-card").removeClass("open");
          $('#referralAcc').addClass('open');
     
}else{
$('html, body').animate({
        scrollTop: $("body").find(this.hash).offset().top
      }, 1000);

}

});
function   staffNumbers(){
var desktopPosition_referral = $("#enroll").offset().top+330;
var mobilePosition_referral = $("#enroll").offset().top+470;
var ipodPosition_referral = $("#enroll").offset().top+370;
$("#dcs_team").find('div.card.component-text-accordion-card.open').removeClass('open');
          var $linkParent = $('#talktous').closest('div.card.component-text-accordion-card');
          $linkParent.addClass('open');
   if (isMobileblue) {
        $('html, body').animate({
        scrollTop: mobilePosition_referral
      }, 1000);
  } else if (isMobileblue1) {
        $('html, body').animate({
        scrollTop: ipodPosition_referral
      }, 1000);
  }else{
        $('html, body').animate({
        scrollTop: desktopPosition_referral
      }, 200);
}

}
});




/*-----------------------------------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",
      "source": "Provider Search",
      "applicationId": "Bluecare",
      "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": "Providers",
      "session": session,
      "userId": "Anonymous",
      "userToken": userToken,
      "hostName": window.location.hostname,
      "ipAddress": "",
      "platform": "BCBST",
      "source": "Providers",
      "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=bluecare" + "&type=bluecare", 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;
      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 = "";
  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=bluecare" + 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);
    console.log(myObj);
    var bannerTitle = myObj.url;
    console.log(bannerTitle);
    if ($("#banner").html().length > 0){
        console.log("Content Already Exisits");	
    }
    else{
      if(bannerTitle === "HealthEquity_banner"){
          $("#banner").append('<p>In our first-ever health equity report, we are looking at the impact of race, ethnicity and other social factors on the health of our neighbors. </p><a href="https://www.bcbst.com/about/diversity-inclusion-health-equity/" target="_blank"  class="button primary">SEE THE REPORT</a>');
          $("#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;
}



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");
  };
  $('#liveSearchResults').on('click', function(){
        searchType = 'suggested search'
        analyticsAdd('search', searchType);
  });
});
});



$(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, '\\$&');
  let regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function anchorDown(bchashes, isMobileblue, element) {
  console.log(bchashes);
  if (bchashes === 'selectkids') {
    $('html, body').animate({
      scrollTop: $("#tellus").offset().top-70
    }, 1000);
  } else if (bchashes === 'selectcommunity') {
    $('html, body').animate({
      scrollTop: $("#selectCommunity").offset().top-90
    }, 1000);
  } else if (bchashes === 'choices') {
    if (isMobileblue) {
      $('html, body').animate({
        scrollTop: $("#ChoicesBCTN").offset().top-70 
      }, 1000);
    } else {
      $('html, body').animate({
        scrollTop: $("#ChoicesBCTN").offset().top-190
      }, 1000);
    }
  } else if (bchashes === 'employment-and-community-first-choices') {
    $('html, body').animate({
      scrollTop: $(".emp-comm-gray").offset().top-90
    }, 1000);
  } else if (bchashes === 'tenncare-select' || bchashes === 'bluecare') {
    if (isMobileblue) {
      $('html, body').animate({
        scrollTop: $("#TennCareEligible").offset().top-30 
      }, 1000);
    } else {
      $('html, body').animate({
        scrollTop: $("#TennCareEligible").offset().top-90
      }, 1000);
    } 
  } else if (bchashes === 'katie-beckett-program') {
    $('html, body').animate({
      scrollTop: $("#programkat").offset().top-90
    }, 1000);
  }

  // Close Navigation
  $('.main-nav, .sub-nav, .header-hamburger-menu').removeClass('open');
  $('.header-hamburger-menu').attr('aria-expanded', 'false');
  $('.header-hamburger-menu').attr('aria-label', 'Main Menu');

  // Shift Navigation Blue Page Indicator
  $('ul.sub-items-list li').css('border-left-color', 'transparent');
  if ($(element).is('li')) {
    $(element).css('border-left-color', '#008cc9');
  } else if ($(element).is('a')) {
    $(element).parent('li').css('border-left-color', '#008cc9');
  }
}


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