// Inline image uploader

AttachImage = Class.create();
AttachImage.uploading = false;

AttachImage.prototype = {
  embed_template: '<a href="#{full_image_url}"><img src="#{image_url}" alt="" /></a>',
  
  initialize: function(link, upload) {
    this._async_request = null;
    this.upload = upload;
    this.link = $(link);
    this.form = this.link.up('form');
    this.textarea = this.form.down('.plain_text').down('.text');
    if(upload) {
      this.file_field = this.form['image[uploaded_data]'];
      if(this.file_field.value == "") {
        alert('Please choose an image to upload.');
      } else {
        this.uploadImage();        
      }
    } else {
      this.url_field = this.form['url'];
      if($F(this.url_field) == "" || $F(this.url_field) == "http://") {
        alert('Please insert an image URL.');
      } else {
        this.attachImage({image_url:$F(this.url_field), full_image_url:$F(this.url_field)});
        this.url_field.value = "http://"; 
      }
    }
  },
  
  uploadImage: function() {
    this.showStatus('uploading');
    this.uploading = true;
    this.saveFormAttributes();
    YAHOO.util.Connect.setForm(this.form, true);
    this._async_request = YAHOO.util.Connect.asyncRequest('PUT', '/inline_images/create', {
      upload: function(o) {
        try {
          var response = o.responseText.stripTags();
          try {
            var retval = eval('(' + response + ')');
            if (retval.image_url && retval.full_image_url) {
              this.onImageSuccess(retval);
              return;
            }
          } catch (ex) {
            this.onImageError(ex.toString());
          }
          this.onImageError(response);
        } catch (e) {
          this.onImageError(e.toString());
        } 
      }.bind(this)
    });
    
    // Activate cancel upload link
    var cancel_link = this.getCancelUploadLink();
    cancel_link.show();
    cancel_link.onclick = this.abortUpload.bind(this);
  },
  
  attachImage: function(params) {
    var img = new Template(this.embed_template).evaluate(params);
    
    this.textarea.focus();
    if(document.selection) {
      var range = this.textarea.createTextRange()       
      range.text += img;
      range.scrollIntoView();
      
  	} else if (this.textarea.selectionStart || this.textarea.selectionStart == '0') {
      var startSelection = this.textarea.selectionStart;
      var endSelection = this.textarea.selectionEnd;
      this.textarea.value = this.textarea.value.substring(0, startSelection) + img + this.textarea.value.substring(endSelection, this.textarea.value.length)
  	} 
    this.showStatus('success');
  },
  
  showStatus: function(status, optional_message) {
    el = this.form.down('.status').show();
    el.select('div').invoke('hide');
    if(status) {  
      el.down('.'+status).show();
      if(status == 'success') {
        new Effect.Highlight(el, {endcolor:'#DFDFDF', duration: 1.3});
        el.down('.'+status).down('a').onclick = function() {
          this.form.down('.pt_attach_image').hide();
          this.form.down('.pt_tab').removeClassName('on');
          this.hideStatus();
          return false;
        }.bind(this);
      }
      if(status == 'fail' && optional_message) {
        el.down('.'+status).update(optional_message)
      }
    }
  },
  
  hideStatus: function() {
    this.form.down('.status').hide();
  },
  
  abortUpload: function() {
    YAHOO.util.Connect.abort(this._async_request, {failure: this.onImageAbort.bind(this)});
    return false;
  },
  
  onImageSuccess: function(params) {
    this.attachImage(params);
    this.resetForm();
  },
  
  onImageAbort: function() {
    this.resetForm();
  },
  
  onImageError: function(e) {
    this.sendErrorMessage(e)
    this.resetForm();
  },
  
  sendErrorMessage: function(e) {
    if(e != "") {
      this.showStatus('fail', e);
    }
  },
  
  saveFormAttributes: function() {
		this.stored_action = this.form.getAttribute('action');
		this.stored_method = this.form.getAttribute('method');
		this.stored_target = this.form.getAttribute('target');
		this.stored_enctype = this.form.getAttribute('enctype');
  },
  
  resetFormAttributes: function() {
    this.form.setAttribute('action', this.stored_action);
		this.form.setAttribute('method', this.stored_method);
		this.form.setAttribute('target', this.stored_target);
		this.form.setAttribute('enctype', this.stored_enctype);
  },
  
  resetForm: function() {
    this.resetFormAttributes();
    this.uploading = false;
    this.file_field.value = "";
    this.getCancelUploadLink().hide();
  },

  getCancelUploadLink: function() {
    return this.form.down('.cancel_upload');
  }
  
}