/**
 * Magic Label
 * 
 * Usage:
 *	1) input fields should have class 'magiclabel'
 *	2) labels should have the id of the associated input field + "-label"
 *	   e.g.:
 *	     <label for='zip-code' id='zip-code-label'>Zip</label>
 *	     <input type='text' name='zip_code' class='magiclabel' id='zip-code'>
 *	
 *	General notes:
 *		-Use css's "position: absolute;" to place your labels atop their related form field
 *		-For your ease, labels should be next to their related input fields in the markup
 *		-Behaviour and Prototype are used.
 * 
 * @author Justin Johnson <justin@booleangate.org>
 * @version 0.0.5a Alpha+1 20070615
 * 
 * @requires Behaviour <http://www.bennolan.com/behaviour/>
 */

 
// So we don't have to have Prototype
if ( typeof $ != "function" ) {
 	$ = function(id) { return document.getElementById(id); }
}

var magiclabel = {
	'init': function() {
		magiclabel.init_type('input');
		magiclabel.init_type('select');
	},
	
	'init_type': function(tag_type) {
		var elements = document.getElementsByTagName(tag_type);

		for ( index in elements ) {
			el = elements[index];

			if ( el.className && el.value &&
				 el.className.indexOf('magiclabel') != -1 && 
				 el.value.length != 0
			) {
				magiclabel.hide(el.id);
			}
		}
	},

	'behaviours': {
		'.magiclabel' : function(element) {
			element.onfocus = function(event) {
				magiclabel.hide(this.id);
				this.className = this.className.replace(/unfocused/g, '') + " focused";
			}
		
			element.onblur = function() {
				if ( this.value.replace(/^(\s)*/, '').replace(/(\s)*$/, '').length == 0 ) {
					magiclabel.show(this.id);
					this.className = this.className.replace(/focused/g, '') + " unfocused";
				}
			}
		}
	},

	'show': function(id) {
		el = (typeof id == "string") ? $(id + "-label") : id;
		if ( el ) {
			el.style.visibility = 'visible';
		}
	},

	'hide': function(id) {
		el = (typeof id == "string") ? $(id + "-label") : id;
		if ( el ) {
			el.style.visibility = 'hidden';
		}
	}
};


Behaviour.register(magiclabel.behaviours);
Behaviour.addLoadEvent(magiclabel.init);
