/* This code is licensed under Creative Commons Attribution 3.0    *
 * You may share and remix the script so long as you attribute the *
 * original author, Andrew January.                                *
 * http://creativecommons.org/licenses/by/3.0/                     */

var Placeholder = Class.create({
	initialize: function()
	{
		// Check to see if the browser already supports placeholder text (introduced in HTML5). If it does,
	    // then we don't need to do anything.
		var i = new Element('input');
	    if ('placeholder' in i) {
	        return false;
	    }
	    
	    this.start();
	},
	
	start: function()
	{
		$$('input[placeholder], textarea[placeholder]').each(function(element) {
			
			// We change the type of password fields to text so their placeholder shows.
			// We need to store somewhere that they are actually password fields so we can convert
			// back when the users types something in.
			if (element.readAttribute('type') == 'password') {
				element.store('realType', 'password');
			}
			
			this.showPlaceholder(element, true);
			element.observe('focus', function(event) {
				this.hidePlaceholder(element)
			}.bind(this));
			
			element.observe('blur', function(event) {
				this.showPlaceholder(element, false)
			}.bind(this));
		}.bind(this));
	},
	
	isPassword: function(input)
	{
		return input.retrieve('realType') == 'password';
	},
	
	valueIsPlaceholder: function(input)
	{
		return input.getValue() == input.readAttribute('placeholder');
	},
	
	showPlaceholder: function(input, loading)
	{
		// FF and IE save values when you refresh the page. If the user refreshes the page
		// with the placeholders showing they will be the default values and the input fields won't
		// be empty. Using loading && valueIsPlaceholder is a hack to get around this and highlight
		// the placeholders properly on refresh.
		if (input.getValue() == '' || (loading && this.valueIsPlaceholder(input)))
		{
			
			if (this.isPassword(input))
			{
				try {
					input.writeAttribute('type', 'input');
				} catch (e) {}
			}
			
			input.setValue(input.readAttribute('placeholder'));
			input.addClassName('placeholder');
		}
	},
	
	hidePlaceholder: function(input)
	{
		if (this.valueIsPlaceholder(input) && input.hasClassName('placeholder'))
		{
			if (this.isPassword(input))
			{
				try {
					input.writeAttribute('type', 'password');
					// Opera loses focus when you change the type, so we have to refocus it.
					input.focus();
				} catch (e) { }
			}
			
			input.value = '';
			input.removeClassName('placeholder');
		}
	}
});

document.observe('dom:loaded', function() {
	new Placeholder();
});
