
/**
 * jQuery plugin to realize grey input default value text fields.
 * Use on label or input element. In case of an input element, default
 * value must be written into the 'value' attribute. In case of a label,
 * the label must contain the default value and point to an input
 * element with the 'for' attribute.
 * @param css style class used to format either label or input field if
 * inactive
 * @author andreas.antener
 */
jQuery.fn.inputLabel = function(style) {
	return this.each(function(){
		var element = jQuery(this);
		var input = null;
		var isLabel = true;
		
		if(element.context.nodeName.toLowerCase() == "input"){
			isLabel = false;
			input = element;
		}else{
			var tf = element.attr("for");
			input = jQuery("#" + tf);
		}
		// TODO: catch case when input field is invalid (no label and no input field)
		
		var inputSet = false;
		var inputLabel = input.val();
		
		// TODO: decide which function to use on the outside, not inside of the callback
		this.hide = function() {
			if(isLabel){
				element.css("textIndent", -10000);
			}else{
				if(!inputSet && input.val() != ""){
					input.val("");
				}
				input.removeClass(style);
			}
		};
		
		this.show = function() {
			if (input.val() == ''){
				if(isLabel){
					element.css("textIndent", 0);
				}else{
					input.addClass(style);
					input.val(inputLabel);
				}
				inputSet = false;
			}else{
				inputSet = true;
			}
		};

		// handlers
		input.focus(this.hide);
		input.blur(this.show);
		input.change(this.hide);
		input.click(this.hide);
		if(isLabel){
			element.addClass(style);
		}else{
			input.addClass(style);
		}
		
		if(input.val() != ""){
			this.hide();
		}
	});
};
