(function($) {
  $.fn.tooltip = function(options) {

    var opts = $.extend({
      opacity: 0.9,
      fadeInDuration: 500,
      fadeOutDuration: 250,
      hoverIntentDelay: 150
    }, options);

    var tooltip = $("#tooltip");
    var hoverIntentTimer;
    
    
    //create the tooltip div if it does not exist
    if (tooltip.length < 1) {
      tooltip = $("<div id='tooltip' class='tooltip-container'></div>");
      $("body").append(tooltip);
    }
    
    this.live("mouseover",
      function(){      
        //store a reference to the hovered dom element
        $this = $(this);
        
        // clear any existing timer
        hoverIntentTimer = clearTimeout(hoverIntentTimer);
        
        if ($this.attr('title') !== "") {

          //clear the title attribute so the default tooltip does not show up
          $this.data('title',$this.attr('title'));
    		  $this.attr('title',"");
          
          tooltip.html("<span class='tooltip-content'>$title</span>".replace(/\$title/g,$this.data('title')));

          var left = $this.offset().left - 10; //($this.offset().left + $this.width() / 2) - tooltip.width()/2;
          var top  = ($this.offset().top + $this.height());
    
      		tooltip.stop().css({ 
    			  display : 'block',
    			  visibility: 'visible',
    			  top  : top + "px", left : left + "px"
      		}).animate({opacity: opts.opacity}, opts.fadeInDuration);
    		}
      }
    );
    this.live("mouseout",
      //on mouseout
    	function(){
    	  //store a reference to the hovered dom element
        $this = $(this);
        $this.attr('title', $this.data('title'));
        
        hoverIntentTimer = setTimeout(function() {
      		tooltip.stop().animate({opacity: 0}, opts.fadeOutDuration);
        }, opts.hoverIntentDelay);
      }
    );
    
    return this;

  };
  
  $(document).ready(function(){
    // Automatically add the tooltips
    $('.tooltip').tooltip();
  });
  
})(jQuery);


