var lastTooltip = null;
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(element, content)
	{ 
		var defaults = {
			offset: 20,
			delay: 200,
			keepOpen: false,
			className: 'tooltip',
			activate: 'mousemove',
			deactivate: 'mouseout',
			appendTo: document.getElementsByTagName('body')[0],
			remote: false
		};
		this.options = Object.extend(defaults, arguments[2] || {});
		this.element = $(element);
		var tooltip = element + '_tooltip';
		if(!$(tooltip))
		{
			var tt = document.createElement("div");
			tt.id = tooltip
			tt.className = this.options.className;
			tt.style.display = 'none';
			this.options.appendTo.appendChild(tt);
		}	
		this.tooltip = $(tooltip);
		this.content = content;
		this.contentLoaded = false;
		this.showTooltipListener = this.show.bindAsEventListener(this);
		this.hideTooltipListener = this.hide.bindAsEventListener(this);
		Event.observe(this.element, this.options.activate, this.showTooltipListener);
		if(this.options.deactivate != false)
		{
			Event.observe(this.element, this.options.deactivate, this.hideTooltipListener);
		}
		this.visible = false;
		this.fullPageSize = getPageSize();
	},
	
	stop: function(e)
	{		
		Event.stopObserving(this.element, this.options.activate, this.showTooltipListener);
		if(this.options.deactivate != false)
		{
			Event.stopObserving(this.element, this.options.deactivate, this.hideTooltipListener);
		}
	},
	
	show: function(e)
	{
		if(this.contentLoaded == false)
		{
			if(this.options.remote == true)
			{
				new Ajax.Updater(this.tooltip, this.content, {asynchronous: true, evalScripts: false});
			}
			else
			{				
				this.tooltip.innerHTML = this.content;
			}	
			this.contentLoaded = true;
		}
		if(lastTooltip != null && lastTooltip != this)
		{
			lastTooltip.hide();
		}
		if(this.options.keepOpen == false)
		{		
			lastTooltip = this;
		}
		var pageX = Event.pointerX(e);
		var pageY = Event.pointerY(e);
		var scroll = getScrollingOffset();
		var pageSize = getInnerDimensions();
		var x = pageX - scroll[0];
		var y = pageY - scroll[1];
		var height = this.options.offset;
		if(y > 2 * pageSize[1] / 3)
		{
			height = -this.tooltip.getHeight() - this.options.offset;
		}
		else if(y > pageSize[1] / 3)
		{
			height = -(this.tooltip.getHeight() / 2);
		}
		if(x > pageSize[0] / 2)
		{
			this.tooltip.setStyle({
				left: 'auto',
				right: this.fullPageSize[0] - pageX + this.options.offset + 'px',
				top: pageY + height + 'px'
			});
		}
		else
		{			
			this.tooltip.setStyle({
				right: 'auto',
				left: pageX + this.options.offset + 'px',
				top: pageY + height + 'px'
			});
		}
		if(this.visible == false || (this.options.deactivate == false && !this.tooltip.visible()))
		{
			this.visible = true;
			this.tooltip.show();
		}
	},
	
	hide: function()
	{
		if(this.options.keepOpen == false)
		{
			this.tooltip.hide();
			this.visible = false;
		}
	}
};

