/*
 * kfTooltip 
 * jQuery plugin for displaying images or AJAX content in lightbox style popup.    
 *  
 * Copyright (c) 2008 Karel Fučík  
 * Licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)  
 */


(function($){

	$.fn.kfTooltip = function(options)
	{  
		options = jQuery.extend({
		    speed: null,
			loadContent: function(){},
			template: '<div class="kfTooltip"></div>',
			timeoutEnter: 300,
			timeoutLeave: 300
		}, options);
		
		var $body = $(window); 

		return this.each(function()
		{
			var timeout, position, $box, show, hide, $this = $(this);
			
			show = function()
			{
				if(!$box) $box = $(options.template).css({ position: 'absolute', display: 'block', opacity: 0}).appendTo('body');
				$box
					.css({ left: 0, top: 0 })
					.bind('mouseenter', function(event)
					{
						timeout && clearTimeout(timeout);
					})
					.bind('mouseleave', function(event)
					{
						timeout && clearTimeout(timeout);
						timeout = setTimeout(hide, options.timeoutLeave);
					});
				
				if(typeof options.loadContent === 'function') options.loadContent($this, $box);
				
				var boxSize = { width: $box.width(), height: $box.height() };
				var boxPosition = { left: position.x, top: position.y };				
				var bodySize = { width: $body.width(), height: $body.height(), scrollLeft: $body.scrollLeft(), scrollTop: $body.scrollTop() };
				if(boxSize.width + boxPosition.left > bodySize.width + bodySize.scrollLeft) boxPosition.left = bodySize.width - boxSize.width + bodySize.scrollLeft;
				if(boxSize.height + boxPosition.top > bodySize.height + bodySize.scrollTop) boxPosition.top = bodySize.height - boxSize.height + bodySize.scrollTop;
				
				$box.css(boxPosition).fadeTo(150, 1);
			};
			
			hide = function()
			{ 
				timeout = null;
				if($box) $box.unbind('mouseenter mouseleave').fadeOut(200, function(){ $box && $box.remove(); $box = null; });				
			};
			
			$this.bind('mousemove', function(event)
			{				
				position = { x: event.pageX, y: event.pageY };
			})
			.bind('mouseenter', function(event)
			{				
				if(timeout) clearTimeout(timeout);
				else timeout = setTimeout(show , options.timeoutEnter);
			})
			.bind('mouseleave', function(event)
			{
				timeout && clearTimeout(timeout);
				timeout = setTimeout(hide, options.timeoutLeave);
			});
		});
	};

})(jQuery);


