var regexp = /^https?:\/\/(www\.)?wegame\.com\/games\/(\w+)/i; // For production use.
//var regexp = /\/games\/(\w+)/i; // For localhost only.
var timeoutId = 0;
window.onload = grabLinks();
function grabLinks() {
    for(var i = 0; i < document.links.length; i++) {
        if(document.links[i].href.match(regexp)) {
            document.links[i].onmouseover = function(e) { handleHover(e, this); };
            document.links[i].onmouseout = function() { destroyWG(); };
        }
    }
};

function handleHover(e, link) {
    var tmp = regexp.exec(link.href);
    var game = tmp[tmp.length - 1];
    var gameIframe = document.createElement("iframe");
    var mouse = findMouse(e);
    gameIframe.src = "http://www.wegame.com/widgets/tooltip/"+game+"/";
    gameIframe.style.top = mouse[1]+5+"px";
    gameIframe.style.left = mouse[0]+5+"px";
    gameIframe.style.zIndex = 100000;
    gameIframe.style.position = "absolute";
    gameIframe.width = '257px';
    gameIframe.height = '211px';
    gameIframe.name = "wgiframe";
    gameIframe.id = "wgiframe";
    gameIframe.scrolling = "no";
    gameIframe.onmouseover = function() { haltDestroy(); };
    gameIframe.onmouseout = function() { destroyWG(); };
    document.body.appendChild(gameIframe);
}

function destroyWG() {
    timeoutId = setTimeout('removeWG();', 500);
}

function removeWG() {
    var wgIframe = document.getElementById("wgiframe");
    if(wgIframe)
        document.body.removeChild(wgIframe);
    window.focus();
}

function haltDestroy() {
    clearTimeout(timeoutId);
}

function findMouse(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return Array(posx, posy);
}