var WidgetStorage = Class.extend({
    init: function() {
        this.widgets = {};
        this.length = 0;
        this.listeners = [];
        this.addListeners();

    },
    add: function(widget) {
        if(typeof this.widgets[widget.uniqueId] === 'undefined') {
            this.widgets[widget.uniqueId] = widget;
            this.length++;
        }

        return this;
    },
    get: function(uniqueId) {
        return this.widgets[uniqueId];
    },
    getBySpecificField: function(key, value) {
        var _self = this,
            result = jQuery.grep(Object.keys(_self.widgets), function(widget) {
            return _self.widgets[widget][key] == value;
        });

        return _self.widgets[result.shift()];
    },
    remove: function(uniqueId) {
        delete this.widgets[uniqueId];
        this.length--;

        return this;
    },
    bindObjects: function() {
        for(var i in this.widgets) {
            this.widgets[i].bindObjectToDom();
        }
    },
    addListeners: function() {
        var _self = this;
        this.listeners[WidgetStorage.BIND_OBJECTS_EVENT] = new signals.Signal();
        this.listeners[WidgetStorage.BIND_OBJECTS_EVENT].add(function() {
            _self.bindObjects();
        });
    },
    dispatch: function(event) {
        try{
            this.listeners[event].dispatch();
        } catch(exception){
            console.error('This event isn\'t binded '+event);
        }

    }
});

WidgetStorage.BIND_OBJECTS_EVENT = 'cswidget.bind_objects';