/**
 * Forms Placeholders plugin for jQuery
 *
 * Copyright (c) 2010 FiftyFootSquid (fiftyfootsquid.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Add placeholders to your forms
 *
 * @example $.initPlaceholders();
 * @desc Adds a placeholder into all your input and textarea fields when the source for your placeholder is title attribut
 *
 * @example <input name="name" id="name" value="" title="Your name" type="text">
 * @desc Example of use of the title attribute in the input field
 *
 * @example <textarea name="message" id="message" cols="35" rows="3" title="Your message"></textarea>
 * @desc Example of use of the title attribute in the textarea
 *
 * @name $.initPlaceholders
 * @cat Plugins/Forms
 * @author Ondrej Rafaj / labs@fiftyfootsquid.com 
 */
 
jQuery.initPlaceholders = function() {
	var elements = $('form input[type="submit"], form button[type="submit"]');
	var element;
	elements.each(function(num) {
		element = elements[num];
		$(element).click(function() {
			var inputs = $('input, textarea');
			return inputs.each(function(num) {
				var input = inputs[num];
				if ($(input).attr('title') == $(input).val()) $(input).val('');
				return false;
			});
		});
	});
	elements = $('input, textarea');
	return elements.each(function(num) {
		var ok = false;
		element = elements[num];
		if ($(element).attr('title') && $(element).val() == "") {
			$(element).val($(element).attr('title'));
			$(element).addClass('placeholder');
			$(element).change(function() {
				$(this).removeClass('placeholder');
			});
			ok = true;
		}
		else if ($(element).attr('title') == $(element).val()) {
			$(this).addClass('placeholder');
			ok = true;
		}
		$(element).focus(function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).removeClass('placeholder');
				$(this).val('');
			}
		});
		if (ok) $(element).blur(function() {
			if ($(this).val() == "") {
				$(this).addClass('placeholder');
				$(this).val($(this).attr('title'));
			}
		});
	});
	
};
