/*
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 *
 * by Ross Shannon, http://www.yourhtmlsource.com/
 */

// Add Namespace
if (typeof(lenox) === 'undefined') {
	lenox = {};
}

lenox.clearDefaultText = function() {
	var clearDefaultText = function(e) {
	    if (this.isDefault) {
	        $(this).val('');
	        this.isDefault = false;
            $(this).removeClass('defaultText');
	    }
	};

	var replaceDefaultText = function(e) {
		var v = $.trim($(this).val());
		var d = $(this).attr('defaultText');
	    if (v == '' && d) {
            $(this).addClass('defaultText');
            this.isDefault = true;
            $(this).val(d);
	    }
	};
	
	var keydown = function(e) {
		// Escape Key
		if (e.keyCode == 27) {
			var v = $.trim($(this).val());
			if (v == '') {
				$(this).blur();
			} else {
	            $(this).removeClass('defaultText');
	            this.isDefault = false;
	            $(this).select();
			}
			e.preventDefault();
			return false;
		}
	};

	return {
		init : function() {
		    var formInputs = $('.cleardefault');
		    formInputs.each(function() {
		    	if (this.type == 'text') {
		    		var v = $.trim($(this).val());
		    		var d = $(this).attr('defaulttext');
		    		// Only assign behavior if defaultext is defined and has a value.
		    		if (d != undefined && $.trim(d).length > 0) {
			    		$(this).focus(clearDefaultText);
			    		$(this).blur(replaceDefaultText);
			    		$(this).keydown(keydown);
			    		this.isDefault = false;
			            $(this).removeClass('defaultText');
			            
			            /* Save the current value */
			            if (v == '' || v == d) {
				            $(this).addClass('defaultText');
			            	$(this).val(d);
			            	this.isDefault = true;
			            }
		    		}
		    	}
		    });
		}
	}
}();
