/** 
  LifeCycle v 0.1
  Utility object to handle script life cycle (loading, init and so on)
  Based on code by Dean Edwards/Matthias Miller/John Resig
  
  (c) 2006 Giorgio Maone - g.maone@informaction.com
  License: GNU
*/

var LifeCycle = {
  handlers: [],
  installed: false,
  triggered: false,
  runOnload: function(handler) {
    this.install();
    this.handlers[this.handlers.length] = handler;
  },
  install: function() {
    if(this.installed) return;
    this.installed = true;
    
    /* for Mozilla/Opera9 */
    if (document.addEventListener) {
      document.addEventListener("DOMContentLoaded", LifeCycle.onload, false);
    }
    
    /* for Internet Explorer */
    /*@cc_on @*/
    /*@if (@_win32)
      document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
      var script = document.getElementById("__ie_onload");
      script.onreadystatechange = function() {
        if (this.readyState == "complete") {
          LifeCycle.onload(); // call the onload handler
        }
      };
    /*@end @*/

    /* for Safari */
    if (/WebKit/i.test(navigator.userAgent)) { // sniff
      this.timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
          LifeCycle.onload(); // call the onload handler
        }
      }, 10);
    }
    
    if(window.onload) {
      this.runOnload(window.onload);
    }
    /* for other browsers */
    window.onload = LifeCycle.onload;
  },
  
  
  onload: function() {
    LifeCycle.callHandlers();
  },
  
  callHandlers: function(ev) {
    if(this.triggered) return;
    this.triggered = true;
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    for(var j = 0; j < this.handlers.length; j++) {
      try {
        this.handlers[j]();
      } catch(e) {}
    }
  }
};



