/*
 * Tooltip JS
 */
ToolTip = Class.create({
	initialize : function(options) {
		
		this.items		= $$('.tooltip');										// All potential elements being able to kick off a tooltip
		this.options	= options;		// Options for the tooltip
		this._title		= '';													// TMP container for title tags to supress browser's tooltips
		var helper		= this;													// Cannot be called self because IE likes to fuck up...
		
		// Apply events on all elements found
		this.items.each(function(element) {
			
			element.observe('mouseover', function(event) {
				helper.mouseover(element, Event.pointer(event));
			});
			
			element.observe('mouseout', function(event) {
				helper.mouseout(element);
			});
		});
	},
		
	create : function(position) { 
		
		$$('body').each(function(element) {
			element.insert({ 'top' : '<div id="tooltip" style="display: none; z-index:10000"></div>'});
		});
		this.move(position);
	},
	
	destroy : function() { 
		
		$$('body')[0].stopObserving('mousemove');
		$$('#tooltip')[0].remove();
		
	},
	
	show : function(content, position) {
	
		this.create(position);
		$$('#tooltip')[0].update(content);
		this.follow();
		$$('#tooltip')[0].show();
		
	},
	
	close : function() {
		
		var t=$$('#tooltip');
        "0" in t?t[0].hide() :0;
		this.destroy();
		
	},
		
	mouseover : function(item, position) {
		
		this._title	= item.title
		item.title	= '';
		this.show(this._title, position);
		
	},
		
	mouseout : function(item) {
		
		this.close();
		item.title	= this._title;
		
	},
	
	follow : function() {
		
		var helper = this;
		$$('body')[0].observe('mousemove', function(event) {
			
			helper.move(Event.pointer(event));
			
		});
		
	},
	
	move : function(position) {
		
		offset 	= 15;
		offsetX	= offset;
		offsetY	= offset;
		
		tollerance	= 10;	// How much space can be between tooltip and viewport border before moving the element?
		
		// Check if our tooltip is out of the viewport
		if((position.x + $$('#tooltip')[0].getWidth() + offset + tollerance) >= document.viewport.getWidth()) {
		
			// Yes it is! Put the tooltip left to the cursor by altering our offset
			offsetX = offset - (2 * offset) - $$('#tooltip')[0].getWidth();
			
		}
		else {
			offsetX = offset;
		}
		// Position our tooltip
		$$('#tooltip')[0].style.left	= position.x + offsetX + "px";
		$$('#tooltip')[0].style.top		= position.y - offsetY + "px";
		
	}
});

if(typeof(ToolTip) != "object") {
    document.observe('dom:loaded', function() {
        ToolTip		= new ToolTip();
    });
}
