(function (Drupal, $, window) {
  Drupal.behaviors.samhsa_data = {
    attach: function (context, settings) {

      // Execute code once the DOM is ready.
      // search place holder

      if ($("body").hasClass("path-all-reports")) {
        $("#views-exposed-form-solr-search-content-page .form-item-keys input[type=\'text\']").attr("placeholder", "Search SAMHSA Data");
      } else if ($(window).width() < 550) {
        $("#views-exposed-form-solr-search-content-page .form-item-keys input[type=\'text\']").attr("placeholder", "Search SAMHSA Reports");
      } else {
        $("#views-exposed-form-solr-search-content-page .form-item-keys input[type=\'text\']").attr("placeholder", "Search SAMHSA Reports and Data Tables");
      }



      if ($('.block').hasClass('Data-Search-Header-Block')) {
        $(".Data-Search-Header-Block .samhsa-data-all-reports-search-form input[type=\'text\']").attr("placeholder", "Search SAMHSA Data");
      }
      //----------------------------------------------------------------------------------------------
      $(document).ready(function () {
        // Expand collapse functionality of reports
        function expandCollapse() {
          var theHeaders = document.querySelectorAll('.expandCollapse h2'), i;
          for (i = 0; i < theHeaders.length; i++) {
            var thisEl = theHeaders[i],
              theId = 'report-section-content-' + i;
            var thisParentId = 'report-section-header-' + i;
            var thisTarget = thisEl.parentNode.querySelector('.report-section-content');
            var thisParent = thisEl.parentNode.querySelector('.report-section-header');
            if (!thisTarget) {
              continue;
            }
            thisParent.setAttribute('id', thisParentId);
            // Create the button
            thisEl.innerHTML = '<button aria-expanded="false" aria-controls="' + theId + '">' + thisEl.textContent + '</button>';
            // Create the expandable and collapsible list and make it focusable
            thisTarget.setAttribute('id', theId);
            thisTarget.setAttribute('aria-hidden', 'true');
          }
          // Make it click
          var theButtons = document.querySelectorAll('.expandCollapse button[aria-expanded][aria-controls]');
          for (i = 0; i < theButtons.length; i++) {
            theButtons[i].addEventListener('click', function (e) {
              var thisButton = e.target;
              var state = thisButton.getAttribute('aria-expanded') === 'false' ? true : false;
              thisButton.setAttribute('aria-expanded', state);
              document.getElementById(thisButton.getAttribute('aria-controls')).setAttribute('aria-hidden', !state);
            });
          }
        }
        expandCollapse();
        // Downloads section script
        jQuery('#sr-figures_tooltip').popup({
          type: 'tooltip',
          vertical: 'bottom',
          transition: '0.3s all 0.1s',
          tooltipanchor: $('#sr-figures_tooltip_open')
        });
        jQuery('#sr-citation_tooltip').popup({
          type: 'tooltip',
          vertical: 'bottom',
          transition: '0.3s all 0.1s',
          tooltipanchor: $('#sr-citation_tooltip_open')
        });
        $(function () {
          $('.faqfield-details .faqfield-question').on('click', function (e) {
            var answer = $(this).next('.faqfield-answer');
            if (!$(answer).is(":visible")) {
              $(this).parent().addClass('open');
            } else {
              $(this).parent().removeClass('open');
            }
          });
        });
      });

      // Execute code once the window is fully loaded.
      //----------------------------------------------------------------------------------------------
      // This function is removed Oct 2023 because we are removing sideblock with SAMHDA branding
      // that this used to act on. -Lera
      // $(window).on('load', function () {
      //   // rearranging downloads and table of contents block in desktop mode
      //   $('.report-downloads, .report-contents').remove().insertBefore($('.did-you-know'));
      //   $(window).breakpoints();
      //   $(window).on('lessThan-lg', function () {
      //     $('.report-downloads, .report-contents').remove().insertAfter($('.report-header'));
      //   });
      //   $(window).on('greaterEqualTo-lg', function () {
      //     $('.report-downloads, .report-contents').remove().insertBefore($('.did-you-know'));
      //   });
      // });

      // Execute code when the window is resized.
      //----------------------------------------------------------------------------------------------
      $(window).resize(function () {
      });
      // Execute code when the window scrolls.
      //----------------------------------------------------------------------------------------------
      $(window).scroll(function () {
      });
    }
  };
  Drupal.behaviors.svg4everybody = {
    attach: function (context, settings) {
      if (svg4everybody) {
        svg4everybody();
      }
    }
  };
  Drupal.behaviors.facettest = {
    attach: function (context, settings) {
      jQuery('.block-facets .block-title').addClass('js-expandmore');
      jQuery('.block-facets .block-content').addClass('js-to_expand');
      // search facet select elements shown script
      jQuery.fn.multiselect = function () {
        $(this).each(function () {
          var checkboxes = $(this).find("input:checkbox");
          checkboxes.each(function () {
            var checkbox = $(this);
            // Highlight pre-selected checkboxes
            if (checkbox.prop("checked"))
              checkbox.parents('.block-content').addClass("is-opened");
            // Highlight checkboxes that the user selects
            checkbox.click(function () {
              if (checkbox.prop("checked"))
                checkbox.parents('.block-content').addClass("is-opened");
              else
                checkbox.parents('.block-content').removeClass("is-opened");
            });
          });
        });
      };
      jQuery(".block-facets").multiselect();
    }
  };
  Drupal.behaviors.didYouKnowUrl = {
    attach: function (context, settings) {
      $(document).ready(function () {
        // If the search term does not have any results and a spellcheck module makes a suggestion,
        // then, modify the redirect url of the new search item to fix the search path and keys.
        if ($('div.sapi-did-you-mean').length && $('span.did-you-mean-prefix').length) {
          var curr_key = $(this).find("div.sapi-did-you-mean a").text();
          var pathname = window.location.href;
          var base_path = pathname.substr(0, pathname.indexOf('/all-reports'));
          var new_url = base_path + '/all-reports?keys=' + curr_key + '&items_per_page=15&sort_bef_combine=field_date_printed_on_report_DESC';
          $(this).find("div.sapi-did-you-mean a").attr('href', new_url);
        }
      });
    }
  };
  Drupal.behaviors.dtagovauChosenAccessibilityFix = {
    attach: function (context, settings) {
      jQuery('body').on('chosen:ready', function (evt, params) {
        jQuery('.js-form-item.js-form-type-select', context).each(function (index, element) {
          jQuery(this).find('.chosen-container-multi input.chosen-search-input').attr('aria-label', jQuery.trim(jQuery(this).find('label').text()));
          jQuery(this).find('.chosen-container-single input.chosen-search-input').attr('aria-label', jQuery.trim(jQuery(this).find('label').text()));
        });
      });
    }
  }
}(Drupal, jQuery, this));

(function ($) {
  $(function () {
    // sliding facets filters
    $('.redraw-search-facets-title a').click(function () {
      $nextArticle = $(this).parents('.block-cbhsq8-reset-search-filters-block').siblings('.block-facets');
      if ($nextArticle.length) {
        $nextArticle.is(':visible') ? $nextArticle.slideUp() : $nextArticle.slideDown();
      }
      return false;
    });
    // web ready view more html and download files
    $('.web-ready-view-files ul , .web-ready-download-files ul').each(function () {
      var ListN = $(this).find('li').length;
      if (ListN > 5) {
        $('li', this).eq(4).nextAll().hide().addClass('toggleable');
        $(this).append('<button class="more"><span>View More</span> <span class="arrow"></span></button>');
      }
    });
    $('.web-ready-view-files ul , .web-ready-download-files ul').on('click', '.more', function () {
      if ($(this).hasClass('less')) {
        $(this).html('<span>View More</span> <span class="arrow"></span>').removeClass('less');
      } else {
        $(this).html('<span>View Less</span>  <span class="arrow"></span>').addClass('less');
      }
      $(this).siblings('li.toggleable').slideToggle();
    });

    $(function () {
      $(window).resize(function () {
        if ($(window).width() <= 848) {
          $('#report_content').remove().insertAfter($('#report_sidebar_1'));

        } else {
          $('#report_content').remove().insertAfter($('#report_header'));
        }
      })
      // make entire search result row clickable
      $(".view-all-reports .views-row").click(function () {
        window.location = $(this).find("a").attr("href");
        return false;
      });

    });
    // Web ready pages Iframe Load
    // iframe hiding
    $(".hide-wr-iframe").click(function () {
      window.history.back();
    });
    $('a.ifrLink').on('click', function (e) {
      e.preventDefault();
      $('#ifrm').css('height', $(window).height() * 0.9 | 0);
      $(".hide-for-iframe").hide();
      $(".wr-iframe-wrapper").show();
      $(".page-wrapper").addClass('extra-width');
      $(".main-content").addClass('extra-margin');
      history.pushState(null, null, window.location.href.split('#')[0]);
      $('#ifrm').get(0).contentWindow.location.replace($(this).attr('href'));
    });
    if ($('p.go-back').length > 0 && document.referrer.indexOf("/data/all-reports") > -1) {
      $('p.go-back a').attr("href", document.referrer);
      $('p.go-back').show();
    } else if ($('p.go-back').length > 0 && $('p.go-back').is(":visible")) {
      $('p.go-back a').attr("href", '');
      $('p.go-back').hide();
    }
    $(window).on('popstate', function (e) {
      if ($('.web-ready-file-link').length) {
        e.preventDefault();
        if ($(".wr-iframe-wrapper").css('display') == 'block') {
          // $('a.hide-wr-iframe').click();
          $(".wr-iframe-wrapper").hide();
          $(".hide-for-iframe").show();
          $(".main-content").removeClass('extra-margin');
          $(".page-wrapper").removeClass('extra-width');
          $(".hide-for-iframe,.wr-iframe-wrapper,.grid-container, .main-content ").css({
            'height': 'auto'
          });
        } else {
          window.location = $('.go-back a').attr('href');
        }
      }
    });
    // taxonomy topics page , columnize the list // search facets - columnize states list
    $('ul.related-topics-list, .taxonomy-term-related-topics ul, .other-topics ul').columnlist({
      size: 3,
      'class': 'column-list',
      incrementClass: 'column-list-'
    });

    jQuery('.report-table-of-contents h3').addClass('js-expandmore');
    jQuery('.report-table-of-contents ul').addClass('js-to_expand');
    // run test on initial page load
    checkSize();
    // run test on resize of the window
    $(window).resize(checkSize);
    //Function to the css rule
    function checkSize() {
      if ($(".report-table-of-contents").css("float") == "none") {
        // Table of contents script
        jQuery('.report-table-of-contents h3').addClass('js-expandmore');
        jQuery('.report-table-of-contents ul').addClass('js-to_expand');
        jQuery('.report-table-of-contents ul').removeClass('is-opened');
      } else {
        // Table of contents script
        jQuery('.report-table-of-contents h3').removeClass('js-expandmore');
        jQuery('.report-table-of-contents ul').removeClass('js-to_expand');
        jQuery('.report-table-of-contents ul').addClass('is-opened');
      }
    }
    // close the DIV
    $('.close').on('click', function (c) {
      $('.anouncements').fadeOut('slow', function (c) {
      });
    });
    // Dialog window
    $(function () {
      var navDialogEl = document.querySelector('.dialog');
      var dialogOverlay = document.querySelector('.dialog-overlay');
      if (navDialogEl || dialogOverlay) {
        var myDialog = new Dialog(navDialogEl, dialogOverlay);
        myDialog.addEventListeners('.open-dialog', '.close-dialog');
      }
    });
    // web ready no parent collection then stretch the description
    if ($('.web-ready-this-collection-block div').hasClass('this-is-collection') && ($('.this-is-collection').contents().length == 0)) {
      $(".web-ready-description").addClass("extend-width");
    }
    // web ready no parent collection or stand alone collection then stretch the description
    if (!$('.web-ready-parent-collection-block span').hasClass("this-report") && !$('.web-ready-this-collection-block div').hasClass("this-is-collection")) {
      // $(".web-ready-description").addClass("extend-width");
      // $(".web-ready-parent-collection-block").parent().css('display', 'none');
    }
  });
  // execute mobile menu
  $(document).ready(function () {
    if (window.location.pathname.indexOf("frequently-asked-questions") > 0 && window.location.hash) {
      setTimeout(function () {
        window.scrollTo(0, 0);
      }, 1);
    }
    $(function () {
      $('#dl-menu').dlmenu({
        animationClasses: { classin: 'dl-animate-in-2', classout: 'dl-animate-out-2' }
      });
      $(".mobile-only").parent().addClass("mobile-only");
    });
    // execute menu active path
    var path = window.location.pathname.split('/');
    path = path[path.length - 1];
    if (path !== undefined) {
      $("ul.sf-menu, ul.sf-menu ul")
        .find("a[href$='" + path + "']") // gets all links that match the href
        .parents('li') // gets all list items that are ancestors of the link
        .children('a') // walks down one level from all selected li's
        .addClass('active');
    }
    // More Like this section responsive tabs
    $('#horizontalTab').responsiveTabs({
      startCollapsed: 'accordion',
      collapsible: true,
      rotate: false
    });
    $('#how-can-we-help').responsiveTabs({
      startCollapsed: 'accordion',
      collapsible: true,
      rotate: false
    });
    // 508 fix - added ARIA labels and values for different needs
    $("h2#block-mainmenu-2-menu").text("Mobile Menu");
    $("h2#block-footer1menu-menu").text("Footer Menu");
    $(".data-footer-menu ul li:first a").attr("aria-label", "Link to SAMHSA Data site Home Page");
    $(".samhsa-footer-menu ul li:first a").attr("aria-label", "Link to SAMHSA Main site Home Page");
    $('#superfish-main-menu a[href^="https://www.samhsa.gov/data/about-us"]').attr("aria-label", "Link to samhsa data site about us page");
    $('#superfish-main-menu a[href^="https://www.samhsa.gov/about-us/contact-us"]').attr("aria-label", "Link to samhsa main site about us contact us page");
    $('#superfish-main-menu a[href^="https://www.samhsa.gov/data/frequently-asked-questions"]').attr("aria-label", "Link to samhsa data site FAQ page");
    $('#block-samhsa-footer-nav-toggle a[href^="/frequently-asked-questions"]').attr("aria-label", "footer Link to samhsa data FAQ page");
    $(".request-ask-link-faq a").attr("aria-label", "Link to SAMHSA Data site FAQ Content");
    $(".request-ask-link-cus a").attr("aria-label", "Link to SAMHSA Data site Contact us form");
    $('.data-collection-list a[href^="/blog"]').attr("aria-label", "Link to samhsa blog site");
    $('#items-footer-social .social-link-blog').attr("aria-label", "Social Media Link to samhsa blog site");
    $('#views-exposed-form-solr-search-content-page label').attr("aria-label", "search SAMHSA Data");
    $('#edit_contact_how_can_we_help_chosen .chosen-search-input').attr("aria-label", "Select message about");
    $('#edit_contact_special_pop_chosen .chosen-search-input').attr("aria-label", "Select message to");
    $('#edit_contact_location_chosen .chosen-search-input').attr("aria-label", "Select location to");
    // aria-label not to be use on link with visible description already showing, e.g. link text
    // $("a.ext").attr("aria-label", "link is external");
    $('a.ext span.ext').addClass('sr-only');
    $('a.ext span.ext').removeAttr("aria-label");
    $('a.ext span.ext').html("This links takes you to the external website" + $(this).parent().text());
    // change aria-label to aria-description to avoid misuse of aria-label for next two items
    $('a[href*=".pdf"]').each(function () {
      var pdfPath = this.getAttribute("href");
      var pdfName = pdfPath.substring(pdfPath.lastIndexOf('/') + 1);
      $(this).attr("aria-description", "This link opens " + pdfName + " file");
    });
    $('a[href*=".pptx"]').each(function () {
      var pptPath = this.getAttribute("href");
      var pptName = pptPath.substring(pptPath.lastIndexOf('/') + 1);
      $(this).attr("aria-description", "This link opens " + pptName + " file");
    });
  });

  // on mobile widths, show and hide a search bar when the search icon is clicked
  $(document).ready(function() {
    $('#top-search-glass-icon').click(function() {
      $('.search-form-wrapper').toggleClass('open');
    });
  });

})(jQuery);