/**
 * innerLabel plugin for jQuery
 * @copyright 2009 info.nl
 * @author Arno Wolkers
 * @version 1.0
 * 
 * Show the label text of a form input element inside the element itself
 *
 *
 * ----------------------------------------
 * HOW TO USE
 * ----------------------------------------
 * $('input').innerLabel();
 * 
 *
 * ----------------------------------------
 * OPTIONS
 * ----------------------------------------
 * See at the bottom of this page for public settings
 * 
 */
(function($){
	$.fn.innerLabel = function(options) {
		var settings = $.extend({}, $.fn.innerLabel.defaults, options);
		
		return this.each(function(i, elem) {
			elem.label = $('label[for='+$(elem).attr('id')+']:last').text();
			
			if (elem.label) {
				if ($(elem).attr('type') != 'password') {
					$(elem).focus(function() {
						removeLabel(elem);
					}).blur(function() {
						addLabel(elem);
					});
					addLabel(elem);
				} else {
					// make a copy of the password field as a textfield
					var replacer = $('<input type="text" />').insertAfter($(elem))
						.attr('class', settings.className +' '+ $(elem).attr('class'))
						.attr('value', elem.label)
						.attr('maxlength', $(elem).attr('maxlength'))
						.attr('size', $(elem).attr('size'))
					$(elem).hide();
					
					$(replacer).focus(function() {
						$(this).hide();
						$(elem).show().focus();
					});
					
					$(elem).blur(function() {
						if ($.trim($(this).val()) == '') {
							$(this).val('').hide();
							$(replacer).show();
						}
					});
				}
				
				$(elem).closest('form').bind('submit',function() {
					if ($.trim($(elem).val()) == elem.label) {
						$(elem).val('');
					}
				});
			}
		});
		
		
		/**
		 * If the value of the field is empty then put the label text inside the field
		 * 
		 * @param {object} elem The given value
		 */
		 function addLabel(elem) {
			if ($.trim($(elem).val()) == '') {
				$(elem).val(elem.label).addClass(settings.className);
			}
		};
		
		/**
		 * If the value of the field equals the label text then empty the field
		 * 
		 * @param {object} elem The given value
		 */
		function removeLabel(elem) {
			if ($(elem).val() == elem.label) {
				$(elem).val('').removeClass(settings.className);
			}
		};
	};
	
	// plugin defaults 
	$.fn.innerLabel.defaults = {
		className : 'innerLabel' // className when innerlabel is active
	};

})(jQuery);
