//////////////////////////////////////////////////////
// MooTools 1.2: Multiple OnLoad Event Processing   //
// (c) Jordan Sherer 2009                           //
//////////////////////////////////////////////////////

var Loader = new Class({ 
    Implements:[Options,Events],
    options:{
        onLoadStarted:$empty, 
        onLoadFinished:$empty
    },
    load_events:[],
    
    initialize:function(options)
    {
        var self = this; 
        
        if(options != undefined && options != null)
        {
            this.setOptions(options);
        }
        
        window.addEvent("domready", function(e){ self.run.call(self, e); });
    },
    
    run:function(e)
    {
        this.fireEvent("loadStarted");
        this.load_events.each(function(f){
            if(f != undefined && f != null && typeof f == 'function')
            {
                f();
            }
        });
        this.fireEvent("loadFinished");
    },
    
    __closure__:function(f, args, self)
    {
        if(args == undefined || args == null){ args = []; }
        if(self == undefined || self == null){ self = null; }
        return function(){ return f.apply(self, args); };
    },
    
    add:function(f, args, self)
    {
        this.load_events.push(this.__closure__(f, args, self));
    },
    
    insert:function(index, f, args, self)
    {
        var last = this.load_events.length - 1;
        if(index > last){ index = last; }
        this.load_events.splice(index, 0, this.__closure__(f, args, self));
    }, 
    
    remove:function(index)
    {
        this.load_events.splice(index, 1);
    },
    
    replace:function(index, f, args, self)
    {
        if(index < this.load_events.length)
        {
            this.load_events[index] = this.__closure__(f, args, self);
        }
    },
    
    test:function()
    {
        alert(this.load_events.length);
    }
});

var loader = new Loader();
/*
loader.addEvent("loadFinished", function(){ alert("Booya!~"); });

loader.add(loader.test, null, loader);

function test()
{
    alert("Wow!");
    alert("This is cool!");
}

loader.add(test);
*/