(function() {
	var visibleModalTip = null;
	$.fn.tooltip = function(options) {
		options = $.extend({
			activation: 'hover',
			target: null,
			width: 'auto',
			text: null,
			tooltip: null,
			// position: 'bottom',
			// align: 'center'
		}, options);

		var showTip = function(ev) {
			var target = options.target? options.target: $(ev? ev.target: this);
			var offset = target.offset();
			var tip = target.data('tooltip');
			if (!tip) {
				if (options.tooltip) {
					tip = options.tooltip.clone();
					if (options.text) {
						tip.find(options.text).html(target.attr('data-tooltip-text'));
					}
				} else {
					tip = $('<span>')
						.addClass('text-tip')
						.css({
							display: 'none'
						});
					tip.append($('<span>').html(options.text? options.text: target.attr('data-tooltip-text')));
				}
				$(document.body).append(tip);
				target.data('tooltip', tip);
				tip.data('tooltip-trigger', target);
				// switch (options.position) {
				// 	case 'top':
				// 		offset.top -= tip.outerHeight() + 2;
				// 		break;
				// 	case 'bottom':
				// 		offset.top += target.outerHeight() + 2;
				// 		break;
				// 	case 'left':
				// 		offset.left -= tip.outerWidth() + 2;
				// 		break;
				// 	case 'right':
				// 		offset.left += target.outerWidth() + 2;
				// 		break;
				// 	default:
				// 		return false;
				// }
				// if ((options.align == 'right') && ((options.position == 'top') || (options.position == 'bottom'))) {
				// 	offset.left -= tip.outerWidth();
				// 	offset.left += target.outerWidth();
				// }
				offset.top += target.outerHeight() + 2;
				offset.left -= Math.round(tip.outerWidth() / 2);
				offset.left += Math.round(target.outerWidth() / 2);
				tip.css(offset);
			}
			tip.show();
			return false;
		}
		var getTip = function(from) {
			from = $(from);
			var tip = from.data('tooltip');
			if (tip) {
				return tip;
			}
			var target = from.data('tooltip-target');
			if (target && (tip = target.data('tooltip'))) {
				return tip;
			}
			return null;
		}
		var hideTip = function(ev, tip) {
			if (!tip) {
				tip = getTip(this);
			}
			if (tip) {
				tip.hide();
			}
			return false;
		}
		var modalTip = function(ev) {
			if (visibleModalTip) {
				hideTip(null, visibleModalTip);
			}
			showTip(ev);
			var tip = getTip(this);
			if (!tip) {
				return false;
			}
			if (tip == visibleModalTip) {
				visibleModalTip = null;
				hideTip(null, tip);
			} else {
				visibleModalTip = tip;
				$(window).bind('click.modalTip', function() {
					hideTip(null, visibleModalTip);
					visibleModalTip = null;
					$(window).unbind('click.modalTip');
					return true;
				});
			}
			return false;
		}

		switch (options.activation) {
			case 'hover':
				this.hover(showTip, hideTip);
				break;
			case 'click':
				this.click(modalTip);
				break;
			default:
				return false;
		}
	}
})();
