(function($){

	var handle = false;
	var corner = '<em class="corner"></em>';
	var timeout = null;

	var pm = {
		settings: {
			id: 'hoverbox',
			top: 0,
			left: 15,
			timeout: 3000
		},
		tooltip: function (event) {
			var h = $('#' + pm.settings.id);
			handle = handle || (h.size() ? h : false);

			if (!handle) {
				// Create an empty div to hold the tooltip
				handle = $('<div style="position:absolute;" id="'+pm.settings.id+'"></div>')
							.appendTo(document.body)
							.hide();
			}

			if (event) {			
				// Make the tooltip follow a cursor
				handle.css({
					top: (event.pageY - pm.settings.top) + "px",
					left: (event.pageX + pm.settings.left) + "px",
					zIndex: 1000
				});
			}

			return handle;
		},
		showTooltip: function (e){
			if (this.title) {
				// Remove default browser tooltips
				this.t = this.title;
				this.title = '';
				this.alt = '';

				pm.tooltip(e).hide().html(this.t + corner).fadeIn('fast');
			}
		},
		hideTooltip: function (){
			if (this.t) {
				this.title = this.t;
				pm.tooltip().hide();
			}
		}
	};

	$.fn.showTooltip = function(right){
		this.each(function(){
			var el = this;
			var pos = $(el).offset();

			var lo = 30,
				to = 25; 

			var e = {
				pageY: pos.top - lo,
				pageX: pos.left - pm.settings.left * 2 - to
			};

			delete timeout;

			pm.showTooltip.call(el, e);

			var w = handle.width();
			handle.css("left", e.pageX - w);

			timeout = setTimeout(function(){
				pm.hideTooltip.call(el);
			}, pm.settings.timeout);
		});
	};

	$.fn.hoverbox = function(options) {
		jQuery.extend(pm.settings, options);

		this.each(function() {
			$(this).hover(
				function(e) {
					showTooltip.call(this);
				},
				function() {
					hideTooltip.call(this);
				}
			);
			
			$(this).mousemove(tooltip);
		});
	};

})(jQuery);

