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

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

  /**
   * Init handler for Delete.
   */
  imce.bind('init', imce.deleteInit = function () {
    // Check if delete permission exists.
    if (imce.hasPermission('delete_files') || imce.hasPermission('delete_subfolders')) {
      // Add toolbar button.
      imce.addTbb('delete', {
        title: Drupal.t('Delete'),
        permission: 'delete_files|delete_subfolders',
        handler: imce.deleteSelection,
        shortcut: 'DEL',
        icon: 'delete'
      });
    }
  });

  /**
   * Deletes the selected items in the active folder.
   */
  imce.deleteSelection = function () {
    var items = imce.getSelection();
    if (imce.validateDelete(items)) {
      if (confirm(Drupal.formatPlural(items.length, 'Delete !filename?', 'Delete the selected @count items?', {'!filename': items[0].name}))) {
        imce.ajaxItems('delete', items);
      }
    }
  };

  /**
   * Validates item deletion.
   */
  imce.validateDelete = function (items) {
    return imce.activeFolder.isReady() && imce.validateCount(items) && imce.validatePermissions(items, 'delete_files', 'delete_subfolders') && imce.validatePredefinedPath(items);
  };

})(jQuery, Drupal, imce);
