
/*

AddEvent Manager, revised 11 June 2005
(c) 2005 Angus Turnbull, TwinHelix Designs http://www.twinhelix.com

Licensed under the CC-GNU LGPL, version 2.1 or later:
http://creativecommons.org/licenses/LGPL/2.1/
This is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/



// Here's the compacted addEvent() function itself.
// PARAMETERS:
//  1) A reference to an object like window or document.
//  2) The name of the event in quotes without the 'on' prefix (e.g. 'mouseover').
//  3) A function reference that is called when the event fires.
//  4) OPTIONAL: A boolean value to disable usage of addEventListener.
// Functions called are automatically passed the correct browser event object.
// It also manages return values, if any of the functions called explicitly returns false,
// then the whole event returns false.

// See below for a usage example.

var aeOL = [];
function addEvent(o, n, f, l){
 var a = 'addEventListener', h = 'on'+n, b = '', s = '';
 if (o[a] && !l) return o[a](n, f, false);
 o._c |= 0;
 if (o[h])
 {
  b = '_f' + o._c++;
  o[b] = o[h];
 }
 s = '_f' + o._c++;
 o[s] = f;
 o[h] = function(e){
  e = e || window.event;
  var r = true;
  if (b) r = o[b](e) != false && r;
  r = o[s](e) != false && r;
  return r;
 };
 aeOL[aeOL.length] = { o: o, h: h };
};
addEvent(window, 'unload', function() {
 for (var i = 0; i < aeOL.length; i++) with (aeOL[i]){
  o[h] = null;
  for (var c = 0; o['_f' + c]; c++) o['_f' + c] = null;
 }
});

// I've used one-char var names here to save space, this is what they mean:
//  aeOL = "AddEvent Object List", to remove events onunload.
//  o = Object to which we're attaching an event.
//  n = Name of event, without the 'on' prefix, e.g. 'mouseover'.
//  f = Function reference, to call when the event fires.
//  l = Legacy event model (i.e. disables addEventListener).
//  h = Handle name of the event with the 'on' prefix e.g. 'onmouseover'.
//  b = Backup name of any old event handler's function: the string name of its
//      method, so it can be accessed and run as o[b] by the manager function.
//  s = String name consisting of a new uniquely generated object method name
//      for the new attached function, accessed/run as o[s].
//  _c = Counter of all 's' and 'b' properties assigned to this object.
//  e = Event object passed to the real event handler function.
//  r = Return value of all processed event handlers.



// Here's a companion cancelEvent() function you can call within your event
// handlers to stop them performing the normal browser action.
// Pass an event object, and the second "c" parameter cancels event bubbling.
function cancelEvent(e, c){
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c){
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};

