/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
(function($) {
	$.formtips = {
		defaults: {
			tippedClass: 'ui-tipped',
			removeTitle: false
		}
	};
	
	$.fn.formtips = function(c) {
		c = $.extend({}, $.formtips.defaults, c);
	
		var tipped = false;
		this.find('input:enabled[type=text], textarea:enabled').each(function() {
			var $t = $(this);
			
			var tip = $t.attr('title');
			if (!tip || tip.length < 1) {
				return;
			}
			
			$t.attr('formtip', tip);
			if (c.removeTitle) {
				$t.removeAttr('title');
			}
			
			// handle initial text
			if ($t.val() == '') {
				$t.val(tip).addClass(c.tippedClass);
			} 
			else {
				$t.removeClass(c.tippedClass);
			}
			
			// handle focus event
			$t.focus(function() {
				var $t = $(this);
				if ($t.hasClass(c.tippedClass)) {
					$t.val('').removeClass(c.tippedClass);
				}
			});
	
			// handle blur event
			$t.blur(function() {
				var $t = $(this);
				if ($t.val() == '') {
					$t.val($t.attr('formtip')).addClass(c.tippedClass);
				}
			});
			
			tipped = true;
		});

		if (tipped) {
			this.submit(function() {
				$(this).find('input:enabled[type=text], textarea:enabled').each(function() {
					if ($(this).hasClass(c.tippedClass)) {
						$(this).val('').removeClass(c.tippedClass);
					}
				});
			});
		}
		
		return this;
	};
})(jQuery);
