
var InputClearDefault = Class.create(
{
	initialize: function( element )
	{
		this.element = $( element );
		this.initDOM();
		this.initOther();
		this.initEvents();
	},
	
	initDOM: function()
	{
		this.dom = {};
		this.dom.parentForm = this.element.up( "form" );
	},
	
	initOther: function()
	{
		this.defaultValue = this.element.getValue();
	},
	
	initEvents: function()
	{
		this.element.observe( 'focus', this.handleFocus.bind( this ) );
		this.element.observe( 'blur', this.handleBlur.bind( this ) );
		
		if( typeof this.dom.parentForm !== "undefined" )
			this.dom.parentForm.observe( "submit", this.handleParentFormSubmit.bind( this ) );
	},
	
	handleFocus: function( e )
	{
		Event.stop( e );
		var currentValue = this.element.getValue();
		
		if( currentValue === this.defaultValue )
		{
			this.element.clear();
			this.element.removeClassName( 'empty' );
		}
	},
	
	handleBlur: function( e )
	{
		Event.stop( e );
		var currentValue = this.element.getValue();
		
		if( currentValue.length == 0 )
		{
			this.element.addClassName( 'empty' );
			this.element.setValue( this.defaultValue );
		}
	},
	
	handleParentFormSubmit: function( e )
	{
		var currentValue = this.element.getValue();
		if( currentValue === this.defaultValue )
		{
			this.element.clear();
		}
	}
});

document.observe( 'dom:loaded', function(){ $$( '.clear-default' ).each( function( el ){ new InputClearDefault( el ) } ) } );