var CONFIRM_REMOVE = false;

function GEvents() {
	var events = new Array();
	var EventMap = false;

	var MySelf = this;

	this.addEventListener = function(eventType, eventName, action) {
		if(!events[eventType]) {
			events[eventType] = new Array();
		} 
		events[eventType][eventName] = action;
	}

	this.removeEventListener = function(eventType, eventName) {
		if(events[eventType] && events[eventType][eventName]) {
			delete events[eventType][eventName];
		}
	}

	this.setPrimaryMap = function(map) {
		EventMap = map;
	}

	this.triggerEvent = function(eventName, object) {
		if(eventName == 'removelayer') {
			return this.onRemoveLayer(object);
		} else if(eventName == 'removeservice') {
			return this.onRemoveService(object);
		} else if(eventName == 'navigate' && EventMap) {
			var inchScale = pixelScaleToInchScale(EventMap, object.Radius);
			if(inchScale > MAP_MAXSCALE) {
				object.Radius = inchScaleToPixelScale(EventMap, MAP_MAXSCALE);
			} else if(inchScale < MAP_MINSCALE) {
				object.Radius = inchScaleToPixelScale(EventMap, MAP_MINSCALE);
			}
		}
		var eventArray = events[eventName];
		for(var i in eventArray) {
			if(eventArray[i] instanceof Array) {
				for(var f = 0; f < eventArray[i].length; f++) {
					eventArray[i][f](object);
				}
			} else {
				eventArray[i](object);
			}
		}

	}

	this.onRemoveLayer = function(layerName) {
		var eventArray = events['removelayer'];
		if(!CONFIRM_REMOVE || confirm('Do you want to remove layer '+layerName+'?')) {
			for(var i in eventArray) {
				eventArray[i](layerName);
			}
			return true;
		} else {
			return false;
		}
		return false;
		
	}

	this.onRemoveService = function(serviceName) {
		var eventArray = events['removeservice'];
		if(!CONFIRM_REMOVE || confirm('Do you want to remove service '+serviceName+'?')) {
			for(var i in eventArray) {
				eventArray[i](serviceName);
			}
			return true;
		} else {
			return false;
		}
		
	}



	this.onLoadedMapbook = function(mapBookXML,objMap) {
		var eventArray = events['loadedmapbook'];
		for(var i in eventArray) {
			eventArray[i](mapBookXML, this, objMap);
		}

	}

	this.changePointScale = function(centerPoint, scale, markup) {
		var circ = new Circle();
		circ.Radius = scale;
		circ.Center = centerPoint;
		circ.Markup = markup;
		this.triggerEvent('navigate',circ);
	}


	this.zoomToUrl = function(url) {
		var http = getHTTPObject();
		http.open("GET", url, true);
		http.onreadystatechange = function () { 
			if(http.readyState == 4) {
				try {
					MySelf.triggerEvent('navigate',
						convertViewString(http.responseText, 
							EventMap.getMapSize()
						)
					);
				} catch (e) {
					/* Do nothing, this has clearly failed */
				}
			}
		}
		http.send();
	}
}
