/*---------->>> HTML5 Form "Placeholder" <<<----------*/
/*---------->>>  VERSION 1.0 (01/21/11)  <<<----------*/

$(formInit);
function formInit() {
	var fieldTypes = $("input[type='text'], input[type='email'], input[type='search'], input[type='tel'], input[type='url'], input[type='password'], textarea"); // <input /> and <textarea> that use "placeholder"

	// Checks if a <form> using any of these elements even exists on the page
	if(fieldTypes.length == 0) {
		return false;
	}

	var fakeInput = document.createElement("input"), // Create fake <input /> to see if "placeholder" attribute is native to browser
	    isNative = !!("placeholder" in fakeInput), // Test fake <input /> for "placeholder"
	    clearValue = function (f, p) { // Create reusable function for clearing "value" if it = "placeholder"
			if (f.val() == p) {
				f.val("");
			}
	    };

	// If "placeholder" is NOT native to the browser, fake it with "value"				
	if(!isNative) {
		$(fieldTypes).each(function(i,field) { // The current form <input /> or <textarea>
			var placeholder = $(field).attr("placeholder"); // Value of "placeholder" attribute
			if(placeholder == $(field).val() || $.trim($(field).val()) == "") {

				// Add placeholder text into the "value" attribute and add ".placeholder" class for styling
				$(field).val(placeholder).addClass("placeholder");
			}

			// On focus, remove the styling class and clear the "value" IF it = "placeholder" text
			$(field).focus(function(){
				$(field).removeClass("placeholder");
				clearValue($(field), placeholder);
			});

			// On blur, add ".placeholder" class and value if the field is empty (besides spaces)
			$(field).blur(function(){
				if($.trim($(field).val()) == "") {
					$(field).addClass("placeholder").val(placeholder);
				}
			});

			// On submit, if "value" = "placeholder", remove that value before it submits
			$(field).parents("form").submit(function () {
				clearValue($(field), placeholder);
			});
		});
	}
}
