(function( $ ){
	
	$.fn.autoclear = function(options) {
		
		/**
		 * Default settings
		 */
		var settings = {
			'clearOnSubmit': true,
			
			'valueKey': 'autoclear-value',
			'formKey': 'autoclear'
		};
		$.extend(settings, options);

		/**
		 * Clear the element if the value is the default
		 * 
		 * @param element - The input element 
		 * 
		 * @return void
		 */
		function clearInput(element) {
			if (element.value == $(element).data(settings.valueKey))
				$(element).val('');			
		}

		/**
		 * Reset the element value if it's empty
		 * 
		 * @param element - The input element 
		 * 
		 * @return void
		 */
		function resetInput(element) {
			if (!element.value.length)
				$(element).val($(element).data(settings.valueKey));
		}
		
		$(this).each(function() {
			if (this.value.length <= 0) return;
			
			$(this).addClass('autoclear').data(settings.valueKey, this.value);

			$(this).focus(function() {
				clearInput(this);
			}).blur(function() {
				resetInput(this);				
			});
			
			if (settings.clearOnSubmit) {
				$form = $(this).parents('form');

				if (!$form.data(settings.valueKey)) {
					$form.data(settings.valueKey, true);
					
					$form.submit(function() {
						$('.autoclear').each(function() {
							clearInput(this);
						});
					});
				}
			}
			
		});
	};
})(jQuery);
