/**
* LabelInput uses the title attribute of a label element to show 
* guiding or hint text into a text input through the label's title attribute.
* e.g. <label id="lblDOB" for="txtDOB" title="mm/dd/yyyy"/>
* Usage examples:
* $('lblDOB').labelInput();
* $('lblDOB').labelInput({hintText: 'first, last', hintClassName: 'myclass'});
* $$('label').invoke('labelInput');
* 
**/
var LabelInput = Class.create({
	forms: [], // references to containing forms
	initialize: function(elLabel, options){
		var elTxtInput = $(elLabel.readAttribute('for'));
		if(!Object.isElement(elTxtInput)){return;}
		this.options = Object.extend({
			hintClassName: 'hint', 						// class to apply to input when it's using the text set.
			hintText: elLabel.readAttribute('title')	// get the text from the options, or the label's title attribute
		}, options || {});
	
		// add the text to text input as an expando property.
		elTxtInput._hintText = this.options.hintText;
		
		elTxtInput.observe('focus', this.__txtInputFocus.bindAsEventListener(this));
		elTxtInput.observe('blur', this.__txtInputBlur.bindAsEventListener(this));
		
		//set the initial hint text, and adjust className
		if(elTxtInput.value == ''){
			elTxtInput.value = elTxtInput._hintText;
		}
		if(elTxtInput.value == elTxtInput._hintText){
			elTxtInput.addClassName(this.options.hintClassName);
		} else{
			elTxtInput.removeClassName(this.options.hintClassName);
		}
		
		// clear out label text on form submit
		var elForm = elLabel.up('form');
		if(elForm && !this.forms.member(elForm)){
			elForm.observe('submit', this.__frmSubmit.bindAsEventListener(this));
			this.forms.push(elForm);
		}
	},
	
	// sets the label text
	__txtInputBlur: function(e){
		var elTxtInput = e.element();
		if (elTxtInput.value == '' && elTxtInput._hintText) {
			// add label text
			elTxtInput.value = elTxtInput._hintText;
			elTxtInput.addClassName(this.options.hintClassName);
		}
		else{
			elTxtInput.removeClassName(this.options.hintClassName);
		}
	},
	
	// removes the label text
	__txtInputFocus: function(e){
		var elTxtInput = e.element();
		if (elTxtInput.value == elTxtInput._hintText) {
			elTxtInput.value = '';
			elTxtInput.removeClassName(this.options.hintClassName);
		}
	},
	
	// makes sure text input values are not set to the label text upon form submission
	__frmSubmit: function(e){
		e.element().getElements().each(function(txtInput){
			if(txtInput._hintText && (txtInput.value == txtInput._hintText)){
				txtInput.clear();
			}
		});
	}
});

// Extend the LABEL tag with LabelInput
Element.addMethods('LABEL', {
	labelInput: function(element, options) {
		new LabelInput(element, options);
		return element;
	}
});

