var _defs = new Object();
var _defUid = 0;
function Definition(id, name, description)
{
    _defs[cleanName(name)] = this;
    this.id = id;
    this.name = name;
    this.description = description;
}

function makeDef(id, name, desc)
{
    return new Definition(id, name, desc);
}

function showDef()
{
    var text = this.innerText || this.textContent || htmlDecode(this.innerHTML);
    var def = _defs[cleanName(text)];
    if (!def)
    {
        return;
    }

    var box = getDefBox(def);
    box.style.width = "auto";
    if (_isMsie)
    {
        box.style.display = "inline";
    }

    box.style.left = 0;

    var thisBounds = getBounds(this);
    box.style.top = thisBounds.y + thisBounds.h + 3;

    var boxBounds = getBounds(box);
	if (_isMsie)
	{
		var mouseY = event.clientY + getScrollY();
		var boxMinY = boxBounds.y - 3;
		var boxMaxY = boxBounds.y + boxBounds.h + 3;
		if (boxMinY < mouseY && boxMaxY > mouseY)
		{
	        //box.style.top = mouseY + thisBounds.h/2 + 4;
	        box.style.top = boxBounds.y + thisBounds.h;
		}
	}

    var EDGE_PADDING = 5;
    var minBoxX = getScrollX() + EDGE_PADDING;
    var maxBoxX = getScrollX() + getWindowWidth() - EDGE_PADDING;
    if (_isGecko)
    {
        maxBoxX -= SCROLLBAR_WIDTH;
    }

    var boxX = Math.round(thisBounds.x + ((thisBounds.w - boxBounds.w) / 2));
    if (boxX < minBoxX)
    {
        boxX = minBoxX;
    }

    if (boxX + boxBounds.w > maxBoxX)
    {
        boxX = maxBoxX - boxBounds.w;
    }

    box.style.left = boxX;

    show(box);
}

function hideDef()
{
    hide(_defBox);
}

function highlightText(root)
{
    if (!root)
    {
        root = document.body;
    }
    var spans = findChildrenByClass(root, "defTerm");
    for (var i = 0; i < spans.length; i++)
    {
        var node = spans[i];
        if (!node)
        {
            continue;
        }
        node.onmouseover = showDef;
        node.onmouseout = hideDef;
    }
}

var _defOrigBounds = null;
var _defBox = null;
function getDefBox(def)
{
    if (!def)
    {
        return null;
    }

    if (!_defBox)
    {
        _defBox = document.createElement("div");
        _defBox.id = "definition";
        hide(_defBox);
        _defBox.innerHTML = "<span class=\"body\"></span>";
        document.body.appendChild(_defBox);
        if (_isMsie)
        {
            _defBox.style.display = "inline";
        }
        _defOrigBounds = getBounds(_defBox);
        hide(_defBox);
    }

    var titleDiv = findChildrenByClass(_defBox, "title")[0];
    if (titleDiv)
    {
        titleDiv.innerHTML = def.name;
    }
    var bodyDiv = findChildrenByClass(_defBox, "body")[0];
    bodyDiv.innerHTML = def.description;

    return _defBox;
}

runOnLoad(highlightText);
