Package.create("ubilabs.form.element");

ubilabs.form.element.Hint = Class.create({
	hint: null,
	className: "hint",
	initialize: function(field, hint){
		this.hint = hint;
		this.field = field;
		this.field.getValue = function(){
			return this.field.value == this.hint ? null : this.field.value;
		}.bind(this);
		this.field.observe("focus", this.enter.bind(this));
		this.field.observe("blur", this.leave.bind(this));
		Event.observe(window, "unload", this.leave.bind(this));
		if (field.hasClassName("empty")){
			field.value = "";	
		}
		this.leave();
	},
	
	enter: function(){
		if (this.field.hasClassName(this.className)){
			this.field.removeClassName(this.className);
			this.field.value = "";
		}		
	},
	
	leave: function(){
		if (!this.field.getValue()){
			this.field.addClassName(this.className);
			this.field.value = this.hint;
		}	
	}
});

document.observe("dom:loaded", function(){
	$$("form").each(function(form){
		form.getElementsBySelector("label.hint").each(function(hint){
			new ubilabs.form.element.Hint($(hint.readAttribute("for")), hint.innerHTML);
		});
	});
});