var timerID = 0;
var tStart  = null;

function activatePopup(element, tag) {
    showLayer(element, tag);
    startTimer();
}

function destroyPopup() {
    stopTimer();
    hideLayer();
}

function getPageCoords (element) {
    var coords = { x: 0, y: 0 };

    while (element) {
        coords.x += element.offsetLeft;
        coords.y += element.offsetTop;
        element = element.offsetParent;
    }

    return coords;
}

function showLayer(element, tag) {
    var layer = document.getElementById('popup-layer');
    layer.style.visibility = 'visible';

    var link = layer.getElementsByTagName('a');

    for (var i = 0; i < link.length; i++) {
        if (link[i].className == 'link-wikipedia') {
            link[i].href = "http://en.wikipedia.org/wiki/" + tag;
        }

        if (link[i].className == 'link-google') {
            link[i].href = "http://www.google.com/search?q=" + tag;
        }

        if (link[i].className == 'link-webster') {
            link[i].href = "http://www.webster.com/cgi-bin/dictionary?va=" + tag;
        }

    }

    var coords = getPageCoords(element);

    layer.style.top  = coords.y + 20 + 'px';
    layer.style.left = coords.x + 20 + 'px';
}

function hideLayer() {
    document.getElementById('popup-layer').style.visibility = 'hidden';
}

function startTimer() {
    tStart = new Date();
    timerID = setTimeout("updateTimer()", 100);
}

function updateTimer() {
   if(timerID) {
      clearTimeout(timerID);
      clockID  = 0;
   }

   if(!tStart)
      tStart = new Date();

   if (new Date().getTime() - tStart.getTime() > 500) {
       destroyPopup();
   }

   timerID = setTimeout("updateTimer()", 100);
}

function stopTimer() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }

   tStart = null;
}
