Tooltip = function(){
	var tooltips = {};
	var x_offset = 5; //the offset of the tooltip to the mouse pointer (can't be zero)
	var y_offset = 2;
	var show_speed = 200; //the speed in which the tooltip shows up in milliseconds
	var timeouts_on ={};
	var timeouts_off ={};
	var target_element_class = 'tooltip_target_element';
	
	function initialize(){
		//scrape the site and bind the elements
		tooltip_array = $$('[class|=tooltip]');
		if(tooltip_array){
			for(var i=0;i < tooltip_array.length;i++){
				//first get the id of the tooltip itself
				var element_id = null;
				var tooltip = tooltip_array[i];
				splitted = tooltip.classNames().toArray()[0].split('-');
				splitted.shift();
				element_id = splitted.join('-');
				bind_element(element_id, tooltip);
			}
		}
	}
	
	function observe_element(element){
		var element_id = element.readAttribute('id');
		var mouse_x = null;
		var mouse_y = null;
		//mouseover
		element.observe('mouseover',function(e){
			var tooltip = get_tooltip_from_event(e);
			if(tooltip){
				if(timeouts_off[element_id]){ clearTimeout(timeouts_off[element_id]);}
				if(timeouts_on[element_id]){ clearTimeout(timeouts_on[element_id]); }
				timeouts_on[element_id] = setTimeout(function(){
					timeouts_on[element_id] = null;
					show(tooltip);
				},show_speed);
			}
		});
		//mouseout
		element.observe('mouseout', function(e){
			var tooltip = get_tooltip_from_event(e);
			clearTimeout(timeouts_on[element_id]);
			if(tooltip){
				if(timeouts_off[element_id]){ clearTimeout(timeouts_off[element_id]); }
				timeouts_off[element_id] = setTimeout(function(){
					timeouts_off[element_id] = null;
					tooltip.setStyle({display: 'none'});
				},5);
			}
		});
		
		//mousemove
		element.observe('mousemove', function(e){
			var tooltip = get_tooltip_from_event(e);
			mouse_x = e.pointerX();
			mouse_y = e.pointerY();
			if(tooltip && tooltip.visible()){
				position_tooltip(tooltip,mouse_x, mouse_y);
			}
		});
		
		function show(tooltip){
			position_tooltip(tooltip,mouse_x, mouse_y);
			tooltip.setStyle({display:'block'});
		}
	}
	
	function get_tooltip_from_event(e){
		var target = Event.element(e);
		if(!target.hasClassName(target_element_class)){
			target = target.up('.'+target_element_class);
		}
		var tooltip_id = tooltips[target.readAttribute('id')];
		return $(tooltip_id);
	}
	
	function position_tooltip(tooltip, x, y){
		//TODO:! need to flip it when we get to the bottom and top of the screen
		tooltip.setStyle({top:(y+y_offset)+'px',left:(x+y_offset)+'px' });
	}
	
	function bind_element(element_id, tooltip){
		if(element_id){
			var element = $(element_id);
			if(element){
				element.addClassName(target_element_class);
				//keep track of the elements we have tooltips for
				tooltips[element_id] = tooltip.readAttribute('id');
				observe_element(element);
			}
		}
	}
	
	this.bind_element = bind_element;
	initialize();
};

var tooltip = new Tooltip();
