// $Id$

/**
 * @file
 * Provides JavaScript additions to the managed file field type.
 *
 * This file provides progress bar support (if available), popup windows for
 * file previews, and disabling of other file fields during AJAX uploads (which
 * prevents separate file fields from accidentally uploading files).
 */

(function($) {

/**
 * Attach behaviors to managed file element upload fields.
 */
Drupal.behaviors.fileValidateAutoAttach = {
  attach: function(context) {
    $('div.form-managed-file input.form-file[accept]', context).bind('change', Drupal.file.validateExtension);
  },
  detach: function(context) {
    $('div.form-managed-file input.form-file[accept]', context).unbind('change', Drupal.file.validateExtension);
  }
};

/**
 * Attach behaviors to the file upload and remove buttons.
 */
Drupal.behaviors.fileButtons = {
  attach: function(context) {
    $('input.form-submit', context).bind('mousedown', Drupal.file.disableFields);
    $('div.form-managed-file input.form-submit', context).bind('mousedown', Drupal.file.progressBar);
  },
  unattach: function(context) {
    $('input.form-submit', context).unbind('mousedown', Drupal.file.disableFields);
    $('div.form-managed-file input.form-submit', context).unbind('mousedown', Drupal.file.progressBar);
  }
};

/**
 * Attach behaviors to links within managed file elements.
 */
Drupal.behaviors.filePreviewLinks = {
  attach: function(context) {
    $('div.form-managed-file .file a, .file-widget .file a', context).bind('click',Drupal.file.openInNewWindow);
  },
  detach: function(context){
    $('div.form-managed-file .file a, .file-widget .file a', context).unbind('click', Drupal.file.openInNewWindow);
  }
};

/**
 * File upload utility functions.
 */
Drupal.file = Drupal.file || {
  /**
   * Client-side file input validation based on the HTML "accept" attribute.
   */
  validateExtension: function(event) {
    // Remove any previous errors.
    $('.file-upload-js-error').remove();

    // Add client side validation for the input[type=file] accept attribute.
    var accept = this.accept.replace(/,\s*/g, '|');
    if (accept.length > 1 && this.value.length > 0) {
      var acceptableMatch = new RegExp('\\.(' + accept + ')$', 'gi');
      if (!acceptableMatch.test(this.value)) {
        var error = Drupal.t("The selected file %filename cannot not be uploaded. Only files with the following extensions are allowed: %extensions.", {
          '%filename': this.value,
          '%extensions': accept.replace(/\|/g, ', ')
        });
        $(this).parents('div.form-managed-file').prepend('<div class="messages error file-upload-js-error">' + error + '</div>');
        this.value = '';
        return false;
      }
    }
  },
  /**
   * Prevent file uploads when using buttons not intended to upload.
   */
  disableFields: function(event){
    var clickedButton = this;

    // Only disable upload fields for AJAX buttons.
    if (!$(clickedButton).hasClass('ajax-processed')) {
      return;
    }

    // Check if we're working with an "Upload" button.
    var $enabledFields = [];
    if ($(this).parents('div.form-managed-file').size() > 0) {
      $enabledFields = $(this).parents('div.form-managed-file').find('input.form-file');
    }

    var $disabledFields = $('div.form-managed-file input.form-file').not($enabledFields);

    // Disable upload fields other than the one we're currently working with.
    $disabledFields.attr('disabled', 'disabled');

    // All the other mousedown handlers (like Drupal's AJAX behaviors) are
    // excuted before any timeout functions will be called, so this effectively
    // re-enables the file fields after other processing is complete even though
    // it is only a 1 second timeout.
    setTimeout(function(){
      $disabledFields.attr('disabled', '');
    }, 1000);
  },
  /**
   * Add progress bar support if possible.
   */
  progressBar: function(event) {
    var clickedButton = this;
    var $progressId = $(clickedButton).parents('div.form-managed-file').find('input.file-progress');
    if ($progressId.size()) {
      var originalName = $progressId.attr('name');

      // Replace the name with the required identifier.
      $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]);

      // Restore the original name after the upload begins.
      setTimeout(function() {
        $progressId.attr('name', originalName);
      }, 1000);
    }
    // Show the progress bar if the upload takes longer than half a second.
    setTimeout(function() {
      $(clickedButton).parents('div.form-managed-file').find('div.ajax-progress-bar').slideDown();
    }, 500);
  },
  /**
   * Open links to files within forms in a new window.
   */
  openInNewWindow: function(event) {
    $(this).attr('target', '_blank');
    window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550');
    return false;
  }
};

})(jQuery);