/**
 * jQuery Plug-in - Compatible with jQuery-1.2.6.js
 *
 * Uses the input's initial value as a label.
 * Removes the label on focus and replaces the label on blur if nothing was written in the field.
 *
 * @author David Lindkvist (Fi)
 * @version 1.0 
 * @version 1.1 JSLint verified 
 * 
 * Usage: $("#myElement").labelinput();
 * 
 */
(function ($) {
	
	//
	// plugin definition
	//
	$.fn.labelinput = function (pluginOptions) {
	  
		// build main options before element iteration
		var opts = $.extend({}, $.fn.labelinput.defaults, pluginOptions);

		// iterate and add each select element as a slider handle
		this.each(function (i) {
			
			var input = $(this);
			
			//store initial value and use as label
			var label = input.val();
			
			var pwd = false;
			var pwdClone = null;
			
			if (input.attr("type") === 'password') {
				
				pwd = true;
				
				//clone original input (cannot use actual clone since we can't modify type without IE throwing exception)
				pwdClone = $('<input type="text">');
				pwdClone.attr("class", input.attr("class"));
				pwdClone.attr("value", input.attr("value"));
				
				//clear original inputs label value
				input.val("");
				
				//hide original and show clone instea
				//input.hide(); not working on hidden elements in Webkit-based browsers, use css() instead.
				input.css({display: 'none'});
				input.before(pwdClone);		
			}
			
			// if password input, add focus listener to cloned text input
			if (pwd) {
				
				pwdClone.focus(function () {
					
					//hide clone and show real input
					input.focus();
				});
				
				/* listen for change event on original input */
				input.change(function () {
					//update classes
					pwdClone.attr("class", input.attr("class"));
				});
		
				/* listen for programmatic focus event */
				input.focus(function () {
					pwdClone.hide();
					input.show();
				});
			}
			
			//add listeners select element
			input.focus(function () {
				
				input.addClass("focus");
				
				if (input.val() === label) {
					input.val("");
				}
				
			}).blur(function () {
				
				input.removeClass("focus");

				//check to see if label should be displayed again
				if (jQuery.trim(input.val()).length === 0) {
					
					//if password input, show fake text input again
					if (pwd) {
						input.hide();
						input.val("");
						pwdClone.attr("class", input.attr("class")); /* update classes incase input has changed */
						pwdClone.show();
					}
					else {
						input.val(label);
					}
				}
					
			});
			
		});
	
	}; //end plugin def
		
	
	//
	// expose plugin defaults
	//
	$.fn.labelinput.defaults = {
		
	};
	
})(jQuery);