/**
 * jQuery Initial input value replacer
 *
 * Sets input value attribute to a starting value based on jQuery semantic in-field inline label plugin by Marco "DWJ" Solazzi
 * @author virtual identity AG - www.virtual-identity.com
 * @license  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * @copyright Copyright (c) 2008 virtual identity AG
 * @version 0.1
 * @requires jQuery 1.2.x
 */
(function ($) {
	/**
	 * Setting input initialization
	 *
	 * @param {String|Object|Bool} text Initial value of the field. Can be either a string, a $ reference (example: $("#element")), or boolean false (default) to search for related label
	 * @param {Object} [opts] An object containing options:
	 * 							color (initial text color, default : "#666"),
	 * 							e (event which triggers initial text clearing, default: "focus"),
	 * 							force (execute this script even if input value is not empty, default: false)
	 * 							keep (if value of field is empty on blur, re-apply initial text, default: true)
	 */
	$.fn.inputLabel = function(text, opts) {
		o = $.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
		var isDefault = function(element) {			
			if(element.type=="select-one"){				
				return $(":selected", element).val()=="";
			}
			return element.value == element.defaultValue;
		}
		var clearInput = function (e) {
			
			var $target = $(e.target);
			var value = $.trim($target.val());
			var defaultValue = $.trim($target.attr("defaultValue"));
			
			if (e.type == e.data.obj.e && isDefault(e.target)) {
				$target.css("color", "").val("");
				if (!e.data.obj.keep) {
					$target.unbind(e.data.obj.e+" blur",clearInput);
				}
			} else if (e.type == "blur" && value == "" && e.data.obj.keep) {
				$target.css("color", e.data.obj.color).val(defaultValue);
			}
		};
		return this.each(function () {
			$this = $(this);
			$this.addClass('inputlabel');
			var labelText = (text || false)
			if (!labelText) {
				labelText = $(this.form).find("label[for=" + this.id + "]").hide().text();
			}
			else if (typeof labelText != "string") {
				labelText = $(labelText).text();
			}
			labelText = $.trim(labelText);
			if (o.force || $this.val() == "" || $this.val()==labelText) {
				if (this.type=="select-one") {
					$this.css("color", o.color);
					$("option:first", $this).text(labelText);	
				} else {
					$this.css("color", o.color).val(labelText).attr('defaultValue', labelText);
				}
			}
			$this.bind(o.e+" blur",{obj:o},clearInput);

		});
	};
})(jQuery);