/**
 * Form behaviours
 */
var autoPopulate = {
	sInputClass:'populate', // Class name for input elements to autopopulate
	sHiddenClass:'structural', // Class name that gets assigned to hidden label elements
	bHideLabels:true, // If true, labels are hidden
	/**
	* Main function
	*/
	init:function() {
		// Check for DOM support
		if (!document.getElementById || !document.createTextNode) {return;}
		// Find all input elements with the given className
		var arrInputs = $$('input.'+autoPopulate.sInputClass, 'textarea.'+autoPopulate.sInputClass);
    
		var iInputs = arrInputs.length;
		var oInput;
		for (var i=0; i<iInputs; i++) {
			oInput = arrInputs[i];
			// Make sure it's a text input
			//if (oInput.type != 'text') { continue; }
			// Hide the input's label
			if (autoPopulate.bHideLabels) { autoPopulate.hideLabel(oInput.id); }
			// If value is empty and title is not, assign title to value
			if((oInput.nodeName == 'INPUT') && (oInput.type == 'text') && (oInput.value == '') && (oInput.title != ''))
			{ 
				oInput.value = oInput.title;
				oInput.addClassName('empty');
			} 
			else if((oInput.nodeName == 'TEXTAREA') && (oInput.innerHTML == '') && (oInput.title != ''))
			{
			  oInput.innerHTML = oInput.title;
			  oInput.addClassName('empty');
			}
			
			// Add event handlers for focus and blur
			Event.observe(oInput, 'focus', function() {
				// If value and title are equal on focus, clear value
				this.removeClassName('empty');
				if (this.value == this.title)
				{
					this.value = '';
					this.select(); // Make input caret visible in IE
				}
				else
				{
					this.removeClassName('empty');
				}
			});
			Event.observe(oInput, 'blur', function() {
				// If the field is empty on blur, assign title to value
				if (!this.value.length)
				{ 
					this.value = this.title;
					this.addClassName('empty');
				}
				else
				{
					this.removeClassName('empty');
				}
			});
		}
	},
	hideLabel:function(sId) {
		var arrLabels = document.getElementsByTagName('label');
		var iLabels = arrLabels.length;
		var oLabel;
		for (var i=0; i<iLabels; i++) {
			oLabel = arrLabels[i];
			if (oLabel.htmlFor == sId) {
				oLabel.className = oLabel.className + ' ' + autoPopulate.sHiddenClass;
			}
		}
	}
};
document.observe("dom:loaded", function() {
  autoPopulate.init();
});	

