jQuery.fn.tooltip = function()
{
	this.each(function()
	{
		if (this.title != '') 
		{
			$(this).data('title', this.title);
			this.title = '';
		}
	});
	
	this.hover(function(e)
	{
		title = $(this).data('title');
		if(title){
			$(document.body).append("<div id='tooltip' class='" + $(this).attr('rel') + "'><div class='sprite-wrapper'><div class='sprite'></div></div><div class='tooltip-content'>" + title + "</div></div>");
			jQuery.tooltipRelocate(e);
			$('#tooltip').fadeIn(100);
		}
		
	}, function()
	{
		$('#tooltip').remove();
	});
	$(document).mousemove(jQuery.tooltipRelocate);
};

/**
 * Set the location of the tooltip
 * 
 * @param {Object} e Browser event
 */
jQuery.tooltipRelocate = function(e) {
	if ($('#tooltip').length > 0 != null) 
	{
		var iX = (document.all) ? event.clientX + $(window).scrollLeft()	: e.pageX;
		var iY = (document.all) ? event.clientY + $(window).scrollTop()		: e.pageY;
		
		var iLeft = ((iX - $(window).scrollLeft() + 40 + $('#tooltip').width()) > $(window).width()) ? iX - $('#tooltip').width() - 20 : iX + 20;
		if (iLeft < $(window).scrollLeft() + 20) 
		{
			iLeft = $(window).scrollLeft() + 20;
		}
		
		var iTop = ((iY - $(window).scrollTop() + $('#tooltip').height()) > $(window).height()) ? iY - $('#tooltip').height() : iY;
		if (iTop < $(window).scrollTop()) 
		{
			iTop = iY;
		}
		
		$('#tooltip').css({
			top	: iTop,
			left: iLeft
		});
	}
}
