/**
 * inplace_preview.js
 * Version 1.0.1
 * Doug McInnes <doug.mcinnes@latimes.com>
 *
 * See README.txt for more info
 */

Object.extend(Ajax.InPlaceEditor.prototype, {
  oldCreateForm: Ajax.InPlaceEditor.prototype.createForm,
  createForm: function() {
    this.oldCreateForm();
    if (this.options.previewLink) {
      this.previewLink = document.createElement("a");
      this.previewLink.href = "#";
      this.previewLink.appendChild(document.createTextNode(this.options.previewText || "Preview"));
      this.previewLink.onclick = this.onclickPreview.bind(this);
      this.previewLink.className = 'editor_preview editor_preview_link';      
      new Insertion.Bottom(this.form, "&nbsp;");
      this.form.appendChild(this.previewLink);
      // create preview element
      this.preview = document.createElement(this.element.tagName);
      this.form.insertBefore(this.preview, this.editField);
      Element.hide(this.preview);
      this.preview.onclick = this.onclickPreview.bind(this);
    }
  },
  onclickPreview: function() {
    if (this.saving) return;
    if (Element.visible(this.preview)) {
      Element.hide(this.preview);
      Element.show(this.editField);
      Element.update(this.previewLink, this.options.previewText || "Preview");
    }
    else {
      Element.update(this.preview, this.options.previewLoadingText || "Preview Loading...");
      if (this.options.loadPreviewURL) {
        // make an Ajax call to render the content
        new Ajax.Updater(
          { success: this.preview,
            failure: null }, 
            this.options.loadPreviewURL, 
            Object.extend({
              parameters: this.options.callback(this.form, this.editField.value)
            }, this.options.ajaxOptions));
      }
      else {
        // or just stuff it in the preview field
        this.preview.update(this.editField.value);
      }
      Element.hide(this.editField);
      Element.show(this.preview);
      Element.update(this.previewLink, this.options.editText || "Edit");
    }
    return false;
  },
  onLeaveEditMode: function() {
    if (this.preview) {
      this.preview.remove();
      this.preview = null;
    }
  }
});

