//class PD.Web.UI.Controls.ControlEventSubscriptionManager

PD.Web.UI.Controls.ControlEventSubscriptionManager = Class.extend({

    //===================================
    // FIELDS
    //===================================

    _options: null,
    _subscriptions: null,
    _eventBus: null,

    //===================================
    // CONSTRUCTOR
    //===================================

    init: function (options) {
        this._subscriptions = {};
        this._options = options || {};
        this._eventBus = options.eventBus;
    },

    //===================================
    // PUBLIC METHODS
    //===================================

    add: function (eventName, fn, context, subscriber) {

        var eventSubscriptions = [];

        if (!(eventName in this._subscriptions)) {
            this._subscriptions[eventName] = [];
        }

        eventSubscriptions = this._subscriptions[eventName];

        eventSubscriptions[eventSubscriptions.length] = fn;

        this._eventBus.subscribe(eventName, fn, context, subscriber);

    },

    clear: function (eventName) {
        if (eventName == null) {
            for (eventName in this._subscriptions) {
                this._clearEventSubscriptions(eventName);
            }
        }
        else {
            this._clearEventSubscriptions(eventName);
        }
    },

    //===================================
    // PUBLIC METHODS
    //===================================

    _clearEventSubscriptions: function (eventName) {
        var that = this;
        if (eventName in this._subscriptions) {
            _.each(this._subscriptions[eventName], function (fn, index) {
                that._eventBus.unsubscribe(eventName, fn);
            });
            delete this._subscriptions[eventName];
        }
    }

});