/**
 * Toggle value in input type text
 * 
 * Copyright (c) 2010 Andrei Valuyev, Minsk Belarus for http://prointerior.by
 * mailto: a.valuyev@gmail.com
 *
**/

(function($){
	$.extend($.fn, {
		toggleValue: function(options){
			return this.each(function() {

				if (!$(this).is('input:text') && !$(this).is(':textarea')) {
					return false;
				}

				if($(this).data('toggleValue')) {
					var thisData = $(this).data('toggleValue');

					if (typeof options == 'string') {
						switch(options) {
							case 'destroy':
								thisData.destroy();
								break;
						}
					} else if (typeof options == 'object') {
						thisData.opt = $.extend(thisData.opt, options);
					}
				} else {			
					$(this).data('toggleValue', new ToggleValue (this, options));
				}
			});
		}
	});
	
	var ToggleValue = function(el, options) {
		var th = this;
		// save input
		th.input = $(el);
			
		th.opt = $.extend({
			focusColor: '',
			defaultValue: ''
		}, options);
		
		th.init();

		return th;
	};
	
	$.extend(ToggleValue.prototype, {
		init: function () {
			var th = this;
			
			th.input.val(th.opt.defaultValue);
			
			th.input.bind('focus.toggleValueFocus', function () {				
				if ($(this).val() == th.opt.defaultValue) {
					if (th.opt.focusColor) {
						th.input.css('color', th.opt.focusColor);
					}
					
					$(this).val('');
				}
			});
			
			th.input.bind('blur.toggleValueBlur', function () {				
				if ($(this).val() == '' ||  $(this).val() == th.opt.defaultValue) {
					if (th.opt.focusColor) {
						th.input.css('color', '');
					}
					
					$(this).val(th.opt.defaultValue);
				}
			});			
		},
		
		destroy: function () {
			this.input.removeData('toggleValue');
			this.input.unbind('focus.toggleValueFocus');
			this.input.unbind('blur.toggleValueBlur');
		}
	});
})(jQuery);



