var SiteComponents = {
    list: [],
    register: function(name, members){
        var component = new SiteComponent(name, members);
        this.list.push(component);
        this[name] = component;
    },
    isReady: false,
    init: function(){
        this.isReady = true;
        jQuery(this.list).each(function(){
            if(this.test()){
                //try {
                    this.init();
                //}
                //catch(e){
                //    if(typeof console != 'undefined' && typeof console.error != 'undefined'){
                //        console.error(e);
                //    }
                //}
            }
            // TODO: figure out how to do finalize event. Hint: may be async
        });
    },
    lookup: function(name){
        return this[name];
    }
};


var SiteComponent = (function() {
    return function(name, members) {
        this.name = name;
        
        var hasInit = false;
        var initArgs = [];
        
        // Handle shortcut
        if(typeof members == 'function'){
            members = {
                init: members
            };
        }

        // Members that each component must have
        this.test = function(){ return true; };
        
        var init = members.init;
        delete members.init;
        this.init = function(){
            // Only allow the init to be executed once when isReady
            if(hasInit){
                return false;
            }
            
            // If jQuery.ready hasn't happened yet, then save the args for passing later
            if(!SiteComponents.isReady){
                initArgs = Array.prototype.slice.call(arguments);
                return false;
            }
            
            jQuery(document).trigger('sitecomponent-init', [this, initArgs]);
            if(init){
                init.apply(this, initArgs);
            }
            hasInit = true;
            return true;
        };

        jQuery.extend(this, members);
    }
})();

SiteComponent.prototype.toString = function(){
    return "SiteComponent<" + this.name + ">";
};


jQuery(document).ready(function() {
    SiteComponents.init();
});

if ( typeof($) === 'undefined' ) {
    var $ = jQuery;
}