var c = 0;

(function($){
  $.fn.extend({
    activetooltip: function(options) {

      var defaults = { 
        'html': null,
        'onshow': null,
        'onhide': null
      }; 
 
      var options = $.extend(defaults, options);

      return this.each(function() {
        var owner = this.ownerDocument
        if (!tooltips[owner])
          tooltips[owner] = createActiveTooltip(owner, options);
      }).mouseover(hover)
        .mouseout(hide);
    },
    
    removetooltip: function(options) {
      return this.each(function() {
        $(this).unbind('mouseover', hover);
        $(this).unbind('mouseout', hide);
        if (tooltips[this.ownerDocument]) {
          this.ownerDocument.body.removeChild(tooltips[this.ownerDocument].elem.get(0));
          delete(tooltips[this.ownerDocument]);
        }
      })
    }
  });

  var tooltips = [];

  function createActiveTooltip(root, options) {
    var ob = {
      'elem': jQuery.create('div', {'id': 'activetooltip'}, options.html, root)
                    .css({'opacity': '0',
                          'position': 'absolute',
                          'top': '-100px',
                          'left': '-100px',
                          'background-color': 'yellow',
                          'padding': '10px'})
                    .mouseover(show)
                    .mouseout(hide)
                    .appendTo(root.body),
      'target': null, // HTML element that is being edited
      'fadeIn': function(target) {
        if (!target)
          target = ob.target
        else if (target != ob.target)
          ob.clear();
        if ($(ob.target).is(':visible'))
          return;
        var t = $(target);
        var p = t.position();
        ob.elem.css({'top':target.offsetTop+t.height()+5,
                    'left':target.offsetLeft+15});
        ob.target = target;
        ob.elem.stop().fadeTo('fast', 1, ob.postshow);
        t.css('outline', '#0000FF dotted thin');
      },
      'fadeOut': function() {
        ob.elem.stop().fadeTo('slow', 0, ob.clear)
      },
      'clear': function() {
        $(ob.target).removeAttr('style');
        ob.elem.css({'top': -100, 'left': -100});
        ob.target = null;
        if (options.onhide)
          options.onhide(ob)
      },
      'postshow': function() {
        if (options.onshow)
          options.onshow(ob)
      },
      'I': null
    }
    ob.elem.get(0).atob = ob;
    return ob
  }
  
  function show() {
    var acbox = tooltips[this.ownerDocument]
    if (acbox.I)
      acbox.I = clearTimeout(acbox.I);
    acbox.fadeIn();
  }
  
  function hide() {
    var acbox = tooltips[this.ownerDocument];
    acbox.I = setTimeout(acbox.fadeOut, 1000);
  }
  
  function hover() {
    var acbox = tooltips[this.ownerDocument]
    if (acbox.I)
      acbox.I = clearTimeout(acbox.I);
    acbox.fadeIn(this);
  }
})(jQuery);

