var hasHintClass = "has-hint"; // elements marked to have a hint
var isHintedClass = "is-hinted"; // elements which hints are actually dislayed 

/**
 * Install hooks for onBlur and onFocus events
 */
jQuery.fn.installHints = function() {
	// hides the input display text stored in the title on focus
	// and sets it on blur if the user hasn't changed it.

	// show hints (initial)
	$(this).each(function(i) {
		jQuery.fn.showHint(this);
	});

	// hook up the blur & focus
	$(this).focus(function() {
		jQuery.fn.hideHint(this);
	}).blur(function() {
		jQuery.fn.showHint(this);
	});
};

jQuery.fn.hideHint = function(element) {
	if ($(element).val() == $(element).attr('title')) {
		$(element).toggleClass(isHintedClass,false);
		$(element).val('');
	}
};

jQuery.fn.showHint = function(element) {
	if ($(element).val() == '') {
		$(element).toggleClass(isHintedClass,true);
		$(element).val($(element).attr('title'));
	}
};
/**
 * Before a form is submitted, all hinted inputs must be erased. 
 */
jQuery.fn.eraseHintsOnSubmit = function() {
	
	if ($(this).data('events')!=null && $(this).data('events').submit!=null) {
		// There is already a submit event handler - do not change it. 
		//  Hints will be submitted with this form!!!
		return;
	}
	
	$(this).submit(function() {
		var $inputs = $(this).find("input[title]."+isHintedClass+",textarea[title]."+isHintedClass);
		$inputs.each(function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).toggleClass(isHintedClass, false);
				$(this).val('');
			}
		});
	});
};

$(document).ready(function() {
	$('input[title].'+hasHintClass).installHints();
	$('textarea[title].'+hasHintClass).installHints();
	$('form').eraseHintsOnSubmit();
}); 

