var frp = frp || {};
frp.web = frp.web || {};
frp.web.widget = frp.web.widget || {};

(function(){
    var Y = YAHOO,
    YL = Y.lang,
    YU = Y.util,
    YE = YU.Event,
    YD = YU.Dom;

    function WidgetController(libraryUrl, libraryVersion) {
        if (libraryUrl) {
            this.libraryUrl = libraryUrl;
        }
        this.libraryVersion = libraryVersion || '1.0';
        this.requiredWidgets = [];
        this.createEvent('widgetsLoaded');
    }
    WidgetController.prototype = {
        libraryUrl: 'http://localhost',
        requiredWidgets: null,
        registeredWidgets: {},
        addWidget: function (required, jsFile, fn) {
            var i;
            for (i =0; i < required.length; ++i) {
                this.requiredWidgets.push(required[i]);
            }
            this.subscribe('widgetsLoaded', function () {
                YAHOO.util.Get.script(jsFile, {
                    onSuccess: function() {
                        fn();
                    }
                });
            });
        },
        pageLoaded: function () {
            var me = this;
            var loader = new frp.Loader(function () {
                loader.require(me.requiredWidgets);
            }, function() {
                me.fireEvent('widgetsLoaded');
            }, this.libraryUrl, 1.2);
        },
        registerWidget: function(name, widget){
            this.registeredWidgets[name] = widget;
        },
        getWidget: function(name){
            return this.registeredWidgets[name];
        }
    };
    // Add event provider utilities to the data request object
    YL.augment(WidgetController, YU.EventProvider);

    frp.web.widget.WidgetController = WidgetController;
}());
