/* Event Dispatcher... A LOT of classes will inherit this! */

SN.Events = new Object();


SN.Events.EventWrapper = function(id, func) {
	this.getID = function() {
		return id;
	};
	
	this.execute = function(e) {
		return func(e);
	};
};

/* Event Dispatcher Class */
SN.Events.EventDispatcher = function() {
    var home = this;
    // Array of events
    var events = {};

    var indices = {};

    var serial = 0;

    this.addEventListener = function(type, FN) {
        var eventWrapper = new SN.Events.EventWrapper(serial++, FN);
        if (events[type]) {
            // type already administered
            events[type].push(eventWrapper);
        } else {
            events[type] = new Array();
            events[type].push(eventWrapper);
            indices[type] = 0;
            home.dispatchEvent('eventadded', { 'obj': eventWrapper, 'type': type });
        }
        return eventWrapper;
    };

    this.dispatchEvent = function(type, eventObj) {
        if (events[type]) {
            var returnVal = true;
            while (events[type] && indices[type] < events[type].length) {
                // Let's add some magic to the eventObj...
                var wrapper = events[type][indices[type]];
                if (!eventObj) {
                    eventObj = {};
                }
                eventObj['obj'] = wrapper;
                var temp = true;
                if (wrapper) {
                    temp = wrapper.execute(eventObj);
                }
                if (returnVal && !temp) {
                    returnVal = false;
                }
                indices[type]++;
            }
            if (indices[type]) {
                indices[type] = 0;
            }
            return returnVal;
        }
        return true;
    };

    this.removeEventListener = function(type, eventWrapper) {
        if (events[type]) {
            // search through and grab the index of the matching function...
            // then remove it!
            var size = events[type].length;
            for (var i = 0; i < size; i++) {
                if (events[type][i].getID() == eventWrapper.getID()) {
                    if (i <= indices[type]) {
                        indices[type]--;
                    }
                    events[type].splice(i, 1);
                    if (!events[type].length) {
                        delete events[type];
                        delete indices[type];
                        serial--;
                        home.dispatchEvent('eventcleared', { 'type': type });
                    }
                    return;
                }
            }
            alert("SN.Events.EventDispatcher.removeEventListener(type, eventWrapper): Could not find function");
        }
    };

    this.peek = function(type) {
        return events[type];
    };
};

