/**
 * @file
 * Provides an event handler for hidden elements in dropdown menus.
 */

(function ($, Drupal, Bootstrap) {
  'use strict';

  /**
   * The list of supported events to proxy.
   *
   * @type {Array}
   */
  var events = [
    // MouseEvent.
    'click', 'dblclick', 'mousedown', 'mouseenter', 'mouseleave', 'mouseup', 'mouseover', 'mousemove', 'mouseout',

    // KeyboardEvent.
    'keypress', 'keydown', 'keyup'
  ];

  /**
   * Bootstrap dropdown behaviors.
   *
   * Proxy any dropdown element events that should actually be fired on the
   * original target (e.g. button, submits, etc.). This allows any registered
   * event callbacks to be fired as they were intended (despite the fact that
   * the markup has been changed to work with Bootstrap).
   *
   * @see \Drupal\bootstrap\Plugin\Preprocess\BootstrapDropdown::preprocessLinks
   *
   * @type {Drupal~behavior#bootstrapDropdown}
   */
  Drupal.behaviors.bootstrapDropdown = {
    attach: function (context) {
      var elements = context.querySelectorAll('.dropdown [data-dropdown-target]');
      for (var k in elements) {
        if (!elements.hasOwnProperty(k)) {
          continue;
        }
        var element = elements[k];
        for (var i = 0, l = events.length; i < l; i++) {
          var event = events[i];
          element.removeEventListener(event, this.proxyEvent);
          element.addEventListener(event, this.proxyEvent);
        }
      }
    },

    /**
     * Proxy event handler for bootstrap dropdowns.
     *
     * @param {Event} e
     *   The event object.
     */
    proxyEvent: function (e) {
      // Ignore tabbing.
      if (e.type.match(/^key/) && (e.which === 9 || e.keyCode === 9)) {
        return;
      }
      var target = e.currentTarget.dataset && e.currentTarget.dataset.dropdownTarget || e.currentTarget.getAttribute('data-dropdown-target');
      if (target) {
        e.preventDefault();
        e.stopPropagation();
        var element = target && target !== '#' && document.querySelectorAll(target)[0];
        if (element) {
          Bootstrap.simulate(element, e.type, e);
        }
        else if (Bootstrap.settings.dev && window.console && !e.type.match(/^mouse/)) {
          window.console.debug('[Drupal Bootstrap] Could not find a the target:', target);
        }
      }
    }
  }

})(jQuery, Drupal, Drupal.bootstrap);
