/*global imce:true*/
(function ($, Drupal, imce) {
  'use strict';

  /**
   * @file
   * Defines Newfolder plugin for Imce.
   */

  /**
   * Init handler for New folder.
   */
  imce.bind('init', imce.newfolderInit = function () {
    if (imce.hasPermission('create_subfolders')) {
      // Add toolbar button
      imce.addTbb('newfolder', {
        title: Drupal.t('New folder'),
        permission: 'create_subfolders',
        content: imce.createNewfolderForm(),
        shortcut: 'Ctrl+N',
        icon: 'folder-add'
      });
    }
  });

  /**
   * Creates new folder form.
   */
  imce.createNewfolderForm = function () {
    var form = imce.newfolderForm;
    if (!form) {
      form = imce.newfolderForm = imce.createEl('<form class="imce-newfolder-form"><input type="text" name="newfolder" class="imce-newfolder-input" size="16" /><button type="submit" name="op" class="imce-newfolder-button">' + Drupal.t('Create') + '</button></form>');
      form.elements.newfolder.placeholder = Drupal.t('Folder name');
      form.onsubmit = imce.eNewfolderSubmit;
    }
    return form;
  };

  /**
   * Submit event for new folder form.
   */
  imce.eNewfolderSubmit = function () {
    var name = this.elements.newfolder.value;
    if (imce.validateNewfolder(name)) {
      imce.ajax('newfolder', {data: {newfolder: name}});
      imce.getTbb('newfolder').closePopup();
    }
    return false;
  };

  /**
   * Validates new folder creation.
   */
  imce.validateNewfolder = function (name, parentFolder) {
    if (!parentFolder) {
      parentFolder = imce.activeFolder;
    }
    if (!parentFolder.isReady() || !parentFolder.getPermission('create_subfolders') || !imce.validateFileName(name)) {
      return false;
    }
    if (parentFolder.getItem(name)) {
      imce.setMessage(Drupal.t('%filename already exists.', {'%filename': name}));
      return false;
    }
    return true;
  };

})(jQuery, Drupal, imce);
