// map
var odvMap = null;
// coordinates of the right mouse click
var ctxCoords = null;
// tooltips array
var toolTipHelpers = new Array();
// map request
var mdvMap;
var bCreateMapRequest = false;
var odvMapResult  = new mapResult();
var odvMapRequest = new mapRequest();


// map configuration
function initMdvMapConfig() {
	// map configuration
	mdvMapConfig.add('serverURL', 'http://efa.vor.at/map/vor/tiles/map/'); 
	mdvMapConfig.add('efaURL', 'XML_MAP_REQUEST');
	mdvMapConfig.add('transparentImg', 'img/transparent.gif');
	mdvMapConfig.add('imagePath', 'img/');
	mdvMapConfig.add('network', 'vor');
	mdvMapConfig.add('defaultScale', zoom);
	mdvMapConfig.add('xCenterReal', x);
	mdvMapConfig.add('yCenterReal', y); 
	mdvMapConfig.add('mapName', 'TEL5');
	mdvMapConfig.add('block', '100');
	mdvMapConfig.add('toolTimeOut', '20');
	mdvMapConfig.add('zoomOnDoubleClick', 'true');
	mdvMapConfig.add('language', mapLanguage);
	mdvMapConfig.add('useMagnifyGlass', 'true');
	mdvMapConfig.add('cursorMove', 'img/grabbing.cur');
	mdvMapConfig.add('useBubbleForEFAInfo', 'true');
	mdvMapConfig.add('useBubbleOverflowForEFAInfo', 'true');
	mdvMapConfig.add('useBubblePinForEFAInfo', 'false');
	mdvMapConfig.add('info.stop.size.width', '250');
	mdvMapConfig.add('info.stop.size.height', '80');
	mdvMapConfig.add('info.poi.size.width', '250');
	mdvMapConfig.add('info.poi.size.height', '80');
	
	// mini map configuration
	mdvMiniMapConfig.add('serverURL', 'http://efa.vor.at/map/vor/tiles/map/');
	mdvMiniMapConfig.add('efaURL', 'XML_MAP_REQUEST');
	mdvMiniMapConfig.add('transparentImg', 'img/transparent.gif');
	mdvMiniMapConfig.add('network', 'vor');
	mdvMiniMapConfig.add('defaultScale', zoom);	
	mdvMiniMapConfig.add('xCenterReal', x);
	mdvMiniMapConfig.add('yCenterReal', y);
	mdvMiniMapConfig.add('mapName', 'TEL5');
	mdvMiniMapConfig.add('block', '100');
	mdvMiniMapConfig.add('toolTimeOut', '20');
	mdvMiniMapConfig.add('zoomOnDoubleClick', 'true');	
	mdvMiniMapConfig.add('cursorMove', 'img/grabbing.cur');
}


// This function loads and initializes the map when the site is loaded.
function onLoadMapHandler(mapUsage) {
	var form = document.forms[0];
	initMdvMapConfig();
	
	for (var i=0; i < form.length; i++) {
		var value = form[i].value;
		if (mdvMap == null) 
			mdvMap = new MDVMapHelper(value, mapUsage);
	}
};


// This function unloads the map when the site is unloaded.
function onUnloadMapHandler() {
	if (mdvMap)
		mdvMap.destroy();
};


// This function destroys the map and mini map and clears the cache.
MDVMapHelper.prototype.destroy = function() {
	this.mdvMap.destroy();
	this.mdvMiniMap.destroy();
	this.mdvMap = null;
	this.mdvMiniMap = null;
};


// This function loads the map and minimap
function MDVMapHelper(value, mapUsage) {
	this.mdvMap = null;
	this.mdvMiniMap = null;
	this.markerLayer = null;
	this.value = value;
	this.marker = null;
	this.sync = null;
	
	// output map functionality
	this.viewport = document.getElementById('mdvMap');
	this.trips = null;
	
	// initialize map and register events
	if (this.mdvMap == null) {
		this.mdvMap = new MDVMap(document.getElementById('mdvMap'));
		
		// correct the map control alt texts
		var controlText = new Array();
		controlText['goNorth'] = goNorth;
		controlText['goWest'] = goWest;
		controlText['goEast'] = goEast;
		controlText['goSouth'] = goSouth;
		controlText['lastResult'] = lastResult;
		controlText['zoomIn'] = zoomIn;
		controlText['zoomOut'] = zoomOut;
		
		if (document.getElementById('itdLPxx_EFA') && document.getElementById('itdLPxx_EFA').value=='true') {
			// context menu and tooltip 
			this.ctxMenuArr = new Array();
			if (mapUsage=='pp') 
				this.ctxMenuArr[0] = new MDVMapMenuItem(setMyLocation, this.setCoordinatesMyLocation);
			else if (mapUsage=='destination')
				this.ctxMenuArr[0] = new MDVMapMenuItem(setDestination, this.setCoordinatesDestination);
			else
				this.ctxMenuArr[0] = new MDVMapMenuItem(setOrigin, this.setCoordinatesOrigin);
			this.ctxMenu = new MDVMapMenu(this.ctxMenuArr);
			new MDVMapContextMenu(this.mdvMap, this.ctxMenu);
			this.mdvMap.events.registerEvent(MDVEvent_CONTEXT_MENU, null, ContextMenuHandler);
			// highlight stop or poi
			this.mdvMap.events.registerEvent(MDVEvent_LAYER_UPDATED, null, this.highlightPoint);
		}
		this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, null, submitObject);
		this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
		
		new MDVMapNavigator(this.mdvMap);
		new MDVMapEFAInfo(this.mdvMap);	
		new MDVMapControl(this.mdvMap, controlText);
		
		
	}
	
	// initialize the mini map
	if (this.mdvMiniMap == null) {
		this.mdvMiniMap = new MDVMap(document.getElementById('mdvMiniMap'));
		new MDVMapNavigator(this.mdvMiniMap); 
	}
	
	// execute map and minimap
	if (this.mdvMap && this.mdvMiniMap) {
		this.mdvMap.execute(mdvMapConfig);			
		this.mdvMiniMap.execute(mdvMiniMapConfig);
		this.sync = new MDVMapSyncBound(this.mdvMap, this.mdvMiniMap);
	}

	// set coordinate marker if not stop or poi
	if (document.getElementById('itdLPxx_EFA') && document.getElementById('itdLPxx_EFA').value=='true' && address) 
		doCoordinate (x, y, zoom, mapUsage, this.mdvMap);


	// map does not move if it is grapped and the mouse moved over the borders of the map
	attachEventListener(document, 'mouseover', this.mdvMap.release.bind(this.mdvMap), false);
	attachEventListener(document, 'mouseover', this.mdvMiniMap.release.bind(this.mdvMiniMap), false);
};


// ==================================================================
// Input map functionality.
// ==================================================================

// Highlights a preselected stop or poi
MDVMapHelper.prototype.highlightPoint = function(id, msg, layer) {
	var idArr = ids.split(':');
	var marked = 0;
	if (layer) {
		var markers = layer.getMarkers();
		for (var m = 0; m < markers.length; m++) {
			var marker = markers[m];			
			var object = marker.getObjectId();
			for (var i = 0; i < idArr.length; i++) {
				if (object.id == idArr[i]) {
					var img = marker.getImage();
					// border
					img.className='markedIcon';
					marked++;
					// List is ought to be unique. No need to continue iteration cycle. Leave...
					break;
				}
			}
			if (marked >= idArr.length) 
				// Leave iteration as soon as required count of markers have been highlighted.
				break;
		}
	}
};


// Sets the marker for an identified address. 
function doCoordinate (x, y, zoomlevel, mapUsage, map) {	
	if (parent && x && y) {
		var mapName = map.config.get('mapName');
		var size = new MDVPoint(250, 80);
		var img = 'img/address.gif';
		var mapLocation;
		if (mapUsage=='destination')
			mapLocation = parent.document.getElementById('name_destination').value;
		else
			mapLocation = parent.document.getElementById('name_origin').value;;
		// set centre
		var mapCoords = new MDVCoordinates(mapName, x, y);
		map.setCentre(mapCoords);
		// set zoomlevel
		map.setZoomLevel(zoomlevel);
		var mapCoords = new MDVCoordinates(mapName, x, y);
		// set marker
			if (!this.marker) {
				marker = map.createMarker(mapCoords, 0, img);
			    var markerTitle = map.createToolTip(size, '<b>' + mapLocation + '</b>');
			    
			    marker.setToolTip(markerTitle);
			    map.addMarker(marker);
			}
			else 
				marker.setCoords(mapCoords);
		map.update();
	}
}


// Processed if clicked on a stop or poi.
function submitObject(id, msg, obj) {
	if (document.getElementById('itdLPxx_EFA') && document.getElementById('itdLPxx_EFA').value=='true' && parent) {
		if (obj.type=='stop'){
			var result = parent.odvMapResult;
			if (result) {
				selIndex=0;
				result.stopList[selIndex]	  = obj.id;
				result.stopNameList[selIndex] = obj.desc;
				result.type			= "stop";
				result.placeName	= "";
				parent.setMapInput();
				parent.focus();
			}
		}
		if (obj.type=='poi'){
			var result = parent.odvMapResult;
			if (result) {
				result.type = "poi";
				result.placeName = "";
				result.placeID = -1;
				result.desc = obj.desc;
				result.omc = obj.omc;
				result.poiID = obj.id;
				parent.setMapInput();
				parent.focus();
			}
		}
		if (obj.type=='coord') {
			var result = parent.odvMapResult;
			if (result) {
				result.desc = ':Map Location';
				result.coordValue = obj.id +':Map Location';
				parent.setMapInput();
				parent.focus();
			}
		}
	}
	// alternative interface for wiener linien quick enquiry form
	else {
		var map_usage = document.getElementById('itdLPxx_usage').value;
		var prefix;
		if (obj.type == 'poi')
			prefix = 'poiID:';
		else 
			prefix = 'stopID:';
			
		if (obj.type == 'poi') {
				document.getElementById('placeInfo_' + map_usage).value = obj.omc + ':-1';
		}
		document.getElementById('typeInfo_' + map_usage).value = obj.type;
		document.getElementById('nameInfo_' + map_usage).value = prefix + obj.id;	

		document.forms[0].submit();
	}
}

// alternative map interface for wiener linien quick enquiry form
function wlEnquiry (name, place, type, map_usage, id, x, y, zoom) {		
	var sessionID = document.getElementById('sessionID').value;
	var requestID = document.getElementById('requestID').value;
	if (document.getElementById('itdLPxx_RURL')) 
		document.location.href= document.getElementById('itdLPxx_RURL').value + "?place_" + map_usage + "=" + place + "&name_" + map_usage + "=" + name + "&type_" + map_usage + "=" + type + "&itdLPxx_usage=" + map_usage + "&sessionID=" + sessionID + "&requestID=" + requestID + "&itdLPxx_id=" + id + "&xCenterReal=" + x + "&yCenterReal=" + y + "&zoomLevel=" + zoom;
}


function mapResult() {
	this.type			= "address";
	this.centerX		= 0;
	this.centerY		= 0;
	this.mapName		= "";
	this.coordValue		= "";
	this.omc			= 0;
	this.placeName		= "";
	this.placeID		= 0;
	this.streetName		= "";
	this.streetID		= 0;
	this.stopList		= new Array();
	this.stopNameList	= new Array();
}


function mapRequest() {
	this.odvMap		= null;
	this.mapUsage	= "unknown";
	this.mapType	= "unknown";
	this.objectList = new Array();
}

// Send map input.
function setMapInput() {
	if (document.getElementById('itdLPxx_EFA') && document.getElementById('itdLPxx_EFA').value=='true') {
		var form = 0;
		if (parent.document.forms[1])
			form = 1;

		if (odvMapResult && odvMapRequest.mapUsage) {
			if (odvMapResult.type == "address") {
				var obj = document.forms[form].elements['placeInfo_'+odvMapRequest.mapUsage]; 
				if (obj) obj.value = odvMapResult.omc + ":" + odvMapResult.placeID;
				obj = document.forms[form].elements['placeState_'+odvMapRequest.mapUsage];
				if (obj) obj.value = "notidentified";
				obj = document.forms[form].elements['typeInfo_'+odvMapRequest.mapUsage];
				if (obj) obj.value = "coord";
				obj = document.forms[form].elements['nameInfo_'+odvMapRequest.mapUsage];
				if (obj) {
					if (odvMapResult.coordValue.length > 0) {
						obj.value = odvMapResult.coordValue;
					}
					else {
						obj.value = odvMapResult.centerX + ":" + odvMapResult.centerY + ":" + odvMapResult.mapName + ":" + odvMapResult.streetName;
					}
				}
				if (odvMapRequest.mapUsage!='dm' && odvMapRequest.mapUsage!='stt'){
					obj = parent.document.forms[form].elements['execInst'];
					if (obj) obj.value = "verifyOnly";
				}
				obj = document.forms[form].elements['nameState_'+odvMapRequest.mapUsage];
				if (obj) obj.value = "notidentified";
			}
			else if (odvMapResult.type == "poi") {
				var obj = parent.document.forms[form].elements['placeInfo_'+odvMapRequest.mapUsage]; 
				if (obj) obj.value = odvMapResult.omc + ":" + odvMapResult.placeID;
				obj = parent.document.forms[form].elements['typeInfo_'+odvMapRequest.mapUsage];
				if (obj) obj.value = "poiID";
				obj = parent.document.forms[form].elements['nameInfo_'+odvMapRequest.mapUsage];
				if (obj) obj.value = odvMapResult.poiID;
				if (odvMapRequest.mapUsage!='dm' && odvMapRequest.mapUsage!='stt'){
					obj = parent.document.forms[form].elements['execInst'];
					if (obj) obj.value = "verifyOnly";
				}
			}		
			else if (odvMapResult.type == "stop"){			
				var obj = parent.document.getElementById('placeInfo_'+odvMapRequest.mapUsage);
				if (obj) obj.value = "";
				obj = parent.document.forms[form].elements['typeInfo_'+odvMapRequest.mapUsage];
				if (obj) obj.value = "stopID";
				var obj = parent.document.forms[form].elements['nameInfo_'+odvMapRequest.mapUsage];
				if (obj) {
					obj.value = "";
					for (var iStop = 0; iStop < odvMapResult.stopList.length; iStop++) {
						if (iStop > 0) obj.value += ":";
						obj.value += odvMapResult.stopList[iStop];
					}
				}
				if (odvMapRequest.mapUsage!='dm' && odvMapRequest.mapUsage!='stt'){
					obj = parent.document.forms[form].elements['execInst'];
					if (obj) obj.value = "verifyOnly";
				}
				obj = parent.document.forms[form].elements['deleteAssignedStops_'+odvMapRequest.mapUsage];
				if (obj) obj.value = '1';		
			}
			parent.document.forms[form].submit();
		}
	}
}


// ==================================================================
// Stop/station, poi and address tooltips.
// ==================================================================

// create a tooltip
MDVMapHelper.prototype.onToolTip = function(id, msg, obj) {
	if (obj.isFixed())
		return;
	if (obj.isVisible()) {
		if (!obj.helper)
			obj.helper = new MDVToolTipHelper(obj);
		obj.helper.execute(obj);
	}
};


function MDVToolTipHelper(toolTip) {
	this.toolTip = toolTip;
	this.processed = false;
}

// This function creates the tooltip bubble.
MDVToolTipHelper.prototype.execute = function(tooltip) {
	if (!this.processed) {
		var name = '';
		name = 'name_' + this.toolTip.getParent().objectId.id;
		var type = tooltip.getParent().objectId.type;
		var omc = tooltip.getParent().objectId.omc;
		var id = tooltip.getParent().objectId.id;
		var body = '<div id="' + name + '">';
		
		body += this.toolTip.getInnerHTML();
		body += '</div>';

		this.toolTip.setInnerHTML(body);
		toolTipHelpers[name] = this;
	}
	this.processed = true;
};


// ==================================================================
// Trip request context menu functions.
// ==================================================================

// The context menu handler gets the mouse coordinates and the centre coordinates 
// when on origen/destination was selected via context menu. The centre coordinates 
// are useful to set the origin/destination marker on the clicked point. 
function ContextMenuHandler(id, status, obj) {
	if(status == true)
		ctxCoords = obj;
}


// This context menu functions submits a selected point.
MDVMapHelper.prototype.setCoordinatesOrigin = function() {
	setCoordinates('origin');
};

MDVMapHelper.prototype.setCoordinatesMyLocation = function() {
	setCoordinates('pp');
};

MDVMapHelper.prototype.setCoordinatesDestination = function() {
	setCoordinates('destination');
};


function setCoordinates(odvUsage) {
	if (parent){
		// text displayed in the GUI
		var text;
		if(odvUsage=='pp')
			text = mapMyLocation;
		else if(odvUsage=='destination')
			text = mapDestination;
		else 
			text = mapOrigin;
			
		var result = parent.odvMapResult;
		if (result) {
			var mapName = mdvMap.mdvMap.config.get('mapName');
			result.desc = text;
			result.coordValue = parseInt(ctxCoords.x) +":" + parseInt(ctxCoords.y) + ":" + ctxCoords.mapName + ":" + text;
			parent.setMapInput();
		}
	}
};	




// ==================================================================
// Event listener.
// ==================================================================

function attachEventListener(target, eventType, functionRef, capture) {
  if (typeof target.addEventListener != "undefined") {
	target.addEventListener(eventType, functionRef, capture);
  }
  else if (typeof target.attachEvent != "undefined") {
	target.attachEvent("on" + eventType, functionRef);
  }
  else {
	eventType = "on" + eventType;

	if (typeof target[eventType] == "function") {
	  var oldListener = target[eventType];

	  target[eventType] = function() {
		oldListener();

		return  functionRef();
	  }
	}
	else {
	  target[eventType] = functionRef;
	}
  }
  return true; 
}


// ==================================================================
// Overwritten map functionality: corrects the highlightning of an icon 
// on map.
// ==================================================================
function MDVMarker_onload (e) {
	e = e ? e : window.event;           

	// We need to wait for the onload event in Firefox as it doesn't provide proper values for img width and height, if we don't wait.
	if (this.marker) {
		this.marker.update();
		if (!this.marker.append && this.marker.layer) {
			this.mdvMap.markerObjects.appendChild(this);
			this.marker.append = true;	   
	   }
	}
}















