// Syntax:
//   new EventHandler(obj, evtType, hnd)
//   evt.cancel(cancelBubble)

// Note:
//   no remove/detach event, sjoerd considers that to be bad practice
//   evtType is a string NOT starting with "on"
//   hnd has one argument: the event
//   hnd will be called by the obj the event is attached to, so 'this' will refer to that obj
//   using this library will not cause memory leaks
//   the event object handed over to the handler has a target property in IE as well
//   the event object handed over to the handler has a cancel method accepting one argument 'cancelBubble'
//   the event object handed over to the handler has leftButton and rightButton booleans, but only in the case of mouse-down/up/move/over/out/enter/leave


// Sample:
//   new EventHandler(document, "click", showClickCoords);
//   function showClickCoords(evt)
//   {
//     evt.cancel(true);
//     alert(this.innerHTML + "\n\n" + evt.target.innerHTML);
//   }

function EventHandler(obj, evtType, hnd)
{
  this.obj = obj;
  this.hnd = hnd;

  var dataIdx = EventHandler.__data.length;
  EventHandler.__data[dataIdx] = this;

  var hnd = EventHandler.__createHandler(dataIdx);

  if (obj.addEventListener)
    obj.addEventListener(evtType, hnd, false);
  else if (obj.attachEvent)
    obj.attachEvent("on" + evtType, hnd);
}                      

EventHandler.__data = [];
EventHandler.__createHandler = function(handlerIdx)
{
  return function(evt) {
    EventHandler.__fixEventObject(evt);

    var evtData = EventHandler.__data[handlerIdx];
    var obj = evtData.obj;

    obj.___hnd = evtData.hnd;
    var result = obj.___hnd(evt);
    obj.___hnd = null;

    return result;
  }
};

EventHandler.eventCancel = function(cancelBubble)
{
  this.returnValue = false;
  if (this.preventDefault)
    this.preventDefault();
  if (cancelBubble)
  {
    this.cancelBubble = true;
    if (this.stopPropagation)
      this.stopPropagation();
  }
};

EventHandler.__fixEventObject = function(evt)
{
  evt.cancel = EventHandler.eventCancel;

  if (typeof(evt.srcElement) != "undefined")
    evt.target = evt.srcElement;

  if (evt.type.indexOf("mouse") == 0)
  {
    evt.leftButton  = (!evt.which && evt.button == 1) || evt.which == 1; 
    evt.rightButton = evt.button == 2;
 }
};

new EventHandler(window, 'beforeunload', LogOutCount);
function LogOutCount()
{
  var xmlhttp = null;
  if (window.XMLHttpRequest)
    xmlhttp = new XMLHttpRequest();
  else if (window.ActiveXObject)
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.open("POST", "/code/lib/logout.asp", false);
  xmlhttp.send(null);
}
