/*
 * jQuery Default Value
 * Copyright 2011 Johan Bergstršm, Isotop (www.isotop.se)
 *
 * Add the default value for the input to a title attribut and call this plugin function on it. eg:
 *
 * <input type="text" class="defaultValue" value="" title="This is my default value text" />
 * 
 * And a label will be placed after input and then place itself within input
 * $().ready(function() {
 * 	$('input.defaultValue').defaultValue();
 * }
*/	
(function($) {
	$.fn.defaultValue = function() {
		
		return this.each(function() {
			
			var $input = $(this);
			$input.before('<div style="position: relative">');
			$input.after('</div>');

			$input.focus(function() {
				
				var $label = $input.next();
				
				// Make sure we remove the correct element by checking that our for attribute is pointing to our input element
				if ($label.attr('for') === $input.attr('name')) {
					if ($input.attr('title') === $label.text())
						$label.fadeOut(200, function(e){
							$this = $(this);
							$this.remove();
							$this.unbind('click');
						});
				}
			});

			$input.blur(function() {
								
				if ($input.val() === '') {
					var $label, _pos, _left, _padding;
					$label = $('<label class="dv-label" for="'+ $input.attr('name') +'">'+ $input.attr('title') +'</label>');
					$input.after($label);
					
					_pos = $input.position();
					
					// Get the padding of the input and multiply by two to get the correct padding for our label
					if ($.browser.msie) {
						_padding = parseInt($input.css('padding-left').substring(0, $input.css('padding-left').indexOf('p')));
					} else {
						_padding = parseInt($input.css('padding-left').substring(0, $input.css('padding-left').indexOf('p'))) * 2;
					}
					
					_left = _padding + _pos.left;
					
					$label.css({
							'position' : 'absolute',
							'top' : _pos.top,
							'left' : _left + 5,
							'line-height' : $input.outerHeight() + 'px',
							'height' : $input.outerHeight() + 'px',
							'width' : $input.innerWidth() - (_padding * 2),
							'overflow' : 'hidden',
							'white-space' : 'nowrap'
							});
					$label.click(function(e) {
						$(this).prev().focus();
					});
					
				}	
			});
			
			// blur onload
			$input.blur();

		});
		
	}
})(jQuery);
