var tipDIVs = [];

// usage: onmouseover|onclick = sparkTip(event, '<p>HTML</p>')
var sparkTip = function (e,content) {
	
	// Get the element of the event callback
	var el = e.target ? e.target : e.srcElement;
		
	// Assign a unique id
	this.uid = function(){var d=new Date;return d.getTime();}
	if (!el.id) el.id = this.uid();
	
	// Each tip has it's own div
	var tipDIV;	var isOn = 0;
	if (typeof tipDIVs[el.id] == 'undefined') {
		tipDIV = document.createElement('div');
		tipDIV.className = 'tip';
		tipDIV.style.display = 'none';
		document.body.appendChild(tipDIV);
		tipDIVs[el.id] = tipDIV;
	}
	else {
		tipDIV = tipDIVs[el.id];
		isOn = 1; // The tip already exists, so it's on
	}
	
	// Hide the tip
	this.destroy = function() {
		document.body.removeChild(tipDIV);
		delete tipDIVs[el.id];
				
		// Delete callbacks to this function
		if(el.onmouseout==arguments.callee||el.onkeydown==arguments.callee) el.onmouseout = el.onkeydown = null;
		if(window.onscroll==arguments.callee||window.onresize==arguments.callee) window.onscroll = window.onresize = null;
		
	}
		
	// Display tip (position on screen)
	this.display = function() {
		wXY = getWindowXY();
		tipDIV.style.top = tipDIV.style.right = tipDIV.style.bottom = tipDIV.style.left = 'auto';		

		// display right or left?
		if (wXY[0]-e.clientX>440)
			tipDIV.style.left = e.clientX+12+'px';
		else
			tipDIV.style.right = wXY[0]-e.clientX+'px';
			
		// display below or above?
		if (e.clientY > wXY[1]/2)
			tipDIV.style.bottom = wXY[1]-e.clientY+6+'px';
		else
			tipDIV.style.top = e.clientY+12+'px';
			
		tipDIV.innerHTML = content;
		tipDIV.style.display = 'block';
	}

	// Action/callback depends on event type
	switch (e.type) {
		
		case 'mouseover':
			el.onmouseout = el.onkeydown = this.destroy;
			this.display();
			break;
		
		case 'click':
			if (!isOn) {
				window.onscroll = window.onresize = this.destroy;
				this.display();
			}
			else {
				this.destroy();
			}
			
			break;
			
		default:
			alert('Event not defined: '+e.type);
	}

}

function getWindowXY() {
	if (self.innerHeight)
		return [self.innerWidth,self.innerHeight];
	if (document.documentElement && document.documentElement.clientHeight) 
		return [document.documentElement.clientWidth,document.documentElement.clientHeight];
	if (document.body) 
		return [document.body.clientWidth,document.body.clientHeight];
}

