/**
 * @file
 * JavaScript behaviors for admin pages.
 */

(function ($, Drupal, debounce) {

  'use strict';

  /**
   * Filters the webform element list by a text input search string.
   *
   * The text input will have the selector `input.webform-form-filter-text`.
   *
   * The target element to do searching in will be in the selector
   * `input.webform-form-filter-text[data-element]`
   *
   * The text source where the text should be found will have the selector
   * `.webform-form-filter-text-source`
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the behavior for the webform element filtering.
   */
  Drupal.behaviors.webformFilterByText = {
    attach: function (context, settings) {
      $('input.webform-form-filter-text', context).once('webform-form-filter-text').each(function () {
        var $input = $(this);
        var $table = $($input.data('element'));
        var $summary = $($input.data('summary'));
        var $noResults = $($input.data('no-results'));
        var $details = $table.closest('details');
        var sourceSelector = $input.data('source') || '.webform-form-filter-text-source';
        var parentSelector = $input.data('parent') || 'tr';
        var $filterRows;

        var hasDetails = $details.length;
        var totalItems;
        var args = {
          '@item': $input.data('item-single') || Drupal.t('item'),
          '@items': $input.data('item-plural') || Drupal.t('items'),
          '@total': null
        };

        if ($table.length) {
          $filterRows = $table.find(sourceSelector);
          $input
            .attr('autocomplete', 'off')
            .on('keyup', debounce(filterElementList, 200))
            .keyup();
          // Make sure the filter input is always focused.
          setTimeout(function () {$input.focus();});
        }

        /**
         * Filters the webform element list.
         *
         * @param {jQuery.Event} e
         *   The jQuery event for the keyup event that triggered the filter.
         */
        function filterElementList(e) {
          var query = $(e.target).val().toLowerCase();

          // Filter if the length of the query is at least 2 characters.
          if (query.length >= 2) {
            // Reset count.
            totalItems = 0;
            if ($details.length) {
              $details.hide();
            }
            $filterRows.each(toggleEntry);

            // Announce filter changes.
            // @see Drupal.behaviors.blockFilterByText
            Drupal.announce(Drupal.formatPlural(
              totalItems,
              '1 @item is available in the modified list.',
              '@total @items are available in the modified list.',
              args
            ));
          }
          else {
            totalItems = $filterRows.length;
            $filterRows.each(function (index) {
              $(this).closest(parentSelector).show();
              if ($details.length) {
                $details.show();
              }
            });
          }

          // Set total.
          args['@total'] = totalItems;

          // Hide/show no results.
          $noResults[totalItems ? 'hide' : 'show']();

          // Update summary.
          if ($summary.length) {
            $summary.html(Drupal.formatPlural(
              totalItems,
              '1 @item',
              '@total @items',
              args
            ));
          }

          /**
           * Shows or hides the webform element entry based on the query.
           *
           * @param {number} index
           *   The index in the loop, as provided by `jQuery.each`
           * @param {HTMLElement} label
           *   The label of the webform.
           */
          function toggleEntry(index, label) {
            var $label = $(label);
            var $row = $label.closest(parentSelector);
            var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
            $row.toggle(textMatch);
            if (textMatch) {
              totalItems++;
              if (hasDetails) {
                $row.closest('details').show();
              }
            }
          }
        }
      });
    }
  };

  /**
   * Filter webform autocomplete handler.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformFilterAutocomplete = {
    attach: function (context) {
      $('.webform-filter-form input.form-autocomplete', context).once('webform-autocomplete')
        .each(function () {
          // If input value is an autocomplete match, reset the input to its
          // default value.
          if (/\(([^)]+)\)$/.test(this.value)) {
            this.value = this.defaultValue;
          }

          // From: http://stackoverflow.com/questions/5366068/jquery-ui-autocomplete-submit-onclick-result
          $(this).bind('autocompleteselect', function (event, ui) {
            if (ui.item) {
              $(this).val(ui.item.value);
              this.form.submit();
            }
          });
        });
    }
  };

  /**
   * Allow table rows to be hyperlinked.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformTableRowHref = {
    attach: function (context) {
      // Only attach the click event handler to the entire table and determine
      // which row triggers the event.
      $('.webform-results-table', context).once('webform-results-table').click(function (event) {
        if (event.target.tagName === 'A' || event.target.tagName === 'BUTTON') {
          return true;
        }

        if ($(event.target).parents('a[href]').length) {
          return true;
        }

        var $tr = $(event.target).parents('tr[data-webform-href]');
        if (!$tr.length) {
          return true;
        }

        window.location = $tr.attr('data-webform-href');
        return false;
      });
    }
  };

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