
$(document).ready(function() {

/* }}} */

/* {{{ tooltip mouseover */

	var fade_time = 300;
	var hover_time = 300;

	$('.detailLink').mouseover(function(){
		// set location variables to check later on mouseleave
		detailpopup_hover = false;
		detaillink_hover = true;
	
		// find associated popup by id with suffix converted from Link to Popup
		popupId = $(this).attr('id').replace('Link','Popup');
		var $popup = $('#'+popupId)
			.prepend($(this).filter('.detailCaret').length < 1 ? '<div class="detailCaret"></div>' : '');

		// get position and dimensions of link and popup
		var position = $(this).position();
		var x = position.left;
		var y = position.top;
		var h_link = $(this).outerHeight();
		var w_link = $(this).outerWidth();
		var w_popup = $popup.outerWidth();

		// set relative position of popup
		if ($(this).hasClass('popupBelow')) {
			x = x + (w_link / 2) - (w_popup / 2);
			y = y + h_link + 8;
			$popup.addClass('popupBelow');
			
			//position caret halfway across popup
			$('.detailCaret').css({'left':w_popup/2 - 8});
		} else {
			// popupup left (default)
			x = x + w_link + 10;
			y = y - (h_link / 2) - 6;
		}
	
		// display popup at same position after hover
		setTimeout(function(){
			if (detaillink_hover) {
				// hide other popups
				$('.detailPopup').fadeOut(fade_time);
				// show intended popup
				$popup.css({'left':x,'top':y}).fadeIn(fade_time);
			}
		},hover_time);

		// fallback click anywhere incase it hangs
		$('body').click(function(event){
			if(!$(event.target).is('.detailLink')) {
				$popup.fadeOut(fade_time);
			}
		});
	}).mouseleave(function(){
		// set location variable for reference in other event handlers
		detaillink_hover = false;

		// fade out popup if the mouse is not on the popup or link
		setTimeout(function(){
			if (!detailpopup_hover && !detaillink_hover) {
				$('.detailPopup').fadeOut(fade_time);
			}
		},hover_time);
	});

	$('.detailPopup').mouseover(function(){
		// set location variables to check later on mouseleave
		detailpopup_hover = true;
		detaillink_hover = false;
	}).mouseleave(function(){
		// set location variable for reference in other event handlers
		detailpopup_hover = false;

		// fade out popup if the mouse is not on the popup or link
		setTimeout(function(){
			if (!detaillink_hover && !detailpopup_hover) {
				$('.detailPopup').fadeOut(fade_time);
			}
		},hover_time);
	});

/* }}} */

});

