(function($){
$.fn.ToolTipDemo = function(bgcolour, fgcolour) {
    return $(this).mouseover(
        function(e) {
            if((!this.title && !this.alt) && !this.tooltipset)
				return;
            var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
            var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
            mouseX += 10;
            mouseY += 10;
            bgcolour = bgcolour || "#eee";
            fgcolour = fgcolour || "#000";

            // if there is no div containing the tooltip
            if(!this.tooltipdiv) {
                // create a div and style it
                var div = document.createElement("div");
				var span = $('<span>' + (this.title || this.alt) + '</span>').appendTo(div);
                this.tooltipdiv = $(div);
                $(div).css({
                    border: "1px solid #ddd",
                    padding: "2px",
                    backgroundColor: bgcolour,
                    color: fgcolour,
                    position: "absolute",
                    'z-index':999
                });
                // add the title/alt attribute to it
                this.title = "";
                this.alt = "";
                $("body").append(div);
                this.tooltipset = true;
				this.wi = span.width();
				this.hi = this.tooltipdiv.height();
            }
            this.wi = Math.max(100, Math.min(this.wi, 400));
			
            this.tooltipdiv.css('width', this.wi + 'px');
			var tooltip_width = this.wi + 32;

			var tooltip_height = this.hi;
			var $win = $(window);
			var winWidth = $win.width();
			var winScrollLeft = $win.scrollLeft();
			var winHeight = $win.height();
			var winScrollTop = $win.scrollTop();
			mouseX = (winWidth < (tooltip_width + mouseX)) ? (mouseX - (Math.min(tooltip_width, (tooltip_width + mouseX)-(winWidth+winScrollLeft)))) : mouseX;
			mouseY = (winHeight < (tooltip_height + mouseY-winScrollTop + 8)) ? (mouseY - 2*tooltip_height - 7) : mouseY + 3;

            this.tooltipdiv.show().css({left: mouseX + "px", top: mouseY + "px"});
        }
    ).mouseout( function() {
            if(this.tooltipdiv) {
                this.tooltipdiv.hide();
            }
        }
    );
}
})(jQuery);
