/*
 *
 * Copyright (c) 2009 Doubleclique (dev [at] doubleclique [dot] com)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license
 *
 */

/**
 *
 * @name     jquery.dql.smartlabels
 * @version  0.4
 * @author   Shane Garelja (shane [at] doubleclique [dot] com)
 * @requires jQuery
 *
 */

/*
 * Form Label plugin for jQuery

Minimum CSS:
label {
	cursor:text;
	position:absolute;
	z-index:2;
}

Ideal markup example:
<div class="inputLayout">
	<span class="fieldHolder ">
		<label for="contactFieldName">Name*</label>
		<input name="Name" id="Name" type="text" value="" autocomplete="off" />
	</span>
</div>

You should also add a noscript option to top of page - e.g.:
<noscript>
	<style>
		label {
			position:static;
		}
	</style>
</noscript>

 */

;
(function ($) {

	$.fn.smartlabels = function (options) {

		var settings = $.extend(
		{
			inputSelector : "input[type='text'], input[type='password'], textarea",
			fadeTo : '0.6',
			keydownCallback : function($el) {
			// Do nothing - you can pass a function to the options param if you want
			}
		},
		options
		);
		return this.each(
			function() {
				var $element, $input, $label, labelHolder;

				$element = $(this);
				$input = $(settings.inputSelector, $element);
				$label = $('label', $element);

                // change by Nathan to cater for the hidden form field
                var inputWidth = $input.outerWidth();
                if (inputWidth == 0)
                    inputWidth = $input.css('width').replace('px', '');

				labelHolder = $('<div></div>').css({
					'position':'relative',
					'width' : inputWidth + 'px',
					'height' : '0px'
				});

				$label.wrap(labelHolder);

				var fadeLabel = function() {
					$label.stop().fadeTo(200, settings.fadeTo);
				};

				$label.bind('click',
					function(e) {
						e.preventDefault();
						$input.focus();
					}
					);
				$input.bind("focus",
					function() {
						if ($.trim($(this).val()).length == 0) {
							fadeLabel();
						}
					}
					);
				$input.bind("blur change",
					function() {
						if ($.trim($(this).val()).length == 0) {
							$label.stop().css({
								'opacity':'1.0',
								'display':''
							});
						} else {
							$label.stop().hide();
							settings.keydownCallback($element);
						}
					}
					);
				$input.keydown(
					function(e) {
						if (e.which == 32 ||
							(48 <= e.which && e.which <= 57) ||
							(65 <= e.which && e.which <= 90) ||
							(97 <= e.which && e.which <= 122)) {
							$label.hide();
							settings.keydownCallback($element);
						}
					}
					);

				if ($.trim($input.val()).length > 0) {
					$label.hide();
				}
			}
			);
	};

})(jQuery);
