if(jQuery) (function($){
	
	$.extend($.fn, {
		cleverBubble: function(o, h) {
			// Defaults
			if( !o ) var o = {};
			if( o.fade_out_delay === undefined ) o.fade_out_delay = 500;
			if( o.fade_in_delay === undefined ) o.fade_in_delay = 1000; 
			if( o.url === undefined ) o.url = "/cleverbubble_callback";
			
			var t = $(this);
			
			var bubble;
			
			var item;
			
			function on_hover()
			{
			
				item = $(this);
			
				var entity_id = item.attr("rel");
				
				bubble.oneTime(o.fade_in_delay, "bubble", function() {
				
					var post_data = {
						id: entity_id
					};
				
					$.ajax({
						success: ajax_success,
						error: ajax_error,
						url: o.url,
						data: post_data,
						type: "POST"
					});
				
				});
				
				item.addClass("hover");
			
			}
			
			function ajax_success(data, textStatus, XMLHttpRequest)
			{
			
				var offset = item.offset();
			
				bubble.find(".content").html(data);
			
			
				bubble.css({
						left: offset.left -18,
						top: (offset.top - bubble.outerHeight() - 20)
				}).stop().fadeIn();
			
			}
			
			function ajax_error(XMLHttpRequest, textStatus, errorThrown)
			{
				//todo handle cleverbubble ajax errors	
			}
			
			
			
			function on_out()
			{
				
				item.removeClass("hover");
				
				bubble.stopTime("bubble");

				bubble.oneTime(o.fade_out_delay, function() {
					if (!bubble.hasClass("hover"))
						bubble.fadeOut();
				});
			}
			
			function init()
			{
			
				t.hover(on_hover, on_out);
				
				bubble = $("<div>").attr("id", "cleverbubble").html('<div class="content"></div><div class="pointer"></div>');
				
				bubble.appendTo("body").hide();
			
				bubble.hover(function(){
					bubble.addClass("hover");	
				}, function(){
					bubble.removeClass("hover");
					bubble.stop().fadeOut();
				});
			
			}
			
			
			
			init();		
			
		}
	});
	
})(jQuery);
