/**
* Line defaultText jquery function
* 
* Sets default text for input fields using one of the following elements:
* - label (with matched 'for' attribute)
* - legend (useful for single fields)
* - custom (specified by passing 'text' property)
* 
* This plugin also provides:
* - hiding of corresponding labels/legend
* - ability to set custom default field class
* 
* @author <brian@line.uk.com>
*/
;(function($)
{
	$.fn.lineDefaultFieldText = function(options)
	{
		var defaults = {
			textSrc: 'label', //forces field to take text from fieldset legend rather than title attribute or specified text
			text: false,
			defaultClass: 'default',
			autoHideSource: true
		};
		var options = $.extend({}, defaults, options);

		return this.each(function()
		{
			var _this = $(this);

			switch(options.textSrc)
			{
				case 'legend':
					var el = _this.parentsUntil('form').last().find('legend');
					var text = el.text();
					hideSource(el);
					break;

				case 'label':
					var _l = $('label[for=' + _this.attr('id') + ']', _this.parentsUntil('form'));

					/* check for a match on for attribute first */
					if(_l.length)
					{
						var text = _l.text();
						hideSource(_l);
					}
					else // check against parent element
					{
						var el = _this.parent().is('label')
						? _this.parent()
						: _this.parent().find('label');

						var text = el.text();

						hideSource(el);
					}
					break;

			case 'custom':
				var el = false;
				var text = options.text.toString();
				break;
			}

			if(_this.val() == '')
			{
				_this.val(text);
				_this.addClass(options.defaultClass);
			}

			_this.focus(function()
			{
				if(_this.val() == text)
				{
					_this.val('');
					_this.removeClass(options.defaultClass);
				}
			})
			.blur(function()
			{
				if(_this.val() == '')
				{
					_this.val(text);
					_this.addClass(options.defaultClass);
				}
			});
		});

		function hideSource(el)
		{
			if(options.autoHideSource)
			{
				el.hide();
			}
		}
	}
})
(jQuery);
