/**
 * 
 * @param {JSON} args A JSON Object with named parameters.
 * @class
 * 
 * @author Martin 'Windgazer' Reurings
 * @requires Event (Prototype)
 */
function TextInputPrefill(args) {
	this.args = args;
	this.init(args);
}

TextInputPrefill.prototype = {
	pfRE:/\s?\bprefilled\b/gi,
	/**
	 * Check if an prefill is still filled in.
	 * 
	 * @return true if prefill is still in the input.
	 */
	hasPrefill:function(target) {
		this.pfRE.test("");
		return (target.className && this.pfRE.test(target.className));
	},
	/**
	 * Initialises the formfield and possibly siblings of it, to observe
	 * the proper events. Sets the prefill and prefilled status.
	 * 
	 * @constructor
	 */
	init:function (args) {
		var e = $(args.id);
		if (!e.value || (e.value == args.prefill)) { //Preserve prefills from backend / browser
			e.value = args.prefill;
			e.className += " prefilled";
			var self = this;
			Event.observe(e, 'focus', function(event){
				return self.unfill(args);
			});
		}
	},
	unfill:function(args) {
		var e = $(args.id);
		if (this.hasPrefill(e)) {
			e.value = "";
			e.className = e.className.replace(this.pfRE, "");
		}
		return false;
	}
}

/**
 * Add an initialiser method to the Tapestry Object tree, this allows associated Mixing classes to easily add new TextInputPrefills.
 */
if (Tapestry.Initializer && !Tapestry.Initializer.newTextInputPrefill) Tapestry.Initializer.newTextInputPrefill = function(args) {
	return new TextInputPrefill(args);
};
else alert("TextInputPrefill is already initialized on T5 or now T5 Initializer can be found (perhaps you're using an incompatible version of T5?)");

/**
 * In case of a desire to use css to set initial display values before the observers are set this will trigger the state after they
 * are finalised so that any css-based values can safely be disabled.
 * Can be used to initialy hide a target using css and after the observers are set disable the display:none value,
 * this would be nessecary in order for scriptaculous Effects to work properly.
 */
Event.observe(window,"load", function(event) {
	(document.documentElement||document.body).className += " TextInputPrefill_INITIALISED";
});
