var GDT = {};
(function () {
	//dont' go more than one level deep.
	GDT.eventKeys = {
		gameplay: {
			afterGameReview: 'gameplay.afterGameReview',
			beforeGameReview: 'gameplay.beforeGameReview',
			afterReleaseGame: 'gameplay.afterReleaseGame',
			beforeReleaseGame: 'gameplay.beforeReleaseGame',
			contractFinished: 'gameplay.contractFinished',
			contractStarted: 'gameplay.contractStarted',
			engineFinished: 'gameplay.engineFinished',
			engineStarted: 'gameplay.engineStarted',
			featureFinished: 'gameplay.featureFinished',
			gameDefinitionCanceled: 'gameplay.gameDefinitionCanceled',
			researchCompleted: 'gameplay.researchCompleted',
			researchStarted: 'gameplay.researchStarted',
			salesCalculated: 'gameplay.salesCalculated',
			trainingFinished: 'gameplay.trainingFinished',
			weekProceeded: 'gameplay.weekProceeded'
		},
		ui: {
			dialogOpen: 'ui.dialogOpen',
			dialogClose: 'ui.dialogClose',
			contextMenuShowing: 'ui.contextMenuShowing',
			beforeShowingNotification: 'ui.beforeShowingNotification'
		},
		saves: {
			saving: 'saves.saving',
			loading: 'saves.loading'
		},
		mod: {
			loaded: 'mod.loaded',
			loadError: 'mod.loadError'
		}
	};

	var _subscribers = {};

	var getSubscribers = function (key) {
		if (!_subscribers.hasOwnProperty(key)) {
			_subscribers[key] = [];
		}
		return _subscribers[key];
	};

	GDT.on = function (key, handler) {
		getSubscribers(key).push(handler);
	};

	GDT.off = function (key, handler) {
		getSubscribers(key).remove(handler);
	};

	GDT.fire = function (obj, key, data) {
		var subs = getSubscribers(key);
		for (var i = 0; i < subs.length ; i++) {
			if (subs[i] != null) {
				try{
					subs[i].call(obj, data);
				} catch (e) {
					Logger.LogWarning('GDT event handler error', e);
				}
			}
		}
	};

	var _scriptsToLoad = 0;

	GDT.loadJs = function (scriptFiles, ready, error) {
		_scriptsToLoad++;
		requireLoad(scriptFiles, function () {
			_scriptsToLoad--;
			if (_scriptsToLoad == 0) {
				GDT.fire(this, GDT.eventKeys.mod.loaded);
			}
			if (ready) {
				ready();
			}
		}, function () {
			_scriptsToLoad--;
			if (_scriptsToLoad == 0) {
				GDT.fire(this, GDT.eventKeys.mod.loadError);
			}
			if (error) {
				error();
			}
		});
	};
})();