/*
 * InPlaceEditor extension that adds a 'click to edit' text when the field is 
 * empty.
 * http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
 */
Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlaceEditor.prototype.__getText = Ajax.InPlaceEditor.prototype.getText;
Ajax.InPlaceEditor.prototype.__leaveEditMode = Ajax.InPlaceEditor.prototype.leaveEditMode;
Ajax.InPlaceEditor.prototype.__createEditField = Ajax.InPlaceEditor.prototype.createEditField;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {

    initialize: function(element, url, options){
        this.__initialize(element,url,options)
        this.setOptions(options);
        this._checkEmpty();
    },

    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            refresh: 'false',
            emptyText: 'click to edit...',
            emptyClassName: 'inplaceeditor-empty'
        }),options||{});
    },

    _checkRefresh: function(){	
  if (this.options.refresh == 'true')
	  while(this.element.firstChild) this.element.removeChild(this.element.firstChild);
    },
    _checkEmpty: function(){
        if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
        }
    },

    getText: function(){
	 $$('.' + this.options.emptyClassName,'#' + this.element.id).each(function(child){ 
	        if (this.element.id == child.parentNode.id) {this.element.removeChild(child);}
        }.bind(this));
        return this.__getText();
    },

    leaveEditMode: function(transport){
        this._checkRefresh();
        this._checkEmpty();
        this.__leaveEditMode(transport);
    },
    createEditField: function(){
        this.__createEditField();
	f= $(this.options.formId);
	var maxLength = this.options.maxLength || 0;
	if (maxLength != 0)  {
		node = this._form.childNodes[0];
		node.setAttribute('maxLength',maxLength);
		if (node.tagName == 'TEXTAREA') {
		   	Event.observe(node,'keyup',function(event) {
			var obj = Event.element(event);
			// thanks to http://www.dynamicdrive.com/dynamicindex16/maxlength.htm	
			var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxLength")) : ""
			if (obj.getAttribute && obj.value.length>mlength)
				obj.value=obj.value.substring(0,mlength)
			});			
		}
         }
     }
});