/**
 * autofill jQuery plugin
 * By Commulec April 2010
 *
 * Adds labels within input fields
 * Takes one parameter: label, which is the attribute of the 
 * input field to use as the label. Default is the title attribute. 
 *
 */

(function($){
  $.fn.autofill = function(options){
	var field = this;
	
	var defaults = {
		clearValues: true, // Future support?
   	label: 'title' // Future support if label: 'label' then remove previous label element, ala progressive enhancement?
	};

	// Extend our default options with those provided.
	var settings = $.extend(defaults, options);
	
	 add_label = function($input, $reset){
			$label = $input.attr(defaults.label);
			if ($reset) {
				$input.removeClass('user_input').val($label);
				if (!$input.hasClass('default_input')) $input.addClass('default_input');
				}
			else {
				if ($input.val() == '') {
					$input.val($label).removeClass('user_input');
					if (!$input.hasClass('default_input')) $input.addClass('default_input');
				}
			}
			return this;
	}
	
	remove_label = function($input, $submit){
		$label = $input.attr(defaults.label);
		if ($input.val() == $label) $input.val('').addClass('user_input');
		if (!$submit) $input.removeClass('default_input');
		return this;
	}
	
	// Apply relevant behaviours
	field.each(function(){ add_label($(this), false); });
	field.focus(function(){ remove_label($(this), false); });
	field.blur(function(){ add_label($(this), false); });	
	$(field[0]).parents('form').find(':reset').click(function(){ // handle form reset 
		field.each(function(){ 
			add_label($(this), true); 
		});
		return false;
	});
	$(field[0]).parents('form').find(':submit').click(function(){ // handle form submit
		field.each(function(){ 
			remove_label($(this), true) 
		});
	});

	// Create object with object template
	function tpl_autofill(){
		this.remove_label = remove_label;
		this.add_label = add_label;
	}
	
	autofill = new tpl_autofill();
	
	return this;
  }
})(jQuery);
