//KB.Tooltip
//
//Shows tooltip-text next to a tooltip base when a input field gets focus.
//You don't write extra script to use functionality, just include this.
//
//As a rule don't interfere with browsers "alt" and "title" rendering.
//Instead use "help" class with a inner span or div whose class is "tooltip".
//Don't use both "help" and "alt","title" attributes. 
//
//Don't hide tooltip elements in css.

$(document).observe
(
	"dom:loaded",
	function()
	{	
		$$(".tooltip-base").each
		(
			function(tooltipbase)
			{
				var inputfield=tooltipbase.down(".input-field input,.input-field textarea");
				if(!inputfield)
					return;

				var tooltiptext=tooltipbase.down(".tooltip-text");
				if(!tooltiptext)
					return;
					
				tooltiptext.setStyle({position:"absolute"}).hide().remove();
				$$("body")[0].insert(tooltiptext);
				
				var tooltipfocus=function(event){
					var tmppos=inputfield.cumulativeOffset();
					tooltiptext.setStyle({top:tmppos.top+"px",left:tmppos.left+inputfield.getWidth()+"px"}).show();
				};
				var tooltipblur=function(event){
					tooltiptext.hide();
				};
			
				inputfield.observe("focus",tooltipfocus).observe("blur",tooltipblur);
			}
		);
		//don't touch aleady present tooltips
		$$(".help:not([title]):not([alt])").each
		(
			function(tooltipcont)
			{
				//remove tooltip element from layout
				var tooltip=tooltipcont.down(".tooltip").setStyle({position:"absolute"}).hide().remove();
				$$("body")[0].insert(tooltip);
				var pos;
				var timeoutid;
				//all variables should be in the closure
				function waitnshow(event)
				{
					//just stay where you are so i can read
					if(tooltip.visible())
						return;
					pos=
					{
						top:(event.pointerY()+24)+"px",
						left:(event.pointerX()+12)+"px"
					};
					//clearTimeout doesn't bail out if timeoutid is invalid
					//reset timer if mouse moved
					clearTimeout(timeoutid);
					timeoutid=setTimeout
					(	
						function()			
						{
							tooltip.setStyle(pos).show();
						},
						1
					);
				}
				tooltipcont.observe("mouseover",waitnshow).observe("mousemove",waitnshow).observe
				(
					"mouseout",
					function()
					{
						//remove whatever action you queued
						clearTimeout(timeoutid);
						if(!tooltip.visible())
							return;
						timeoutid=setTimeout
						(	
							function()			
							{
								tooltip.hide();
							},
							300
						);
					}
				);
			}
		);
	}
);
