/*
 *	Fancy Labels Plugin.
 *	Author: Rémy Bach
 *	Version: 1.0
 *	
 *	This plugin was just a quick throw-together thing and as such, could probably do with some cleaning up sometime ;)
 *	
 *	Options:
 *		slide - Boolean - Whether or not to animate the label's position on focus and blur. Default is false.
 *		fade - Number between 0 and 1 - What opacity to fade to. Default is 0.5.
 *	
 *	Example:
 *		jQuery('input[type=text], textarea').each(function() {
 *			// Apply the css here so that people without js enabled can still use the form properly.
 *			jQuery(this).siblings('label').css({
 *				'cursor':'text',
 *				'position':'absolute',
 *				'left':'3px',
 *				'top':'3px'
 *			});
 *		}).fancyLabels();
 */
(function($){
  $.fn.fancyLabels = function(opts) {
	var _originalLeft = false;
	var _opts = (opts) ? opts : {fade: 0.5};
	
    return this.each(function() {
		// If the field has a value on page load (pre-populated), hide the label.
		if ($(this).attr('value') != '') {
			$(this).parent().siblings('label').hide();
		}
		
		$(this).focus(function() {
			var _label = $(this).parent().siblings('label');
			var _left = $(this).width()-_label.width()-1; // extra 1px just in case.

			if (!_originalLeft) _originalLeft = _label.css('left');
			
			if (_opts && _opts.slide && _opts.fade) {
				_label.animate({'left':_left+'px', 'opacity':_opts.fade});
			} else if (_opts && _opts.slide) {
				_label.animate({'left':_left+'px'});
			} else {
				_label.animate({'opacity':_opts.fade});
			}
		}).blur(function() {
			if ($(this).val() == '') {
				if (_opts && _opts.slide && _opts.fade) {
					$(this).parent().siblings('label').animate({'left':_originalLeft, 'opacity':'1'});
				} else if (_opts && _opts.slide) {
					$(this).parent().siblings('label').animate({'left':_originalLeft});
				} else {
					$(this).parent().siblings('label').animate({'opacity':'1'});
				}
			}
		}).keyup(function() {
			if ($(this).attr('value') != '') {
				if (!_opts.slide) {
					$(this).parent().siblings('label:visible').hide();
				} else {
					$(this).parent().siblings('label:visible').fadeOut();
				}
			} else {
				if (!_opts.slide) {
					$(this).parent().siblings('label:not(:visible)').show();
				} else {
					$(this).parent().siblings('label:not(:visible)').fadeIn();
				}
			}
		});
    });
  };
})(jQuery);
