var editors = Array();

Ajax.ContentEditor = Class.create();
Ajax.ContentEditor.defaultHighlightColor = "#FFFF99";
Ajax.ContentEditor.prototype = {
  initialize: function(element, options) {
    this.element = $(element);

    this.options = Object.extend({
      savingText: "Saving...",
      clickToEditText: "Double click to edit",
      rows: 20,
      cols: 50,
      size: 20,
      /*onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },*/
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      edittype: "textarea",
      handleLineBreaks: false,
      loadingText: 'Loading...',
      hoverClassName: 'frontendedithover',
      editFieldTextareaClassName: 'frontendedittextarea',
      editFieldTextClassName: 'frontendedittext',
      savingClassName: 'frontendedit-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'frontendeditform',
      highlightcolor: Ajax.ContentEditor.defaultHighlightColor,
      highlightendcolor: "#FFFFFF",
      externalControl:	null,
      submitOnBlur: false
    }, options || {});
	
    this.url = "global/ajax/fronteditsave.php";
   	this.oldInnerHTML = this.element.innerHTML;
   	this.dirty = false;
    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }
    
    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }
    
    this.element.title = this.options.clickToEditText;
    
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'dblclick', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    this.offsetWidth = this.element.offsetWidth;
    this.offsetHeight = this.element.offsetHeight;  
 
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    Field.scrollFreeActivate(this.editField);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
   
    this.createEditField();

    /*if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }*/
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  createEditField: function() {
    var text;
    
    text = this.element.innerHTML;
   
	 var obj = this;
    
    if (this.options.edittype == "text") {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = "value";
      textField.value = text;
      //textField.style.backgroundColor = this.options.highlightcolor;
      //var size = this.options.size || this.options.cols || 0;
      //if (size != 0) textField.size = size;
      //textField.setAttribute("width", this.offsetWidth);
      //textField.setAttribute("height", this.offsetHeight);
      this.editField = textField;
      Element.addClassName(this.editField, this.options.editFieldTextClassName)
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = "value";
      textArea.value = text;
      
   //   textArea.rows = this.options.rows;
     // textArea.cols = this.options.cols;
      	this.editField = textArea;
      	Element.addClassName(this.editField, this.options.editFieldTextareaClassName)
    }
    this.editField.style.width = this.offsetWidth + "px";
    this.editField.style.height = this.offsetHeight + "px";
    this.editField.style.scrollWidth = this.offsetWidth + "px";
    this.editField.style.scrollHeight = this.offsetHeight + "px";
    	
    if(this.element.currentStyle) {
      	var style = this.element.currentStyle;
    } else {
     	var style = document.defaultView.getComputedStyle(this.element, "");
    }
	
    this.editField.style.fontSize = style.fontSize;
    this.editField.style.fontFamily = style.fontFamily;
    
   	Event.observe(this.editField, "blur", this.onBlur.bindAsEventListener(this));
	Event.observe(this.editField, "keypress", this.onEditKeyPress.bindAsEventListener(this));
    this.form.appendChild(this.editField);
  }, 
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onEditKeyPress: function(event) {
  	if(event.keyCode==27){
		return this.onBlur(event);	
	}	
  },
  onBlur: function(event) {
  	this.element.innerHTML = this.editField.value;
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  saveContent: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    if(this.dirty) {
    	//console.log("This is a dirty thing!!!", this.oldInnerHTML);
    var form = this.form;
    var value = this.element.innerHTML;
    
    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();
    
    new Ajax.Updater(
      { 
        success: this.element,
         // don't update on failure (this could be an option)
        failure: null
      },
      this.url,
      Object.extend({
      	method: "post",
        parameters: "varname=" + this.element.id + "&value=" + escape(value),
        onComplete: this.onComplete.bind(this),
        onFailure: this.onFailure.bind(this)
      }, this.options.ajaxOptions)
    );
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
    }
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    offsetWidth = this.element.offsetWidth;
    offsetHeight = this.element.offsetHeight; 
    this.element.innerHTML = this.options.savingText;
    offsetHeightAfter = this.element.offsetHeight;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.width = offsetWidth + "px";
   	this.element.style.height = offsetHeight + "px";
    //this.element.style.scrollWidth = offsetWidth + "px";
    //this.element.style.scrollHeight = offsetHeight + "px";
    
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    if(!this.dirty) {
    	//this.element.style.backgroundColor = this.options.highlightcolor;
    	//this.element.style.border = "1px solid #000000";
    	   this.effect = new Effect.Opacity(this.element, {
   				duration: 0.5,
    			from: 1,
   				to: 0
   			});
   			this.effect = new Effect.Opacity(this.element, {
   				duration: 0.5,
    			from: 0,
   				to: 1
   			});
    }
    /*if (this.effect) {
      this.effect.cancel();
    }*/
 
    //Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
  	if(!this.dirty) {
    	//if (this.options.backgroundColor) {
      		//this.element.style.backgroundColor = this.oldBackground;
      		//this.element.style.border = "0px solid #000000";
    	//}
    	/*this.effect = new Effect.Opacity(this.element, {
   				duration: 0.1,
    			from: 0.5,
   				to: 1.0
   			});*/
    	//Element.removeClassName(this.element, this.options.hoverClassName)
    	if (this.saving) return;
    	/*this.effect = new Effect.Highlight(this.element, {
      		startcolor: this.options.highlightcolor,
      		endcolor: this.options.highlightendcolor,
      		restorecolor: this.originalBackground
    	});*/
  	} 
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
     if(this.element.innerHTML != this.oldInnerHTML) {
     	//this.element.style.backgroundColor = "#d3d3d3";
     	this.effect = new Effect.Fade(this.element, {
   			from: 0.5,
   			to: 0.5
   		});
    	this.dirty = true;
    	showFrontEndEditPanel();
    	//this.effect.cancel();
    } else {
    	this.effect = new Effect.Fade(this.element, {
   			from: 0.5,
   			to: 1.0
   		});
   		this.dirty = false;
   		//this.element.style.backgroundColor = this.originalBackground;
   	}
    Element.show(this.element);
   
    this.editing = false;
    this.saving = false;
    
    this.onLeaveEditMode();
  },
 revert: function() {
  	this.element.innerHTML = this.oldInnerHTML;
  	//this.element.style.backgroundColor = this.originalBackground;
  	if(this.dirty) {
  		this.effect = new Effect.Fade(this.element, {
   				from: 0.5,
   				to: 1.0
   			});
  		this.dirty = false;
  	}
  },
  onComplete: function(transport) {
  	//console.log("New html: ", this.element.innerHTML);
  	this.dirty = false;
  	this.oldInnerHTML = this.element.innerHTML;
    this.leaveEditMode();
    //this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};