MapTooltip = Class.create();

MapTooltip.prototype = {

  initialize: function( element, tooltip ) {

    this.element = $( element );
    this.tooltip = $( tooltip );

    // Initialize the tooltip element
    this.tooltip.hide();
	  this.tooltip.setStyle( { position: "absolute" } );

    // Get the dimensions of the tooltip
    this.tooltipDimensions = this.tooltip.getDimensions();

    this.elementDimensions = this.element.getDimensions();

    // Setup the events
    this.mouseoverListener = this.showTooltip.bindAsEventListener( this );
    this.mouseoutListener = this.hideTooltip.bindAsEventListener( this );

    // Attach to the mouseover & mouseout of the map marker
    Event.observe( this.element, 'mouseover', this.mouseoverListener );
    Event.observe( this.element, 'mouseout', this.mouseoutListener );

    // We also attach the show/hide event to the actual tooltip to stop 
    // flickering if the user moves over the tooltip while it's visible
    Event.observe( this.tooltip, 'mouseover', this.mouseoverListener );
    Event.observe( this.tooltip, 'mouseout', this.mouseoutListener );
  },


  showTooltip: function( event ) {

    // Get the dimensions of the element that triggers the tooltip
    // We do this here rather than in initialize because firefox 
    // couldn't see the dimensions until now.
    this.elementDimensions = this.element.getDimensions();

    // If we're in the middle of fading; cancel the fade
    if (this.fadeEffect) this.fadeEffect.cancel();

    // calculate the offset required
    var offsetTop = ( this.tooltipDimensions.height - 3 ) * -1;
    var offsetLeft = ( ( this.tooltipDimensions.width / 2 ) - ( this.elementDimensions.width / 2 ) ) * -1;

    // Set the position by cloning the position of the element that triggers 
    // the tooltip and applying the calculated offset
    Position.clone( this.element, this.tooltip, { offsetTop: offsetTop, 
                                                  offsetLeft: offsetLeft, 
                                                  setWidth: false, 
                                                  setHeight: false 
                                                } );

    // Display it
    this.appearEffect = new Effect.Appear(this.tooltip, { duration: 0.3 });
  },


  hideTooltip: function( event ) {

    // If still in the middle of appearing; cancel that appearance
    if (this.appearEffect) this.appearEffect.cancel();

    // Slowly fade out of sight
    this.fadeEffect = new Effect.Fade(this.tooltip, { duration: 0.4 });
  }

}
