/*
For displaying labels inside the input field
load at the end of the layout or html.

Approach described in: http://www.alistapart.com/articles/makingcompactformsmoreaccessible
design pattern: http://ui-patterns.com/pattern/InputPrompt
prototype vers: http://blog.barros.ws/2008/07/30/overlabel-with-prototype/
*/

var OverLabel = Class.create({
	initialize: function(obj) {
		var field;
		// Skip labels that do not have a named association with another field.
		if(!obj.readAttribute('for') || !(field = $(obj.readAttribute('for')))){ return false; }

		//alert("initializing obj " + obj.identify());
		this.label = obj;
		this.field = field;
		// apply overlabel style and hide for non empty fields
		obj.className = 'overlabel-apply';
		obj.hide();

		// setup event handlers

		//field.onfocus = function () {	$(obj.identify()).hide(); }
		//field.observe('focus', function() {	$(obj.identify()).hide(); });
		field.observe('focus', this.hide.bindAsEventListener(this))

		//field.onblur = function () { if($(this).value === ''){	$(obj.identify()).show(); }	}
		//field.observe('blur', function() { if($(this).value === ''){ $(obj.identify()).show(); }});
		field.observe('blur', this.show.bindAsEventListener(this));

		// handle cliks to label element, safari fix
		//obj.onclick = function () { $($(this).readAttribute('for')).focus(); }
		//obj.onclick = function () { $(field.identify()).focus(); }
		obj.observe('click', function () { $(field.identify()).focus(); })

		if(field.value == ''){ this.show(); }
		return true;
	},

	show: function(){
		if(this.field.value === ''){ this.label.show(); }
		
		width = this.field.getWidth()-
			parseInt(this.label.getStyle('padding-left'))-parseInt(this.label.getStyle('padding-right'))-
			parseInt(this.label.getStyle('margin-left'))-parseInt(this.label.getStyle('margin-right'));
		height = this.field.getHeight()-
			parseInt(this.label.getStyle('padding-top'))-parseInt(this.label.getStyle('padding-bottom'))-
			parseInt(this.label.getStyle('margin-top'))-parseInt(this.label.getStyle('margin-bottom'));
		this.label.style.width = width+'px';
		this.label.style.height = height+'px';
		//this.label.style.left = this.field.positionedOffset()[0] + "px";
		// top positioning would case problems when there are more hidden or unhidden elements.
//		var offset = this.field.positionedOffset();
//		this.label.style.left = offset[0] + "px";

//		this.label.style.top = offset[1] + "px";
	},
	
	hide: function(){ this.label.hide(); }
});

// call this after page updates
function OverLabelInit(search_str){
	$$(search_str+'.overlabel').each(function(obj) {	new OverLabel(obj);	});
}

Event.observe(window,'load',function (){
	OverLabelInit('');
 });
