// Global javascript (loaded on all pages in Pattern Lab and Drupal)
// Should be used sparingly because javascript files can be used in components.

// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

/**
 * Rocketship UI JS
 *
 * contains: triggers for functions
 * Functions themselves are split off and grouped below each behavior
 */

(function (Drupal, once, window, document) {
  "use strict";

  // Set namespace for frontend UI javascript.
  if (typeof window.rocketshipUI == 'undefined') {
    window.rocketshipUI = {};
  }

  var self = window.rocketshipUI;

  ///////////////////////////////////////////////////////////////////////
  // Behavior for Tabs: triggers
  ///////////////////////////////////////////////////////////////////////

  Drupal.behaviors.rocketshipUISearchBlock = {
    attach: function (context, settings) {
      const searchBlock = document.querySelectorAll('.block--region-header-top.block--search-redirect-block'),
        trigger = document.querySelectorAll('.block--region-header-top.block--search-redirect-block h2');

      // Use the Mobile menu function drom the rocketshipUI namespace.
      if (trigger.length && searchBlock.length) {
        self.search(trigger, searchBlock);
      }
    }
  };

  /**
   * Mobile menu functionality
   */
  self.search = (trigger, wrapper) => {
    // open/close wrapper.
    once('search', trigger).forEach((triggerElement) => {
      triggerElement.addEventListener('click', (e) => {
        wrapper.classList.toggle('js-open');
        e.preventDefault();
      });
    });
  };

})(Drupal, once, window, document);
