(function($)
{
	$.fn.flextip = function(content, settings)
	{
		if (!content)
			content = "";
			
		settings = $.extend
		(
			{
				xPadding: 15,
				yPadding: 10,
				width: null
			},
			settings
		);
		
		return this.each(function()
		{
			var tip = null;
			var $window = $(window);
			
			this.setPosition = function(e)
			{
				if (tip === null)
					return;
					
				var tipWidth = tip.width();
				var tipHeight = tip.height();
				var windowWidth = $window.width();
				var windowHeight = $window.height();
				var scrollTop = $window.scrollTop();
				
				if (!(windowWidth > tipWidth && windowWidth - e.pageX - settings.xPadding < tipWidth))
					tip.css("left", e.pageX + settings.xPadding + "px");
				else
					tip.css("left", windowWidth - tipWidth + "px");

				if (!(windowHeight > tipHeight && windowHeight + scrollTop - e.pageY - settings.yPadding < tipHeight))
					tip.css("top", e.pageY + settings.yPadding + "px");
				else if (e.pageY + tipHeight > windowHeight)
					tip.css("top", e.pageY - tipHeight - settings.yPadding + "px");
				else
					tip.css("top", e.pageY + settings.yPadding + "px");
				
				if (parseInt(tip.css("top"), 10) < scrollTop)
					tip.css("top", scrollTop + "px");
			};
			
			$(this).mouseover
			(
				function(e)
				{
					if (!this.flextipExists)
					{
						this.flextip = $("<div/>");
						tip = $(this.flextip);
						
						if (typeof content == "string")
							content = $("<div/>").text(content);

						content = $(content).clone();
						content.attr("id", content.attr("id") + "Clone");
						content.css("display", "block");
						content.css("visibility", "visible");
						tip.append(content);

						if (!tip.hasClass("flextip"))
							tip.addClass("flextip");
							
						tip.css("position", "absolute");
						if (settings.width !== null)
							tip.css("width", settings.width);
						tip.attr("id", this.id + "flextip");
						
						$("body").append(tip);
						this.flextipExists = true;
					}
					else
						tip.show();
				}
			);
			$(this).mouseover(this.setPosition);

			$(this).mouseout(function(e)
			{
				tip.hide();
				tip.css("left", "-10000px");
			});

			$(this).mousemove(this.setPosition);
		});
	};
	
	$.debug = function(obj, regex)
	{
		var result = "";

		for (var x in obj)
		{
			if (!regex || (regex && regex.test(x)))
				result += x + "\n";
		}

		return result;
	};
})(jQuery);
