(function($){
	
	$.fn.tooltip = function(input)
	{
		if(input === undefined || input === null) {
			input = {};
		}
		
		if(typeof input == 'string') {
			input = { selector: input };
		}
		
		if(typeof input == 'object') {
			input = $.extend({}, $.fn.tooltip.defaults, input);
		}
		
		return this.each(function(i)
		{
			var $this = $(this);
			
			if(typeof input == 'object' && input.selector != null)
			{
				var $tooltip = $(input.selector);
				
				$this
					.mouseover(function()
					{
						if(input.before !== null) {
							input.before($this, $tooltip);
						}
						
						$tooltip.css('position', 'absolute').css('z-index', 1000).show();
					})
					.mousemove(function(e)
					{					
						var x = e.pageX + input.offsetX;
						var y = e.pageY + input.offsetY;
														
						var width = $tooltip.width();
						var height = $tooltip.height();

						y -= height / 2;
						
						var windowWidth = -1, windowHeight = -1;
					  
					  	if(typeof(window.innerWidth) == 'number') { //Non-IE
							windowWidth = window.innerWidth;
							windowHeight = window.innerHeight;
						} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { //IE 6+ in 'standards compliant mode'
							windowWidth = document.documentElement.clientWidth;
							windowHeight = document.documentElement.clientHeight;
						}
						
					  	if(windowWidth != -1) {
					  		if(e.clientX + width > windowWidth) {
					  			x = e.clientX - width - 30;
					  		}
					  	}
					
					  	if(windowHeight != -1) {
					  		while(e.clientY + (height / 2) > windowHeight) {
					  			e.clientY--;
					  			y--;
					  		}
					  	}
					
						$tooltip.css('left', x).css('top', y);
					})
					.mouseout(function()
					{
						$tooltip.hide();
						
						if(input.after !== null) {
							input.after($this, $tooltip);
						}
					});
			}
		});
	};
	
	$.fn.tooltip.defaults = {
		selector: null, // The selector of the tooltip
		offsetX: 30,
		offsetY: 0,
		before: null, // A function to call before showing the tooltip. function(item, tooltip)
		after: null // A function to call before hiding the tooltip function(item, tooltip)
	};

})(jQuery);