/* Copyright (c) 2009-2010, Experion Inc.  All rights reserved. */

function setInnerText(elem, text)
{
	if (typeof elem == 'string') { elem = document.getElementById(elem); }
	if (typeof elem.innerText != 'undefined')
	{
		// IE
		if (text === '') { text = ' '; }
		elem.innerText = text;
	}
	else
	{
		elem.textContent = text;
	}
}

function FancyTip(elem, text, popupLocation)
{
	this.anchor = elem;
	
	if (!popupLocation)	{ popupLocation = FancyTip.POPUP_NW; }
	
	YAHOO.util.Event.addListener(this.anchor, 'mouseover', this.show, this, true);
	YAHOO.util.Event.addListener(this.anchor, 'mouseout', this.onmouseout, this, true);

	this.elem = document.createElement('div');
	this.elem.className = 'fancy-tip';
	var span = document.createElement('span');
	this.elem.appendChild(span);
	if (text)
	{
		span.innerHTML = text;
	}
	else
	{
		setInnerText(span, this.anchor.title);
	}

	document.body.appendChild(this.elem);
	
	var pos = YAHOO.util.Dom.getXY(this.anchor);

	if (popupLocation == FancyTip.POPUP_NW)
	{
		this.elem.style.left = (pos[0] + this.anchor.offsetWidth + 5) + 'px';
		this.elem.style.top  = pos[1] + 'px';
	}
	else
	{
		// POPUP_SE
		this.elem.style.left   = (pos[0] - this.elem.offsetWidth - 5) + 'px';
		this.elem.style.top    = (pos[1] + this.anchor.offsetHeight - this.elem.offsetHeight) + 'px';
		this.elem.className += ' se';
	}
	
	this.elem.style.display = 'none';
	
	this.anchor.title = '';
	
    this.anim = new YAHOO.util.Anim(
            this.elem,
            { opacity: {from: 1, to: 0 } },
            0.25 /* duration */,
            YAHOO.util.Easing.easeNone);
    var _elem = this.elem;
    this.anim.onComplete.subscribe(function() {
    	if (FancyTip.fading == _elem)
    	{
    		_elem.style.display = 'none';
    		YAHOO.util.Dom.setStyle(_elem, "opacity", 1);
    	}
    });
}

FancyTip.prototype = {
    show: function() {
		if (FancyTip.fading) { 
			FancyTip.fading.style.display = 'none';
			FancyTip.fading = null;
		}
		YAHOO.util.Dom.setStyle(this.elem, "opacity", 1);
		this.elem.style.display = 'block';
	},
		
    hide: function() {
		FancyTip.fading = this.elem;			
		this.anim.animate();
	},
	
	onmouseout: function(ev) {
		// figure out if we actually left the element - see http://www.quirksmode.org/js/events_mouse.html
		var reltg = ev.relatedTarget ? ev.relatedTarget : ev.toElement;
		while (reltg  &&  reltg != this.anchor) { 
			reltg = reltg.parentNode;
		}
		if (!reltg)
		{
			this.hide();
		}
	}
};

FancyTip.fading = null;

FancyTip.POPUP_NW = 1;
FancyTip.POPUP_SE = 2;
