/**
 * Another tooltips JS
 */
Handler.add(window, "load", enableTooltipLinks);

var delay;

function enableTooltipLinks() {
    // get all links that have tooltip class
    var links = getElementsByClass('tooltip', document, 'a');

    // associate event handlers with all of them
    each(links, addTooltipEventHandlers);

    // add an invisible tooltip div at the end of document
    var image = document.createElement('div');
    image.id='tooltip-image';
    image.className='hidden-tooltip-image';

    var body = document.getElementsByTagName('body')[0];
    body.appendChild(image);
}

function addTooltipEventHandlers(link) {
    Handler.add(link, 'mouseover', delayShowTooltip);
    Handler.add(link, 'mouseout', delayHideTooltip);
}

function delayShowTooltip(event) {
    clearDelays();

    // get the link element that initiated the event
    // if the event source is image,
    // then grab the link that contains this image.
    var link = event.target;
    if (link.tagName.toLowerCase() == 'img') {
        link = link.parentNode;
    }

    // get the tooltip element
    var tooltip = document.getElementById('tooltip-image');

    // create new image element and place it inside tooltip
    var img = document.createElement('img');
    tooltip.appendChild(img);

    // use link target as the image source, but add a scaling parameter
    img.src = link.href;

    // place the tooltip to a position relative to link
    var pos = findPos(link);
    tooltip.style.left = "0px";
    tooltip.style.top = (pos[1] - 50) + "px";

    // make the tooltip visible
    tooltip.className = 'visible-tooltip-image';
}

function delayHideTooltip(event) {
    clearDelays();
    delay = setTimeout(hideTooltip, 250);
}

function hideTooltip() {
    var tooltip = document.getElementById('tooltip-image');
    tooltip.className = 'hidden-tooltip-image';
}

function clearDelays() {
    if (delay) {
        clearTimeout(delay);
    }

    // hide the tooltip
    var tooltip = document.getElementById('tooltip-image');
    tooltip.className = 'hidden-tooltip-image';

    // remove old image inside tooltip if it exists
    var images = tooltip.getElementsByTagName('img');
    if (images.length > 0) {
        tooltip.removeChild(images[0]);
    }
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}