PageLoadingEventHandler = Class.create();
PageLoadingEventHandler.prototype =
{
    initialize: function()
    {
      this.queue = $H();
      this.eventQueue = $A();
      this.waitFor('html');

    },
    waitFor: function(what)
    {
      this.queue[what] = true;
    },
    loaded: function(what)
    {
      // OK, handle newer version of prototype ..
      if(typeof(this.queue.remove) == "undefined")
          this.queue.unset(what);
      else
          this.queue.remove(what);

      if(this.queue.size() == 0)
          this._onComplete();

    },
    doLoad: function()
    {
      this.loaded('html');
    },
    registerOnComplete: function(prio,handler)
    {
      this.eventQueue[this.eventQueue.size()] = new OnHandlerEntry(prio,handler);
    },
    _onComplete:function()
    {

       // OK, everything is loaded and initialized,
       // lets dispatch our handlers as well..
       this.eventQueue.sort(this._prioSort);

       var num = this.eventQueue.size();

       for(var i = 0; i < num; i++)
       {
         var obj = this.eventQueue[i];
         if(obj)
         {
           var f = obj.handler;
           f();
         }
       }
    },
    _prioSort: function(a,b)
    {
      if(a.prio > b.prio)
          return 1;
      else
          return -1;
    }
};

function OnHandlerEntry(prio,handler)
{
    this.prio = prio;
    this.handler = handler;
}

var PageLoading = null;

function loaded(what)
{
  PageLoading.loaded(what);
}
function waitFor(what)
{
  if(PageLoading == null)
  {
    PageLoading = new PageLoadingEventHandler();
    Event.observe(window, 'load',PageLoading.doLoad.bind(PageLoading));
  }
  PageLoading.waitFor(what);
}

function registerOnComplete(prio,handler)
{
  if(PageLoading == null)
  {
    PageLoading = new PageLoadingEventHandler();
    Event.observe(window, 'load',PageLoading.doLoad.bind(PageLoading));
  }
  PageLoading.registerOnComplete(prio,handler);
}
