/**
 * @file
 * JavaScript behaviors for element #states.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  /**
   * Element #states builder.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformElementStates = {
    attach: function (context) {
      $(context).find('.webform-states-table--condition').once('webform-element-states').each(function () {
        var $condition = $(this);
        var $selector = $condition.find('.webform-states-table--selector select');
        var $value = $condition.find('.webform-states-table--value input');
        var $trigger = $condition.find('.webform-states-table--trigger select');

        // Initialize autocompletion.
        $value.autocomplete({minLength: 0}).on('focus', function () {
          $value.autocomplete('search', '');
        });

        // Initialize trigger and selector.
        $trigger.on('change', function () {$selector.change();});

        $selector.on('change', function () {
          var selector = $selector.val();
          var sourceKey = drupalSettings.webformElementStates.selectors[selector];
          var source = drupalSettings.webformElementStates.sources[sourceKey];
          var notPattern = ($trigger.val().indexOf('pattern') === -1);
          if (source && notPattern) {
            // Enable autocompletion.
            $value
              .autocomplete('option', 'source', source)
              .addClass('form-autocomplete');
          }
          else {
            // Disable autocompletion.
            $value
              .autocomplete('option', 'source', [])
              .removeClass('form-autocomplete');
          }
        }).change();
      });
    }
  };

})(jQuery, Drupal, drupalSettings);
