/*
 * InPlaceEditor extension that adds a 'click to edit' text when the field is 
 * empty.
 */

Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlaceEditor.prototype.__getText = Ajax.InPlaceEditor.prototype.getText;
Ajax.InPlaceEditor.prototype.__onComplete = Ajax.InPlaceEditor.prototype.onComplete;
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,{
            emptyText:  this.options.mesajCampGol,
            emptyClassName: 'inplaceeditor-empty',
            onEnterEditMode: function(form, value) { toggleKeys(1); },
			onLeaveEditMode: function(form, value) { toggleKeys(0); }
        }),options||{});
    },

    _checkEmpty: function(){
		//alert(this.element.innerHTML.length);
    	if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
             
        }
        else {
        	//remove html
        	//this.element.innerHTML = this.element.innerHTML.replace(/<\/?[^>]+(>|$)/g, "");
        	//add <br>
        	this.element.innerHTML = this.element.innerHTML.replace(/([^>])\n/g, '$1<br/>');
        }
        
    },

    getText: function(){
		
        //alert(this.element.innerHTML);
        
        var arr = this.element.select('span');
        
        //se fute in safari 3.1
     	//var arr = document.getElementsByClassName(this.element,this.options.emptyClassName);
     	//alert(arr);
     	for(i=0;i<arr.length;i++)
     	{
     		var spanEl = arr[i];
     		spanEl.remove();
     	}
        
        //cand se deschide textarea sa inlocuiasca <br> cu /n ca sa nu-l deruteze pe utilizator
        this.element.innerHTML = this.element.innerHTML.replace(/([^>])<br>/g, '$1\n');
        
        if(this.options.textDeEditat.length>0) this.element.innerHTML = this.options.textDeEditat;
        return this.__getText();
    },

    onComplete: function(transport){
    	alert(transport);
        this._checkEmpty();
        this.__onComplete(transport);
    }
});