(function ($, Drupal, CKEDITOR) {
  'use strict';

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

  CKEDITOR.plugins.add('imce', {
    // Define commands and buttons
    init: function (editor) {
      editor.addCommand('imceimage', {
        exec: CKEDITOR.imce.imageDialog
      });
      editor.ui.addButton('ImceImage', {
        label: CKEDITOR.imce.imageLabel(),
        command: 'imceimage',
        icon: editor.config.ImceImageIcon
      });
    }
  });

  /**
   * Global container for helper methods.
   */
  CKEDITOR.imce = CKEDITOR.imce || {

    /**
     * Returns image button label.
     */
    imageLabel: function () {
      return Drupal.t('Insert images using Imce File Manager');
    },

    /**
     * Opens Imce for inserting images into CKEditor.
     */
    imageDialog: function (editor) {
      var width = Math.min(1000, parseInt(screen.availWidth * 0.8));
      var height = Math.min(800, parseInt(screen.availHeight * 0.8));
      var url = CKEDITOR.imce.url('sendto=CKEDITOR.imce.imageSendto&type=image&ck_id=' + encodeURIComponent(editor.name));
      editor.popup(url, width, height);
    },

    /**
     * Imce sendto handler for image selection.
     */
    imageSendto: function (File, win) {
      var imce = win.imce;
      var editor = CKEDITOR.instances[imce.getQuery('ck_id')];
      if (editor) {
        var i;
        var lines = [];
        var selection = imce.getSelection();
        for (i in selection) {
          if (!imce.owns(selection, i)) {
            continue;
          }
          File = selection[i];
          if (File.width) {
            lines.push('<img src="' + File.getUrl() + '" width="' + File.width + '" height="' + File.height + '" alt="' + File.formatName() + '" />');
          }
        }
        editor.insertHtml(lines.join('<br />'));
      }
      win.close();
    },

    /**
     * Returns Imce url.
     */
    url: function (query) {
      var url = Drupal.url('imce');
      if (query) {
        url += (url.indexOf('?') === -1 ? '?' : '&') + query;
      }
      return url;
    }

  };

})(jQuery, Drupal, CKEDITOR);
