// create tool tips unobtrusively
// simplified from http://blog.innerewut.de/files/tooltip/tooltip-v0.2.js

// example html:
// <a href="" class="tooltip" title="hello world" id="mylink"></a>
// <a href="" class="tooltip" title="hello world" id="mylink2"></a>

Event.observe( window, 'load', function() {
  $$('.tooltip').each( function(e) {
    createToolTip( e ); 
  });
});

function tooltipIdFor( e ) {
  return e.id + '_text';
}
function tooltipElementFor( e ) {
  return $( tooltipIdFor(e) );
}

function hideToolTip( evnt ) {
  tooltipElementFor(this).hide();
}

function showToolTip( evnt ) { 
  var min_distance_x = 15;
  var min_distance_y = 15;
  
  Event.stop( evnt );
  
var div = tooltipElementFor(this);

//move tooltip div

  var pos = Position.page( this );
  var link_x = 0 // pos[0];
  var link_y = 0 //pos[1];
  
//  (borrowed code)
  var mouse_x = Event.pointerX(evnt);
  var mouse_y = Event.pointerY(evnt);

// decide if we need to switch sides for the tooltip
  var element_width = div.getWidth();
  var element_height = div.getHeight();

  if ( (element_width + mouse_x) >= ( getWindowWidth() - min_distance_x) ){ // too big for X
    mouse_x = mouse_x - element_width;
    // apply min_distance to make sure that the mouse is not on the tool-tip
    mouse_x = mouse_x - min_distance_x;
  } else {
    mouse_x = mouse_x + min_distance_x;
  }

  if ( (element_height + mouse_y) >= ( getWindowHeight() - min_distance_y) ){ // too big for Y
    mouse_y = mouse_y - element_height;
    // apply min_distance to make sure that the mouse is not on the tool-tip
    mouse_y = mouse_y - min_distance_y;
  } else {
    mouse_y = mouse_y + min_distance_y;
  }

  // now set the right styles (TODO: zindex doesn't work correctly?)
  div.setStyle( { position:'absolute', top: mouse_y-link_y+"px", left: mouse_x-link_x+"px", zIndex: 1000 } );

  //show tooltip div
  div.show();
}

function getWindowHeight(){
  var innerHeight;
  if (navigator.appVersion.indexOf('MSIE')>0) {
	  innerHeight = document.body.clientHeight;
  } else {
	  innerHeight = window.innerHeight;
  }
  return innerHeight;	
}

function getWindowWidth(){
  var innerWidth;
  if (navigator.appVersion.indexOf('MSIE')>0) {
	  innerWidth = document.body.clientWidth;
  } else {
	  innerWidth = window.innerWidth;
  }
  return innerWidth;	
}

function createToolTip( e ) {
//  console.debug( "making tooltip for element: " + e.id )
  tip_text = e.getAttribute('title');
  div_id = tooltipIdFor(e);
  // construct hidden div
  html = '<div id="'+div_id+'" class="tooltip text" style="display:none">'+tip_text+'</div>';
  // new Insertion.After( e, html );
  new Insertion.Top( $$('body').first(), html );
  Event.observe( e, "mouseover", showToolTip.bindAsEventListener(e));
  Event.observe( e, "mouseout", hideToolTip.bindAsEventListener(e));
  e.onclick = "return false;"
  // remove title attribute so we don't get double displays of the text
  e.removeAttribute('title');
}
