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

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

  /**
   * Init handler for Upload.
   */
  imce.bind('init', imce.uploadInit = function () {
    if (imce.hasPermission('upload_files')) {
      // Add toolbar button
      imce.addTbb('upload', {
        title: Drupal.t('Upload'),
        permission: 'upload_files',
        content: imce.createUploadForm(),
        shortcut: 'Ctrl+Alt+U',
        icon: 'upload'
      });
    }
  });

  /**
   * Creates the upload form.
   */
  imce.createUploadForm = function () {
    var els;
    var el;
    var exts;
    var form = imce.uploadForm;
    var name = 'files[imce][]';
    if (form) {
      return form;
    }
    form = imce.uploadForm = imce.createEl('<form class="imce-upload-form" method="post" enctype="multipart/form-data" accept-charset="UTF-8">' +
    '<div class="imce-form-item imce-form-file">' +
      '<label>' + Drupal.t('File') + '</label>' +
      '<input type="file" name="' + name + '" class="imce-file-input" multiple />' +
    '</div>' +
    '<div class="imce-form-actions">' +
      '<button type="submit" name="op" class="imce-upload-button">' + Drupal.t('Upload') + '</button>' +
    '</div>' +
    '<input type="hidden" name="jsop" value="upload" />' +
    '<input type="hidden" name="token" />' +
  '</form>');
    // Set action
    form.action = imce.getConf('ajax_url');
    els = form.elements;
    // Set token
    els.token.value = imce.getConf('token');
    // Set accepted extensions.
    el = els[name];
    exts = imce.getConf('extensions', '');
    // Skip for * which is interpreted incorrectly by some browsers.
    if (exts !== '*') {
      el.accept = '.' + exts.replace(/\s+/g, ',.');
    }
    // Ajax upload
    if (imce.canAjaxUpload()) {
      imce.activeUq = new imce.UploadQueue({name: name, accept: el.accept});
      form.insertBefore(imce.activeUq.el, form.firstChild);
      form.className += ' uq';
      if (imce.getConf('upload_auto_start', 1)) {
        form.className += ' auto-start';
      }
      form.onsubmit = imce.eUploadQueueSubmit;
    }
    // Iframe upload
    else {
      form.setAttribute('target', 'imce_upload_iframe');
      form.appendChild(imce.createEl('<input type="hidden" name="active_path" />'));
      form.appendChild(imce.createEl('<input type="hidden" name="return_html" value="1" />'));
      form.onsubmit = imce.eUploadIframeSubmit;
    }
    return form;
  };

  /**
   * Submit event for upload form with the upload queue.
   */
  imce.eUploadQueueSubmit = function (event) {
    imce.activeUq.start();
    return false;
  };

  /**
   * Submit event for upload form with iframe.
   */
  imce.eUploadIframeSubmit = function (event) {
    if (!imce.validateUploadForm(this)) {
      return false;
    }
    imce.createUploadIframe();
    this.elements.active_path.value = imce.activeFolder.getPath();
    imce.uploadSetBusy(true);
  };

  /**
   * Validates upload form before submit.
   */
  imce.validateUploadForm = function (form) {
    var i;
    var file;
    var input = form.elements['files[imce][]'];
    var files = input.files;
    // HTML5
    if (files) {
      if (!files.length) {
        return false;
      }
      for (i = 0; file = files[i]; i++) {
        if (!imce.validateFileUpload(file)) {
          return false;
        }
      }
      return true;
    }
    // Old file input
    if (input.value) {
      file = {name: input.value.split(input.value.indexOf('/') === -1 ? '\\' : '/').pop()};
      return imce.validateFileUpload(file);
    }
    return false;
  };

  /**
   * Validates a file before uploading.
   */
  imce.validateFileUpload = function (file) {
    // Extension
    var exts = imce.getConf('extensions', '');
    if (exts !== '*' && !imce.validateExtension(imce.getExt(file.name), exts)) {
      return false;
    }
    // Size
    var maxsize = imce.getConf('maxsize');
    if (maxsize && file.size && file.size > maxsize) {
      imce.setMessage(Drupal.t('%filename is %filesize exceeding the maximum file size of %maxsize.', {
        '%filename': file.name,
        '%filesize': imce.formatSize(file.size),
        '%maxsize': imce.formatSize(maxsize)
      }));
      return false;
    }
    // Name
    if (!imce.validateFileName(file.name)) {
      return false;
    }
    // Trigger validators.
    return $.inArray(false, imce.trigger('validateFileUpload', file)) === -1;
  };

  /**
   * Creates upload iframe.
   */
  imce.createUploadIframe = function () {
    var el = imce.uploadIframe;
    if (!el) {
      el = imce.uploadIframe = imce.createEl('<iframe name="imce_upload_iframe" class="imce-upload-iframe" style="position: absolute; top: -9999px; left: -9999px;" src="javascript: "></iframe>');
      document.body.appendChild(el);
      setTimeout(function () {
        el.onload = imce.eUploadIframeLoad;
      });
    }
    return el;
  };

  /**
   * Load event of upload iframe.
   */
  imce.eUploadIframeLoad = function (event) {
    var text;
    var response;
    var doc;
    var $body;
    var el = this;
    try {
      doc = el.contentDocument || el.contentWindow && el.contentWindow.document;
      if (doc) {
        $body = $(doc.body);
        if (text = $body.find('textarea').eq(0).val()) {
          response = $.parseJSON(text);
        }
        $body.empty();
      }
    }
    catch (err) {
      imce.delayError(err);
    }
    imce.uploadIframeComplete(response, text);
  };

  /**
   * Complete handler of iframe upload;
   */
  imce.uploadIframeComplete = function (response, text) {
    // Got a proper response
    if (response) {
      imce.ajaxProcessResponse(response);
      if (response.added) {
        imce.uploadResetInput(imce.uploadForm.elements['files[imce][]']);
        imce.getTbb('upload').closePopup();
      }
    }
    // Failed
    else {
      imce.setMessage(Drupal.t('Invalid response received from the server.'));
      if (text) {
        imce.setMessage('<pre>' + Drupal.checkPlain(text) + '</pre>');
      }
    }
    imce.uploadSetBusy(false);
  };

  /**
   * Set upload busy state.
   */
  imce.uploadSetBusy = function (state) {
    $('.imce-upload-button', imce.uploadForm).toggleClass('busy', state)[0].disabled = state;
  };

  /**
   * Check support for ajax upload.
   */
  imce.canAjaxUpload = function () {
    var support = imce.ajaxUploadSupport;
    if (support == null) {
      try {
        support = !!(window.FormData && (new XMLHttpRequest().upload));
      }
      catch (err) {
        support = false;
      }
      imce.ajaxUploadSupport = support;
    }
    return support;
  };

  /**
   * Resets a file input.
   */
  imce.uploadResetInput = function (input) {
    // Try value reset first
    if ($(input).val('').val()) {
      // Use form reset
      var form = document.createElement('form');
      var parent = input.parentNode;
      form.style.display = 'none';
      parent.insertBefore(form, input);
      form.appendChild(input);
      form.reset();
      parent.insertBefore(input, form);
      parent.removeChild(form);
    }
  };

})(jQuery, Drupal, imce);
