/**
 * tooltip
 * 
 * Usage: $(selector).tooltip();
 * 
 * You can add a css class via the rel attribute. (rel="classname1")
 * 
 * NOTE: Html of the tooltip is modified to suit the kraamkamer.nl needs (sprite)
 * 
 * @author Michiel Nugter
 * @copyright Synetic
 */

var aTooltips		= {};
var iNumTooltips	= 0;

jQuery.fn.tooltip = function()
{
	//First remove the title tags and store them in the data-store, disableing the normal browser title.
	this.each(function()
	{
		if (this.title != '') 
		{
			iNumTooltips++;
			if(this.id == '')
			{
				this.id = 'tooltip_' + iNumTooltips;
			}
			aTooltips[this.id] = this.title;
			this.title = '';
			
			//Then bind a hover effect to show the title
			$(this).hover(function(e)
			{
				if ($('#tooltip').length > 0) 
				{
					$('#tooltip').remove();
				}
				$(document.body).append("<div id='tooltip' class='" + $(this).attr('rel') + ' ' + $(this).attr('name') + "'><div class='sprite-wrapper'><div class='sprite'></div></div><div class='tooltip-content'>" + aTooltips[this.id] + "</div></div>");
				jQuery.tooltipRelocate(e);
				$('#tooltip').fadeIn(300);
			}, 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
		});
	}
}