$(document).ready(function() {
    $(".screenshot").hover(function(e){
        $("body").append("<p id='screenshot'><img src='"+ $(this).attr("rel") +"' alt='Anteprima immagine' /></p>");
        var mousex = e.pageX + 20; //Get X coodrinates
        var mousey = e.pageY + 20; //Get Y coordinates
        var tipWidth = $("#screenshot").width(); //Find width of tooltip
        var tipHeight = $("#screenshot").height(); //Find height of tooltip
        var tipVisX = $(window).width() - (mousex + tipWidth);
        var tipVisY = $(window).height() - (mousey + tipHeight);
        if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 20;
        } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 20;
        }
        $("#screenshot").css({  top: mousey, left: mousex });		
		$("#screenshot").fadeIn(600);
		
    }, function() {
        $("#screenshot").remove();
    }).mousemove(function(e) {
        var mousex = e.pageX + 20; //Get X coodrinates
        var mousey = e.pageY + 20; //Get Y coordinates
        var tipWidth = $("#screenshot").width(); //Find width of tooltip
        var tipHeight = $("#screenshot").height(); //Find height of tooltip
        var tipVisX = $(window).width() - (mousex + tipWidth);
        var tipVisY = $(window).height() - (mousey + tipHeight);
        if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 20;
        } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 20;
        }
        $("#screenshot").css({  top: mousey, left: mousex });
    });
});

