/**
 * @file
 * JavaScript behaviors for HTML editor integration.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  // @see http://docs.ckeditor.com/#!/api/CKEDITOR.config
  Drupal.webform = Drupal.webform || {};
  Drupal.webform.htmlEditor = Drupal.webform.htmlEditor || {};
  Drupal.webform.htmlEditor.options = Drupal.webform.htmlEditor.options || {};

  /**
   * Initialize HTML Editor.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformHtmlEditor = {
    attach: function (context) {
      if (!window.CKEDITOR) {
        return;
      }

      $(context).find('textarea.js-html-editor').once('webform-html-editor').each(function () {
        var $textarea = $(this);

        var allowedContent = drupalSettings['webform']['html_editor']['allowedContent'];

        // Load additional CKEditor plugins used by the Webform HTML editor.
        // @see \Drupal\webform\Element\WebformHtmlEditor::preRenderWebformHtmlEditor
        // @see \Drupal\webform\WebformLibrariesManager::initLibraries
        var plugins = drupalSettings['webform']['html_editor']['plugins'];

        // If requirejs is present don't use the codemirror plugin.
        // @see Issue #2936147: ckeditor.codemirror plugin breaks admin textarea.
        // @todo Remove the below code once this issue is resolved.
        if (plugins.codemirror
          && drupalSettings.yamlEditor
          && drupalSettings.yamlEditor.source
          && drupalSettings.yamlEditor.source.indexOf('noconflict') !== -1) {
          delete plugins.codemirror;
          if ('console' in window) {
            window.console.log('YAML Editor module is not compatible with the ckeditor.codemirror plugin. @see Issue #2936147: ckeditor.codemirror plugin breaks admin textarea.');
          }
        }

        for (var plugin_name in plugins) {
          if (plugins.hasOwnProperty(plugin_name)) {
            CKEDITOR.plugins.addExternal(plugin_name, plugins[plugin_name]);
          }
        }

        var options = {
          // Turn off external config and styles.
          customConfig: '',
          stylesSet: false,
          contentsCss: [],
          allowedContent: allowedContent,
          // Use <br> tags instead of <p> tags.
          enterMode: CKEDITOR.ENTER_BR,
          shiftEnterMode: CKEDITOR.ENTER_BR,
          // Set height.
          height: '100px',
          // Remove status bar.
          resize_enabled: false,
          removePlugins: 'elementspath,magicline',
          // Toolbar settings.
          format_tags: 'p;h2;h3;h4;h5;h6',
          // extraPlugins
          extraPlugins: ''
        };

        // Add toolbar.
        if (!options.toolbar) {
          options.toolbar = [];
          options.toolbar.push({name: 'styles', items: ['Format', 'Font', 'FontSize']});
          options.toolbar.push({name: 'basicstyles', items: ['Bold', 'Italic', 'Subscript', 'Superscript']});
          // Add IMCE image button.
          if (CKEDITOR.plugins.get('imce')) {
            CKEDITOR.config.ImceImageIcon = drupalSettings['webform']['html_editor']['ImceImageIcon'];
            options.extraPlugins += (options.extraPlugins ? ',' : '') + 'imce';
            options.toolbar.push({name: 'insert', items: ['ImceImage', 'SpecialChar']});
          }
          else {
            options.toolbar.push({name: 'insert', items: ['SpecialChar']});
          }

          // Add link plugin.
          if (plugins['link']) {
            options.extraPlugins += (options.extraPlugins ? ',' : '') + 'link';
            options.toolbar.push({name: 'links', items: ['Link', 'Unlink']});
          }
          options.toolbar.push({name: 'colors', items: ['TextColor', 'BGColor']});
          options.toolbar.push({name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']});
          options.toolbar.push({name: 'tools', items: ['Source', '-', 'Maximize']});
        }

        // Add autogrow plugin.
        if (plugins['autogrow']) {
          options.extraPlugins += (options.extraPlugins ? ',' : '') + 'autogrow';
          options.autoGrow_minHeight = 60;
          options.autoGrow_maxHeight = 300;
        }

        // Add CodeMirror integration plugin.
        if (plugins['codemirror']) {
          options.extraPlugins += (options.extraPlugins ? ',' : '') + 'codemirror';
          options.codemirror = {
            mode: 'text/html'
          };
        }

        options = $.extend(options, Drupal.webform.htmlEditor.options);

        // Catch and suppress
        // "Uncaught TypeError: Cannot read property 'getEditor' of undefined".
        //
        // Steps to reproduce this error.
        // - Goto any form elements.
        // - Edit an element.
        // - Save the element.
        try {
          CKEDITOR.replace(this.id, options).on('change', function (evt) {
            // Save data onchange since Ajax dialogs don't execute form.onsubmit.
            $textarea.val(evt.editor.getData().trim());
          });
        }
        catch (e) {
          // Do nothing.
        }
      });
    }
  };

})(jQuery, Drupal, drupalSettings);
;
/**
 * @file
 * JavaScript behaviors for other elements.
 */

(function ($, Drupal) {

  'use strict';

  /**
   * Toggle other input (text) field.
   *
   * @param {boolean} show
   *   TRUE will display the text field. FALSE with hide and clear the text field.
   * @param {object} $element
   *   The input (text) field to be toggled.
   * @param {string} effect
   *   Effect.
   */
  function toggleOther(show, $element, effect) {
    var $input = $element.find('input');
    var hideEffect = (effect === false) ? 'hide' : 'slideUp';
    var showEffect = (effect === false) ? 'show' : 'slideDown';

    if (show) {
      // Limit the other inputs width to the parent's container.
      // If the parent container is not visible it's width will be 0
      // and ignored.
      var width = $element.parent().width();
      if (width) {
        $element.width(width);
      }

      // Display the element.
      $element[showEffect]();
      // If not initializing, then focus the other element.
      if (effect !== false) {
        $input.trigger('focus');
      }
      // Require the input.
      $input.prop('required', true).attr('aria-required', 'true');
      // Restore the input's value.
      var value = $input.data('webform-value');
      if (typeof value !== 'undefined') {
        $input.val(value);
        var input = $input.get(0);
        // Move cursor to the beginning of the other text input.
        // @see https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome
        if ($.inArray(input.type, ['text', 'search', 'url', 'tel', 'password']) !== -1) {
          input.setSelectionRange(0, 0);
        }
      }
      // Refresh CodeMirror used as other element.
      $element.parent().find('.CodeMirror').each(function (index, $element) {
        $element.CodeMirror.refresh();
      });
    }
    else {
      // Hide the element.
      $element[hideEffect]();
      // Save the input's value.
      $input.data('webform-value', $input.val());
      // Empty and un-required the input.
      $input.val('').prop('required', false).removeAttr('aria-required');
    }
  }

  /**
   * Attach handlers to select other elements.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformSelectOther = {
    attach: function (context) {
      $(context).find('.js-webform-select-other').once('webform-select-other').each(function () {
        var $element = $(this);

        var $select = $element.find('select');
        var $input = $element.find('.js-webform-select-other-input');

        $select.on('change', function () {
          var isOtherSelected = $select
            .find('option[value="_other_"]')
            .is(':selected');
          toggleOther(isOtherSelected, $input);
        });

        var isOtherSelected = $select
          .find('option[value="_other_"]')
          .is(':selected');
        toggleOther(isOtherSelected, $input, false);
      });
    }
  };

  /**
   * Attach handlers to checkboxes other elements.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformCheckboxesOther = {
    attach: function (context) {
      $(context).find('.js-webform-checkboxes-other').once('webform-checkboxes-other').each(function () {
        var $element = $(this);
        var $checkbox = $element.find('input[value="_other_"]');
        var $input = $element.find('.js-webform-checkboxes-other-input');

        $checkbox.on('change', function () {
          toggleOther(this.checked, $input);
        });

        toggleOther($checkbox.is(':checked'), $input, false);
      });
    }
  };

  /**
   * Attach handlers to radios other elements.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformRadiosOther = {
    attach: function (context) {
      $(context).find('.js-webform-radios-other').once('webform-radios-other').each(function () {
        var $element = $(this);

        var $radios = $element.find('input[type="radio"]');
        var $input = $element.find('.js-webform-radios-other-input');

        $radios.on('change', function () {
          toggleOther(($radios.filter(':checked').val() === '_other_'), $input);
        });

        toggleOther(($radios.filter(':checked').val() === '_other_'), $input, false);
      });
    }
  };

  /**
   * Attach handlers to buttons other elements.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformButtonsOther = {
    attach: function (context) {
      $(context).find('.js-webform-buttons-other').once('webform-buttons-other').each(function () {
        var $element = $(this);

        var $buttons = $element.find('input[type="radio"]');
        var $input = $element.find('.js-webform-buttons-other-input');
        var $container = $(this).find('.js-webform-webform-buttons');

        // Create set onchange handler.
        $container.on('change', function () {
          toggleOther(($(this).find(':radio:checked').val() === '_other_'), $input);
        });

        toggleOther(($buttons.filter(':checked').val() === '_other_'), $input, false);
      });
    }
  };

})(jQuery, Drupal);
;
/**
 * @file
 * JavaScript behaviors for select menu.
 */

(function ($, Drupal) {

  'use strict';

  /**
   * Disable select menu options using JavaScript.
   *
   * @type {Drupal~behavior}
   */
  Drupal.behaviors.webformSelectOptionsDisabled = {
    attach: function (context) {
      $('select[data-webform-select-options-disabled]', context).once('webform-select-options-disabled').each(function () {
        var $select = $(this);
        var disabled = $select.attr('data-webform-select-options-disabled').split(/\s*,\s*/);
        $select.find('option').filter(function isDisabled() {
          return ($.inArray(this.value, disabled) !== -1);
        }).attr('disabled', 'disabled');
      });
    }
  };


})(jQuery, Drupal);
;
