/**
 * Outline view
 *
 * @require App.Wireframe.Events
 */
(function($) {

  /**
   * Public methods
   *
   * @var Object
   */
  var public_methods = {

    /**
     * Initialise context popup
     *
     * @param Object options
     *      subobjects_urls
     *      initial_object
     * @returns jQuery
     */
    init : function(options) {
      return this.each(function () {
        var wrapper = $(this);

        wrapper.addClass('basic_upload');

        // initial settings
        this.sab_data = { 'settings' : jQuery.extend({}, settings, options), 'items' : {} };

        this.sab_data.form = wrapper.parents('form:first');

        // wrapper for controls
        this.sab_data.hidden_wrapper = wrapper.find('div.upload_button');

        // select attachments table
        this.sab_data.attachments_table = wrapper.find('table.select_attachments_list');

        // control
        this.sab_data.control =$('<input type="file" name="attachment">').appendTo($('<div class="uploading_control"></div>').appendTo(this.sab_data.hidden_wrapper)).css({
          'opacity' : 0
        });

        // button
        this.sab_data.button = this.sab_data.hidden_wrapper.find('a.link_button').click(function () {
          wrapper.get(0).sab_data.control.click();
        });

        // what happens when user chooses file
        this.sab_data.control.change(function () {
          upload_file.apply(wrapper.get(0), [$(this)]);
        });

        // what happens when user clicks delete
        init_deleting_attachments.apply(this);

        // initial attachments
        add_initial_attachments.apply(this);
      });
    },

    /**
     * reset the control
     *
     * @param Object milestone
     */
    reset : function () {
      return this.each(function () {
        reset.apply(this);
      });
    }
  };

  /**
   * Upload file
   *
   * @param jquery control
   */
  var upload_file = function (control) {
    var wrapper = $(this);
    var parent_form = wrapper.parents('form:first');

    var filename = ('' + control.val()).replace(/^.*[\\\/]/, '');
    var row = insert_attachment_row.apply(this, [filename, null]);

    parent_form.ajaxSubmit({
      'url'       : this.sab_data.settings.upload_url,
      'data'      : { 'submitted' : 'submitted' },
      'dataType'  : 'json',
      'success'   : function (response) {
        finalize_attachment_row.apply(wrapper.get(0), [row, response['id']]);
      },
      'error'     : function (response) {
        finalize_attachment_row.apply(wrapper.get(0), [row]);
        App.Wireframe.Events.trigger('async_operation_error', [ App.Wireframe.Utils.responseToErrorMessage(response), response ]);
      }
    });

    control.val('');

  }; // upload_file

  /**
   * Inserts the attachment row in table
   *
   * @param String attachment_filename
   * @param Number attachment_id
   */
  var insert_attachment_row = function (attachment_filename, attachment_id) {
    var extension;
    var extension_icon;
    var dot_index = attachment_filename.lastIndexOf('.');

    if (dot_index >= 0) {
      extension = attachment_filename.split('.').pop().toLowerCase();
      extension_icon = App.Wireframe.Utils.imageUrl('/file-types/16x16/' + extension + '.png', 'environment');
    } else {
      extension_icon = App.Wireframe.Utils.imageUrl('/file-types/16x16/default.png', 'environment');
    } // if

    var current_icon = extension_icon;
    if (!attachment_id) {
      current_icon = App.Wireframe.Utils.indicatorUrl();
    } // if

    var row = $('<tr real_attachment_id="' + (attachment_id ? attachment_id : '') + '" real_icon="' + extension_icon + '" class="' + (attachment_id ? attachment_id : 'uploading') + '">' +
      '<td class="fileicon">' +
        '<img src="' + current_icon + '">' +
      '</td>' +
      '<td class="filename">' +
        '<div title="' + App.clean(attachment_filename) + '">' + App.excerpt(App.clean(attachment_filename), 20) + '</div>' +
        '<input type="hidden" name="' + this.sab_data.settings.name + '" value="' + (attachment_id ? attachment_id : '') + '">' +
      '</td>' +
      '<td class="delete_attachment">' +
        '<a href="#">Remove</a>' +
      '</td>' +
    '</tr>').appendTo(this.sab_data.attachments_table);

    if (!attachment_id) {
      this.sab_data.form.addClass('uploading');
    } // if

    return row;
  }; // insert_attachment_row


  /**
   * Finalize uploading
   *
   * @param jQuery row
   * @param Number attachment_id
   */
  var finalize_attachment_row = function (row, attachment_id) {
    if (attachment_id) {
      row.find('td.fileicon img').attr('src', row.attr('real_icon'));
      row.find('td.filename input[type="hidden"]').attr('value', attachment_id);
      row.removeClass('uploading')
    } else {
      row.remove();
    } // if

    if (!this.sab_data.attachments_table.find('tr.uploading').length) {
      this.sab_data.form.removeClass('uploading');
    } // if
  }; // finalize_attachment

  /**
   * Initialize deleting attachments
   */
  var init_deleting_attachments = function () {
    var wrapper = $(this);

    this.sab_data.attachments_table.delegate('td.delete_attachment a', 'click', function () {
      var anchor = $(this);
      var row = anchor.parents('tr:first');
      var attachment_id = row.find('td.filename input[type="hidden"]').val();

      if (attachment_id) {
        wrapper.append('<input type="hidden" name="' + wrapper.get(0).sab_data.settings.delete_name + '" value="' + attachment_id + '" class="attachment_pending_deletion" />');
      } // if

      row.remove();

      if (!wrapper.get(0).sab_data.attachments_table.find('tr.uploading').length) {
        wrapper.get(0).sab_data.form.removeClass('uploading');
      } // if
    });
  }; // init_deleting_attachments

  /**
   * Add initial attachments to the list
   */
  var add_initial_attachments = function () {
    var wrapper = $(this);

    if (!this.sab_data.settings.existing_attachments) {
      return false;
    } // if

    $.each(this.sab_data.settings.existing_attachments, function (index, attachment) {
      insert_attachment_row.apply(wrapper.get(0), [attachment['filename'], attachment['id']]);
    });
  }; // add_initial_attachments

  /**
   * Reset widget to initial state
   */
  var reset = function () {
    this.sab_data.attachments_table.empty();
    $(this).find('.attachment_pending_deletion').remove();
  }; // reset

  ////////////////////////////////////////////////////////// PLUGIN INITIAL DATA ///////////////////////////////////////////////////////////

  /**
   * Plugin name
   *
   * @var String
   */
  var plugin_name = 'selectAttachmentsBasic';

  /**
   * Initial diagram settings
   *
   * @var Object
   */
  var settings = {

  }; // settings

  ///////////////////////////////////////////////////////// PLUGIN FRAMEWORK STUFF /////////////////////////////////////////////////////////
  /**
   * Register jQuery plugin and handle public methods
   *
   * @param mixed method
   * @return null
   */
  $.fn[plugin_name] = function(method) {
    if (public_methods[method]) {
      return public_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
      return public_methods.init.apply(this, arguments);
    } else {
      $.error('Method ' +  method + ' does not exist in jQuery.' + plugin_name);
    } // if
  };

})(jQuery);