
/**
Provides 'auto-hiding' default values in text and textarea fields.
The default values are obtained from the HTML using the alt attribute.  When
this script is run, default values are added to every form text input and
text area element that has an alt attribute.

Adding default values is as simple as including this file and adding non-empty
alt tags to your text input and textarea elements.

@author    Leon Matthews <leon@lost.co.nz>
@copyright Copyright 2008 Leon Matthews. All rights reserved.
@link      http://www.lost.co.nz/
*/
(function()
{
	/**
	Remove default text from form element on focus
	*/
	function onFocusHandler()
	{
		var alt = this.getAttribute('alt');
		if( this.value == alt)
		{
			this.value = '';
		}
	}

	/**
	Restore default text on form element on blur, if empty
	*/
	function onBlurHandler()
	{
		var alt = this.getAttribute('alt');
		if( ! this.value )
		{
			this.value = alt;
		}
	}

	/**
	Add event handlers to all form elements in document that have alt attributes
	*/
	function init()
	{
		var i, needsValidation, form, j, elem, alt;
		
		// Loop through all forms in document
		for( i=0; i<document.forms.length; i++)
		{
			needsValidation = false;
			form = document.forms[i];

			// Loop through elements in current form
			for( j=0; j < form.elements.length; j++ )
			{
				elem = form.elements[j];

				// We care about text, and Textarea elements
				if( elem.type == 'text' || elem.type == 'textarea')
				{
					alt = elem.getAttribute('alt');
					if( alt )
					{
						// Add default text (if empty)
						if( ! elem.value )
						{
							elem.value = alt;
						}

						// Install event handlers
						elem.onfocus = onFocusHandler;
						elem.onblur = onBlurHandler;
					}
				}
			}
		}
	}
	
	// Initialisation -- have init() run once page has finished loading
	var $;
	if( $ && $(document).ready )		// jQuery
	{
		$(document).ready( init );
	}
	else if( window.addEventListener)	// DOM Level-2
	{
		window.addEventListener('load', init, false);
	}
	else if( window.attachEvent)		// Sigh... Internet Explorer
	{
		window.attachEvent('onload', init);
	}

})();
