/**
 * @file
 * JavaScript behaviors for Webform UI.
 */

(function ($, Drupal, drupalSettings, once) {

  'use strict';

  /**
   * Move toggle weight element to the first child of the edit form.
   *
   * This ensure the toggle weight link is aligned with the add element actions.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformUiElementsToggleWeight = {
    attach: function (context, settings) {
      $(once('webform-ui-elements-toggle-weight', 'form.webform-edit-form', context)).each(function () {
        var $form = $(this);
        $form.find('.tabledrag-toggle-weight-wrapper').prependTo($form);
      });
    }
  };

  /**
   * Remove .button-primary class from .action-links .button-secondary.
   *
   * The seven.theme adds the .button-primary class to all actions.
   *
   * @type {Drupal~behavior}
   *
   * @see webform_ui_preprocess_menu_local_action()
   * @see seven_preprocess_menu_local_action()
   * @see webform_ui.module.css
   */
  Drupal.behaviors.webformUiElementsActionsSecondary = {
    attach: function (context, settings) {
      $(once('webform-ui-elements-webform-actions-secondary', '.action-links .button--secondary', context)).each(function () {
        $(this).removeClass('button--primary');
      });
    }
  };

  /**
   * Adds keyboard support to the form builder.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformUiElementsKeyboard = {
    attach: function (context, settings) {
      var $table = $(once('webform-ui-elements-keyboard', '.webform-ui-elements-table', context));

      // Disable autosubmit when Enter is pressed on 'Required' checkboxes.
      $table.find('td input:checkbox')
        .on('keyup keypress', function (e) {
          if (e.which === 13) {
            e.preventDefault();
            return false;
          }
        });

      // Move keyboard focus up (38) or down (40).
      $table.find('td:first-child a:not(.tabledrag-handle), td input:checkbox, td .webform-dropbutton li.dropbutton-action a, td .webform-dropbutton button')
        .on('keydown', function (event) {
          if (event.which === 38 || event.which === 40) {
            var $cell = $(this).closest('td');
            var $row = $cell.parent();
            var direction = (event.which === 38) ? 'prev' : 'next';
            var index = $cell.index();
            var tagName = this.tagName;
            while ($row[direction]().length) {
              $row = $row[direction]();
              $cell = $row.find('td').eq(index).find(tagName);
              if ($cell.length) {
                $cell.trigger('focus');
                break;
              }
            }
            event.preventDefault();
          }
        });

      // Move keyboard focus left (37) or right (39).
      $table.find('td a:not(.tabledrag-handle), td input, td select, td button')
        .on('keydown', function (event) {
          if (event.which === 37 || event.which === 39) {
            var $cell = $(this).closest('td');
            var direction = (event.which === 37) ? 'prev' : 'next';
            var $focus;

            // Move keyboard focus within operations dropbutton.
            if ($(this).closest('.webform-dropbutton').length) {
              if (direction === 'next' &&
                this.tagName === 'A' &&
                $(this).parent('.dropbutton-action').length) {
                $cell.find('button').trigger('focus');
                event.preventDefault();
                return;
              }
              else if (direction === 'prev' && this.tagName === 'BUTTON') {
                $cell.find('a').trigger('focus');
                event.preventDefault();
                return;
              }
            }

            while ($cell.length) {
              $cell = $cell[direction]();
              $focus = $cell.find('a:visible, input:visible, select:visible');
              if ($focus.length) {
                $focus.trigger('focus');
                event.preventDefault();
                return;
              }
            }
          }

        });
    }
  };

  /**
   * Monitor the element's key (aka machine name).
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformUiElementKey = {
    attach: function (context) {
      if (!drupalSettings.webform_ui ||
        !drupalSettings.webform_ui.reserved_keys ||
        !$(context).find(':input[name="key"]').length) {
        return;
      }

      // Monitor the machine name and display a warning when a reserved word is
      // being used.
      // There is no way to capture changes to the key val.
      // @see core/misc/machine-name.js.
      var currentKey;
      setInterval(function () {
        var value = $(':input[name="key"]').val();
        if (value === currentKey) {
          return;
        }
        currentKey = value;

        if ($.inArray(value, drupalSettings.webform_ui.reserved_keys) !== -1) {
          // Customize and display the warning message.
          $('[data-drupal-selector="edit-key-warning"]').show();
          $('#webform-ui-reserved-key-warning').html(
            Drupal.t("Please avoid using the reserved word '@key' as the element's key.", {'@key': value})
          );
        }
        else {
          // Hide the warning message.
          $('[data-drupal-selector="edit-key-warning"]').hide();
        }

      }, 300);
    }
  };

})(jQuery, Drupal, drupalSettings, once);
