$(document).ready(function() {
    //Tooltips
    $(".tip_trigger").hover(function(){
        tip = $(this).find('.tip');
        tip.fadeIn(); //Show tooltip
    }, function() {
        tip.fadeOut(); //Hide tooltip
    }).mousemove(function(e) {
        var mousex = e.pageX + 0; //Get X coodrinates
        var mousey = e.pageY + 0; //Get Y coordinates
        var tipWidth = tip.width(); //Find width of tooltip
        var tipHeight = tip.height(); //Find height of tooltip

        //Distance of element from the right edge of viewport
        var tipVisX = $(window).width() - (mousex + tipWidth);
        //Distance of element from the bottom of viewport
        var tipVisY = $(window).height() - (mousey + tipHeight);

        if ( tipVisX < 0 ) { //If tooltip exceeds the X coordinate of viewport
            mousex = e.pageX - tipWidth - 0;
        } if ( tipVisY < 0 ) { //If tooltip exceeds the Y coordinate of viewport
            mousey = e.pageY - tipHeight - 0;
        }
        //Absolute position the tooltip according to mouse position
        tip.css({  top: mousey, left: mousex });
    });
});
