/*
  implements a daisy chain of event handlers.
  support:
    window.onload
    window.document.on*
    
  sample:
  
  window.DaisyChain.add("load", f1);
  window.DaisyChain.add("load", f2);
  window.DaisyChain.add("mousedown", f3);
  
  window.DaisyChain.debug("load"); 
    this method alert()s everything on the onload chain
  
  Author: Alex Fung <alexfung1980@hotmail.com>
  April 1998

  Modification August 2000 Alex Fung <alexfung1980@hotmail.com>
  with IE5.0 or above, use the attachEvent/detachEvent methods directly.
 */

function myDaisyChain() {
  function _add(x,y) {
    if (document.childNodes) (x=="load" ? window : window.document).attachEvent("on" + x, y); // IE5+ only
    else {
      var hand = eval("window." + ((x=="load")?"":"document.") + "on" + x);
      if (hand) {
        var chain = eval("window.DaisyChain." + x);
        if (chain) {
          chain[chain.length] = y;
        } else {
          eval("chain = window.DaisyChain." + x + " = new Array()");
          chain[0] = hand;
          chain[1] = y;
          eval("window." + ((x=="load")?"":"document.") + "on" + x + " = " + this.generic);
        }
      } else eval("window." + ((x=="load")?"":"document.") + "on" + x + " = " + y);
    }
  }
  this.add = _add;
  function _remove(x,y) {
    if (document.childNodes) {
      (x=="load" ? window : window.document).detachEvent("on" + x, y);
      return true;
    } else {
      var hand = eval("window." + ((x=="load")?"":"document.") + "on" + x);
      if (hand) {
        if (hand  == y) {
          eval("window." + ((x=="load")?"":"document.") + "on" + x + " = null;");
          return true;
        }
        var chain = eval("window.DaisyChain." + x);
        if (chain) {
          if (hand != chain) return false;
          for (var i = 0 ; i < chain.length; i++) {
            if (chain[i] == y) {
              chain[i] = null;
              if (i == chain.length - 1) i--;
              return true;
            }
          }
        } 
      } 
      return false;
    }
  }
  this.remove = _remove;
  function _debug(x) {
    var hand = eval("window." + ((x=="load")?"":"document.")+ "on" + x);
    if (hand) {
      var chain = eval("window.DaisyChain." + x);
      if (chain) {
        alert("chain");
        alert(chain.length);
        for (var i = 0; i < chain.length; i++) alert(chain[i]);
      } else {
        alert("direct hand");
        alert(hand);
      }
    } else {
      alert("none");
    }
  }
  this.debug = _debug;
  function _generic() {
    var x = window.event.type;
    var chain = eval("window.DaisyChain." + x);
    if (chain) for (var i = 0; i < chain.length; i++) if (chain[i]) chain[i]();
    else eval("window." + ((x=="load")?"":"document.") + "on" + x + " = null");
  }
  this.generic = _generic;
}
window.DaisyChain = new myDaisyChain();


