/*
 * Tooltip JS
 * @author Jakob Hormann <jakob.hormann@rocket-internet.de>
 */
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
		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);
			});
			
			element.observe('mouseout', function(event) {
				helper.mouseout(element);
			});
		});
	},
		
	create : function() { 
		
		$$('body').each(function(element) {
			
			element.insert({ 'top' : '<div id="tooltip" style="display: none;"></div>'});
			
		});
		
	},
	
	destroy : function() { 
		
		$$('body')[0].stopObserving('mousemove');
		$$('#tooltip')[0].remove();
		
	},
	
	show : function(content) {
	
		this.create();
		$$('#tooltip')[0].update(content);
		this.follow();
		$$('#tooltip')[0].show();
		
	},
	
	close : function() {
		
		$$('#tooltip')[0].hide();
		this.destroy();
		
	},
		
	mouseover : function(item) {
		
		this._title	= item.title
		item.title	= '';
		this.show(this._title);
		
	},
		
	mouseout : function(item) {
		
		this.close();
		item.title	= this._title;
		
	},
	
	follow : function() {
		offset 	= 15;
		offsetX	= offset;
		offsetY	= offset;
		
		tollerance	= 10;	// How much space can be between tooltip and viewport border before moving the element?
		
		$$('body')[0].observe('mousemove', function(event) {
			
			// Check if our tooltip is out of the viewport
			if((Event.pointerX(event) + $$('#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	= Event.pointerX(event) + offsetX + "px";
			$$('#tooltip')[0].style.top		= Event.pointerY(event) - offsetY + "px";
			
		});
		
	}
});