jQuery(document).ready(function() {

  // 508 fix to apply aria-label to chosen inputs for 508 compliance
  jQuery('.chosen-search-input').attr('aria-label', 'Choose some options');

  // 508 fix to full pager, removing role attribute from <li>
  jQuery('li.pager__item--ellipsis').removeAttr('role');

    // 508 fix to apply role="presentation" to iframes
    jQuery('iframe').attr('role', 'presentation');

    // 508 fix to apply aria-label to location search form
    jQuery('#dynamic-home-form input.usa-input').attr('aria-label', 'location');

    jQuery("label[for='edit-field-dv2-declaration-date-value-min--2']").text("Year (Start)");

    jQuery("label[for='edit-field-dv2-declaration-date-value-max--2']").text("Year (End)");

    jQuery("label[for$='value-min']").text("Start Date");

    jQuery("label[for$='value-max']").text("End Date");

    var res = window.location.href.split('/');

    var last = res[res.length-1];
    var pre_last = res[res.length-2];
    var pre_pre_last = res[res.length-3];
    var pre_pre_pre_last = res[res.length-4];

    var libraryblockExists = jQuery('#views-exposed-form-document-libraries-block-1').length > 0;

    if (libraryblockExists) {
      if(jQuery('#views-exposed-form-document-libraries-block-1').length ) {
        console.log('library block exists');
        var field = 'name';
        var url = window.location.href;
        if (url.indexOf('?' + field + '=') != -1) {
          jQuery('#views-exposed-form-document-libraries-block-1').scrollIntoView(true);
        }
      }
    }

    if (last.split("?")[0] =='search' && pre_pre_last=='cbrn-tools') {
      console.log('cbrn js activated');
      if (jQuery('div#block-views-block-book-search-block-1').find('div:nth-child(2)').find('div').hasClass('view-content')) {
        jQuery('div#block-views-block-book-search-block-1').find('div:nth-child(2)').find('div').addClass('view-content').css('display','none');
      }
      var frm = jQuery('#views-exposed-form-book-search-block-2');
      if (frm.length > 0) {
        frm.attr('action','/cbrn-tools/key-planning-factors-chemical-incident/search');
      }
    }

    if ((pre_pre_last=='locations') && (pre_last=='contact')) {
      console.log('Part of USAJobs block');
      var selector = jQuery('#searchable > li:nth-child(84) > p > span.location-set');
      if (selector) {
        selector.style.display = "none";
      }
    }

    if (pre_last=='locations') {
      var y = jQuery(".usa-sidenav__sublist  .menu-level-4");
            if (y) {
             y.style.display = "none";
            }

      var z = jQuery(".menu_name-main");
            if (z) {
             z.style.display = "none";
            }

      setTimeout(
        function() {
          var x = jQuery("[aria-label^='Status message']");
          console.log(x);
          if (x) {
           x.style.display = "none";
          }
        }, 100);
    }

    window.addEventListener('load', (event) => {
      if (jQuery && jQuery('fieldset.tag-container').length) {
          jQuery("div[id^=block-views-block-events-block-]").insertBefore("fieldset.tag-container");
      }
      if (jQuery && jQuery('a[href^="https://www.disasterassistance.gov/DAC/govBenefitReceiver.do?action=LOGIN"]').length) {
          console.log('homepage apply for assistance link');
          jQuery('a[href^="https://www.disasterassistance.gov/DAC/govBenefitReceiver.do?action=LOGIN"]').attr('target','_blank').attr('rel','noreferrer');
      }
    });

  //When a user presses enter or clicks a dropdown with the class expanded move focus to first element in dropdown
  jQuery(".usa-nav__primary-item").keyup(function (e) {
      e.preventDefault();
      //When a user tabs to a primary menu item, hide the previous menu (via uswds attr settings)
      if((e.which || e.keyCode) == 9) {
          if (jQuery(e.target).hasClass("usa-nav__link")) {
            var button = jQuery(this).prev(".usa-nav__primary-item").children("button");
            var ul = jQuery(this).prev(".usa-nav__primary-item").children("ul");
            button.attr("aria-expanded","false");
            ul.prop("hidden", true);
          }
      }
      if((e.which || e.keyCode) == 13) {
          var first_child = jQuery("ul li:first:first-child a", this);
          jQuery(first_child).focus();
      }
  });

  var all_menu = jQuery(".usa-nav__primary");
  var last_child = jQuery("ul.usa-megamenu").last();
  var last_child2 = jQuery(last_child).find(".usa-nav__submenu-item").last();

  jQuery(last_child2).focusout(function (e) {
    var button = jQuery(all_menu).find(".usa-nav__primary-item").children("button");
    button.attr("aria-expanded","false");
    var ul = jQuery(all_menu).find(".usa-nav__primary-item").children("ul");
    ul.prop("hidden", true);
  });

  if (jQuery && jQuery('#edit-field-dv2-declaration-date-value-min--2').length) {
       jQuery('#edit-field-dv2-declaration-date-value-min--2').keypress(function (event) {
          // Only ASCII character in that range allowed
          var ASCIICode = (event.which) ? event.which : event.keyCode
          if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
              return false;
          return true;
      });
  }

  if (jQuery && jQuery('#edit-field-dv2-declaration-date-value-max--2').length) {
       jQuery('#edit-field-dv2-declaration-date-value-max--2').keypress(function (event) {
          // Only ASCII character in that range allowed
          var ASCIICode = (event.which) ? event.which : event.keyCode
          if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
              return false;
          return true;
      });
  }

  jQuery(".usa-nav__secondary-links:first-child li").keyup(function (e) {
      e.preventDefault();
      //When a user tabs to a primary menu item, hide the previous menu (via uswds attr settings)
      if((e.which || e.keyCode) == 9) {
          var button = jQuery(".region-primary-menu").find(".usa-nav__primary-item:last-child").children("button");
          var ul = jQuery(".region-primary-menu").find(".usa-nav__primary-item:last-child").children("ul");
          button.attr("aria-expanded","false");
          ul.prop("hidden", true);
      }
  });

  jQuery(".language-switcher-language-url > li > ul > li:last-child").focusout(function (e) {
      e.preventDefault();
      var button = jQuery(".language-switcher-language-url").find(".usa-nav__primary-item ").children("button");
      var ul = jQuery(".language-switcher-language-url").find(".usa-nav__primary-item").children("ul");
      button.attr("aria-expanded","false");
      ul.prop("hidden", true);
  });


    // 508 fix adding keyboard focus loop if the wcm_survey popup shows
    // First check to see if survey is showing and mov focus to Yes
    if (window.location.href.indexOf('#wcm-survey-target-id') > 0) {
        jQuery( ".button.yes a" ).focus();
    }

    // hitting tab key moves focus back and forth between Yes and No
    jQuery("#wcm-survey-popup .button a").keydown(function(e){
        if(jQuery('.button.yes a').is(":focus") && (e.which || e.keyCode) == 9 && !e.shiftKey){
            e.preventDefault();
            console.log('yes message');
            jQuery('.button.no a').focus();
        } else if(jQuery('.button.no a').is(":focus") && (e.which || e.keyCode) == 9 && !e.shiftKey){
            e.preventDefault();
            jQuery(".button.yes a").focus();
            console.log('no message');
        }
    });

    //location pages action menu region float to top
    var e = jQuery(".menu_name-locations-sidebar.menu-level-1");
    var prev = jQuery(".menu_name-locations-sidebar.menu-level-1").prev();
    if (e) {
      if (prev) {
        jQuery(prev).insertAfter(".menu_name-locations-sidebar.menu-level-0 li:nth-child(2)");
        jQuery(e).insertAfter("ul.usa-sidenav.menu_name-locations-sidebar.menu-level-0 > li:nth-child(3)");
        jQuery(".usa-sidenav.menu_name-locations-sidebar.menu-level-0 > ul > li:nth-child(3)").remove();
      }
    }

    //location pages action menu region float to top
    var e = jQuery(".menu_name-locations-sidebar-revised.menu-level-1");
    var prev = jQuery(".menu_name-locations-sidebar-revised.menu-level-1").prev();
    if (e) {
      if (prev) {
        jQuery(prev).insertAfter(".menu_name-locations-sidebar-revised.menu-level-0 li:nth-child(2)");
        jQuery(e).insertAfter("ul.usa-sidenav.menu_name-locations-sidebar-revised.menu-level-0 > li:nth-child(3)");
        jQuery(".usa-sidenav.menu_name-locations-sidebar-revised.menu-level-0 > ul > li:nth-child(3)").remove();
      }
    }

    // code to fix reset button issue on views filters jumping to wrong display  https://www.drupal.org/project/drupal/issues/1109980
    // note specfic subview needs exposed-form-scroll class to activate (and header with an id=exposed-form-scroll)
    jQuery(document).delegate(
      "div.exposed-form-scroll > div.view-filters > form.views-exposed-form input[data-drupal-selector='edit-reset']",
      "click",
      function (event) {
        event.preventDefault();
        window.location.replace(
          "https://" + window.location.hostname + window.location.pathname + "?efs=1"
        );
        return false;
      }
    );

    //scroll down to exposed form
    if(window.location.href.indexOf("efs") != -1) {

      jQuery([document.documentElement, document.body]).animate({
              scrollTop: jQuery("#exposed-form-scroll").offset().top
          }, 20);
    }

    jQuery(document).on('ajaxComplete', function(event, xhr, settings) {
      jQuery("label[for*='value-min']").text("Start Date");
      jQuery("label[for*='value-max']").text("End Date");
    });

});