// Tooltip object holder.
var tooltips = new Array();
var toolkeys = new Array();

function tooltip ( id, tooltip )
{
	this.id = id;
	this.elementId = tooltip;

	this.loaded = false;
	this.text = '';
	this.tooltip = '';
	this.visible = false;

	// Hook events and tipsy to the DOM element.
	this.hook = function()
	{
		$j('#'+this.elementId).tipsy({
			fallback: 'Loading...',
			html: true,
			trigger: 'manual',
			gravity: $j.fn.tipsy.autoNSWE 
		});

		$j('#'+this.elementId).mouseenter( function()
		{
			tooltips[ $j(this).attr('id') ].show();
		});
		
		$j('#'+this.elementId).mouseleave( function()
		{
			tooltips[ $j(this).attr('id') ].hide();
		});
		$j('#'+this.elementId).click( function(event)
		{
			event.PreventDefault();
		});
	};

	this.show = function()
	{
		if( this.loaded == false )
		{
			this.load();
		}
		this.visible = true;
		$j( '#'+this.elementId ).tipsy("show");
	};

	this.hide = function()
	{
		this.visible = false;
		$j( '#'+this.elementId ).tipsy("hide");
	};

	// Set the tooltip and reset tipsy.
	this.setTooltip = function( tooltip )
	{
		if( this.visible )
			$j( '#'+this.elementId ).tipsy("hide");
		$j( '#'+this.elementId ).attr('original-title', tooltip );
		if( this.visible )
			$j( '#'+this.elementId ).tipsy("show");
	};

	this.parseResponse = function( id, text )
	{
		if( this.id == id )
		{
			this.setTooltip( text );
			this.loaded = true;
		}
	};

	// Request via JSONP tooltip data.
	this.load = function()
	{
		$j.getJSON( '/index.htm?Action=ajax_lookup&Mode=tooltip&TooltipId='+this.id+'&Callback=?', function( response )
		{
			if( response != undefined || response.result.id != '' )
			{
				for (i=0; i<toolkeys.length; i=i+1)
				{
					key = toolkeys[i];
					if (typeof(tooltips[key]) == "object")
						tooltips[key].parseResponse( response.result.id, response.result.tooltip );
				}
			}
		});
	};
	// Begin the magic.
	this.hook();
}

$j(document).ready( function()
{
	// Search for tooltips
	$j(".tooltip").each(function()
	{
		var classList = $j(this).attr('class').split(/\s+/);
		var TTElement = $j(this).attr('id');
		$j.each( classList, function(index, item)
		{
			var id = item.match(/^tooltip\_id\_([A-z]+)/);
			if( id != null )
			{
				if( id[1] != undefined )
				{
					if( tooltips[ TTElement ] == undefined )
					{
						// Create a new tooltip object.
						tooltips[ TTElement ] = new tooltip( id[1], TTElement );
						toolkeys.push(TTElement);
					}
				}
			}
		});
	});
});

