/*
 * 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.
 *
 */
// CSS class names
// put any class name you want
// define this in external css (example provided)

var $j = jQuery.noConflict(); // makes jquery compatible with Prototype http://css-tricks.com/using-jquery-in-magneto/

var inactive = "inactive";
var active = "active";
var focused = "focused";
var pwLabel = "Password *";
var labels = this;

this.label2value = function(){
	// function
	$j("label").each(function(){
		if(!$j(this).hasClass('skip')){
			obj = $j(this).siblings("input[id='" + $j(this).attr("for") + "'], textarea[id='" + $j(this).attr("for") + "']");
			// console.log($j(this).text());
			if ( !$j(obj).val() || $j(obj).val() == "" || $j(obj).val() == $j(this).text()) {
				if(($j(obj).attr("type") == "text") || ($j(obj).attr("type") == "textarea")){	
					$j(obj).addClass(inactive);			
					var text = $j(this).text();
					$j(this).css("display","none");
					$j(obj).val(text);
					$j(obj).focus(function(){
						$j(this).addClass(focused);
						$j(this).removeClass(inactive);
						$j(this).removeClass(active);
						if($j(this).val() == text) $j(this).val("");
					});
					$j(obj).blur(function(){
						$j(this).removeClass(focused);
						if($j(this).val() == "") {
							$j(this).val(text);
							$j(this).addClass(inactive);
						} else {
							$j(this).addClass(active);
						};
					});
				} 
			} else {
				$j("#search_form label").css("display", "none");
				return;
			}
		}
	});
};

/**************************************
* add support for password fields
**************************************/
this.onPasswordFocus = function(e){
	if(e.val() == pwLabel){
		var obj = $j('<input name="login[password]" type="password" class="input-text required-entry" style="width:250px" />');
		e.replaceWith(obj);
		$j(obj).blur(function(){
			labels.onPasswordBlur($j(this));
		});
	}
};
this.onPasswordBlur = function(e){
	if(e.val() == ""){
		var obj = $j('<input type="text" class="input-text required-entry" style="width:250px" />');
		e.replaceWith(obj);
		obj.val(pwLabel);
		$j(obj).focus(function(){
			labels.onPasswordFocus($j(this));
		});
	}
};

this.clearInputs = function(){
	$j("form").submit(function() {
		$j("label").each(function(){
			var obj = document.getElementById($j(this).attr("for"));
			if($j(obj).hasClass(inactive)){
				$j(obj).val(null);
			}
		});
	});

	$j(window).unload( function () {
		$j("label").each(function(){
			var obj = document.getElementById($j(this).attr("for"));
			if($j(obj).hasClass(inactive)){
				$j(obj).val(null);
			}
		});
	});
};

// on load
$j(document).ready(function(){
	label2value();
	clearInputs();
});

