/*
 Copyright 2013 Adobe Systems Incorporated.  All rights reserved.
 
Purpose:
LiveEditEvent is the event handling implementation inside LiveEdit

*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, maxerr: 50 */
/*global writeDWLog*/

function LiveEditEvent() {
    'use strict';
    this.listeners = {};
    this.contexts = {};
    this.isDebugging = true;
}

LiveEditEvent.prototype = {
/*
Event handling mechanisms for all HUDS.
Every HUD will hold instance of this object
Events List:
Please refer to Constants.JS and all the events are
listed under DW_LIVEEDIT_EVENTS
*/
    constructor: LiveEditEvent,

    addListener: function (type, listener, liveEditContext) {

        'use strict';
        if (!this.listeners[type]) {
            this.listeners[type] = [];
        }

        if (!this.contexts[type]) {
            this.contexts[type] = [];
        }

        this.listeners[type].push(listener);
        this.contexts[type].push(liveEditContext);
    },

    fire: function (event) {
        'use strict';
        var listeners, contexts, i, len;
        if (typeof event === "string") {
            event = {
                type: event
            };
        }
        if (!event.target) {
            event.target = this;
        }

        if (!event.type) {
            throw new Error("Event object missing 'type' property.");
        }
        if (this.listeners[event.type] instanceof Array) {
            listeners = this.listeners[event.type];
            contexts = this.contexts[event.type];
            for (i = 0, len = listeners.length; i < len; i += 1) {
                listeners[i].call(contexts[i], event);
            }
        }
    },

    removeListener: function (type, listener) {
        'use strict';
        var listeners, contexts, i, len;
        if (this.listeners[type] instanceof Array) {
            listeners = this.listeners[type];
            contexts = this.contexts[type];
            for (i = 0, len = listeners.length; i < len; i += 1) {
                if (listeners[i] === listener) {
                    listeners.splice(i, 1);
                    contexts.splice(i, 1);
                    break;
                }
            }
        }
    }
};
