var _popupFrames = [];
var _popupInfo = new Object();

function PopupInfo(id, name, width, height, fn)
{
    _popupInfo[cleanName(name)] = this;
    this.id = id;
    this.name = name;
    this.width = width;
    this.height = height;
    if (typeof fn == "string")
    {
        this.filename = fn;
    } else {
        this.filename = name;
    }
}

function makePopup(id, name, width, height, filename)
{
    return new PopupInfo(id, name, width, height, filename);
}

function highlightPopups()
{
    var spans = findChildrenByClass(document.body, "popupTerm");
    for (var i = 0; i < spans.length; i++)
    {
        var node = spans[i];
        node.popupType = "terms";
        node.onclick = popupFrame;
    }

    var spans = findChildrenByClass(document.body, "popupSource");
    for (var i = 0; i < spans.length; i++)
    {
        var node = spans[i];
        node.popupType = "sources";
        node.onclick = popupFrame;
    }

    var spans = findChildrenByClass(document.body, "popupLarge");
    for (var i = 0; i < spans.length; i++)
    {
        var node = spans[i];
        node.popupType = "large";
        node.onclick = popupFrame;
    }

	var spans = findChildrenByClass(document.body, "popupVideo");
    for (var i = 0; i < spans.length; i++)
    {
        var node = spans[i];
        node.popupType = "video";
        node.onclick = popupFrame;
    }
}

function popupFrame(type)
{
    var type = this.popupType;
    var name;

	var images = this.getElementsByTagName("img");
    if (images.length < 1)
	{
        var text = this.innerText || this.textContent || htmlDecode(this.innerHTML);
        name = cleanName(text);
    } else {
		var src = images.item(0).src;
		var dot = src.lastIndexOf('_');
		var slash = src.lastIndexOf('/');
		name = cleanName(src.substring(slash+1, dot));
    }
    var info = _popupInfo[name];
	if (info == null)
	{
		return;
	}
    var left = window.screenLeft || window.screenX;
    var top = window.screenTop || window.screenY;
    if (!_isMac)
    {
        closeChildFrames();
    }
    var win = window.open("../popups/"+type+"/"+info.filename+".html","popupFrame","alwaysRaised=yes,left="+left+",top="+top+",width="+info.width+",height="+info.height+",resizable,scrollbars=no");
    if (!win)
    {
        return null;
    }
    _popupFrames[_popupFrames.length] = win;
	win.focus();

    return win;
}

function closeChildFrames()
{
    for (var i = 0; i < _popupFrames.length; i++)
    {
        var win = _popupFrames[i];
        if (win && !win.closed)
        {
            win.close();
        }
    }
    _popupFrames = [];
}

runOnLoad(highlightPopups);
runOnUnload(closeChildFrames);

