//	Javascript class developped by Michaël Villar
//	http://www.nemstudio.com/
//	Require script.aculo.us library
//	Cette création est mise à disposition selon le Contrat Paternité-Partage des Conditions Initiales 
//	à l'Identique 2.0 Belgique disponible en ligne http://creativecommons.org/licenses/by-sa/2.0/be/ 
//	ou par courrier postal à Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
TextModifier = Class.create();
TextModifier.prototype = {
	input : Object,
	options : "",
	original : "",
	timeout : "",
	
	initialize: function(input) {
		this.options = Object.extend({
			type: "text",
			onChanged: "",
			size: "50",
			cols: "50",
			rows: "10",
			style: "",
			empty: true}, arguments[1] || {});
		this.input = $(input);
		this.input.ref = this;
		this.makeClickable();
		window["TextModifier"+input] = this;
	},
	
	makeClickable: function() {
		this.input.onclick = function() {
			this.ref.click();
		}	
	},
	
	click: function() {
		tmp = this.input.innerHTML;
		tmp = tmp.replace(/"/g,"&quot;");
		this.input.onclick = "";
		this.original = tmp;
		
		if (this.options.type == "text") {
			this.input.innerHTML = '<input style="'+this.options.style+'" id="'+this.input.id+'input'+'" type="text" value="'+tmp+'" size="'+this.options.size+'" />';
		}
		else if (this.options.type == "textarea") {
			tmp = tmp.replace(/\n/g,"");
			tmp = tmp.replace(/<BR>/g,"\n");
			this.input.innerHTML = '<textarea style="'+this.options.style+'" id="'+this.input.id+'input'+'" cols="'+this.options.cols+'" rows="'+this.options.rows+'">'+tmp+'</textarea>';
		}
		
		nInput = $(this.input.id+"input");
		nInput.ref = this;
		if (this.options.type != "textarea") {
			nInput.onkeyup = function(event) {
				code = event.keyCode;
				if (code == 13) {
					nInput.onblur = "";
					this.ref.valid();
				}
			}
		}
		nInput.onblur = function() {
			this.ref.blured();
		}
		nInput.focus();
		nInput.select();
	},
	
	blured: function() {
		// To prevent safari bug
		clearTimeout(this.timeout);
		this.timeout = setTimeout('TextModifier'+this.input.id+'.valid();',10);
	},
	
	valid: function() {
		nInput = $(this.input.id+"input");
		name = nInput.value;
		if ((name == '' && !this.options.empty) || name == this.original) {
			this.input.innerHTML = this.original;
			this.makeClickable();
		}
		else {
			name = name.escapeHTML();
			if (this.options.type == "textarea") {
				name = name.replace(/\n/g,"<BR>");
			}
			if (this.options.onChanged != "")
				this.options.onChanged(name);
			this.input.innerHTML = name;
			this.makeClickable();
		}
	}
}
