$(document).ready(function(){ 
    /*
    $(".headerloginbutton").click(function(){
      $(".headerlogin").toggleClass("hidden");
      $(".login-top").toggleClass("hidden");
      $(".white-login-caret").toggle("rotate-arrow");
      $(".logintext").toggleClass("invisible");
  
    });
  $(".login-form-close").click(function(){
      $(".headerlogin").toggleClass("hidden");
      $(".login-top").toggleClass("hidden");
      $(".white-login-caret").toggle("rotate-arrow");
      $(".logintext").toggleClass("invisible");
    });
    */



//BEGIN add or remove "selected" class

$(document).on("click",".headerdropdown .accordionquestion.closed",function() {
    $(".headerdropdown .accordionquestion").removeClass("selected");
    $(this).addClass("selected");
});
$(document).on("click",".headerdropdown .accordionquestion.open",function() {
    $(this).removeClass("selected");
});

//END add or remove "selected" class



    $("#whiteclosex").click(function(){
      $(".headerlogin").toggleClass("hidden");
      $(".white-login-caret").toggleClass("hidden");
      $(".logintext").toggleClass("invisible");
    });
    $(".searchbutton").click(function(){
      $(".searchbutton img").toggleClass("hidden");
      $(".searchblock").toggleClass("hidden");
      $(".searchinput").val("");
      $(".dropdownsearchinput").val("");
      $(".searchinput").focus();
    });
  $(document).on("click",".dropdownbutton.begin",function() {
          $('.dropdownbuttontopline').animate(
              //{ deg: 315 },
              { deg: 135 },
              {
              duration: 300,
              step: function(now) {
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
                  //$(this).css({ marginTop: '14px' });
                  $(this).css({ marginTop: '7px' });
              }
              }
          );
          $('.dropdownbuttonmiddleline').animate(
              { deg: 45 },
              {
              duration: 300,
              step: function(now) {
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
              }
              }
          );
          $('.dropdownbuttonbottomline').animate(
              //{ deg: 315 },
              { deg: 135 },
              {
              duration: 300,
              step: function(now) {
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
                  //$(this).css({ marginBottom: '14px' });
                  $(this).css({ marginBottom: '9px' });
                  $(this).css({ display: 'none' });
              }
              }
          );
          $(".headerdropdown").toggleClass("hidden");
          $(".dropdownbutton").toggleClass("begin");
          $(".dropdownbutton").toggleClass("end");
          //The following function is needed because, without it, the main navigation displays incorrectly when you open the main nav a second time. The height value may need to change if the design changes.
          $(".bigselector99 .bigselectorchoices").animate({//////////
              height: '250px'
          });

//BEGIN highlight current page
let matchCounter = 0;
$('.headerdropdown .accordionanswer a').each(function() {
    let linkHref = $(this).attr("href");
    linkHref = linkHref.replaceAll("/","");
    let currentPath = window.location.pathname;
    currentPath = currentPath.replace("/tailwind","");
    currentPath = currentPath.replaceAll("/","");
    if(currentPath == linkHref){ 
        $(this).addClass("selected"); 
        matchCounter = matchCounter + 1;
if($(this).parents(".accordioncard").find(".accordionquestion").hasClass("closed")){
            $(this).parents(".accordioncard").find(".accordionquestion").trigger("click"); 
        }
    }
});
//END highlight current page


//BEGIN highlight and open category if no match
let currentPath = window.location.pathname;
currentPath = currentPath.replace("/tailwind","");
currentPath = currentPath.replaceAll("/","");
if(matchCounter ==0){
  console.log("no match");
  $('.headerdropdown .accordionquestion').each(function() {
    let currentCategory = $(this).attr("category")
    if(currentPath.indexOf(currentCategory) > -1){
      $(this).trigger("click"); //open category
    }
  });
}
//END highlight and open category if no match


    });

  $(document).on("click",".dropdownbutton.end",function() {
          $('.dropdownbuttontopline').animate(
              { deg: 0 },
              {
              duration: 300,
              step: function(now) {
                  //$(this).css({ marginTop: '6px' });
                  $(this).css({ marginTop: '0px' });
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
              }
              }
          );
          $('.dropdownbuttonmiddleline').animate(
              { deg: 0 },
              {
              duration: 300,
              step: function(now) {
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
              }
              }
          );
          $('.dropdownbuttonbottomline').animate(
              { deg: 0 },
              {
              duration: 300,
              step: function(now) {
                  $(this).css({ display: 'block' });
                  //$(this).css({ marginBottom: '6px' });
                  $(this).css({ marginBottom: '0px' });
                  $(this).css({ transform: 'rotate(' + now + 'deg)' });
              }
              }
          );
          $(".headerdropdown").toggleClass("hidden");
          $(".dropdownbutton").toggleClass("begin");
          $(".dropdownbutton").toggleClass("end");
          $(".bigselector99 .bigselectorchoices").animate({
              height: '0px'
          });
$(".headerdropdown .accordionquestion").removeClass("selected");
$(".headerdropdown .accordionanswer a").removeClass("selected");
$(".headerdropdown .accordionquestion").removeClass("open");
$(".headerdropdown .accordionquestion").addClass("closed");

    });
  });
  
  $(document).ready(function(){
    //$("a[target='_blank']").addClass("icon-offsite");
    //$("a[target='_blank']").removeClass("icon-more");
    //$("a[target='_blank']").removeClass("icon-plus");
  });
  
  
  /*  --------------- Login box LOGIN functionality --------------- */
  var brokerLoginURL;
  var employerLoginURL;
  var memberLoginURL;
  if(window.location.host=="www.bcbst.com"||window.location.host=="bcbst.com"){
  brokerLoginURL = "https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=FormLoginBroker";
  employerLoginURL ="https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=FormLoginEmployer";
  memberLoginURL ="https://sso.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
  } else if(window.location.host=="test.bcbst.com" || window.location.host=="test1.bcbst.com" || window.location.host=="test2.bcbst.com" ){
  brokerLoginURL = "https://sso3.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterBrokerPortal&SpSessionAuthnAdapterId=FormLoginBroker";
  employerLoginURL ="https://sso3.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterEmployerPortal&SpSessionAuthnAdapterId=FormLoginEmployer";
  memberLoginURL ="https://sso3.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
  } else if(window.location.host=="public-dev.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://sso2.bcbst.com/pf/adapter2adapter.ping?IdpAdapterId=FormIDPAdapterMemberPortal&SpSessionAuthnAdapterId=LoginTest";
  }
  
  
  
  /******** Form Submission for Header Logins ***********/
  
  function updateURL(loginSelection) {
  if (loginSelection == "mem") {
      document.getElementById("login-form-header").action = memberLoginURL;
      document.getElementById("registration-link").setAttribute("href", "/register-member");
  document.getElementById("forgot-link").setAttribute("href", "/forgot-password");
  } else if (loginSelection == "bro") {
      document.getElementById("login-form-header").action = brokerLoginURL;
      document.getElementById("registration-link").setAttribute("href", "/register/?reg=broker");
  document.getElementById("forgot-link").setAttribute("href", "/forgotpassword?usage=forgot");
  } else if (loginSelection == "emp") {
      document.getElementById("login-form-header").action = employerLoginURL;
      document.getElementById("registration-link").setAttribute("href", "/register/?reg=EMPV");
  document.getElementById("forgot-link").setAttribute("href", "/forgotpassword?usage=forgot");
  } else if (loginSelection == "pro") {
  console.log("pro")
      window.location.href = "https://provider.bcbst.com/";
  }
  }
  
  
  
  function postOkheader() {
  try {
      var ok = document.getElementById('okheader');
      ok.value = 'clicked';
      var myDropdown = document.getElementById('accountTypeh');
      var myUser = myDropdown.options[myDropdown.selectedIndex].value;
      updateURL(myUser);
      document.getElementById('login-form-header').submit();
      return false;
  } catch (error) {
      console.log("error " + error);
  }
  }
  
  
  
  /*-----------------------------------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 buildQuerySignal(query, filter) {
  
  var timestamp = getDateISO();
  var hours = getLocalHour(); //Getting the hour of day, because this is the hour from the user's perspective
  var dow = getLocalDOW(); //Getting the local day of week, because this is the day from the user's perspective
  
  var filterQuery = [];
  var filterSummary = [];
  var filterField = "";
  
  if (filter) {
  filterQuery = ["mime_type:(\"application/pdf\")"];
  filterSummary = ["mime_type/application/pdf"];
  filterField = "mime_type";
  }
  
  var payload = [
  {
    "type": "request",
    "timestamp": timestamp,
    "count_i": 1,
    "params": {
      "date_year": timestamp,
      "date_month": timestamp,
      "query": query,
      "date_day": timestamp,
      "flag_s": "event",
      "query_orig_s": query,
      "platform": "BCBST",
      "source": "Public Search",
      "query_t": query,
      "user_id": "Anonymous",
      "filterQueries": filterQuery,
      "filter": filterSummary,
  
      "filter_field": filterField,
      "user_token": "Anonymous",
      "day_of_week": dow,
      "date": timestamp,
      "attr_date_": [
        timestamp
      ],
      "attr_timestamp_tdt_": [
        timestamp
      ],
      "hour_of_day": hours,
      "collection": "MAIN"
    }
  }
  ];
  return JSON.stringify(payload);
  }
  
  function buildClickSignal(query, filter, docid, start, position) {
  
  var timestamp = getDateISO();
  var hours = getLocalHour(); //Getting the hour of day, because this is the hour from the user's perspective
  var dow = getLocalDOW(); //Getting the local day of week, because this is the day from the user's perspective
  
  var filterQuery = [];
  var filterSummary = [];
  var filterField = "";
  
  if (filter) {
  filterQuery = ["mime_type:(\"application/pdf\")"];
  filterSummary = ["mime_type/application/pdf"];
  filterField = "mime_type";
  }
  
  var payload = [
  {
    "type": "click",
    "timestamp": timestamp,
    "count_i": 1,
    "params": {
      "date_year": timestamp,
      "date_month": timestamp,
      "query": query,
      "date_day": timestamp,
      "flag_s": "event",
      "doc_id": docid,
      "query_orig_s": query,
      "platform": "BCBST",
      "source": "Public Search",
      "user_id": "Anonymous",
      "user_token": "Anonymous",
      "day_of_week": dow,
      "date": timestamp,
      "attr_date_": [
        timestamp
      ],
      "attr_timestamp_tdt_": [
        timestamp
      ],
      "hour_of_day": hours,
      "query_id": "",
      "browser_type": navigator.appName,
      "browser_version": fullVersion,
      "url_type": "absolute",
      "os_device": deviceType,
      "browser_name": browserName,
      "count_i": 1,
      "parent_s": "",
      "host": window.location.hostname,
      "app_id": "Public Search",
      "query_t": [
        query
      ],
      "ctype": "result",
      "owner_s": "",
      "session": "",
      "ctx_prev_uri": "",
      "ctx_prev_query": "",
      "os_manufacturer": navigator.userAgent,
      "group_s": "",
      "request_id_s": "",
      "fusion_query_id": "",
      "url_path": "",
      "os_group": OSName,
      "label": "",
      "url": docid,
      "ctx_prev_path": [
  
      ],
      "referrer": "",
      "url_domain": document.domain,
      "os_name": OSName,
      "ip_address": "",
      "page_title": document.title,
      "id": "",
      "os_id": 0,
      "res_offset": start,
      "res_pos": position,
      "collection": "MAIN"
    }
  }
  ];
  
  return JSON.stringify(payload);
  }
  
  
  /*Get Fusion */
  function getFusion(url, callBack, retries){
  $.ajax({
  type: 'GET',
  url: url,
  dataType: 'json',
  success: callBack,
  error: function(){
   if (!retries){
    retries = 0;
   }
   else if (retries >= 3){
    console.log("Retries Exceeded for " + url);
    return
   }
   setTimeout(function(){getFusion(url, callBack, retries + 1)}, 1000);
  }
  });
  }
  
  /*Post Fusion */
  function postFusion(url, data, retries){
  $.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: function(){},
  error: function(XMLHttpRequest, textStatus, errorThrown){
   if (!retries){
    retries = 0;
   }
   else if (retries >= 3){
    console.log("Retries Exceeded for " + url);
    return
   }
   setTimeout(function(){postFusion(url, data, retries + 1)}, 1000);
  }
  });
  }
  
  /*Post Query Signal */
  function postQuerySignal(query, filter){
  postFusion("/public-search/signal", buildQuerySignal(query, filter));
  }
  
  /*Post Click Signal */
  function postClickSignal(query, filter, docid, start, position){
  postFusion("/public-search/signal", buildClickSignal(query, filter, docid, start, position));
  }
  
  /*Result Click */
  function resultClick(index, docid){
  postClickSignal(currentQuery, currentFilter, docid, currentStart, index);
  }
  
  /*Suggest Method */
  function suggest(query){
  getFusion("/public-search/suggestion?inquiry=" + query + "*", 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;
  
  /*Query Method*/
  function queryFusion(query, start, rows, filter){
  currentStart = start;
  currentFilter = filter;
  currentQuery = query;
  pdfValue = "0";
  console.log("Total number of PDF files: " + pdfValue);
  postQuerySignal(query, filter);
  getFusion("/public-search/inquiry?inquiry=" + query + (filter ? "&filterQuery=mime_type:(%22application/pdf%22)" : "") + "&cursorValue=" + (start*rows) + "&numberOfRows=" + rows, function (jsonObj){	
  var parseJson_2 = JSON.parse(jsonObj.data.inquiryResponse);	
  console.log(parseJson_2);
  $('#liveSearchResults').html('');
  $('#searchResults').html('');
  $('#banner').html('');
  updatePagination(parseJson_2, start);
  var numR = parseJson_2.response.numFound;
  document.getElementById("returnedOutput").innerHTML = "";
  $("#returnedOutput").append("<p>Total Number of Results:" + " " + numR + "</p>");
  console.log("Number of returned results: " + numR);
  if (numR > 0){
    document.getElementById("results-pagination").style.display = "flex";
  }
  
  /*Banner
  console.log(parseJson_2.fusion.banner);
  if (parseJson_2.fusion.banner){
  document.getElementById("banner").style.display = "block";
    parseJson_2.fusion.banner.forEach(function(banner) {
      var bannerContent = JSON.parse(banner);
      var bannerID = bannerContent.url;
      var bannerTitle = bannerContent.title;
      var bannerDesc = bannerContent.description;
      
      $('#banner').append('<p><strong>' + bannerTitle + '</strong><br><strong>' + bannerDesc + ' ' + '</strong><a href="' + bannerID + '">' + 'LEARN MORE' + '</a></p>');
      
    });
  }
  */
  
  
  
  /*Display Search Results*/
  parseJson_2.response.docs.forEach(function(doc, index){
    var displayTitle = doc.title;
    var displayDesc = doc.description;
    var hrefID = doc.id;
    var pdfCheck = hrefID.substr(hrefID.lastIndexOf('.')).toLowerCase();
    if (pdfCheck  === '.pdf') {
      pdfValue++;
    }
    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>" + "<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>" + "<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");
  queryFusion(searchField, start, 10, pdfFilter);
  }
  
  /*Pagination*/
  function clickValue(value){
  submitSearch(value);
  }
  
  function updatePagination(parseJson_2, currentPage){
  document.getElementById("results-pagination").innerHTML = "";
  var totalReturned = parseJson_2.response.numFound; //Total found
  var rowsPerPage = 10;
  var maxPagesFirst = 5;
  var maxPagesSecond = 2;
  var pageThreshold = 5;
  var remaining;
  var totalPages = Math.ceil(totalReturned/rowsPerPage);    
  
  
  if(currentPage > 0){
  //enable prev (link w/currentPage-1)
  $('#results-pagination').append('<li class="page-item active"><span class="page-link" href="#" tabindex="-1" onclick="clickValue(' + (currentPage -1) + ')">Previous</span>');
  }else{
  //disable prev
  $('#results-pagination').append('<li class="page-item disabled"><span class="page-link" href="#" tabindex="-1">Previous</span>');
  }
  
  if(currentPage >= pageThreshold && currentPage  >= (totalPages - pageThreshold)){
  //Format 2 ... 5
  remaining = paginate(totalReturned, maxPagesSecond, rowsPerPage,0);
  $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
  remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage, totalPages - pageThreshold);
  }else  if(currentPage >= pageThreshold ){
  //Format 2 ... 5 ... 2
  remaining = paginate(totalReturned, maxPagesSecond, rowsPerPage,0);
  $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
  remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage,currentPage);
     //Format 5 ... 2
  if(remaining.pagesLeft > 0) {
    $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
    paginate(totalReturned, maxPagesSecond, rowsPerPage, remaining.pageCount - (remaining.pagesLeft-2 > 0  ? 2 : 1));
  }
  }else {
  //Format 5 ... 2
  remaining = paginate(totalReturned, maxPagesFirst, rowsPerPage,currentPage);
  if(remaining.pagesLeft > 0) {
    $('#results-pagination').append('<li class="page-item">' + '<span class="page-link">' + '...' + '</span></li>'); //Ellipses
    paginate(totalReturned, maxPagesSecond, rowsPerPage, remaining.pageCount - (remaining.pagesLeft-2 > 0  ? 2 : 1));
  }
  }
  
  if(currentPage != (totalPages-1)){
  //enable next (Link with currentPage+1)
  $('#results-pagination').append('<li class="page-item active"><span class="page-link" onclick="clickValue(' + (currentPage + 1) + ')">Next</span>');
  }else{
  //disable next
  $('#results-pagination').append('<li class="page-item disabled"><span class="page-link">Next</span>');
  }
  }
  
  
  function paginate( totalResults, maxPages, rowsPerPage, startPage ){
  var total = Math.ceil(totalResults/rowsPerPage)*rowsPerPage;    
  var pageCount = Math.ceil(totalResults/rowsPerPage);    
  var remaining = {
  pageCount: pageCount,
  pagesConsumed: -1,
  pagesLeft: -1,
  rowsLeft: -1
  };
  
  pageCount = Math.min(pageCount,maxPages+startPage);
  remaining.pagesConsumed = pageCount;
  remaining.pagesLeft = remaining.pageCount - remaining.pagesConsumed;
  remaining.rowsLeft = totalResults - (remaining.pagesConsumed * rowsPerPage);
  
  for (let index = startPage; index < pageCount; index++) {
  var value = (index+1);
  $('#results-pagination').append('<li class="page-item"><span class="page-link" onclick="clickValue(' + index + ')">' + value + '</span></li>');	
  }
  
  return remaining;
  }
  
  
  <!--Live Search Part-->
  $(document).ready(function(){
  $('#search-input-dev').keyup(function(event){
  if (event.which === "/n"){
    submitSearch(0);
  }
  if($('#search-input-dev').val().length > 2){
    suggest($('#search-input-dev').val());
  };	
  if($('#search-input-dev').val().length === 0){
    suggest($('#search-input-dev').val());
    console.log("search is zero");
  };
  
  });
  });
  
  
  
  <!--Get Search Results-->
  $(document).ready(function(){
  var qString = window.location.search;
  var currentURL = window.location.href;
  var userInput = getParameterByName("q" , qString);
  $('#search-input-dev').val(userInput);
  if (userInput && userInput.length > 0){
  submitSearch(0);
  }
  /*Checkbox Filter*/	
  $('#pdfFilter').change(function(){
  submitSearch(0);
  });
  });
  
  
  
  function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, '\\$&');
  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }
  
  
  
  
  $(document).ready(function(){
  
      //Change the accordion number in the IDs of the accordion if more than one accordion on same page (default is 1). E.g., if you choose "2" then change every reference to "accordion1answer3" to "accordion2answer3". Consider a field in the PT/AT to enter the number. That field would populate the numbers in the code below. Use logic in PT to control visibility of empty items.
    $(document).on("click",".accordionquestion.closed",function() {
      accordionNumber = this.id.match(/\d+/);
      currentChoice = $(this).attr("id").slice(-1);
      $("#accordion" + accordionNumber + " .accordionquestion").attr("aria-expanded","false");//
$(this).attr("aria-expanded","true");//
      $("#accordion" + accordionNumber + " .accordionanswer").addClass("hidden");
      $("#accordion" + accordionNumber + " .accordionquestion").removeClass("open");
  $("#accordion" + accordionNumber + " .accordionquestion").removeClass("mobileselectortopchoice");
      $("#accordion" + accordionNumber + " .accordionquestion").addClass("closed");
      $("#accordion" + accordionNumber + "answer" + currentChoice).removeClass("hidden");
      $("#accordion" + accordionNumber + "question" + currentChoice).removeClass("closed");
      $("#accordion" + accordionNumber + "question" + currentChoice).addClass("open");
  $("#accordion" + accordionNumber + "question" + currentChoice).addClass("mobileselectortopchoice");
    });


    $(document).on("click",".accordionquestion.open",function(event) {
      accordionNumber = this.id.match(/\d+/);
      currentChoice = $(this).attr("id").slice(-1);
      $("#accordion" + accordionNumber + " .accordionquestion").attr("aria-expanded","false");//
      $("#accordion" + accordionNumber + " .accordionanswer").addClass("hidden");
      $("#accordion" + accordionNumber + " .accordionquestion").removeClass("open");
      $("#accordion" + accordionNumber + " .accordionquestion").addClass("closed");
      $("#accordion" + accordionNumber + "question" + currentChoice).removeClass("open");
      $("#accordion" + accordionNumber + "question" + currentChoice).addClass("closed");



    });
  
  
  
  });
  
  
  $(document).ready(function(){
     
  //bigselector function
      //Change the bigselector number in the IDs of the bigselector if more than one bigselector on same page (default is 1. Bigselector in header is 99). E.g., if you choose "2" then change every reference to "bigselector1topchoice3" to "bigselector2topchoice3". Consider a field in the PT/AT to enter the number. That field would populate the numbers in the code below. Use logic in PT to control visibility of empty items.
  $(document).on("click",".bigselectortopchoice",function() {
      bigSelectorNumber = this.id.match(/\d+/);
      bigSelectorCurrentChoice = $(this).attr("id").slice(-1);
      $(".bigselectorcategory").addClass("hidden");
      $("#bigselector" + bigSelectorNumber + "category" + bigSelectorCurrentChoice).removeClass("hidden");
      $(".bigselectortopchoice").removeClass("selected");
      $("#bigselector" + bigSelectorNumber + "topchoice" + bigSelectorCurrentChoice).addClass("selected");
  });
  
  
  
  });
  
  $(document).ready(function(){
  var environment = "";
  var scriptHostname = "";
  var scriptURLBeginning = "https://";
  var scriptURLEnding = "/wcm/connect/theme%20elements/themeelements(sa)/outagemessage2?wcmitemid=348b1bd2-ccc6-4fa9-9de4-5b9c3b01b09e&WCM_Page.ResetAll=TRUE&CACHE=NONE&CONTENTCACHE=NONE&CONNECTORCACHE=NONE&SRV=Page";
  var scriptURL = "";
  var hostname = window.location.hostname;
  if(hostname.indexOf("anwas")>-1 || hostname.indexOf("dev.")>-1 || hostname.indexOf("dev-")>-1){
  scriptURL = scriptURLBeginning + "anwas65.bcbst.com:10042" + scriptURLEnding;
  }else if(hostname.indexOf("andxtst")>-1 || hostname.indexOf("test.")>-1 || hostname.indexOf("test-")>-1){
  scriptURL = scriptURLBeginning + "test.bcbst.com" + scriptURLEnding;
  }else{
  scriptURL = scriptURLBeginning + "www.bcbst.com" + scriptURLEnding;
  }
  
  let myScript = document.createElement("script");
  myScript.setAttribute("src", scriptURL);
  myScript.setAttribute("type","text/javascript")
  myScript.setAttribute("async", "false");
  let head = document.head;
  head.insertBefore(myScript, head.firstElementChild);
  myScript.addEventListener("load", scriptLoaded, false);
  
  function scriptLoaded() {
  
  var startCommaSplit = startDate.split(",");
  var startDateMonthDayYear = startCommaSplit[0] + "," + startCommaSplit[1];
  var startTimeRaw = startCommaSplit[2];
  var startTimeRawSplit = startTimeRaw.split(" ");
  var startAmPm = startTimeRawSplit[2];
  var startHourMinuteSecond = startTimeRawSplit[1];
  var startHourMinuteSecondSplit = startHourMinuteSecond.split(":");
  var startHour = parseInt(startHourMinuteSecondSplit[0]);
  var startMinute = parseInt(startHourMinuteSecondSplit[1]);
  var startSecond = parseInt(startHourMinuteSecondSplit[2]);
  if(startAmPm == "PM" && startHour != 12){
  startHour = startHour+12;
  }else if(startAmPm == "AM" && startHour == 12){
  startHour = 0;
  }else{
  }
  var startDateFinal = new Date(startDateMonthDayYear + " " + startHour + ":" + startMinute + ":" + startSecond);
  
  var endCommaSplit = endDate.split(",");
  var endDateMonthDayYear = endCommaSplit[0] + "," + endCommaSplit[1];
  var endTimeRaw = endCommaSplit[2];
  var endTimeRawSplit = endTimeRaw.split(" ");
  var endAmPm = endTimeRawSplit[2];
  var endHourMinuteSecond = endTimeRawSplit[1];
  var endHourMinuteSecondSplit = endHourMinuteSecond.split(":");
  var endHour = parseInt(endHourMinuteSecondSplit[0]);
  var endMinute = parseInt(endHourMinuteSecondSplit[1]);
  var endSecond = parseInt(endHourMinuteSecondSplit[2]);
  if(endAmPm == "PM" && endHour != 12){
  endHour = endHour+12;
  }else if(endAmPm == "AM" && endHour == 12){
  endHour = 0;
  }else{
  }
  var endDateFinal = new Date(endDateMonthDayYear + " " + endHour + ":" + endMinute + ":" + endSecond);
  
  /*
  var currentDate = new Date();
  if(currentDate>startDateFinal && currentDate<endDateFinal){
  console.log("within the window!");
  $("#usernameh").attr("title", outageMessage);
  $("#login-form #username").attr("title", outageMessage);
  }else{
  console.log("NOT within the window");
  $("#usernameh").attr("title", "");
  $("#login-form #username").attr("title", "");
  }
  */
  
  var currentDate = new Date();
  if(currentDate>startDateFinal && currentDate<endDateFinal){
  console.log("within the window!");
  $(".bcOutageTooltipText").html(outageMessage);
  $(".bcOutageMessageTooltipHolder .bcTooltip").removeClass("invisible");
  //$("#login-form #username").attr("title", outageMessage);
  }else{
  console.log("NOT within the window");
  $(".bcOutageTooltipText").html('');
  $(".bcOutageMessageTooltipHolder .bcTooltip").addClass("invisible");
  //$("#login-form #username").attr("title", "");
  }
  
  }
  
  $(".stMainContent.wpthemeMainContent").css("padding-top","0px");
  
  
  });
  
  
  /*add tooltips to rich text fields*/
      $(document).ready(function(){
          const richTextToolTips = [];
          var count = 1;
          var toolTipReplacement = "";
          $("*[name*='richTextToolTip']").each(function() {
              toolTipReplacement = "<div class='bcTooltipHolder relative text-center align-top inline-block p-0 w-20 h-20 ml-0'><img class='inline relative bottom-5' src='/wcm/connect/a07cf65f-89ba-4a0a-b984-e6480ad23891/icon__warning-small-blue.svg?MOD=AJPERES&amp;CACHEID=ROOTWORKSPACE-a07cf65f-89ba-4a0a-b984-e6480ad23891-mSDaaMf' alt='Information icon'><div class='bg-white leading-16 p-10 rounded-bcbst shadow-bcbst absolute font-roman border border-gray-400 bcTooltip bottom-full left-1/2 mb-10' style='font-size:14px;transform:translateX(-50%);min-width:150px'>" + $(this).attr("alt") + "<div class='absolute text-gray-400 text-center w-full text-18 bottom-0 -mb-20 pb-4 right-0 mr-3'>&nbsp;&#9660;</div><div class='absolute text-white text-center w-full text-16 bottom-0 -mb-18 pb-4 right-0 mr-3'>&nbsp;&#9660;</div></div></div>"
              $(this).replaceWith(toolTipReplacement);
          });
      });
  
  $(document).ready(function(){
  $("[summary*='summaryToClass']").each(function(){
  $(this).addClass($(this).attr("summary"));
  });
  });
  
  
  
  
  
  /*******Userstory 580875- Menu Nav Optimizations Changes by surya for Health equity- Start******/
  var MobileTab = /Android|webOS|iPhone|BlackBerry/i.test(navigator.userAgent) ? true : false;
  var mappedObj1 = {
   "About": "About Us Overview",
   "Diversity Inclusion": "Diversity, Inclusion & Health Equity",
   "Diversity Inclusion Health Equity" : "Diversity, Inclusion & Health Equity",
   "Improving Health" : "Diversity, Inclusion & Health Equity",
   "Social Determinants" : "Diversity, Inclusion & Health Equity",
   "Behavioral Health Disparities" : "Diversity, Inclusion & Health Equity",
   "Covid 19 Health Disparities" : "Diversity, Inclusion & Health Equity",
   "Chronic Condition Health Disparities": "Diversity, Inclusion & Health Equity",
   "Cancer Screening Health Disparities" : "Diversity, Inclusion & Health Equity",
   "Child Adolescent Well Care Health Disparities" : "Diversity, Inclusion & Health Equity",
   "Maternal Health Disparities" : "Diversity, Inclusion & Health Equity"
  }
  var mappedObj = {
  "About": "About Us"
  }
  $(document).ready(function() {
  var submenu = sessionStorage.getItem('Navsubmenu');
  var myPath = window.location.pathname;
  if (myPath.split('/' [1] !== "/")) {
      var text = myPath.split('/')[1].toLowerCase().replace(/-/g, " ")
      var Nav = text.replace(/(?:^|\s)\S/g, function(a) {
          return a.toUpperCase();
      });
  }
  if (myPath.split('/')[2]) {
      var text1 = myPath.split('/')[2].toLowerCase().replace(/-/g, " ");
      var submenu1 = text1.replace(/(?:^|\s)\S/g, function(a) {
          return a.toUpperCase();
      });
  }
  if (myPath.split('/')[3]) {
      var text2 = myPath.split('/')[3].toLowerCase().replace(/-/g, " ")
      var NavsubThird = text2.replace(/(?:^|\s)\S/g, function(a) {
          return a.toUpperCase();
      });
  }
  if (myPath.split('/')[4]) {
      var text3 = myPath.split('/')[4].toLowerCase().replace(/-/g, " ")
      var NavsubFour = text3.replace(/(?:^|\s)\S/g, function(a) {
          return a.toUpperCase();
      });
  }
  if (NavsubThird && !NavsubFour) {
      submenu1 = NavsubThird;
  }
  if(NavsubFour){
      submenu = "";
      submenu1 = "";
  }
  if (mappedObj[Nav]) {
      sessionStorage.setItem('Navsub', mappedObj[Nav]);
      if (!(myPath.split('/')[2]) && !(myPath.split('/')[3])) {
          submenu1 = Nav;
      }
  } else {
      sessionStorage.setItem('Navsub', Nav);
  }
  if (mappedObj1[submenu1]) {
      sessionStorage.setItem('Navsubmenu', mappedObj1[submenu1]);
  }  else if(submenu == null || submenu1){  
          sessionStorage.setItem('Navsubmenu', submenu1);
         }else{
            sessionStorage.setItem('Navsubmenu', submenu); 
         }
  });
  var height = $(window).height();
  var width = $(window).width();
  
  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 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 != '/')) {
          $(".bigselectorchoices").children().each(function (navel, el) {
              el.classList.remove("selected");
              var storedValue = sessionStorage.getItem('Navsub');
              var selectedValue = el.innerText;
              if (storedValue === "About") {
                  storedValue = "About Us";
              } 
              if (storedValue === selectedValue) {
                  isValue = true;
                  el.classList.add("selected");
  bigSelectorNumber = this.id.match(/\d+/);
      bigSelectorCurrentChoice = $(this).attr("id").slice(-1);
      $(".bigselectorcategory").addClass("hidden");
      $("#bigselector" + bigSelectorNumber + "category" + bigSelectorCurrentChoice).removeClass("hidden");
      $(".bigselectortopchoice").removeClass("selected");
      $("#bigselector" + bigSelectorNumber + "topchoice" + bigSelectorCurrentChoice).addClass("selected");
              }
          });
          $(".bigselectorcategory").children()
              .each(function (subel, subEle)
          {
              var storedSubValue = sessionStorage.getItem('Navsubmenu');
             var selectedSubValue = subEle.children[0].text;
              if (storedSubValue === selectedSubValue) {
                  isSubvalue = true;
                  subEle.classList.add('newClassName');
                  if ((document.body.clientWidth < 768) || (height > width)) {
                      $('.newClassName a').css('color', '#008cc9');
                      mobileSwitch = true;
                  } else {
  console.log("added color")
                      $('.newClassName a').css('border-left-color', '#008cc9');
                      mobileSwitch = false;
                  }
              }
              
          });
      } 
  }
  $(document).on("click",".dropdownbutton.begin",function() {
      $('.accordionquestion').each(function(navel, el){
          el.classList.remove("selected");
          el.classList.remove("mobileselectortopchoice");
          var storedValue = sessionStorage.getItem('Navsub');
          var selectedValue = el.firstElementChild.innerText;
          if (storedValue === "About") {
              storedValue = "About Us";
          } 
          if (storedValue === selectedValue) {
              isValue = true;
  el.classList.remove("closed");
              el.classList.add("open");
  el.classList.add("mobileselectortopchoice");
  $('#accordion99answer4').removeClass("hidden");
          }
          
          });
         $(".accordionanswer").children()
              .each(function (subel, subEle)
          {
              var storedSubValue = sessionStorage.getItem('Navsubmenu');
             var selectedSubValue = subEle.children[0].text;
              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 a').css('border-left-color', '#008cc9');
                      mobileSwitch = false;
                  }
              }
              
          });
  });
  $(window).resize(function() {
  alterClass();
  });
  /*******Userstory 580875- Menu Nav Optimizations Changes by surya for Health equity- End******/
  
  
  
  //BEGIN clickousel code
  $(document).ready(function(){
  
  var clickouselCounter = 1;
  var clickouselVisibleSlideNumber = [];
  $(".clickouselOuter").each(function(){
      $(this).addClass("clickouselOuter" + clickouselCounter);  
      $(".clickouselOuter" + clickouselCounter + " .clickouselArrowLeft").attr("id","clickouselArrowLeft" + clickouselCounter); 
      $(".clickouselOuter" + clickouselCounter + " .clickouselArrowRight").attr("id","clickouselArrowRight" + clickouselCounter);
      var clickouselItemCounter = 1
      $(".clickouselOuter" + clickouselCounter + " .clickouselItem").each(function(){
          $(this).closest(".clickousel").addClass("clickousel" + clickouselCounter);
          $(this).addClass("clickousel" + clickouselCounter + "Item" + clickouselItemCounter);
          $(".clickouselOuter" + clickouselCounter + " nav").append("<div class='w-10 h-10 rounded-full bg-blue-lightgray block cursor-pointer clickouselIndicator' id='clickouselNav"+clickouselCounter+"Item"+clickouselItemCounter+"'><div class='w-10 h-10 rounded-full bg-blue-strong block cursor-pointer toggleableGraphs hidden'></div></div>");
          clickouselVisibleSlideNumber[clickouselItemCounter] = 1;
          clickouselItemCounter++;
      });
      clickouselCounter++;
  });
  $(".clickouselIndicator:first-child div").removeClass("hidden");
  
  $(".clickouselArrowRight").click(function(){
      selectedRightArrow = parseInt(this.id.substring(this.id.lastIndexOf("Right") + 5));
      var currentClickouselLength = $(".clickousel" + selectedRightArrow).children().length;
      $(".clickousel" + selectedRightArrow + " .clickouselItem").addClass("hidden");
      if(clickouselVisibleSlideNumber[selectedRightArrow] == currentClickouselLength){
          clickouselVisibleSlideNumber[selectedRightArrow] = 1;
          $(".clickousel" + selectedRightArrow + "Item1").removeClass("hidden");
          $(".clickouselOuter" + selectedRightArrow + " .clickouselIndicator div").addClass("hidden");
          $("#clickouselNav" + selectedRightArrow + "Item1 div").removeClass("hidden");
      }else{
          clickouselVisibleSlideNumber[selectedRightArrow] += 1;
          $(".clickousel" + selectedRightArrow + "Item" + clickouselVisibleSlideNumber[selectedRightArrow]).removeClass("hidden");
          $(".clickouselOuter" + selectedRightArrow + " .clickouselIndicator div").addClass("hidden");
          $("#clickouselNav" + selectedRightArrow + "Item" + clickouselVisibleSlideNumber[selectedRightArrow] + " div").removeClass("hidden");
      }
  });
  
  $(".clickouselArrowLeft").click(function(){
      selectedLeftArrow = parseInt(this.id.substring(this.id.lastIndexOf("Left") + 4));
      var currentClickouselLength = $(".clickousel" + selectedLeftArrow).children().length;
      $(".clickousel" + selectedLeftArrow + " .clickouselItem").addClass("hidden");
      if(clickouselVisibleSlideNumber[selectedLeftArrow] == 1){
          clickouselVisibleSlideNumber[selectedLeftArrow] = currentClickouselLength;
          $(".clickousel" + selectedLeftArrow + "Item" + clickouselVisibleSlideNumber[selectedLeftArrow]).removeClass("hidden");
          $(".clickouselOuter" + selectedLeftArrow + " .clickouselIndicator div").addClass("hidden");
          $("#clickouselNav" + selectedLeftArrow + "Item" + clickouselVisibleSlideNumber[selectedLeftArrow] + " div").removeClass("hidden");
      }else{
          clickouselVisibleSlideNumber[selectedLeftArrow] = clickouselVisibleSlideNumber[selectedLeftArrow]-1;
          $(".clickousel" + selectedLeftArrow + "Item" + clickouselVisibleSlideNumber[selectedLeftArrow]).removeClass("hidden");
          $(".clickouselOuter" + selectedLeftArrow + " .clickouselIndicator div").addClass("hidden");
          $("#clickouselNav" + selectedLeftArrow + "Item" + clickouselVisibleSlideNumber[selectedLeftArrow] + " div").removeClass("hidden");
      }
  });
  
  
  $(".clickouselIndicator").click(function(){
      selectedClickousel = parseInt(this.id.substring(this.id.lastIndexOf("Nav") + 3));
      selectedClickouselItem = parseInt(this.id.substring(this.id.lastIndexOf("Item") + 4));
      clickouselVisibleSlideNumber[selectedClickousel] = selectedClickouselItem;
      $(".clickousel" + selectedClickousel + " .clickouselItem").addClass("hidden");
      $(".clickouselOuter" + selectedClickousel + " .clickouselIndicator div").addClass("hidden");
      $(".clickousel" + selectedClickousel + "Item" + selectedClickouselItem).removeClass("hidden");
      $("#clickouselNav" + selectedClickousel + "Item" + selectedClickouselItem + " div").removeClass("hidden");
  });   
  
  });
  
  //END clickousel code
  
  //BEGIN colorful chart accessibility
  
  $(document).ready(function(){
  
      // $('.popUpMsg').on('focusout', function() {
      //     $(this).addClass("hidden");
      // });
      $(document).mouseup((e) => {
          const container = $(".popUpMsg");
          if (!container.is(e.target) && container.has(e.target).length === 0) container.addClass("hidden");
      });
  
      $(".seeMore").on("click", function(){
          console.log($(this).parents());
          $(this).parents(".seeMoreCardItem").find(".popUpMsg").removeClass("hidden");
          $(this).parents(".seeMoreCardItem").find(".closeMod").trigger("focus");
      });
      $(".closeMod").on("click", function(){
          $(this).parents(".seeMoreCardItem").find(".popUpMsg").addClass("hidden");
          $(this).parents(".seeMoreCardItem").find(".seeMore").trigger("focus");
      });
      $('.popUpMsg').on('keydown', function(e) {
        if (e.keyCode == 27) { 
          $(this).find(".closeMod").trigger("click");
        }
      });
  });
  
  //END colorful chart accessibility
  
  /* start - 713713 - accessibility - when the chart is expanded it should loop back to close after going through all links */
  
  $(document).ready(function(){
  var boxPopUp = document.getElementsByClassName("popUpMsg");
  
  for(var i=0;i<boxPopUp.length;i++){
    var links = boxPopUp[i].getElementsByClassName("link");
    var lastLink = links[links.length - 1];
    console.log("links" , lastLink )
  
  lastLink.addEventListener("keydown" , function(event){
    console.log("test");
    if(event.keyCode === 9){
      event.preventDefault();
     console.log("parent" , this.parentNode);
     console.log("currentNode" , this);
     this.parentNode.parentNode.parentNode.getElementsByClassName("link")[0].focus()
  }
  });
  }
  });
  /* end - 713713 - accessibility - when the chart is expanded it should loop back to close after going through all links */
  
  
  
/* Start -  info Icon open on focus and hide on outfocus */
$(document).ready(function(){
    let diversityMemberPageFocus = document.querySelectorAll(".diversityMemFocus");
    diversityMemberPageFocus.forEach(function(item){
        item.addEventListener("focus" , function(event){
            this.nextElementSibling.classList.remove("bcTooltip");
        })
        item.addEventListener("focusout" , function(event){
            this.nextElementSibling.classList.add("bcTooltip");
        })
    })
  });
  /* End -  info Icon open on focus and hide on outfocus */
  


let isMobile = false;
$(document).ready(() => {
    ///////////////////////////////////////////////
    // Mobile Check
    ///////////////////////////////////////////////
    checkMobile();

    if (isMobile === true) {
        $('.accordion_lvl_2_container').removeClass('active');
    }

    ///////////////////////////////////////////////
    // Dynamic Mobile Functions
    ///////////////////////////////////////////////
    mobilePhoneLink();
    $(window).on("resize", () => {
        checkMobile();
        if (isMobile === true) {
            mobilePhoneLink();
            // Mobile sidenav view
            $('.accordion_lvl_2_container').removeClass('active');
        } else {
            // Desktop sidenav view
            const activeSection = $('.accordion_lvl_1_item.active').attr('id');
            const sectionNumber = activeSection.split('__')[1];
            $(`#accordion_lvl_2__${sectionNumber}`).addClass('active');
        }
    });

    ///////////////////////////////////////////////
    // Accordion Open/Close
    ///////////////////////////////////////////////
    // Get all elements with class "accordion_single_title" in the accordion_single
    const Accordion_Titles = document.querySelectorAll('.accordion_single_title');

    // Add a click event listener to each title in the accordion_single
    Accordion_Titles.forEach(accordionTitle => {
        accordionTitle.addEventListener('click', () => {

            // Find the parent div with class "accordion_single_item" in the accordion_single
            const parentLi = accordionTitle.closest('.accordion_single_item');

            // Check if the clicked item is already active
            const isActive = parentLi.classList.contains('active');

            // Remove the "active" class from all items in accordion_single
            Accordion_Titles.forEach(title => {
            const parentLi = title.closest('.accordion_single_item');
            parentLi.classList.remove('active');
            });

            // If the clicked item was not already active, add the "active" class
            if (!isActive) {
            parentLi.classList.add('active');
            }
        });
    });

    //////////////////////////
    // Side nav
    //////////////////////////
    $('.accordion_lvl_1 .accordion_lvl_1_item').on('click', (event) => {
        const clickedSection = $(event.target).parents('.accordion_lvl_1_item').attr('id');
        const navItem = clickedSection.split('__')[1];
        $('.accordion_lvl_1_item, .accordion_lvl_2_container, .accordion_single_item').removeClass('active');
        $(`#${clickedSection}, #accordion_lvl_2__${navItem}`).addClass('active');
        if (isMobile === true) {
            $('.accordion_lvl_1').addClass('hidden');
        }
    });
    $('.icon_back_link').on('click', (event) => {
        event.preventDefault();
        $('.accordion_lvl_2_container').removeClass('active');
        $('.accordion_lvl_1').removeClass('hidden');
    });
});
///////////////////////////////////////////////
// Mobile Check Function
///////////////////////////////////////////////
function checkMobile() {
    const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if(width < 1024) isMobile = true;
    else isMobile = false;
};

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

/////////////////////////////////////
///  Login Global Function
/////////////////////////////////////
function member_login(location){
  let hostEnvironment = "";
  let hostRegex = /test|www|rlse/g;
  let filteredEnvironment = hostRegex.exec(location)[0];
  if(filteredEnvironment == 'test'){hostEnvironment = 'test' }
  else{hostEnvironment = 'www'}
  if(hostEnvironment === 'test'){window.location.href = 'https://portals-stge.bcbst.com/login'}
  else{window.location.href = 'https://my.bcbst.com/login.'}
}