var fadeSpeedMs = 400;
var save_offset_top = 0;

$(function()
{
	$(".employee_image").each(function()
	{
		$(this).hover(handlerIn, handlerOut);
		
		//sets the grid and info box's image using its id
		var getid = $(this).attr("id").substring(5);
		var path = "/wp-content/uploads/2011/07/" + getid + ".png";
		
		$(this).css("background-image", "url(" + path + ")");
		
		var new_img = $("<img />");
		new_img.attr("src", path);
		new_img.addClass("employee_info_img");
		$(this).find(".employee_info").prepend(new_img);
	});
});

function handlerIn()
{
	//hide any info boxes currently fading out, prevents weird animation 
	//glitches like animation stacking
	$(".employee_info").stop(true, true).hide();
	
	var info = $(this).find(".employee_info");
	
	//fade in to 99% to combat IE8's attempted sabotage with clearType
	info.stop().fadeTo(fadeSpeedMs, 0.99); 

	//read in info box offset in case the css is ever redesigned,
	//save it for reference to reset the box after it fades out
	save_offset_top = info.position().top;

	//offset info box if "collision" with bottom of browser window
	var info_bottom = info.outerHeight() + $(this).position().top + save_offset_top;
	var browser_bottom = $(window).height() + $(window).scrollTop();
	var diff = info_bottom - browser_bottom;
	var new_top = Math.min(save_offset_top, save_offset_top - diff);
	
	//offset info box if "collision" with top of browser window
	var check_top = $(this).position().top + new_top - $(window).scrollTop();
	new_top = Math.max(new_top, new_top - check_top);

	//offset info box if "collision" with top of page
	//necessary because of a z-index issue on live site which causes
	//info boxes to be drawn behind logos and nav bar at top of page
	new_top = Math.max(new_top, 235 - $(this).position().top - save_offset_top);

	//offset info box if "collision" with bottom of page
	//only seemed to be a problem with the bottom row in FF
	var check_bottom = $(document).height() - $("#footer").outerHeight() - info.outerHeight() - $(this).position().top;
	new_top = Math.min(new_top, check_bottom);
	
	info.css("top", new_top);
	
	//consequence of having to add ".shadow" divs around ".employee_image" for IE shadows to work
	//not even sure if this is technically correct, because I thought the max for z-index was 100
	$(this).css("z-index", 205);
	info.css("z-index", 206);
}

//used for both mouseLeave and mouseClick (click currently disabled)
function handlerOut()
{
	var info = $(this).find(".employee_info");
	info.stop(true, true).fadeOut(fadeSpeedMs, function()
	{
		info.css("top", save_offset_top);
		
		//consequence of having to add ".shadow" divs around ".employee_image" for IE shadows to work
		info.css("z-index", 10);
		info.parent().css("z-index", 9);
	});
}
