/**
 * showLabelsAsValue.js
 * Version 0.1 by AP aka bigbear3001
 * 
 * needs jQuery to work. 
 * 
 * This moves the given label into the value fiel of the linked input element.
 * Also there are functions binded to focus and submit event to correct value if
 * user wants to enter some text or submits the form.
 * 
 * Example Use:
 * 	jQuery(document).ready(function(){
 *		//init all labels in my form
 * 		jQuery("#myform").find("label").each(initShowLabelsAsValues);
 * 	});
 **/
var INIT_ATTRIBUTE = "initialized_text";
var EMPTY_VALUE = "";

function initShowLabelsAsValues(label){
	if(!label)label = this;
	//this function must be called for each label element
	var label_val = jQuery(label).html().replace(/[:]$/,"");
	var input_element = jQuery("[id="+jQuery(label).attr("for")+"]");
	if(jQuery(input_element).attr("type").substr(0,6) == "select"){
		jQuery(input_element).find("option:first").text(label_val);
	} else {
		if(jQuery(input_element).val()=="")jQuery(input_element).val(label_val);
		jQuery(input_element).attr(INIT_ATTRIBUTE,label_val);
		jQuery(input_element).focusin(SLAV_hide_init_text);
		jQuery(input_element).focusout(SLAV_show_init_text);
		jQuery(input_element).parents("form").one("submit",SLAV_prepare_submit);
	}
	jQuery(label).hide();
}

function SLAV_hide_init_text() {
	if(jQuery(this).val() == jQuery(this).attr(INIT_ATTRIBUTE)){
		jQuery(this).val(EMPTY_VALUE);
		jQuery(this).focus();
	}
}

function SLAV_show_init_text() {
	if(jQuery(this).val() == EMPTY_VALUE && jQuery(this).attr(INIT_ATTRIBUTE)) {
		jQuery(this).val(jQuery(this).attr(INIT_ATTRIBUTE));
	}
}

function SLAV_prepare_submit() {
	jQuery(this).find("input").each(function(){
		if(!jQuery(this).attr(INIT_ATTRIBUTE) || jQuery(this).val() == jQuery(this).attr(INIT_ATTRIBUTE)){
			jQuery(this).val(EMPTY_VALUE);
		}
	});
	return true;
}
