/// <reference path="../Elements.ts" />
module Elements.HoverInfo {
    var hoverbox = document.getElementById("hoverInfo");
    var contentTarget = document.getElementById("hoverContent");
    var width = 0;
    var height = 0;

    function empty () {
        while (contentTarget.firstChild != undefined) {
            contentTarget.removeChild(contentTarget.firstChild);
        }
    }

    export function makeHoverable (element : Element, contents : Array<Element | Text>) {
        element.addEventListener("mouseenter", (e : MouseEvent) => {
            Elements.HoverInfo.hoverStart(e, contents);
        });

        element.addEventListener("mousemove", (e : MouseEvent) => {
            Elements.HoverInfo.hoverMove(e);
        });

        element.addEventListener("mouseout", (e : MouseEvent) => {
            Elements.HoverInfo.hoverEnd();
        });
    }

    export function hoverStart (e : MouseEvent, contents : Array<Element | Text>) {
        empty();
        for (let i = 0; i < contents.length; i++) {
            contentTarget.appendChild(contents[i]);
        }
        hoverbox.style.display = "block";


        hoverbox.style.left = "0px";
        hoverbox.style.top = "0px";
        width = hoverbox.offsetWidth;
        height = hoverbox.offsetHeight;

        hoverMove(e);
    }

    export function hoverMove (e : MouseEvent) {
        let left = e.clientX - (width/2);
        let top = e.clientY - (height) - 6;

        if (top < 0) {
            top = e.clientY + 6;
        }

        if (left < width) {
            left = width;
        }

        // Width seems to not be considering the border, even though we applied border-box
        // I don't care enough to figure this out so there's a margin on the side!
        if (left + width > Elements.screenWidth) {
            left = Elements.screenWidth - width;
        }

        hoverbox.style.left = Math.round(left) + "px";
        hoverbox.style.top = Math.round(top) + "px";
    }

    export function hoverEnd () {
        hoverbox.style.display = "none";
    }
}