var whos_open = false;
var cbox_over = false;
var whos_leaving = false;
var cbox_width;
var cbox_height;
var cbox_pos;
var cbox_over_pos;
var whos_width = 511;
var whos_height = 351;
var mouseX;
var mouseY;
$(document).ready(function() {
	init_tooltip();
});

function init_tooltip()
{
		cbox_width = $('.cbox').width();
	cbox_height = $('.cbox').height();
	$().bind('mousemove', function(e){
     mouseX = e.pageX;
     mouseY = e.pageY;
  });
	$('.cbox').bind('mouseenter', function(e) {
		cbox_mouseenter(this);
	});
	$('.cbox').bind('mouseleave', function() {
		cbox_mouseleave();
	});
	$('.whoswho').bind('mouseleave', function() {
		if (!whos_leaving) {
			whos_leaving = true;
			$(this).animate({opacity: 1.0}, 500, function() {
				if (whos_open && ((cbox_over == false) || (cbox_pos.top != cbox_over_pos.top) || (cbox_pos.left != cbox_over_pos.left)) && ((mouseX < (cbox_pos.left + cbox_width)) || (mouseX > (cbox_pos.left + cbox_width + whos_width)) || (mouseY < (cbox_pos.top - 190)) || (mouseY > (cbox_pos.top + (whos_height - 190))))) {
					$('.whoswho').animate({ marginLeft: 0 }, 1000).fadeOut('fast');
					whos_open = false;
				}
				whos_leaving = false;
			});
		}
	});
	$('#johnny').bind('mouseleave', function() {
		if (!whos_leaving) {
			whos_leaving = true;
			if (whos_open) {
				var whos_left = cbox_pos.left + cbox_width;
				var whos_top = cbox_pos.top - 190;
			}
			$(this).animate({opacity: 1.0}, 500, function() {
				if (whos_open && ((mouseX < whos_left) || (mouseX > (whos_left + whos_width)) || (mouseY < whos_top) || (mouseY > (whos_top + whos_height)))) {
					$('.whoswho').animate({ marginLeft: 0 }, 1000).fadeOut('fast');
					whos_open = false;
				}
				whos_leaving = false;
			});
		}
	});
}

function cbox_mouseenter(this1)
{
	cbox_over = true;
	cbox_over_pos = $(this1).offset();
	$(this1).animate({opacity: 1.0}, 1000, function() {
		var this_pos = $(this1).offset();
		if ($('#show_ww').is(':checked') && cbox_over && (cbox_over_pos.left == this_pos.left) && (cbox_over_pos.top == this_pos.top)) {
			$('#tooltipcontent').html('<span style="display:block;margin:150px 0 0 225px"><img src="images/tooltiploader.gif" alt="loading"/></span>');  
			cbox_pos = cbox_over_pos;
			$(".whoswho").css( { "left": (cbox_pos.left + cbox_width) + "px", "top":(cbox_pos.top - 190) + "px" } );
			if (!whos_open) {
				$('.whoswho').fadeIn('fast');
				whos_open = true;
			}
			
			$.ajax(
				{
					url: 'ui/tooltip/' + $(this1).attr('id'),
					cache: true,
					success: function(data)
						{
							$('#tooltipcontent').hide().html(data).fadeIn('slow');
						}
				}
			);
		}
	});
}

function cbox_mouseleave()
{
	cbox_over = false;
}
