/*
 * label2value
 * jquery based script for using form labels as text field values
 * more info on http://cssglobe.com/post/1500/using-labels- 
 *
 * Copyright (c) 2008 Alen Grakalic (cssglobe.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

this.label2value = function(){
	// CSS class names
	// put any class name you want
	// define this in external css (example provided)
	var inactive = "inactive",
		active = "active",
		focused = "focused";
		
	// function
	$("label").each(function(){
		$label = $(this);
		if($label.attr("class").indexOf("replace") != -1){
			$obj = $("#"+$label.attr("for"));
			if($obj[0].tagName.toLowerCase() == "textarea"){	
				var text = $label.text();
				$label.hide();			
				$obj.addClass(inactive)
					.val(text)
					.focus(function(){	
						$event = $(this);
						$event.addClass(focused).removeClass(inactive).removeClass(active);
						if($event.val() == text) $event.val("");
					})
					.blur(function(){
						$event = $(this);
						$event.removeClass(focused);													 
						if($event.val() == "") {
							$event.val(text).addClass(inactive);
						} else {
							$event.addClass(active);		
						};				
					});				
			} else if (($obj.attr("type") == "text") || ($obj.attr("type") == "password")) {
				$label.hide();	
				var id = $obj.attr("id");
					
				if ($("#"+id+"_temp").attr("id") != id+"_temp") {
					var text = $(this).text(),
						name = $obj.attr("name"), 
						classes = $obj.attr("class"),
						tabindex = $obj.attr("tabindex"),
						html = '<input type="text" name="'+name+'_temp" id="'+id+'_temp" class="'+classes+'" value="'+text+'" tabindex="'+tabindex+'" />';
						
					$obj.before(html).removeAttr("tabindex")
						.hide()
						.blur(function(){
							$event = $(this);											 
							if($event.val() == "") {
								$event.removeClass(focused).removeAttr("tabindex").hide().prev().addClass(inactive).attr("tabindex", tabindex).show();
							} else {
								$event.removeClass(focused).addClass(active);		
							};			
						})
						.prev().addClass(inactive).focus(function(){
							$event = $(this);
							$event.next().addClass(focused).removeClass(inactive).removeClass(active);			  
							if($event.val() == text) {
								$event.next().attr("tabindex", tabindex).show().focus();
								$event.hide().removeAttr("tabindex");
							}
						});	
				}
			};	
		};
	});		
};
// on load
$(document).ready(function(){	
	label2value();	
});