var decalX = 15, decalY = 15;
function RECT() {
    this.Left = 0;
    this.Top = 0;
    this.Bottom = 0;
    this.Right = 0;
}
var init = function() {
	$("body").append("<div id=\"hint\"></div>");
    $(".listener").mousemove(mouseOverHandler).mouseout(mouseOutHandler);
};

var mouseOverHandler = function(e) {
    var hint = $("#hint");
    if (hint.is(":hidden") || hint.html() == "") {
        var source = $(this).children(".hint:first").html();
        if (hint.html() != source)
            hint.html(source);
    }
    var position = getPosition(hint, e.pageX + decalX, e.pageY + decalY);
    hint.css("left", position.x + "px").css("top", position.y + "px");
    if (hint.is(":hidden"))
        hint.show();
        //hint.show();
    
};

var mouseOutHandler = function() {
    var hint = $("#hint");

    if (hint.is(":visible")) {
        //if (hint.css("visibilty") == "visible")
        hint.hide().html("");
        //hint.html("");
    }
};

var getPosition = function(hint, x, y) {
    var initialY = y, initialX = x;
    var clientRect = new RECT();
    with (clientRect) {
        Left = $(window).scrollLeft();// - target.offset().left;
        Top = $(window).scrollTop();// - target.offset().top;
        Right = Left + $(window).width();
        Bottom = Top + $(window).height();
        var maxX = 0, maxY = 0;
        maxX = Right - hint.width() - decalX;
        maxY = Bottom - hint.height() - decalY;

        if (x > maxX) {
            if (Math.abs(x - Left) > Math.abs(x - Right))
                x = initialX - hint.width() - 2 * decalX;
            else
                x = maxX;
            if (x < Left)
                x = Left;
        }

        if (y > maxY) {
            if (Math.abs(y - Top) > Math.abs(y - Bottom))
                y = initialY - hint.height() - 2 * decalY;
            else
                y = maxY;
            if (y < Top) {
				if (x < Left)
	                y = Top;
				else
					y = initialY;
			}
        }

    }
    var result = new Object();
    result.x = x;
    result.y = y;
    return result;
};

$(document).ready(init);
