// JavaScript Document

// Set path to load image
var _pathToLoadImage = "../../images/ajax-loader2.gif";
// set server page
var _ajaxPage = "./yearevents_ajax.php";

// Animation options
var animOptions = {
	time:250,
	hideDelay:750,
	distance:-10
};

// Tracker
var animTracker = {
	hideDelayTimer:null,
	beingShown:false,
	shown:false
};

function ib_init(domelements)
{
	$(domelements).each(function() {		
		var trigger = $(this);
			
		// set the mouseover and mouseout on trigger
		trigger.bind('mouseover',function (e) {
			hover(e,this);
		});
		trigger.bind('mouseout',function() {
      ib_hide();
    });
	});
}

function ib_show(e,obj)
{
	var posX = e.pageX;
	var posY = e.pageY;
	
	// Add box to body
	$("body").append("<div id='IB_window'></div>");
	var popup = $('div#IB_window');
	var trigger = $(obj);
		
	// reset position of popup box
	popup.css({
		'left': posX+'px',
		'top': posY+'px'
	});
	
	// Add title
	if (trigger.text() != undefined && trigger.text() !== '')
	{
		popup.append("<div id='IB_Title'>"+trigger.text()+"</div>");
	}
	// Add loading image
	popup.append("<div id='IB_content'><img src=\""+imgLoader.src+"\" alt='Loading...' /></div>");
	
	// Now animate it's opacity and position
	popup.show();
	popup.animate(
		{
		top: '-=' + animOptions.distance + 'px',
		opacity: 1
		}, 
		animOptions.time, 
		'swing', 
		function() {
			// once the animation is complete, set the tracker variables
			animTracker.beingShown = false;
			animTracker.shown = true;
			
			// Call the server page to get the content
			var content = $("#IB_content");

			content.load(
				_ajaxPage,
				{
					gid:trigger.attr('id'),
					action:'term_description'
				}
			);
		}
	);
	
	// bin mouseover / mouseout event
	popup.bind('mouseover',function(e) {
		hover(e,obj);
	});
	popup.bind('mouseout',function () {
  	ib_hide();
	});
}

function ib_hide()
{
	if (animTracker.hideDelayTimer) clearTimeout(animTracker.hideDelayTimer);
	
	if (animTracker.shown == false){
		return;
	}
	else
	{
		var popup = $('div#IB_window');
		// store the timer so that it can be cleared in the mouseover if required
		animTracker.hideDelayTimer = setTimeout(function () {
			animTracker.hideDelayTimer = null;
			popup.animate({
				top: '-=' + animOptions.distance + 'px',
				opacity: 0
			}, animOptions.time, 'swing', function () {
				// once the animate is complete, set the tracker variables
				animTracker.shown = false;
				// hide the popup entirely after the effect (opacity alone doesn't do the job)
				popup.hide();
				popup.remove();
			});
		}, animOptions.hideDelay);
	}
}

function hover(e,obj)
{
	// stops the hide event if we move from the trigger to the popup element
	if (animTracker.hideDelayTimer) clearTimeout(animTracker.hideDelayTimer);
	
	// don't trigger the animation again if we're being shown, or already visible
	if (animTracker.beingShown || animTracker.shown) 
	{
		return;
	} 
	else 
	{
		animTracker.beingShown = true;
		
		ib_show(e,obj);
	}
}
