(function ($) {
	$.fn.tooltip = function (html, options) {
		var opts = $.extend({}, $.fn.tooltip.defaults, options);
		
		if (opts.name != '') {
			opts.name = opts.name + '_tooltip';
		} else {
			opts.name = 'tooltip';
		}
		
		if (opts.action != 'attach') {
			$.fn.tooltip.attachEvents(this, html, opts);
		} else {
			$.fn.tooltip.build(this, html, opts);
		}
	};
	
	$.fn.tooltip.defaults = {
		name: '',
		action: 'attach',
		position: 'static',
		offset_x: 2,
		offset_y: 2,
		corner: false,
		
		debug: false
	};
	
	$.fn.tooltip.attachEvents = function (obj, html, opts) {
		var $obj = $(obj);
		
		$obj.hover(
			function () {
				$.fn.tooltip.build(this, html, opts);
			},
			
			function () {
				var $tooltip = $('#' + opts.name);
			
				if ($tooltip.length > 0) {
					$('#' + opts.name).remove();
				}
			}
		);
		
		if (opts.position == 'mouse') {
			$obj.mousemove(function (e) {
				var $obj = $(this);
				var $tooltip = $('#' + opts.name);

				if ($tooltip.length > 0) {
					var offset, page_x, page_y;
					
					if ($obj.css('position') != 'static') {
						offset = $obj.offset();
						page_x = ((e.pageX - offset.left) + opts.offset_x) + 'px';
						page_y = ((e.pageY - offset.top) + opts.offset_y) + 'px';
					} else {
						page_x = (page_y + opts.offset_y) + 'px';
						page_y = (page_x + opts.offset_x) + 'px';
					}
					
					$tooltip.css({
						'position': 'absolute',
						'top': page_y,
						'left': page_x
					});
	
					if (opts.debug) {
						debug(page_x, page_y);
					}
				}
			});
		}
	};
	
	$.fn.tooltip.build = function (obj, html, opts) {
		var $obj = $(obj);
		
		if ($('#' + opts.name, $obj).length == 0) {
			$obj.append('<div id="' + opts.name  + '"><div class="tool">' + html + '</div><div class="tip"></div></div>');
		}
	};
	
	// private functions
	function debug (x, y) {
		if (window.console && window.console.log) {
			window.console.log('x: ' + x + ', y: ' + y);
		}
	};
})(jQuery);
