$(function(){
	$.extend({
		// wether there's an ajax request going on
		ajax_on:    false	
	});
	$.fn.extend({
		tooltip: function(opts){
			var obj = this;
			obj.ajax_on = false;
			var defaults = {};
			defaults.effect_time = 300;
			// this class is used to close opened tooltips
			defaults.cssclass_shown = 'js_tooltip_netscience';
			defaults.cssclass_loading = 'ajax_box_loading';
			
			// merge options with defaults
			opts = $.extend({}, defaults, opts);	
			
			if(typeof opts.sourceurl == 'undefined') return false;
			
			this.each(function(){
				var tooltip_id = 'tooltip_' + opts.id_type_object + '_' + $(this).attr('rel');
				
				$(this).hover_pointer();
				
				$(this).click(function(event){
					var trigger = $(this);
					
					// hides previously-opened tooltips
					$('.' + opts.cssclass_shown).hide();
					
					// tooltip already created for this link, just show it
					if($('#' + tooltip_id).length != 0){
						$('#' + tooltip_id).bind_to_mousepos(event);					
						$('#' + tooltip_id).fadeIn(opts.effect_time);
						return;
					}

					var tooltip = $(document.createElement('div'));
					tooltip.attr('id', tooltip_id);
					tooltip.addClass(opts.cssclass_shown);
					tooltip.bind_to_mousepos(20, undefined, event);
					$('body').append(tooltip);	
					var tooltip = $('#' + tooltip_id);
					
					$.ajax({
						url: 		opts.sourceurl,
						context:	document.body,
						data: 		{ 
						    id_type_object: opts.id_type_object, 
						    id_object: trigger.attr('rel'),
							id_ract: opts.id_ract
					    },
					    contentType: 'application/x-www-form-urlencoded; charset=utf-8',		
						dataType: 	'html',
						beforeSend: function(){ 
							if($.ajax_on) return false; 
							$.ajax_on = true; 
							return true;
						},
						success: function(data){ 
							$.ajax_on = false; 
							if(typeof opts.cssclass == 'string') tooltip.addClass(opts.cssclass);
							tooltip.append(data); 
							// add a click event to the close tooltip link, if any
							if($('.js_tooltip_close', tooltip).length > 0){
								$('.js_tooltip_close').click(function(){ tooltip.hide(); });
							}	
							
							tooltip.prepend(close);
						}							
					});						
				});
			});
		}
	});
});
