// map
var mdvMapsArr = new Array();
var mdvMapConfigs = new Array();
var mdvMiniMapConfigs = new Array();
var usages = new Array("origin", "destination", "via", "dm", "ttb", "stt", "pp");
// stop or poi ids
var idArr = new Array();
// coordinates of the right mouse click
var ctxCoords = null;
// tooltips array
var toolTipHelpers = new Array();
// initial center and zoom level
var x = '5601329'
var y = '817315';
var zoom = '3';
// output
var mdvOutputMaps = new Array();

// map configuration
function initMdvInlineMapConfig(usage) {
	// map configuration
	mdvMapConfigs[usage] = mdvMapConfig.clone();
	mdvMapConfigs[usage].add('serverURL', 'http://efa.vor.at/map/vor/tiles/map/'); 
	mdvMapConfigs[usage].add('efaURL', 'XML_MAP_REQUEST');
	mdvMapConfigs[usage].add('transparentImg', 'img/transparent.gif');
	mdvMapConfigs[usage].add('imagePath', 'img/');
	mdvMapConfigs[usage].add('network', 'vor');
	mdvMapConfigs[usage].add('defaultScale', zoom);
	mdvMapConfigs[usage].add('xCenterReal', x); // 5601329
	mdvMapConfigs[usage].add('yCenterReal', y); // 817315
	mdvMapConfigs[usage].add('mapName', 'TEL5');
	mdvMapConfigs[usage].add('block', '100');
	mdvMapConfigs[usage].add('toolTimeOut', '20');
	mdvMapConfigs[usage].add('zoomOnDoubleClick', 'true');
	mdvMapConfigs[usage].add('language', mapLanguage);
	mdvMapConfigs[usage].add('useMagnifyGlass', 'true');
	mdvMapConfigs[usage].add('cursorMove', 'img/grabbing.cur');
	mdvMapConfigs[usage].add('useBubbleForEFAInfo', 'true');
	mdvMapConfigs[usage].add('useBubbleOverflowForEFAInfo', 'true');
	mdvMapConfigs[usage].add('useBubblePinForEFAInfo', 'false');
	mdvMapConfigs[usage].add('info.stop.size.width', '300');
	mdvMapConfigs[usage].add('info.stop.size.height', '230');
	mdvMapConfigs[usage].add('info.poi.size.width', '250');
	mdvMapConfigs[usage].add('info.poi.size.height', '80');
	
	// mini map configuration
	mdvMiniMapConfigs[usage] = mdvMiniMapConfig.clone();
	mdvMiniMapConfigs[usage].add('serverURL', 'http://efa.vor.at/map/vor/tiles/map/');
	mdvMiniMapConfigs[usage].add('efaURL', 'XML_MAP_REQUEST');
	mdvMiniMapConfigs[usage].add('transparentImg', 'img/transparent.gif');
	mdvMiniMapConfigs[usage].add('network', 'vor');
	mdvMiniMapConfigs[usage].add('defaultScale', '3');	
	mdvMiniMapConfigs[usage].add('xCenterReal', '5601329');
	mdvMiniMapConfigs[usage].add('yCenterReal', '817315');
	mdvMiniMapConfigs[usage].add('mapName', 'TEL5');
	mdvMiniMapConfigs[usage].add('block', '100');
	mdvMiniMapConfigs[usage].add('toolTimeOut', '20');
	mdvMiniMapConfigs[usage].add('zoomOnDoubleClick', 'true');	
	mdvMiniMapConfigs[usage].add('cursorMove', 'img/grabbing.cur');
}

// output map configuration
function mdvOutputMapConfig (obj) {
	// map
	obj.config.add('serverURL','http://efa.vor.at/map/vor/tiles/map/'); 
	obj.config.add('transparentImg', 'img/transparent.gif');
	obj.config.add('tripURL', '../wienLite/XSLT_TRIP_REQUEST2');
	obj.config.add('network', 'vor');
	obj.config.add('defaultScale', '2');
	obj.config.add('xCenterReal', x);
	obj.config.add('yCenterReal', y);
	obj.config.add('mapName', 'TEL5');
	obj.config.add('imagePath', 'img/');
	obj.config.add('block', '100');
	obj.config.add('zoomOnDoubleClick', 'true');
	obj.config.add('useMagnifyGlass', 'true');
	obj.config.add('cursorMove', 'img/grabbing.cur');
	obj.config.add('trips.marker.size.height', '150');
	obj.config.add('trips.marker.size.width', '250');
	obj.config.add('toolTimeOut', '20');
	obj.config.add('language', mapLanguage);
	obj.config.add('zoomOnDoubleClick', 'true');
	obj.config.add('useMagnifyGlass', 'true');
	obj.config.add('cursorMove', 'img/grabbing.cur');
	obj.config.add('trips.polyline.size.height', '65');
	obj.config.add('trips.polyline.size.width', '300');
	obj.config.add('trips.polyline.opacity', '1');
	obj.config.add('trips.polyline.weight', '4');
	
	// mot colours 	
	obj.config.add('motColour_0', '#0000FF'); 	// nicht belegt
	obj.config.add('motColour_1', '#FF0000');	// ubahn
	obj.config.add('motColour_2', '#00797A');	// s-bahn
	obj.config.add('motColour_3', '#FF0000');	// bus
	obj.config.add('motColour_4', '#7AA6FF');	// tram
	obj.config.add('motColour_5', '#0000FF');	// nicht belegt
	obj.config.add('motColour_6', '#0000FF');	// train
	obj.config.add('motColour_7', '#0000FF');	// nicht belegt
	obj.config.add('motColour_8', '#0000FF');	// anruf sammeltaxi
	obj.config.add('motColour_9', '#0000FF');	// nicht belegt
	obj.config.add('motColour_10', '#0000FF');	// nicht belegt
	obj.config.add('motColour_11', '#0000FF');	// nicht belegt
	obj.config.add('motColour_12', '#0000FF');	// nicht belegt
	obj.config.add('motColour_99', '#009B00');	// fussweg
	obj.config.add('motColour_100', '#009B00');	// fussweg
	obj.config.add('motColour_101', '#0000FF');	// fahrrad (bike & ride)	
	obj.config.add('motColour_102', '#0000FF');	// fahrrad (take bike along)
	obj.config.add('motColour_103', '#0000FF');	// pkw (kiss & ride)
	obj.config.add('motColour_104', '#0000FF');	// pkw (park & ride)
	obj.config.add('motColour_105', '#0000FF');	// taxi 
	obj.config.add('motColour_106', '#0000FF');	// pkw (monomodal)
	obj.config.add('motColour_107', '#000000');	// fahrrad (monomodal)
	obj.config.add('motColour_108', '#0000FF');
	
	// mini map
	obj.miniMapConfig.add('serverURL', 'http://efa.vor.at/map/vor/tiles/map/'); 
	obj.miniMapConfig.add('transparentImg', 'img/transparent.gif');
	obj.miniMapConfig.add('tripURL', '../wienLite/XSLT_TRIP_REQUEST2');
	obj.miniMapConfig.add('network', 'vor');
	obj.miniMapConfig.add('defaultScale', '2');
	obj.miniMapConfig.add('xCenterReal', x);
	obj.miniMapConfig.add('yCenterReal', y);
	obj.miniMapConfig.add('mapName', 'TEL5');
	obj.miniMapConfig.add('imagePath', 'img/');
	obj.miniMapConfig.add('block', '100');
	obj.miniMapConfig.add('zoomOnDoubleClick', 'true');
	obj.miniMapConfig.add('useMagnifyGlass', 'true');
	obj.miniMapConfig.add('cursorMove', 'img/grabbing.cur');
	obj.miniMapConfig.add('toolTimeOut', '20');
}


// This function loads and initializes the map when the site is loaded.
function onLoadInlineMapHandler(mapUsage, xCenter, yCenter) {
	if (document.getElementById('mdvMap_' + mapUsage)) {
		document.getElementById('mdvMap_' + mapUsage).style.display = 'block';
	
		initMdvInlineMapConfig(mapUsage);

		if (mapUsage && document.getElementById('mdvMap_' + mapUsage)) {
			if (mdvMapsArr[mapUsage] == null) 
				mdvMapsArr[mapUsage] = new MDVMapHelper(mapUsage, xCenter, yCenter);
		}
	}
	// output maps
	else {
		var maps = document.getElementsByTagName('div');
		for (var i=0; i < maps.length; i++) {
			if (maps[i].className == 'map mdvMap outputMap') {
				mdvOutputMaps[maps[i].id]  = new MDVMapHelperResults(maps[i]);
			}
		}
	}
};


// This function unloads the map when the site is unloaded.
function onUnloadInlineMapHandler() {
	for(var i=0; i<usages.length; i++) {
		var usage = usages[i];
		if (mdvMapsArr[usage]) 
			mdvMapsArr[usage].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(mapUsage, xCenter, yCenter) {
	this.mdvMap = null;
	this.mdvMiniMap = null;
	this.markerLayer = null;
	this.value = null;
	this.marker = null;
	this.sync = null;
	this.usage = mapUsage;
	
	// initialize map and register events
	if (this.mdvMap == null) {
		this.mdvMap = new MDVMap(document.getElementById('mdvMap_' + this.usage));
		
		// 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;
		
		// context menu and tooltip 
		this.ctxMenuArr = new Array();
		if (this.usage=='pp') 
			this.ctxMenuArr[0] = new MDVMapMenuItem(setMyLocation, this.setCoordinatesMyLocation);
		else if (this.usage=='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, this, ContextMenuHandler);
		// highlight stop or poi
		this.mdvMap.events.registerEvent(MDVEvent_LAYER_UPDATED, this, this.highlightPoint);
			
		this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, submitObject);
		this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
		
		new MDVMapNavigator(this.mdvMap);
		new MDVMapEFAInfo(this.mdvMap);	
		new MDVMapControl(this.mdvMap, controlText);
		
		this.markerLayer = this.mdvMap.createLayer('vipMarkers');
		this.mdvMap.addLayer(this.markerLayer);
	}
	
	// initialize the mini map
	if (this.mdvMiniMap == null) {
		this.mdvMiniMap = new MDVMap(document.getElementById('mdvMiniMap_' + this.usage));
		new MDVMapNavigator(this.mdvMiniMap);
	}
	
	// execute map and minimap
	if (this.mdvMap && this.mdvMiniMap) {
		this.mdvMap.execute(mdvMapConfigs[mapUsage]);			
		this.mdvMiniMap.execute(mdvMiniMapConfigs[mapUsage]);
		this.sync = new MDVMapSyncBound(this.mdvMap, this.mdvMiniMap);
	}

	// sets the zoomlevel and centre for an identified locality
	this.doIdentified(xCenter, yCenter);

	// 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) {
	if (layer && idArr) {
		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[this.usage].length; i++) {
				if (object.id == idArr[this.usage][i].id) {
					var img = marker.getImage();
					img.className='markedIcon';
					break;
				}
			}
		}
	}
};


// Sets the zoomlevel and center for an identified locality
MDVMapHelper.prototype.doIdentified = function(xCenter, yCenter) {
	if (xCenter!='' && xCenter!='') {
		var usage = this.usage;
		var mapName = this.mdvMap.config.get('mapName');
		var mapCoords = new MDVCoordinates(mapName, xCenter, yCenter);
		this.mdvMap.setCentre(mapCoords);
		this.mdvMap.setZoomLevel(7);
		
		// address (selected by click or entered by form) 
		if(document.getElementById('type_' + usage) && (document.getElementById('type_' + usage).value=='coord' || document.getElementById('type_' + usage).value=='address' || ((document.getElementById('type_' + usage).value=='any') && (document.getElementById('anyType_' + usage) && document.getElementById('anyType_' + usage).value!='stop' && document.getElementById('anyType_' + usage).value!='poi')))) {
			// set origin/destination marker			
			if (xCenter!='' && yCenter!='' && mapName!='') {
				var marker = new MDVCoordinates(mapName, parseInt(xCenter), parseInt(yCenter));
				//this.setMarker(marker, usage);
				this.marker = this.mdvMap.createMarker(marker, 0, this.getMarkerImage());
				this.markerLayer.addMarker(this.marker);
			}
		}
		
		this.mdvMap.update();
	}	
} 

// Processed if clicked on a stop or poi.
function submitObject(id, msg, obj) {
	var type = obj.type;
	var omc = obj.omc;
	var id = obj.id;
	var form = 0;
	var usage = this.usage;
	var prefix;
	
	if (this.usage == 'ttb' && document.forms[1]) {
		form = 1;
	}

	if (type == 'poi') {
		prefix = '';
		type = 'poiID';
	}
	else 
		prefix = 'stopID:';
		
	if (document.getElementById('placeInfo_' + usage)) {
		if (type=='poiID')
			document.getElementById('placeInfo_' + usage).value = omc + ':-1';
		else 
			document.getElementById('placeInfo_' + usage).value = '0:0';
	}
	if (document.getElementById('typeInfo_' + usage)) 	
		document.getElementById('typeInfo_' + usage).value = type;
	if (document.getElementById('nameInfo_' + usage))
		document.getElementById('nameInfo_' + usage).value = prefix + id;
	
	if (usage!='dm' && usage!='stt' && usage!='ttb')	
		document.forms[form].execInst.value = 'verifyOnly';
	document.forms[form].submit();
}


// Returns the image for the adress marker.
MDVMapHelper.prototype.getMarkerImage = function(){
	var img = 'img/address.gif';

	if (this.usage == 'origin')
			img = 'img/origin.gif';
	else
			img = 'img/destination.gif';
			
	var i = new Image();
		i.src = img;

	return img;
}

// If map is available: Synchronisation of map with name list

function mapSynchronisation (obj, usage) {
	if (document.getElementById('itdLPxx_mapOpen_' + usage).value == 'true') 
		mdvMapsArr[usage].onChangeList(obj);
}


// Synchronisation of map with name list.
MDVMapHelper.prototype.onChangeList = function(obj) {	
	/*this.mdvMap.setZoomLevel(7);
	
	var selectedIndex = 0;
	if (obj != null) {
		selectedIndex = obj.selectedIndex;
	}
	var temp = idArr[this.usage][selectedIndex];
	
	switch (temp.type) {
		case 'place':
			this.doPlace(temp);
			break;
		case 'stop':
			this.doStop(temp);
			break;
		case 'poi':
			this.doPOI(temp);
			break;
		case 'address':
			if (temp.x == '' && temp.y == '' && temp.streetID > 0) {
				this.doAddress(temp);
				break;
			}
		default:
			this.doCoordinates(temp);
			break;
	}
	
	this.mdvMap.update();*/
};


// ==================================================================
// 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.processed == null) {
			
			if (!obj.helper)
				obj.helper = new MDVToolTipHelper(obj);
			obj.helper.execute(obj);
		}
		else if (obj.getParent().objectId.type == 'STOP' || obj.getParent().objectId.type == 'stop') { 
			obj.dm.getDepartures(obj.getParent().objectId.id);
		}
	}
};

function MDVToolTipHelper(toolTip) {
	this.toolTip = toolTip;
	this.processed = false;
}

// This function creates the tooltip bubble.
MDVToolTipHelper.prototype.execute = function(tooltip) {
	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;
	
	// load departure monitor
	if (type=='STOP' || type=='stop') {
		tooltip.dm = new MDVEFADepartureMonitor(tooltip.parentMarker.objectId.id, name, '../dm/XSLT_DM_REQUEST');
		tooltip.dm.getDepartures(id);
	}
	
	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() {
	var usage = 'origin';
	var form = 0;
	
	if (this.usage == 'ttb' && document.forms[1]) 
		form = 1;

	if (document.forms[form].itdLPxx_mapUsage)
		usage = document.forms[form].itdLPxx_mapUsage.value;
		
	setCoordinates(usage);
};

MDVMapHelper.prototype.setCoordinatesMyLocation = function() {
	setCoordinates('pp');
};

MDVMapHelper.prototype.setCoordinatesDestination = function() {
	setCoordinates('destination');
};


function setCoordinates(usage) {
	// text displayed in the GUI
	var text;
	if(usage=='pp')
		text = mapMyLocation;
	else if(usage=='destination')
		text = mapDestination;
	else 
		text = mapOrigin;
	
	var form = 0;
	if (usage == 'ttb' && document.forms[1]) {
		form = 1;
	}
	if (mdvMapsArr[usage] && mdvMapsArr[usage].mdvMap) {
		var mapCentre = mdvMapsArr[usage].mdvMap.getCentre();
		var text = (usage === 'destination') ? mapDestination : mapOrigin;
		document.getElementById('typeInfo_' + usage).value = 'coord';
		
		if (document.getElementById('type_' + usage)) {
			document.getElementById('type_' + usage).value = 'coord';
		}
		if (document.getElementById('nameState_' + usage)) {
			document.getElementById('nameState_' + usage).value = 'empty';
		}
		if (document.getElementById('placeState_' + usage)) {
			document.getElementById('placeState_' + usage).value = 'empty';
		}
		if (document.getElementById('placeInfo_' + usage)) {
			document.getElementById('placeInfo_' + usage).value = '';
		}
		if (document.getElementById('place_' + usage)) {
			document.getElementById('place_' + usage).value = '';
		}
		
		document.getElementById('nameInfo_' + usage).value = parseInt(ctxCoords.x) + ':' + parseInt(ctxCoords.y) + ':' + ctxCoords.mapName + ':' + text;
		if (usage!='dm' && usage!='stt' && usage!='ttb')
			document.forms[form].execInst.value = 'verifyOnly';
		document.forms[form].submit();
	}
};	


// ====================================================
// Output maps
// ====================================================

function MDVMapHelperResults(viewport) {
	this.viewport = viewport;
	this.config = mdvMapConfig.clone();
	this.miniMapConfig = mdvMiniMapConfig.clone();
	
	if (this.config.params.length > 0)
		return false;
		
	// load map configuration
	mdvOutputMapConfig(this);	

	this.mdvMap = null;
	this.mdvMiniMap = null;
	this.trips = null;
	this.mdvMapTripsLoaded = false;
	
}

// create output map
MDVMapHelperResults.prototype.display = function() {
	// lazy creation
	if (!this.mdvMap) {
		this.mdvMap = new MDVMap(this.viewport);
		
		// 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;
		
		new MDVMapEFAInfoEx(this.mdvMap);
		new MDVMapControl(this.mdvMap, controlText);

		this.trips =	new MDVMapEFATrips(this.mdvMap);
		new MDVMapNavigator(this.mdvMap);
		// initialize the mini map
		
		if (!this.mdvMiniMap) {
			var minimapId = this.viewport.id.split('_')[1];
			if (document.getElementById('mdvMiniOutputMap_' + minimapId)) {
				this.mdvMiniMap = new MDVMap(document.getElementById('mdvMiniOutputMap_' + minimapId));
				new MDVMapNavigator(this.mdvMiniMap); 
				this.mdvMiniMap.execute(this.miniMapConfig);
				
				this.mdvMapSync = new MDVMapSyncBound(this.mdvMap, this.mdvMiniMap);
				
			}
		}
		this.mdvMap.execute(this.config);
		this.mdvMapSync.updateMiniMap(null, null, this.mdvMap);
	}
};

// display a journey on output map
MDVMapHelperResults.prototype.displayJourney = function(sessionID, requestID, tripIndex) {
	if (!this.mdvMapTripsLoaded) {
		this.trips.loadTrip(sessionID, requestID, tripIndex, true);
		this.mdvMapTripsLoaded = true;
	}
}


// ==================================================================
// Departure Monitor functions.
// ==================================================================

function MDVEFADepartureMonitor(name, id, url) {
	this.name  	= name;
	this.id 	= id;
	this.url 	= url;
}


MDVEFADepartureMonitor.prototype.getDepartures = function (identifier) {
	var params = { language: mapLanguage, type_dm: 'stop', name_dm: this.name, mode: 'direct', limit: 5, itdLPxx_identifier: this.id, itdLPxx_mapLanguage: mapLanguage, itdLPxx_name: this.name};
		$.post(this.url, params, MDVEFADepartureMonitor_onComplete)
};

function MDVEFADepartureMonitor_onComplete(response) {
	var id = response.substr(response.indexOf("id=\""));
	id = id.substr(4, id.indexOf("_dm\">")-4);
	
	var text = response; 

	var target = document.getElementById(id);
	target.innerHTML += '<br/><br/>' + text;
}


// ==================================================================
// 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;	   
	   }
	}
}
















