/* require jQuery */
function getNewY(e, imgHeight) {
        var newY = e.pageY;
        var margin = 0.1;
                    
        if (e.clientY < 0.5*$(window).height()) {
            // below
            newY = e.pageY;
            // not under screen bottom
            if (e.clientY + imgHeight > (1-margin)*$(window).height()) {
                newY = newY - (e.clientY+imgHeight-(1-margin)*$(window).height());
            }
        } else {
            // above
            newY = e.pageY-imgHeight;
            // not above screen top
            if (e.clientY < imgHeight + margin*$(window).height()) {
                newY = newY + (imgHeight - e.clientY+margin*$(window).height());
            }
        }
        return newY;
}
    
    // FIXME Use a generic function instead of copying/modifying getNewY()
function getNewX(e, imgWidth) {
        var newX = e.pageX;
        var margin = 0.1;
                    
        if (e.clientX < 0.5*$(window).width()) {
            // below
            newX = e.pageX;
            // not under screen bottom
            if (e.clientX + imgWidth > (1-margin)*$(window).width()) {
                newX = newX - (e.clientX+imgWidth-(1-margin)*$(window).width());
            }
        } else {
            // above
            newX = e.pageX-imgWidth;
            // not above screen top
            if (e.clientX < imgWidth + margin*$(window).width()) {
                newX = newX + (imgWidth - e.clientX+margin*$(window).width());
            }
        }
        return newX;
}

$(document).ready(function(){
        $(".mouseoverpopup").hover(
            function(e) {               
                var imgHeight = $(this).find("span").height();
                var imgWidth = $(this).find("span").width();
                
                if (      imgHeight < 0.8*$(window).height()
                     && imgWidth < 0.8*$(window).width()) {
                    $(this).find("span").fadeIn(1000);
                    
                    var newY = getNewY(e, imgHeight);
                    var newX = getNewX(e, imgWidth);
                    
                    $(this).find("span").css( { 'left' : newX, 'top': newY} );
                }
            },
            function() {
                $(this).find("span").fadeOut(500);
            });
            
        $(".mouseoverpopup").mousemove(
            function(e) {
                var imgHeight = $(this).find("span").height();
                var imgWidth = $(this).find("span").width();
                
                if (      imgHeight < 0.8*$(window).height()
                     && imgWidth < 0.8*$(window).width()) {
                    $(this).find("span").fadeIn(2000);
                    
                    var newY = getNewY(e, imgHeight);
                    var newX = getNewX(e, imgWidth);
                    
                    $(this).find("span").css( { 'left' : newX, 'top': newY} );
                }
            });
});
