var mdvOAKMapHelper = null;
var storedPOIHierarchy = '';
var rdrct = null;

function onLoadMapHandler(viewport) {
	if (document.getElementById('mdvMap') && typeof mdvMapConfig == 'object') {
		mdvOAKMapHelper = new MDVMapOAKHelper(document.getElementById('mdvMap'), document.getElementById('mdvMiniMap'));
	} else if (document.getElementById('mdvMap') && typeof mdvMapConfig != 'object') {
		alert('Error encountered while loading resources required for the mapping system. Please check your internet connection and try again.');
	}
}

function MDVMapOAKHelper(mapDiv, miniDiv) {
	this.mdvMap = null;
	this.mdvMiniMap = null;
	this.mdvSync = null;
	this.mdvMapper = null;
	this.mdvRailSystems = null;
	this.mdvMapTrips = null;

	this.mousePos = null;
	this.clickPos = null;
	this.releasePos = null;
	this.clickJob = null;
	
	this.stops = [];
	this.markers = [];
	this.markers['dm'] = null;
	this.markers['origin'] = null;
	this.markers['destination'] = null;
	
	this.state = null;
	
	this.markerOffset = [];
	this.markerOffset['planATrip'] 	= new MDVPoint(0.17, 0.69);
	this.markerOffset['nss'] 		= new MDVPoint(0.15, 0.7);

	// Reduction Mask Array
	this.red = [
			{ maxScale:     700, epsilon:   1 },
			{ maxScale:    1375, epsilon:   2 },
			{ maxScale:    2750, epsilon:   2 },
			{ maxScale:    5500, epsilon:   2 },
			{ maxScale:   11000, epsilon:   5 },
			{ maxScale:   22000, epsilon:   8 },
			{ maxScale:   44000, epsilon:  15 },
			{ maxScale:   88000, epsilon:  25 },
			{ maxScale:  176000, epsilon:  40 },
			{ maxScale:  352000, epsilon:  60 },
			{ maxScale:  704000, epsilon: 140 },
			{ maxScale: 1400000, epsilon: 300 }
		];
	
	this.execute(mapDiv, miniDiv);
}

MDVMapOAKHelper.prototype.toString = function () {
	var str = "";
	
	if (this.mdvMap == null || this.mdvMap.config == null)
		return str;
	
	var state = '{ zoom: ' + this.mdvMap.config.getZoomLevelIndex() + ', center: new MDVCoordinates("MTCV", ' + this.mdvMap.getCentre().x + ', ' + this.mdvMap.getCentre().y + ') }';
	
	switch (this.getState()) {
		case 0:			
			// Trip Planner
			
			if (this.markers['origin']) {
				this.markers['origin'].toString = function() {
					var s = '{ coords: new MDVCoordinates("MTCV", ' + this.getCoords().x + ', ' + this.getCoords().y + ') }';
					return s;
				};
			}

			if (this.markers['destination']) {
				this.markers['destination'].toString = function() {
					var s = '{ coords: new MDVCoordinates("MTCV", ' + this.getCoords().x + ', ' + this.getCoords().y + ') }';
					return s;
				};
			}
			
			if (this.mdvMapTrips) {
				this.mdvMapTrips.toString = function() {
					var str = '{}';
					if (this.sessionID && this.sessionID != '') {
						str = '{ sessionID: "' + this.sessionID + '", requestID: "' + this.requestID + '", routePos: "' + this.routePos + '" }';
					}
					return str;
				};
			}
			
			var points = '';
			
			if (this.markers['origin']) {
				points += 'origin: ' + this.markers['origin'];
			}
			
			if (this.markers['destination']) {
				if (points.length > 0)
					points += ', ';
				points += 'destination: ' + this.markers['destination'];
			}
			
			str = '{ tp: { state: ' + state + ', trips: ' + this.mdvMapTrips + ', points: { ' + points + ' } } }';
			
			break;
		case 1:
			// Nearby Routes and Services

			if (this.markers['dm']) {
				this.markers['dm'].toString = function() {
					var s = '{ coords: new MDVCoordinates("MTCV", ' + this.getCoords().x + ', ' + this.getCoords().y + ') }';
					return s;
				};
			}
			
			var points = '';
			
			var arr = '[ ';
			var i=0;
			for (s in this.stops) {
				if (this.stops[s].id >= 0) {
					this.stops[s].toString = function() {
						str = '';						
						str = '{ coords: new MDVCoordinates("MTCV", ' + this.getCoords().x + ', ' + this.getCoords().y + '), factor: new MDVPoint(' + this.xFactor + ', ' + this.yFactor + '), img: "' + this.imgSrc + '" }';
						
						return str;
					};										
					if (i > 0)
						arr += ', ';
					arr += this.stops[s];					
					i++;
				}
			}
			arr += ' ]';
			
			if (this.markers['dm']) {
				points += 'dm: ';
				points += this.markers['dm'];
			}
			
			var routes = '[]';
			if (this.mdvMapper && this.mdvMapper.routes.length > 0) {				
				this.mdvMapper.routes.toString = function () {
					var str = '[ ';
						for (var i=0; i < this.length; i++) {
							var r = this[i];
							var coords = [ 0, 0 ];
							
							if (r.coords.length > 0)
								coords = r.coords.split(':');
								
							if (i > 0)
								str += ', ';
							str += '{ line: "' + r.retrieve + '", type: ' + r.type + ', coords: new MDVCoordinates("MTCV", ' + coords[0] + ', ' + coords[1] + ') }';
						}
					str += ' ]';
					return str;
				};
				
				routes = this.mdvMapper.routes.toString();
			}
			
			str = '{ nrs: { state: ' + state + ', points: { ' + points + ' }, stops: ' + arr + ', routes: ' + routes +  ' } }';

			break;
		case 2:
			// Rail Systems
			
			var lines = '[]';
			if (this.mdvRailSystems && this.mdvRailSystems.current && this.mdvRailSystems.current.length > 0) {
				this.mdvRailSystems.current.toString = function() {
					var ret = '[ ';
					for (var i=0; i < this.length; i++) {
						var l = this[i];
						if (i > 0)
							ret += ', ';
						ret += l;
					}
					ret += ' ]';
					
					return ret;
				};
				
				lines = this.mdvRailSystems.current.toString();
			}
			
			str = '{ rp: { state: ' + state + ', lines: ' + lines + ' } }';

			break;
	}
		
	return str;
};

MDVMapOAKHelper.prototype.planTo = function(id) {
	var baseURL = 'XSLT_TRIP_REQUEST2?language=en&sessionID=0&itdLPxx_homepage=secondStep';
	var params  = '&type_destination=stopID&name_destination=' + id;
	
	var target = baseURL + params;
		
	window.location = target;
};

MDVMapOAKHelper.prototype.planFrom = function(id) {
	var baseURL = 'XSLT_TRIP_REQUEST2?language=en&sessionID=0&itdLPxx_homepage=secondStep';
	var params  = '&type_origin=stopID&name_origin=' + id;
	
	var target = baseURL + params;
		
	window.location = target;
};

MDVMapOAKHelper.prototype.link = function(id, usage) {
	var target = parseInt(id);
	
	if (!this.mdvMapTrips || !this.mdvMapTrips.polylines)
		return;
		
	for (var i=0; i < this.mdvMapTrips.polylines.length; i++) {
		var p = this.mdvMapTrips.polylines[i];	
		
		if (p.leg.points[0].ref.id == id &&
			p.leg.points[0].usage == usage) {
			
			if (p.markers[usage] && p.markers[usage].toolTip)
				p.markers[usage].toolTip.display();
			
			return;
		} else if (p.leg.points[1].ref.id == id &&
			p.leg.points[1].usage == usage) {
			
			if (p.markers[usage] && p.markers[usage].toolTip)
				p.markers[usage].toolTip.display();

			return;
		}
	}
};

MDVMapOAKHelper.prototype.loadTrip = function (sessionID, requestID, routePos) {


	this.mdvMapTrips.loadTrip(sessionID, requestID, routePos);

	if (!this.mdvMapTrips.sessionID) {
		for (var i=0; i < countRoutes; i++) {
			mdvEventLog.trigger('SECTION1_ITINERARY_GENERATED', 'itinerary.html', '', '&ext=' + i);
		}
	}
		
	mdvEventLog.trigger('SECTION1_ITINERARY_VIEWED', 'itinerary.html', '');
	
	var spans = document.getElementsByTagName('span');
	for (var i=0; i < spans.length; i++) {
		var s = spans[i];
		
		if (s.name && s.name.indexOf('operator_') != -1) {
			var p = s.name.split('_')[1];
			var o = s.getAttribute('operator');
			
			if (parseInt(p) == routePos && o != '') {				
				mdvEventLog.trigger('SECTION1_AGENCY_APPEARS_IN_ITINERARY', 'itinerary.html', o, i + '&agencyids=' + o);
			}				
		}
	}
	
	this.mdvMapTrips.sessionID = sessionID;
	this.mdvMapTrips.requestID = requestID;
	this.mdvMapTrips.routePos = routePos;
	
	document.getElementById('routePos').value = routePos;
}

MDVMapOAKHelper.prototype.checkState = function () {
	var nameStateOrig = document.getElementById('nameState_origin');
	var nameStateDest = document.getElementById('nameState_destination');
	var nameStateDM = document.getElementById('nameState_dm');

	var nameOrig = document.getElementById('name_origin');
	var nameDest = document.getElementById('name_destination');
	var nameDM = document.getElementById('name_dm');
	
	var locationDm = document.getElementById('location_dm');
	
	if (nameStateOrig && nameStateOrig.value == 'list') {
		var e = { srcElement: nameOrig };
		
		this.setListEntry(e);
		
		attachEventListener(nameOrig, 'change', this.setListEntry.bind(this), false);
	} else if (nameStateOrig && nameStateOrig.value == 'identified') {
		this.setIdentifiedEntry(nameOrig);
	}
	
	if (nameStateDest && nameStateDest.value == 'list') {
		var e = { srcElement: nameDest };
		
		this.setListEntry(e);
		
		attachEventListener(nameDest, 'change', this.setListEntry.bind(this), false);
	} else if (nameStateDest && nameStateDest.value == 'identified') {
		this.setIdentifiedEntry(nameDest);
	}
	
	if (nameStateDM && nameStateDM.value == 'list') {
		var e = { srcElement: nameDM };
		
		this.setListEntry(e);
		
		attachEventListener(nameDM, 'change', this.setListEntry.bind(this), false);
	} else if (locationDm && locationDm.getAttribute('x') && locationDm.getAttribute('y')) {
		this.setIdentifiedEntry(locationDm);
	}
	
	if ((nameStateOrig && nameStateOrig.value == 'list' && this.markers['origin']) &&
		(nameStateDest && nameStateDest.value == 'list' && this.markers['destination'])) {
		
		var newC = new MDVCoordinates('MTCV', (this.markers['origin'].getCoords().x + this.markers['destination'].getCoords().x) / 2, (this.markers['origin'].getCoords().y + this.markers['destination'].getCoords().y) / 2);
		this.mdvMap.setZoomLevel(3);
		this.mdvMap.setCentre(newC);
		this.mdvMap.update();
	}
	
	var beautify = { origin: null, destination: null };
	
	// Revise Search, Reverse, Onward....
	if (nameStateOrig && nameStateOrig.value == 'notidentified' &&
		nameOrig && nameOrig.value == 'Selected from Map' &&
		nameOrig.getAttribute('x') && nameOrig.getAttribute('y')) {
		
		this.setIdentifiedEntry(nameOrig, false);
		beautify.origin = new MDVCoordinates('MTCV', nameOrig.getAttribute('x'), nameOrig.getAttribute('y'));
	}
		
	if (nameStateDest && nameStateDest.value == 'notidentified' &&
		nameDest && nameDest.value == 'Selected from Map' &&
		nameDest.getAttribute('x') && nameDest.getAttribute('y')) {
		
		this.setIdentifiedEntry(nameDest, false);
		beautify.destination = new MDVCoordinates('MTCV', nameDest.getAttribute('x'), nameDest.getAttribute('y'));
	}
	
	// Beautify
	if (beautify.origin && beautify.destination) {
		var newCentre   = new MDVCoordinates('MTCV', 0, 0);
			newCentre.x = Math.floor(0.5 + (beautify.origin.x + beautify.destination.x) / 2);
			newCentre.y = Math.floor(0.5 + (beautify.origin.y + beautify.destination.y) / 2);
			
		var dist   = new MDVPoint(0, 0);
			dist.x = Math.abs(beautify.destination.x - beautify.origin.x);
			dist.y = Math.abs(beautify.destination.y - beautify.origin.y);
			
		var zls = this.mdvMap.config.getZoomLevels();
		var tzl = 0;
		var found = new MDVPoint(0, 0);
		
		for (var z=zls.length-1; z >= 0; z--) {
			var zl = zls[z];
			
			var tiles = this.mdvMap.getViewportExtends();
				tiles.width  /= parseInt(zl.get('tileSizeX'));
				tiles.height /= parseInt(zl.get('tileSizeY'));
			
			var viewport   = new MDVPoint(0, 0);
				viewport.x = parseInt(zl.get('realWidth')) / parseInt(zl.get('numberOfTilesX')) * tiles.width;
				viewport.y = parseInt(zl.get('realHeight')) / parseInt(zl.get('numberOfTilesY')) * tiles.height;
			
			if (dist.x < viewport.x) {
				tzl = z;
				found.x = true;
			}
				
			if (dist.y < viewport.y) {
				tzl = z;
				found.y = true;
			}
			
			if (found.x && found.y)
				break;
		}
		
		this.mdvMap.setZoomLevel(tzl);		
		this.mdvMap.setCentre(newCentre);
		this.mdvMap.update();
	} else if (beautify.origin) {
		this.mdvMap.setCentre(beautify.origin);
		this.mdvMap.update();
	} else if (beautify.destination) {
		this.mdvMap.setCentre(beautify.destination);
		this.mdvMap.update();
	}
};

MDVMapOAKHelper.prototype.setIdentifiedEntry = function (src) {
	if (!src)
		return false;
		
		var x = src.getAttribute('x');
		var y = src.getAttribute('y');
		
		if (x == null || y == null)
			return;
			
		var coords = new MDVCoordinates('MTCV', x, y);
		
		switch (src.id) {
			case 'name_dm':
			case 'location_dm':
				var locationTypeDm = document.getElementById('locationType_dm');
			
				if (this.getState() != 1)
					return;
			
				if (!this.markers['dm']) {
					this.markers['dm'] = this.mdvMap.createMarker(coords, this.markerOffset['nss'].clone(), 'fw/mdv/pin_nss.png');
					this.mdvMap.addMarker(this.markers['dm']);
				} else
					this.markers['dm'].setCoords(coords);
			break;
			case 'name_origin':
				if (!this.markers['origin']) {
					this.markers['origin'] = this.mdvMap.createMarker(coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_start.png');
					this.mdvMap.addMarker(this.markers['origin']);
				} else
					this.markers['origin'].setCoords(coords);
			break;
			default:
				if (!this.markers['destination']) {
					this.markers['destination'] = this.mdvMap.createMarker(coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_end.png');
					this.mdvMap.addMarker(this.markers['destination']);
				} else
					this.markers['destination'].setCoords(coords);
			break;
		}
		
		if (arguments.length == 1) {
			this.mdvMap.setCentre(coords);
			this.mdvMap.setZoomLevel(5);
			this.mdvMap.update();
		}
};

MDVMapOAKHelper.prototype.setListEntry = function (e) {
	var src = e.srcElement ? e.srcElement : e.target;
	
	var nInput = document.getElementById('nInput' + src.id.substr(src.id.indexOf('_')));	
	var pInput = document.getElementById('pInput' + src.id.substr(src.id.indexOf('_')));
	
	if (src && src.selectedIndex >= 0 && src[src.selectedIndex] && src[src.selectedIndex].getAttribute('x') && src[src.selectedIndex].getAttribute('y')) {
		var x = src[src.selectedIndex].getAttribute('x');
		var y = src[src.selectedIndex].getAttribute('y');
		var coords = new MDVCoordinates('MTCV', x, y);
		
		switch (src.name) {
			case 'name_dm':
				if (!this.markers['dm']) {
					this.markers['dm'] = this.mdvMap.createMarker(coords, this.markerOffset['nss'].clone(), 'fw/mdv/pin_nss.png');
					this.mdvMap.addMarker(this.markers['dm']);
				} else
					this.markers['dm'].setCoords(coords);
			break;
			case 'name_origin':
				if (!this.markers['origin']) {
					this.markers['origin'] = this.mdvMap.createMarker(coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_start.png');
					this.mdvMap.addMarker(this.markers['origin']);
				} else
					this.markers['origin'].setCoords(coords);
			break;
			default:
				if (!this.markers['destination']) {
					this.markers['destination'] = this.mdvMap.createMarker(coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_end.png');
					this.mdvMap.addMarker(this.markers['destination']);
				} else
					this.markers['destination'].setCoords(coords);
			break;
		}
		
		if (nInput && src[src.selectedIndex] && src[src.selectedIndex].getAttribute('input') &&
			pInput && src[src.selectedIndex] && src[src.selectedIndex].getAttribute('locality')) {

			nInput.value = src[src.selectedIndex].getAttribute('input');
			pInput.value = src[src.selectedIndex].getAttribute('locality');
		}
		
		this.mdvMap.setCentre(coords);
		this.mdvMap.setZoomLevel(5);
		this.mdvMap.update();
	}
};

MDVMapOAKHelper.prototype.setClickMarkers = function () {
	this.clickJob = null;

	var nameStateOrig = document.getElementById('nameState_origin');
	var nameStateDest = document.getElementById('nameState_destination');
	var nameOrig = document.getElementById('name_origin');
	var nameDest = document.getElementById('name_destination');
	
	var requestID = document.getElementById('requestID');
	
	var defaultText = 'Address, Intersection or Landmark';
	
	if (!nameStateOrig || !nameStateDest)
		return;

	if (this.clickPos && !this.markers['origin'] && (nameStateOrig.value == 'empty' || parseInt(requestID.value) > 1) && nameOrig && (nameOrig.value == defaultText || nameOrig.value == '')) {
		this.markers['origin'] = this.mdvMap.createMarker(this.clickPos.clone(), this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_start.png');
		this.mdvMap.addMarker(this.markers['origin']);		
		
		this.clickPos = null;
		
		if (nameOrig) {
			nameOrig.value = 'Selected from Map';
			nameOrig.style.color = '#000000';
		}
	} else if (this.clickPos && !this.markers['destination'] && (nameStateDest.value == 'empty' || parseInt(requestID.value) > 1) && nameDest && (nameDest.value == defaultText || nameDest.value == '')) {
		this.markers['destination'] = this.mdvMap.createMarker(this.clickPos.clone(), this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_end.png');
		this.mdvMap.addMarker(this.markers['destination']);

		this.clickPos = null;
		
		if (nameDest) {
			nameDest.value = 'Selected from Map';
			nameDest.style.color = '#000000';
		}
	}
	
};

MDVMapOAKHelper.prototype.setDMClickMarker = function () {
	this.clickJob = null;

	var nameStateDM = document.getElementById('nameState_dm');
	var nameDM = document.getElementById('name_dm');
	
	if (!nameStateDM)
		return;

	if (this.clickPos && !this.markers['dm'] && nameStateDM.value == 'empty') {
		this.markers['dm'] = this.mdvMap.createMarker(this.clickPos.clone(), this.markerOffset['nss'].clone(), 'fw/mdv/pin_nss.png');
		this.mdvMap.addMarker(this.markers['dm']);		
		
		this.clickPos = null;
		
		if (nameDM)
			nameDM.value = 'Selected from Map';
			nameDM.style.color = '#000000';
	} 
	
};

MDVMapOAKHelper.prototype.onSubmit = function () {
	var nameOrig = document.getElementById('name_origin');
	var nameDest = document.getElementById('name_destination');
	var nameVia = document.getElementById('name_via');
	var nameDM = document.getElementById('name_dm');

	var nOrig = document.getElementById('nInput_origin');
	var nDest = document.getElementById('nInput_destination');
	var nVia = document.getElementById('nInput_via');
	var nDM = document.getElementById('nInput_dm');

	var pOrig = document.getElementById('pInput_origin');
	var pDest = document.getElementById('pInput_destination');
	var pVia = document.getElementById('pInput_via');
	var pDM = document.getElementById('pInput_dm');

	// Map selection?
	if (this.markers['origin'] && nameOrig && nameOrig.value == 'Selected from Map') {
		var typeOrig = document.getElementById('type_origin');		
		var nameInfoOrig = document.getElementById('nameInfo_origin');
		
		var coords = this.markers['origin'].getCoords();
		
		typeOrig.value = 'coord';
		nameInfoOrig.value = coords.x + ':' + coords.y + ':' + coords.mapName + ':' + nameOrig.value;
	}

	if (this.markers['destination'] && nameDest && nameDest.value == 'Selected from Map') {
		var typeDest = document.getElementById('type_destination');		
		var nameInfoDest = document.getElementById('nameInfo_destination');

		var coords = this.markers['destination'].getCoords();

		typeDest.value = 'coord';
		nameInfoDest.value = coords.x + ':' + coords.y + ':' + coords.mapName + ':' + nameDest.value;
	}
	
	if (this.markers['dm'] && nameDM && nameDM.value == 'Selected from Map') {
		var typeDM = document.getElementById('type_dm');		
		var nameInfoDM = document.getElementById('nameInfo_dm');

		var coords = this.markers['dm'].getCoords();

		typeDM.value = 'coord';
		nameInfoDM.value = coords.x + ':' + coords.y + ':' + coords.mapName + ':' + nameDM.value;
	}
	
	// List == Input?
	if (nameOrig && nameOrig.selectedIndex >= 0 && nOrig && pOrig) {
		var s = nameOrig[nameOrig.selectedIndex];
		var c = true;
		var inputOrig = document.getElementById('nameInput_origin');
		var placeOrig = document.getElementById('place_origin');
		
		if (s.getAttribute('input') != nOrig.value) {			
			inputOrig.value = nOrig.value;
			c = false;
		}
		
		if (s.getAttribute('locality') != pOrig.value) {			
			placeOrig.value = pOrig.value;
			if (c)
				inputOrig.value += ' ';
		}
	}

	if (nameDest && nameDest.selectedIndex >= 0 && nDest && pDest) {
		var s = nameDest[nameDest.selectedIndex];
		var c = true;
		var inputDest = document.getElementById('nameInput_destination');
		var placeDest = document.getElementById('place_destination');
		
		if (s.getAttribute('input') != nDest.value) {
			inputDest.value = nDest.value;
			c = false;
		}
		
		if (s.getAttribute('locality') != pDest.value) {
			placeDest.value = pDest.value;
			if (c)
				inputDest.value += ' ';
		}
	}
	
	if (nameVia && nameVia.selectedIndex >= 0 && nVia && pVia) {
		var s = nameVia[nameVia.selectedIndex];
		var c = true;
		var inputVia = document.getElementById('nameInput_via');
		var placeVia = document.getElementById('place_via');
		
		if (s.getAttribute('input') != nVia.value) {
			inputVia.value = nVia.value;
			c = false;
		}
		
		if (s.getAttribute('locality') != pVia.value) {
			placeVia.value = pVia.value;
			if (c)
				inputVia.value += ' ';
		}
	}
	
	
	if (nameDM && nameDM.selectedIndex >= 0 && nDM && pDM) {
		var s = nameDM[nameDM.selectedIndex];
		var c = true;
		var inputDM = document.getElementById('nameInput_dm');
		var placeDM = document.getElementById('placeInput_dm');
		
		if (s.getAttribute('input') != nDM.value) {
			inputDM.value = nDM.value;
			c = false;
		}
		
		if (s.getAttribute('locality') != pDM.value) {
			placeDM.value = pDM.value;
			if (c)
				inputDM.value += ' ';
		}
	}
	
};

MDVMapOAKHelper.prototype.onToolTip = function (id, msg, obj) {
	if (showStationsInMap != null && showStationsInMap == true && obj.isVisible() && obj.processed != true) {
		var name = obj.getInnerHTML();
		
		obj.setInnerHTML(name + '<br/><br/><a href="http://204.94.80.141/areamaps/XSLT_ROP_REQUEST?language=en&command=direct&net=oak&reqType=stopmap&stopID=' + (parseInt(obj.getParent().getObjectId().id) - 10000000) + '" target="_blank">Stop/Station Area Map</a>');
		obj.processed = true;
		
		return;
	}
	
	if (!obj.isVisible() || !obj.getParent() || !obj.getParent().leg || obj.done)
		return;
		
	var p = document.getElementById('spanTable_' + document.getElementById('routePos').value);
	var t = obj.getInnerHTML();
		
	if (p && p.innerHTML) {
		var temp = t.replace(/\>Trip /gi, '>' + p.innerHTML + ' ');
		obj.done = true;
		obj.setInnerHTML(temp);
	}
};

MDVMapOAKHelper.prototype.getFacilities = function (div, stop) {	
	var target = div.parentElement || div.parentNode;
	
	if (!target)
		return;
		
	var stopID = stop.split('_')[0];
		
	var text  = '<map name="switch_' + stopID + '"><area href="javascript:mdvOAKMapHelper.changeFacilities(1, \'' + stop + '\')" coords="0,0,80,30"/><area href="javascript:mdvOAKMapHelper.changeFacilities(2, \'' + stop + '\')" coords="72,0,143,30"/><area href="javascript:mdvOAKMapHelper.changeFacilities(3, \'' + stop + '\')" coords="145,0,216,30"/><area href="javascript:mdvOAKMapHelper.changeFacilities(4, \'' + stop + '\')" coords="218,0,288,30"/></map>';
		text += '<div style="width: 292px; height: 300px; position: relative; left: -5px; background: url(fw/bubble_facilities1_bg.gif) no-repeat; padding: 0px; margin: 0px;" id="bubbleBg_' + stopID + '">';
		text += '<img src="fw/mdv/transparent.gif" usemap="#switch_' + stopID + '" width="259" height="31"/>';
		text += '<div style="width:290px; height:108px; padding-top: 4px; padding-left: 0px; font-size: 120%; overflow: auto; overflow-y: auto; overflow-x: hidden;" id="facilities_' + stopID + '">';
		text += '<div style="padding: 5px; width:238px;" id="fContent_' + stopID + '">';
		text += 'Loading...';
		text += '</div>';
		text += '</div>';
	
	target.innerHTML = text;
	
	var c = document.getElementById('fContent_' + stopID);	
	this.fetchFacilities('parking', stop, c);

	var f = document.getElementById('facilities_' + stopID);
	var i = document.getElementById('fInfo_' + stopID);	
	
	if (!i)
		return;
	
	var iheight = this.mdvMap.getObjHeight(i);
	if (iheight > 0)
		f.style.height = (parseInt(f.style.height) - iheight) + 'px';
	else
		f.style.height = (parseInt(f.style.height) - 1) + 'px';		
};

MDVMapOAKHelper.prototype.fetchFacilities = function (state, stop, div) {
	var arr = stop.split('_');	
	var stopID = '';
	var area = '';
	var platform = '';
	var URL = 'XSLT_REQUEST';
	
	if (arr.length >= 1)
		stopID = arr[0];
		
	if (arr.length >= 2)
		area = arr[1];

	if (arr.length >= 3)
		platform = arr[2];
		
	if (state == 'features' || state == 'routes')
		URL = 'XSLT_DM_REQUEST';
		
	
	var _params = { language: 'en', itdLPxx_provider: 'facilities', itdLPxx_type: state, itdLPxx_stopID: stopID, itdLPxx_area: area, itdLPxx_platform: platform, lsShowTrainsExplicit: 1, type_dm: 'stopID', name_dm: stopID };
		_params = $H(_params);
		_params = _params.toQueryString();

	var _ajax = new Ajax.Request(URL, { method: 'post', parameters: _params, onComplete: this.onFacilitiesComplete.bind(div) });
};

MDVMapOAKHelper.prototype.onFacilitiesComplete = function (response) {
	this.innerHTML = response.responseText;
};

MDVMapOAKHelper.prototype.changeFacilities = function (state, stop) {
	var stopID = stop.split('_')[0];
	var target = document.getElementById('bubbleBg_' + stopID);
	var c = document.getElementById('fContent_' + stopID);	
	var tab = 'parking';
	
	if (target) {
		target.style.backgroundImage = 'url(fw/bubble_facilities' + state + '_bg.gif)';
		c.innerHTML = 'Loading...';
		
		switch (state) {
			case 1:
				tab = 'parking';
				break;
			case 2:
				tab = 'cycling';
				break;
			case 3:
				tab = 'routes';
				break;
			case 4:
				tab = 'features';
				break;
			default:
				tab = 'parking';
				break;
		}
		
		this.fetchFacilities(tab, stop, c);
	}
};

MDVMapOAKHelper.prototype.execute = function (mapDiv, miniDiv) {

	if (!mapDiv)
		return false;
		
	// Map
	this.mdvMap = 	new MDVMap(mapDiv);
	this.mdvMapTrips = new MDVMapEFATrips(this.mdvMap, { getMarker: getTripMarker, reductionList: this.red });
					new MDVMapNavigator(this.mdvMap);
					new MDVRectZoom(this.mdvMap, {
						opacity: 0.0,
						border: '3px solid red',
						useButton: true,
						buttonImg: 'panBtn.png',
						buttonImgOver: 'panBtn_rollover.png',
						buttonImgActive: 'panBtn_active.png',

						buttonPosLeft: '11px',
						buttonPosTop: '390px'						
					});	
					new MDVMapControl(this.mdvMap, {
						posTop: '3px',
						posLeft: '3px'
					});
					
	if (showStationsInMap != null && showStationsInMap == true) {
		new MDVMapEFAInfoEx(this.mdvMap);
		this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, populateMapInfo);
	}					
					
	var config = mdvMapConfig.clone();
	this.applyConfig(config);
	
	// Map Events
	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.onMapInitialised);
	this.mdvMap.events.registerEvent(MDVEvent_MOUSE_MOVED, this, this.onMouseMove);
	this.mdvMap.events.registerEvent(MDVEvent_MOUSE_DOWN, this, this.onMouseDown);
	this.mdvMap.events.registerEvent(MDVEvent_MOUSE_UP, this, this.onMouseUp);
	this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.onClicked);
	//this.mdvMap.events.registerEvent(MDVEvent_AJAX_CALLBACK, this, this.onTripCompleteCallback);
	this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
	
	this.mdvMap.execute(config);
	
	if (!miniDiv)
		return false;
	
	// MiniMap
	this.mdvMiniMap = new MDVMap(miniDiv);
					  new MDVMapNavigator(this.mdvMiniMap);
	this.mdvMiniMapConfig = mdvMiniMapConfig.clone();
	this.applyMiniConfig(this.mdvMiniMapConfig);

	var mdvMapSlider = new MDVMapSlider(this.mdvMap, {
		sliderOffsetTop: 64,
		sliderOffsetLeft: 18
	});	
	new MDVMapScale(this.mdvMap, {});		
	
	attachEventListener(document, 'mouseup', this.mdvMap.release.bind(this.mdvMap), false);
	attachEventListener(document, 'mouseup', mdvMapSlider.onKnobUp.bind(mdvMapSlider), false);
	
	for (var i=0; i < document.forms.length; i++) {
		attachEventListener(document.forms[i], 'submit', this.onSubmit.bind(this), false);
	}
	
	var sessionID = document.getElementById('sessionID').value;
	var requestID = document.getElementById('requestID').value;	
	
	//IE 7 Bug
	if(sessionID==0 && document.getElementById('sessionID').id!=sessionID && document.forms['formTripRequestResult'])
	{
		sessionID = document.forms['formTripRequestResult'].sessionID.value;
	}
	
	var target = this.getHighlightedTrip();
	
	if (target)
		this.loadTrip(sessionID, requestID, target);

	this.checkState();
	
	if (this.getState() == 1) {
		this.mapStops();
		this.mdvMapper = new MDVMapOAKObjectMapper(this);
	} else if (this.getState() == 2)
		this.mdvRailSystems = new MDVMapOAKRailSystems(this);
		
	if (this.getState() == 0 && target) {
		mdvEventLog.trigger('SECTION1_ITINERARY_MAP', 'coverage.html', '');
	} else if (this.getState() == 0) {
		mdvEventLog.trigger('SECTION1_TRIPPLANNER_COVERAGE_MAP', 'coverage.html', '');		
	}
};

MDVMapOAKHelper.prototype.onTripCompleteCallback = function (id, msg, obj) {
	if (msg != 'MDVMapEFATrips')
		return;

	var start = obj.trips.trip.legs[0] || obj.trips.trip.legs.leg;
	var end   = obj.trips.trip.legs[obj.trips.trip.legs.length-1] || obj.trips.trip.legs.leg;
	
	if (start) {
		var c = start.path.split(' ')[0].split(',');
		this.markers['origin'] = this.mdvMap.createMarker(new MDVCoordinates('MTCV', c[0], c[1]), this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_start.png');		
		this.mdvMap.addMarker(this.markers['origin']);
	}	

	if (end) {
		var c = end.path.split(' ')[end.path.split(' ').length-1].split(',');
		this.markers['destination'] = this.mdvMap.createMarker(new MDVCoordinates('MTCV', c[0], c[1]), this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_end.png');
		this.mdvMap.addMarker(this.markers['destination']);
	}	
};

MDVMapOAKHelper.prototype.getHighlightedTrip = function () {
	for (var i=1; i <= 100; i++) {
		var temp = document.getElementById('itineraryBox_' + i );
		if (temp && temp.style.display != 'none')
			return i;
	}
	
	return null;
};

MDVMapOAKHelper.prototype.onMouseMove = function (id, msg, obj) {	
	this.mousePos = obj;
};

MDVMapOAKHelper.prototype.onMouseUp = function (id, msg, obj) {
	this.releasePos = this.mousePos.clone();
	
	var src = obj.srcElement ? obj.srcElement : obj.target;
	
	if (src.offsetParent && src.offsetParent.id == 'mdvMap_mdvMarkers')
		return;

	if (src.offsetParent && src.offsetParent.tagName == 'svg')
		return;
		
	if (this.clickJob != null) {
		window.clearTimeout(this.clickJob);
		this.clickJob = null;
		
		return;
	}
		
	if (this.releasePos.equals(this.clickPos)) {
		switch (this.getState()) {
			case 1:
				this.clickJob = window.setTimeout("mdvOAKMapHelper.setDMClickMarker()", 500);				
			break;
			case 0:
				this.clickJob = window.setTimeout("mdvOAKMapHelper.setClickMarkers()", 500);
			break;
		}
	}
};

MDVMapOAKHelper.prototype.onMouseDown = function (id, msg, obj) {
	this.clickPos = this.mousePos.clone();
};

MDVMapOAKHelper.prototype.onClicked = function (id, msg, obj) {
	var nameOrig = document.getElementById('name_origin');
	var nameDest = document.getElementById('name_destination');
	var nameDM = document.getElementById('name_dm');

	var placeOrig = document.getElementById('place_origin');
	var placeDest = document.getElementById('place_destination');
	var placeDM = document.getElementById('place_dm');

	var nameStateOrig = document.getElementById('nameState_origin');
	var nameStateDest = document.getElementById('nameState_destination');
	var nameStateDM = document.getElementById('nameState_dm');
	
	var locationTypeDm = document.getElementById('locationType_dm');
	
	var sum = document.getElementById('collapsingSummary');
	
	if (sum)
		return;
	
	if (this.markers['origin'] && 
		this.markers['origin'].id == obj.marker.id &&
		nameStateOrig.value != 'list' &&
		nameStateOrig.value != 'identified') {
		
		this.mdvMap.removeMarker(this.markers['origin']);
		this.markers['origin'] = null;
		
		if (nameOrig && nameOrig.value == 'Selected from Map')
			nameOrig.value = 'Address, Intersection or Landmark';
		
		if (placeOrig)
			placeOrig.value = '';
			
	} else if (this.markers['destination'] &&
		this.markers['destination'].id == obj.marker.id &&
		nameStateDest.value != 'list' &&
		nameStateDest.value != 'identified') {
		
		this.mdvMap.removeMarker(this.markers['destination']);
		this.markers['destination'] = null;

		if (nameDest && nameDest.value == 'Selected from Map')
			nameDest.value = 'Address, Intersection or Landmark';
		
		if (placeDest)
			placeDest.value = '';
			
	} else if (this.markers['dm'] &&
		this.markers['dm'].id == obj.marker.id &&
		nameStateDM.value != 'list' &&
		nameStateDM.value != 'identified' &&
		locationTypeDm == null) {
		
		this.mdvMap.removeMarker(this.markers['dm']);
		this.markers['dm'] = null;

		if (nameDM && nameDM.value == 'Selected from Map')
			nameDM.value = '';
		
		if (placeDM)
			placeDM.value = '';
	}
};

MDVMapOAKHelper.prototype.onMapInitialised = function (id, msg, obj) {
	if (this.mdvMiniMap && 
		this.mdvMap &&
		this.mdvMap.config &&
		this.mdvMiniMap.config &&
		this.mdvMiniMap.config.getZoomLevel(this.mdvMap.config.getZoomLevelIndex())==null) {
		
		if (getParent(this.mdvMiniMap.viewport)) {
			getParent(this.mdvMiniMap.viewport).style.display = 'none';
			this.mdvSync.hideButton(true);
		}
		
	} else if (this.mdvMap && this.mdvMiniMap && this.mdvMiniMap.state != 1
		&& this.mdvMiniMapConfig.getZoomLevel(this.mdvMap.config.getZoomLevelIndex())!=null) {

		getParent(this.mdvMiniMap.viewport).style.display = 'block';
		
		this.mdvMiniMapConfig.add('defaultScale', this.mdvMap.config.getZoomLevelIndex());

		this.mdvMiniMap.execute(this.mdvMiniMapConfig);
		this.mdvSync = new MDVMapSyncBound(this.mdvMap, this.mdvMiniMap);
		this.mdvSync.execute(this.mdvMiniMap.viewport.offsetParent);
	} else if (this.mdvMiniMap && 
		this.mdvMap &&
		this.mdvMap.config &&
		this.mdvMiniMap.config &&
		this.mdvMiniMap.viewport &&
		getParent(this.mdvMiniMap.viewport) &&
		getParent(this.mdvMiniMap.viewport).style.display == 'none') {
		
		getParent(this.mdvMiniMap.viewport).style.display = 'block';		
		this.mdvSync.hideButton(false);
		this.mdvMiniMap.setCentre(this.mdvMap.getCentre().clone());
		this.mdvMiniMap.update();
		
	}
};

MDVMapOAKHelper.prototype.applyConfig = function (config) {	
	for (var z in config.zoomLevels) {
		if (typeof config.zoomLevels[z] == 'object') {
			for (var p in config.zoomLevels[z].params) {
				if (typeof config.zoomLevels[z].params[p] == 'string') {
				
					if (parseInt(z) <= 6 && p == 'showSTOP')
						config.zoomLevels[z].params[p] = 'false';
					else if (p == 'showSTOP')
						config.zoomLevels[z].params[p] = 'true';
					if (p == 'showPOI')
						config.zoomLevels[z].params[p] = 'false';
					if (p == 'showSTOP.majorMeans')
						config.zoomLevels[z].params[p] = '6';					
				}
			}
		}			
	}
	
	config.add('defaultScale', '1');
	config.add('serverURL', 'http://maps.tripplanner.transit.511.org/maps/oak/tiles/');
	config.add('efaURL', '../lite/XSLT_COORD_REQUEST');
	config.add('tripURL', '../lite/XSLT_TRIP_REQUEST2');
	config.add('transparentImg', 'fw/mdv/transparent.gif');
	config.add('imagePath', 'fw/mdv/');
	config.add('cursorMove', 'fw/mdv/grabbing.cur');
	config.add('mapName', 'MTCV');
	config.add('network', 'OAK');
	config.add('tooltipHandler', 'onclick');
	config.add('useMagnifyGlass', 'true');
	config.add('omitDoubleClick', 'true');
	config.add('useBubbleForEFAInfo', 'true');
	config.add('useBubbleOverflowForEFAInfo', 'false');
	config.add('xCenterReal', '562725');
	config.add('yCenterReal', '841665');
	config.add('block', '100');
	
	config.add('useToolTipScrollToFit', 'true');
	config.add('hotspotOnMouseWheel', 'true');
	
	config.add('info.stop.size.width', '210');
	config.add('info.stop.size.height', '80');
  	config.add('trips.marker.size.width', '310');
    config.add('trips.marker.size.height', '206');
  	config.add('trips.polyline.size.width', '220');
    config.add('trips.polyline.size.height', '105');
	
	config.add('useDirectionsForEFATrips', 'false');
    config.add('trips.polyline.arrows.max', '112');
    config.add('trips.polyline.arrows.maxScale', '200000');
	
	config.add('trips.polyline.opacity', '0.8');

	/* Linienbreite - Standard sind 3 */
	config.add('trips.polyline.weight', '4');

	// configuration of output map
	config.add('motColour_0', '#0000FF'); 	// nicht belegt
	config.add('motColour_1', '#FF0000');	// ubahn
	config.add('motColour_2', '#00797A');	// s-bahn
	config.add('motColour_3', '#525252');	// bus
	config.add('motColour_4', '#7AA6FF');	// tram
	config.add('motColour_5', '#0000FF');	// nicht belegt
	config.add('motColour_6', '#990000');	// train
	config.add('motColour_7', '#0000FF');	// nicht belegt
	config.add('motColour_8', '#0000FF');	// anruf sammeltaxi
	config.add('motColour_9', '#003366');	// schiff
	config.add('motColour_10', '#162A80');	// schiff
	config.add('motColour_11', '#162A80');	// nicht belegt
	config.add('motColour_12', '#162A80');	// nicht belegt
	config.add('motColour_99', '#009999');	// fussweg
	config.add('motColour_100', '#009999');	// fussweg
	config.add('motColour_101', '#009999');	// fahrrad (bike & ride)	
	config.add('motColour_102', '#009999');	// fahrrad (take bike along)
	config.add('motColour_103', '#009999');	// pkw (kiss & ride)
	config.add('motColour_104', '#009999');	// pkw (park & ride)
	config.add('motColour_105', '#00CCFF');	// taxi 
	config.add('motColour_106', '#0000FF');	// pkw (monomodal)
	config.add('motColour_107', '#000000');	// fahrrad (monomodal)
	config.add('motColour_108', '#0000FF');
};

MDVMapOAKHelper.prototype.applyMiniConfig = function (config) {
	config.add('defaultScale', '1');
	config.add('serverURL', 'http://maps.tripplanner.transit.511.org/maps/oak/tiles/');
	config.add('transparentImg', 'fw/mdv/transparent.gif');
	config.add('imagePath', 'fw/mdv/');
	config.add('cursorMove', 'images/grabbing.cur');
	config.add('mapName', 'MTCV');
	config.add('network', 'OAK');
	config.add('useMagnifyGlass', 'true');
	config.add('omitDoubleClick', 'true');
	config.add('xCenterReal', '562725');
	config.add('yCenterReal', '841665');
	config.add('block', '100');
};

MDVMapOAKHelper.prototype.clear = function (update, className) {

	if (this.markers['origin']) {
		this.mdvMap.removeMarker(this.markers['origin']);
		this.markers['origin'] = null;
	}
	
	if (this.markers['destination']) {
		this.mdvMap.removeMarker(this.markers['destination']);
		this.markers['destination'] = null;
	}

	if (this.mdvMapTrips)
		this.mdvMapTrips.clear();

	
	if (this.mdvRailSystems)
		this.mdvRailSystems.clear();
		
	if (className == 'nearbyRoutesSelected' || className == 'nearbyStopsSelected')
		return true;
		
	if (this.markers['dm']) {
		this.mdvMap.removeMarker(this.markers['dm']);
		this.markers['dm'] = null;
	}
	
	var pois = this.mdvMap.getLayer('efa_pois');
	if (pois)
		pois.removeAllMarkers();
		
	if (this.mdvMapper)
		this.mdvMapper.clear();
	
	for (var stop in this.stops) {
		if (this.stops[stop] && this.stops[stop].id != null)
			this.mdvMap.removeMarker(this.stops[stop]);
	}
	
	if (!update && this.mdvMap) {
		this.mdvMap.setZoomLevel(parseInt(this.mdvMap.config.get('defaultScale')));
		this.mdvMap.setCentre(new MDVCoordinates('MTCV', this.mdvMap.config.get('xCenterReal'), this.mdvMap.config.get('yCenterReal')));
		this.mdvMap.update();
	}
	
	
	var sessionID = 0;
	var requestID = 0;
	
	var sIDs = document.getElementsByName('sessionID');
	var rIDs = document.getElementsByName('requestID');
	
	for (var i=0; i < sIDs.length; i++) {
		if (parseInt(sIDs[i].value) != 0) {
			sessionID = sIDs[i].value;
			break;
		}
	}

	for (var i=0; i < rIDs.length; i++) {
		if (parseInt(rIDs[i].value) != 0) {
			requestID = rIDs[i].value;
			break;
		}
	}
	
	var target = this.getHighlightedTrip();
	var state = this.getState();
	
	if (state == 0) {
		mdvEventLog.trigger('SECTION1_TRIP_PLANNING_PAGE_GENERATED', 'index.html', '');			
		
		if (target) {
			this.loadTrip(sessionID, requestID, target);
			mdvEventLog.trigger('SECTION1_ITINERARY_MAP', 'index.html', '');
		}
		else
			mdvEventLog.trigger('SECTION1_TRIPPLANNER_COVERAGE_MAP', 'index.html', '');

		this.checkState();
	} else if (state == 1) {
		mdvEventLog.trigger('SECTION1_NEAR_BY_SERVICES_PAGE_GENERATED', 'index.html', '');
		mdvEventLog.trigger('SECTION1_NEAR_BY_SERVICE_MAP', 'index.html', '');		
		this.mapStops();
	} else if (state == 2 || className == 'tab3Selected') {
		mdvEventLog.trigger('SECTION1_RAIL_SYSTEM_PAGE_GENERATED', 'index.html', '');
		mdvEventLog.trigger('SECTION1_RAIL_SYSTEM_MAP', 'index.html', '');		
		if (!this.mdvRailSystems) {
			var rs = document.getElementById('railSystems') ? document.getElementById('railSystems').value : null;
			this.mdvRailSystems = new MDVMapOAKRailSystems(this, rs);
		} else {
			this.mdvRailSystems.restore();
		}
	}
	
	return true;
};

MDVMapOAKHelper.prototype.isUntouched = function (className)  {
	if (this.mdvRailSystems && this.mdvRailSystems.untouched == false && className == 'tab1Selected') {
		var str = { itdLPxx_rs: this.toString() };
			str = $H(str);
		    str = str.toQueryString();

			if (window.location && window.location.href) {
				rdrct = 'XSLT_TRIP_REQUEST2?language=en&itdLPxx_homepage=secondStep&' + str;
				window.setTimeout( "window.location.href = rdrct;", 0);				
			} else {
				window.location = 'XSLT_TRIP_REQUEST2?language=en&itdLPxx_homepage=secondStep&' + str;
			}
		return false;
	} else if (this.mdvRailSystems && this.mdvRailSystems.untouched == false && className == 'tab2Selected') {
		var str = { itdLPxx_rs: this.toString() };
			str = $H(str);
		    str = str.toQueryString();

			if (window.location && window.location.href) {
				rdrct = 'XSLT_DM_REQUEST?language=en&' + str;
				window.setTimeout( "window.location.href = rdrct;", 0);				
			} else {
				window.location = 'XSLT_DM_REQUEST?language=en&' + str;
			}
		return false;
	}
	
	return true;
};

MDVMapOAKHelper.prototype.mapStops = function () {
	var strongs = document.getElementsByTagName('strong');
	var locs = { x: [], y: [] };
	var that = this;
	
	function getAgencies(id) {
		var a = [];
		var obj = document.getElementById(id);
		
		if (obj == null)
			return null;	
		
		for (var i=1; i <= 50; i++) {
			var c=document.getElementById(id + '_' + i)
			if (c && c.firstChild)
				a.push(c.firstChild.nodeValue.trim());
		}
		
		a.sort();
		
		var e = null;
		var u = [];
		while (e = a.pop()) {
			if (u.length == 0 || u[0] != e) {
				u.unshift(e);
			}
		}
		
		var str = u.join(', ');
		return str;
	}
	
	if (strongs && strongs.length > 0) {
		for (var i=0; i < strongs.length; i++) {
			var s = strongs[i];
			var efaId = s.getAttribute('efa_id');
			if (s == null || efaId == null || efaId == '')
				continue;
								
			var x = s.getAttribute('x');
			var y = s.getAttribute('y');
			var t = s.getAttribute('type');
			var m = this.getIcon(t);
			
			var agencies = getAgencies(s.id.substring(5));
			
			locs.x.push(x);
			locs.y.push(y);
			
			var coords = new MDVCoordinates('MTCV', x, y);			
			var marker = this.mdvMap.createMarker(coords, new MDVPoint(0, 0), m);

			
			var tt = this.mdvMap.createToolTip(new MDVPoint(320, 202), this.getContent(s, agencies));
				tt.done = true;
				tt.stop = efaId;
				marker.setToolTip(tt);
				marker.efaID = efaId;
			this.mdvMap.addMarker(marker, false);
			
			this.stops['s_' + efaId + '_' + t] = marker;
			
			this.addStopClickHandler(s, marker);
		}
		
		for (var i=0; i < strongs.length; i++) {
			var s = strongs[i];
			var mId = s.getAttribute('m_id');

			if (s == null || mId == null || mId == '')
				continue;
				
			var t = s.getAttribute('type');
			var marker = this.stops['s_' + mId + '_' + t];
			
			if (marker) {
				this.addStopClickHandler(s, marker);
			}
		}
	}
	
	var lineState = null;
	eval('lineState = ' + this.state + ';');
	
	if (lineState && lineState.nrs && lineState.nrs.routes) {
		for (var r in lineState.nrs.routes) {
			var	f = lineState.nrs.routes[r];
			if (typeof f == 'function')
				continue;
				
			this.mdvMapper.mapIt('0', f.type, f.line, '0');
		}
	}
	
	if (locs.x.length > 0 && locs.y.length > 0) {
		var centre = this.getNewCentre(locs);
		var zl = 7;
		
		this.mdvMap.setCentre(centre);
		this.mdvMap.setZoomLevel(zl);
		this.mdvMap.update();
	}
};

MDVMapOAKHelper.prototype.getContent = function (item, agencies) {

	var text  = '<div class="smallHeader"><span id="span_' + item.getAttribute('efa_id') + '">';
		text += item.getAttribute('name');
		text += '</span></div>'
		text += '<div class="content" id="stop_' + item.getAttribute('efa_id') + '">';
		//text += '<a href="#">Save to My511</a>';
		//text += '<br/>';

		if (agencies.length > 0) {
			text += '<b>';
			text += agencies.indexOf(',') != -1 ? 'Agencies: ' : 'Agency: ';
			text += agencies;
			text += '</b>';
			text += '<br/>';
			text += '<br/>';
		}
		
		var stopID = item.getAttribute('efa_id');
		var f = item.getAttribute('facilities');
		f = (f != null) && f == 'true' ? true : false;
		
		// text += '<a href="javascript:getNearbyAttractions(\'91075670\',\'0\',' + item.getAttribute('x') +',' + item.getAttribute('y') +',\'stop_' + item.getAttribute('efa_id') +'\');">Nearby Attractions</a>';
		text += '<br/>';
		if (((parseInt(stopID)-10000000) >= 1000 && (parseInt(stopID)-10000000) < 1500) || f) {
			text += '<a href="javascript:void(0);" onclick="mdvOAKMapHelper.getFacilities(this, \'' + stopID +'__\')">Facilities</a>';
			text += '<br/>';
		}
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.zoomIn(new MDVCoordinates(\'MTCV\', ' + item.getAttribute('x') + ', ' + item.getAttribute('y') + '));">Zoom in</a>';
		text += '<br/>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planTo(' + item.getAttribute('efa_id') + ')">Plan a trip to this location</a>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planFrom(' + item.getAttribute('efa_id') + ')">Plan a trip from this location</a>';
		text += '<br/>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.getScheduledDeps(' + item.getAttribute('efa_id') + ', \'\')">Scheduled Departures from this location</a>';
	return text;
};

MDVMapOAKHelper.prototype.addStopClickHandler = function (obj, marker) {
	var p = obj.parentElement || obj.parentNode;

	do {
		if (p && p.tagName == 'TABLE') {
			p.marker = marker;
			attachEventListener(p, 'click', this.onStopClick.bind(this), false);
			return;
		}
	} while(p = p.parentElement || p.parentNode);
};

MDVMapOAKHelper.prototype.onStopClick = function (e) {
	e = e ? e : window.event;
	
	var obj = e.srcElement ? e.srcElement : e.target;
	var p = obj.parentElement || obj.parentNode;

	var that = this;
	
	// WARUM NICHT BEI RAIL STATIONS 
	function resetMarkerBorders () {
	

		for (var s in that.stops) {
		
		
			if (that.stops[s] && that.stops[s].id != null) {
				that.stops[s].img.style.border = '';
				
				var img = that.stops[s].imgSrc;
				
				that.stops[s].img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" +  img + ");"
				
			}
		}
	}
	
	do {
		if (p && p.marker) {
			/*resetMarkerBorders();
			//p.marker.img.style.border = '2px solid #C80805';
			
			if(p.marker.imgSrc=='fw/miniIcons/greenTriangle.gif'){
				p.marker.img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fw/miniIcons/greenTriangle_active.gif');"
				//p.marker.imgSrc = "fw/miniIcons/greenTriangle_active.gif"
			}
			else if(p.marker.imgSrc=='fw/miniIcons/redSquare.gif'){
				p.marker.img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fw/miniIcons/redSquare_active.gif');"
				//p.marker.imgSrc = "fw/miniIcons/redSquare_active.gif"

			}
			else{
				p.marker.img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fw/miniIcons/blueCircle_active.gif');"
				//p.marker.imgSrc = "fw/miniIcons/blueCircle_active.gif"
			}*/
			
			if (p.marker.toolTip)
				p.marker.toolTip.display();
			
			return;
		}		
	} while(p = p.parentElement || p.parentNode);
};

MDVMapOAKHelper.prototype.getNewCentre = function (locs) {
	var x = 0;
	var y = 0;

	locs.x.sort(function (a, b) { return parseInt(b) - parseInt(a); });
	locs.y.sort(function (a, b) { return parseInt(b) - parseInt(a); });
	
	x = (parseInt(locs.x[0]) + parseInt(locs.x[locs.x.length-1])) / 2;
	y = (parseInt(locs.y[0]) + parseInt(locs.y[locs.y.length-1])) / 2;
	
	return new MDVCoordinates('MTCV', Math.floor(0.5 + x), Math.floor(0.5 + y));
};

MDVMapOAKHelper.prototype.getNewZoomLevel = function (locs) {
	var extd = this.mdvMap.getViewportExtends();

	locs.x.sort(function (a, b) { return parseInt(b) - parseInt(a); });
	locs.y.sort(function (a, b) { return parseInt(b) - parseInt(a); });

	var dist = new MDVPoint(parseInt(locs.x[0]) - parseInt(locs.x[locs.x.length-1]), 
			parseInt(locs.y[0]) - parseInt(locs.y[locs.y.length-1]));

    var zls = this.mdvMap.config.getZoomLevels();	
	var bHeight = false; var bWidth = false;
	var zoom = 4;
	
	for (var z=zls.length-1; z >= 0; z--) {
		var zl = zls[z];
		
		var number = new MDVPoint(extd.width / parseInt(zl.get('tileSizeX')), 
						extd.height / parseInt(zl.get('tileSizeY')));
		var size = new MDVPoint(parseInt(zl.get('realWidth')) / parseInt(zl.get('numberOfTilesX')),
					parseInt(zl.get('realHeight')) / parseInt(zl.get('numberOfTilesY')));
					
		var real = new MDVPoint(number.x * size.x, number.y * size.y);
		
		if (!bWidth && real.x > dist.x) {
			zoom = z;
			bWidth = true;
		}
		
		if (!bHeight && real.y > dist.y) {
			zoom = z;
			bHeight = true;
		}
		
		if (bWidth && bHeight)
			break;
	}
	
	return zoom;	
};

MDVMapOAKHelper.prototype.getIcon = function (mot) {
	var ext = '_active';
	
	if (arguments.length >= 2)
		ext = arguments[1];
	
	switch (parseFloat(mot)) {
		case 6:
			return 'fw/miniIcons/redSquare' + ext + '.gif';
		break;
		
		case 3:
			return 'fw/miniIcons/blueCircle' + ext + '.gif';
		break;
		
		case 10:
			return 'fw/miniIcons/greenTriangle' + ext + '.gif';
		break;
		default:
			return 'fw/miniIcons/blueCircle' + ext + '.gif';
		break;
	}
	
	return null;
};

MDVMapOAKHelper.prototype.getState = function () {
	var planTripBox = document.getElementById('planTripBox');
	
	if (!planTripBox)
		return null;
		
	switch (planTripBox.className) {
		case 'tab3Selected':
			return 2;
		case 'tab2Selected':
			return 1;
		default:
			return 0;
		
	}
	
	return null;
};

MDVMapOAKHelper.prototype.mapIt = function (id, type, line, coords) {
	if (this.mdvMapper == null)
		this.mdvMapper = new MDVMapOAKObjectMapper(this);	
	this.mdvMap.hideToolTips();
	this.mdvMap.cancelMoveBySeq();
	this.mdvMapper.mapIt(id, type, line, coords);	
};

MDVMapOAKHelper.prototype.unmapIt = function () {


	if (this.mdvMapper == null)
		this.mdvMapper = new MDVMapOAKObjectMapper(this);
		
	//this.mdvMapper.mapIt(type, line);
	this.mdvMapper.clear();
};

MDVMapOAKHelper.prototype.zoomIn = function (coords) {
	if (coords && this.mdvMap.setCentre(coords)) {
		this.mdvMap.hideToolTips();
		this.mdvMap.setZoomLevel(8);
		this.mdvMap.update();
	}
};

MDVMapOAKHelper.prototype.getScheduledDeps = function (id, divaLine) {

	var ampmSelect 	= document.getElementById('ampmSelect');
	var timeInput 	= document.getElementById('timeInput');
	var timeInputHour 	= document.getElementById('timeInputHour');
	var timeInputMinute 	= document.getElementById('timeInputMinute');
	var dateInput	= document.getElementById('monthDayYearFieldRS');
	

	var dmDate 	= document.getElementById('dmDate');
	var dmTime	= document.getElementById('dmTime');	
	
	var _params = { language: 'en', sessionID: 0, itdLPxx_provider: 'tooltip', type_dm: 'stopID', name_dm: id, mode: 'direct', limit: 8 };
	if (divaLine.length > 0) {
		_params['ptOptionsActive'] = '1';
		_params['inclMOT_0'] = '1';
		_params['includedMeans'] = 'checkbox';
	}
		
	if (ampmSelect && timeInput && dateInput || ampmSelect && timeInputHour && timeInputMinute && dateInput) {
		if (ampmSelect.selectedIndex == 0)
			_params['itdTimeAMPM'] = 'AM';
		else
			_params['itdTimeAMPM'] = 'PM';

		
		if(timeInputHour && timeInputMinute){
			_params['itdTimeHour'] = timeInputHour.value;
			_params['itdTimeMinute'] = timeInputMinute.value;
		}
		else{
			var time = timeInput.value.split(':');
			_params['itdTimeHour'] = time[0];
			_params['itdTimeMinute'] = time[1];	
		}
		
		
		var date = dateInput.value.split('/');
		
		_params['itdDateMonth'] = date[0];
		_params['itdDateDay'] = date[1];
		_params['itdDateFullYear'] = date[2];
	}
	
	if (dmDate && dmTime) {
		_params['itdDate'] = dmDate.value;
		_params['itdTime'] = dmTime.value;
	}

	_params = $H(_params);
	_params = _params.toQueryString();
	
	var element = document.getElementById('stop_' + id);
	
	if (!element)
		return;

	var _ajax = new Ajax.Request('XSLT_DM_REQUEST', { method: 'post', parameters: _params, onComplete: this.onToolTipCallback.bind(element) });
};

MDVMapOAKHelper.prototype.onToolTipCallback = function (response) {	
	this.innerHTML = response.responseText;
};

function MDVMapOAKObjectMapper(helper) {
	this.helper  = helper;
	this.mdvMap  = this.helper.mdvMap;
	this.routes  = [];
	this.rotator = new MDVRotator();
	this.zl 	 = this.mdvMap.config.getZoomLevelIndex();
	this.rep	 = [];
	
	// new layer for routes
	this.layer  = this.mdvMap.createLayer('routes');
	this.mdvMap.addLayer(this.layer);
	
	MDVMapOAKObjectMapper.prototype.getIcon = MDVMapOAKHelper.prototype.getIcon;
	
	this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
	//this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.onZoom);
	
	this.execute();
}

MDVMapOAKObjectMapper.prototype.execute = function() {
	var mapits = document.getElementsByName('mapIt');
	
	for (var i=0; i < mapits.length; i++) {
		var m = mapits[i];
		var line = m.getAttribute('line');
			line = line.replace(/\ /gi, '_');
			line = line.replace(/\:/gi, '_');
		
		if (line && !this.rep[line]) {
			this.rep[line] = [];
			this.rep[line].push(m.id);
		} else if (line && this.rep[line]) {
			this.rep[line].push(m.id);
		}
		
	}
};

MDVMapOAKObjectMapper.prototype.clear = function () {
	var p=null; 
	var l=null;
	while (p = this.routes.pop()) {
		this.remove(p);
	}
	
	this.checkClearLink();
};

MDVMapOAKObjectMapper.prototype.checkClearLink = function () {
	var nrsClearMap = document.getElementById('nrs_clearMap');
	
	if (nrsClearMap && this.rotator.isVacant())
		nrsClearMap.style.visibility = 'hidden';
	else if (nrsClearMap && !this.rotator.isVacant() && !document.all)
		nrsClearMap.style.visibility = 'visible';
};

MDVMapOAKObjectMapper.prototype.getScheduledDeps = function (id) {
	return;
};

MDVMapOAKObjectMapper.prototype.mapIt = function (id, type, line, coords) {
	for (var r=0; r < this.routes.length; r++) {
		var route = this.routes[r];
		
		if (route && route.obj && route.obj.getAttribute('line') == line)
		{
			this.rotator.free(route.obj.line);
			this.remove(route);
			this.routes.splice(r, 1);
			return;
		}			
	}
	
	this.fetch (id, type, line, coords);	
};

MDVMapOAKObjectMapper.prototype.onZoom = function (id, msg, obj) {
	if (this.zl != obj.config.getZoomLevelIndex()) {		
		var pls =  this.layer.getPolylines();
		
		for (var i=0; i < pls.length; i++) {
			var p = pls[i];
			while (d = p.directions.pop()) {
				this.layer.removeMarker(d);
			}
			
			// We are waiting for the coloured dirctions....
			p.directions = p.getDirections();
			
			for (var d=0; d < p.directions.length; d++) {
				this.layer.addMarker(p.directions[d], d == p.directions.length-1);
			}
			
		}
	
		this.zl = obj.config.getZoomLevelIndex();
	}
};

MDVMapOAKObjectMapper.prototype.apply = function (item) {
	if (!item)
		return;
		
	var line = item.retrieve;
	
	if (item.obj)
		line = item.obj.getAttribute('line');
	
		line = line.replace(/\ /gi, '_');
		line = line.replace(/\:/gi, '_');	
		
	var targets = this.rep[line];
	
	for (var i=0; i < targets.length; i++) {
		
		var target = document.getElementById(targets[i]);
		
		if (!target)
			continue;
			
		var n = target.firstChild;	
		
		while (n) {
			if (n.nodeType == 3) {
				n.nodeValue = 'Unmap It';
				break;
			}
				
			n = n.nextSibling;
		}
		
		var img = document.getElementById('img_' + targets[i]);
		
		if (img) {
			img.src = item.image;
		}
	}
};

MDVMapOAKObjectMapper.prototype.remove = function (item) {
	if (!item)
		return;
	
	if (item.obj && item.obj.line)
		this.rotator.free(item.obj.line);
	else
		this.rotator.free(item.retrieve);

	var p = null;
	while (p = item.polylines.pop()) {
		var d = null;
		while (d = p.directions.pop()) {
			this.layer.removeMarker(d);
		}
	
		this.layer.removePolyline(p);
	}
	
	var s = null;
	while (s = item.stops.pop()) {
		this.layer.removeMarker(s);
	}

	var line = item.retrieve;
	
	if (item.obj)
		line = item.obj.getAttribute('line');

		line = line.replace(/\ /gi, '_');
		line = line.replace(/\:/gi, '_');	
		
	var targets = this.rep[line];

	for (var i=0; i < targets.length; i++) {	
		var target = document.getElementById(targets[i]);
		var n = target.firstChild;	
		
		while (n) {
			if (n.nodeType == 3) {
				n.nodeValue = 'Map It';
				break;
			}
				
			n = n.nextSibling;
		}
		
		var img = document.getElementById('img_' + targets[i]);
		
		if (img) {
			img.src = 'fw/mdv/inactive.gif';
		}
	}
	
	this.checkClearLink();
};

MDVMapOAKObjectMapper.prototype.fetch = function (id, type, line, coords) {
	// Syntax: line=oak:52047:_:R:y07::0
	var _param = { line: line, 
				hideBannerInfo: 1, 
				coordListOutputFormat: 'STRING', 
				filterEpsilon: '10.0',
				returnSinglePath: '1',
				itdLPxx_id: id,
				itdLPxx_line: line,
				itdLPxx_type: type,
				itdLPxx_coords: coords	};
				
		_param = $H(_param);
		_param = _param.toQueryString();

	var _ajax = new Ajax.Request('../lite/XSLT_GEOOBJECT_REQUEST', { method: 'post', parameters: _param, onComplete: this.onRouteCallback.bind(this) });
	
};

MDVMapOAKObjectMapper.prototype.onRouteCallback = function (request) {
	var json = request.responseText;
	var efa = null;
	
	eval('efa = ' + json + ';');
	
	if (!efa || !efa.geoObjects || 
		!efa.geoObjects.items || 		
		!efa.geoObjects.items.item.paths ||
		!efa.geoObjects.items.item.mode.diva)
			return;
			
	this.checkSize();
	
	var p = efa.parameters[0] || efa.parameters;
	var i=0;
	var id='';
	var coords = null;
	var retrieve = null;
	
	do {
		i++;
		
	 	if (p && p.name == 'coords') {
			coords = p.value;
		}

	 	if (p && p.name == 'line') {
			retrieve = p.value;
		}
		
		if (p && p.name == 'id') {
			id = p.value;
		}
		
	} while (p = efa.parameters[i]);
	
	if (coords) {
		var c = coords.split(':');
		
		if (c.length == 2) {			
			this.mdvMap.setCentre(new MDVCoordinates('MTCV', c[0], c[1]));
			this.mdvMap.update();
		}
	}
	
	efa.geoObjects.items.item.mode.diva.toString = function () {		
		var branch = this.branch;
		
		if (branch < 10)
			branch = '0' + branch;

		var line = this.line;

		if (line < 10)
			line = '00' + line;
		else if (line < 100)
			line = '0' + line;
		
		return this.network + ':' + branch + line + 
			':' + this.supplement.replace(/\_/gi, ' ') + ':' + this.direction + ':' +
			this.project + '::0';
	};
	
	var mapItId = document.getElementById(id);
	var attr = retrieve;
	if (mapItId && mapItId.getAttribute('line'))
		attr = mapItId.getAttribute('line');		
	
	var f = this.rotator.require(attr);
	var color = f.color;
	var img   = f.image;
	
	var item = { obj: mapItId, color: color, image: img, retrieve: retrieve,
		line: efa.geoObjects.items.item.mode.diva.toString(), 
		type: efa.geoObjects.items.item.mode.code, coords: coords,
		polylines: [], stops: []
	}
	
	var path = efa.geoObjects.items.item.paths[0] || efa.geoObjects.items.item.paths.path;
	var i = 0;
	
	do {
		i++;
		var p = this.mdvMap.createPolyline(path);
		p.add('colour', color);
		p.add('opacity', '1');
		
		p.directions = p.getDirections();
		
		for (var d=0; d < p.directions.length; d++) {
			this.layer.addMarker(p.directions[d], d == p.directions.length-1);
		}
		
		this.layer.addPolyline(p, efa.geoObjects.items.item.paths[i]==null);
		if (item)
			item.polylines.push(p);		
		
	} while (path = efa.geoObjects.items.item.paths[i]);
	
	i = 0;
	
	var stop = efa.geoObjects.items.item.points[0] || efa.geoObjects.items.item.points;	
	
	do {
		i++;
		
		var cs     = stop.ref.coords.split(',');
		var coords = new MDVCoordinates('MTCV', cs[0], cs[1]);
		var marker = null;
		
		if (coords.x > 0 && coords.y > 0) {		
			marker = this.mdvMap.createMarker(coords, new MDVPoint(0.5, 0.5), this.getIcon(efa.geoObjects.items.item.mode.code, '75'));
			
			var tt = this.mdvMap.createToolTip(new MDVPoint(320, 202), this.getContent(stop));
			tt.stop = stop;
			marker.setToolTip(tt);
			
			this.layer.addMarker(marker, efa.geoObjects.items.item.points[i]==null);
		}		

		if (item && marker)
			item.stops.push(marker);
		
		stop = efa.geoObjects.items.item.points[i];
	} while (stop);
	
	this.apply(item);
	
	this.routes.push(item);
	
	this.checkClearLink();
};

MDVMapOAKObjectMapper.prototype.getContent = function (stop) {
	var that = this;
	function match(a) {
		for (s in that.helper.stops) {
			if (that.helper.stops[s].id >= 0) {
				if (that.helper.stops[s].efaID == stop.ref.id)
					return true;
			}
		}
		
		return false;
	}
	
	var isCluster = match(stop);

	var motValue = '12';
	var cs  = stop.ref.coords.split(',');
	var nrs = { name_dm: cs[0] + ':' + cs[1] + ':MTCV:' + stop.name };
		nrs = $H(nrs);
		nrs = nrs.toQueryString();
		
	var trITMOTvalue = document.getElementById('trITMOTvalueSelector');
	if (trITMOTvalue)
		motValue = trITMOTvalue[trITMOTvalue.selectedIndex].value;


	var text  = '<div class="smallHeader"><span id="span_' + stop.ref.id + '">';
		text += stop.name;
		text += '</span></div>'
		text += '<div class="content" id="stop_' + stop.ref.id + '">';
		//text += '<a href="#">Save to My511</a>';
		//text += '<br/>';
		//text += '<a href="javascript:getNearbyAttractions(\'91075670\',\'0\',' + cs[0] +',' + cs[1] +',\'stop_' + stop.ref.id +'\');">Nearby Attractions</a>';
		//text += '<br/>';
		if ((parseInt(stop.ref.id)-10000000) >= 1000 && (parseInt(stop.ref.id)-10000000) < 1500) {
			text += '<a href="javascript:void(0);" onclick="mdvOAKMapHelper.getFacilities(this, \'' + stop.ref.id +'__\')">Facilities</a>';
			text += '<br/>';
		}
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.zoomIn(new MDVCoordinates(\'MTCV\', ' + cs[0] + ', ' + cs[1] + '));">Zoom in</a>';
		text += '<br/>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planTo(' + stop.ref.id + ')">Plan a trip to this location</a>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planFrom(' + stop.ref.id + ')">Plan a trip from this location</a>';
		text += '<br/>';
		text += '<br/>';

		if (isCluster)
			text += '<a href="javascript:mdvOAKMapHelper.getScheduledDeps(' + stop.ref.id + ', \'\');">Scheduled Departures from this location</a>';
		else
			text += '<a href="XSLT_DM_REQUEST?language=en&sessionID=0&maxAssignedStops=1&useAllStops=1&tryToFindLocalityStops=1&lsShowTrainsExplicit=1&execInst=normal&type_dm=coord&itOptionsActive=1&trITMOT=100&trITMOTvalue=' + motValue + '&' + nrs + '">Nearby Routes and Services</a>';
		
	return text;
};


MDVMapOAKObjectMapper.prototype.onToolTip = function (id, msg, obj) {

	var stopNameDiv = document.getElementById('span_' + obj.stop);

	if(obj.stop.ref){
		stopNameDiv = document.getElementById('span_' + obj.stop.ref.id);
	}
	
	if(stopNameDiv.offsetWidth > 282){
		
		stopNameDiv.innerHTML = stopNameDiv.innerHTML.substring(0,38) + '...'
	}

};



MDVMapOAKObjectMapper.prototype.checkSize = function() {
	if (this.routes.length >= 3) {
		var trash = this.routes.shift();
		
		var line = trash.retrieve;
		if (trash.obj.line)
			line = trash.obj.line
			
		this.rotator.free(line);
		
		this.remove(trash);
	}
};

function MDVMapOAKRailSystems(helper) {
	this.helper = helper;
	this.url = { json: 'scripts/RailEx.json', dm: 'XSLT_DM_REQUEST' };
	this.data = null;
	this.graph = [];
	this.drawn = [];
	this.current = [];
	this.stops = [];
	this.dots = [];
	this.pre = null;
	
	this.untouched = true;
	
	this.zoomLevel = this.helper.mdvMap.config.getZoomLevelIndex();
	
	this.layer = this.helper.mdvMap.createLayer('railSystems');	
	this.helper.mdvMap.addLayer(this.layer);
	
	this.helper.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
	this.helper.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.checkDots);	
	
	if (arguments.length == 2 && arguments[1] != null)
		this.pre = arguments[1];

	this.execute();
}

MDVMapOAKRailSystems.prototype.getContent = function(stop, target) {
	var cs = stop.ref.coords.split(',');
	
	var i=0;
	var imgs = '<span style="margin-left: 4px">';
	var line = stop.lineIDs[i] || stop.lineIDs.id;
	var divaLine = '';
	
	if (target && target.ref && target.ref.line) {
		divaLine = target.ref.line;
	}
	
	do {
		var path = 'fw/mdv/dots/dot_' + line + '.gif';
		imgs += '<img src="' + path + '" style="padding-right: 3px;"/>';
		i++;
	} while(line = stop.lineIDs[i]);	
	
	imgs += '</span>';
	
	
	
	/*var stopName= stop.name;
	
	if(stopName.length > 38){
		stopName = stopName.substring(0,38) + '...';
	} */
	
	var text  = '<div class="smallHeader"><span id="span_' + stop.ref.id + '">';
		text += stop.name;
		//text += imgs;
		text += '</span></div>'
		text += '<div class="content" id="stop_' + stop.ref.id + '">';
		//text += '<a href="#">Save to My511</a>';
		//text += '<br/>';
		//text += '<a href="javascript:getNearbyAttractions(\'91075670\',\'0\',' + cs[0] +',' + cs[1] +',\'stop_' + stop.ref.id +'\');">Nearby Attractions</a>';
		text += '<br/>';

		if (((parseInt(stop.ref.id)-10000000) >= 1000 && (parseInt(stop.ref.id)-10000000) < 1500) || parseInt(target.groupID) != 5) {
			text += '<a href="javascript:void(0);" onclick="mdvOAKMapHelper.getFacilities(this, \'' + stop.ref.id +'__\')">Facilities</a>';
			text += '<br/>';
		}

		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.zoomIn(new MDVCoordinates(\'MTCV\', ' + cs[0] + ', ' + cs[1] + '));">Zoom in</a>';
		text += '<br/>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planTo(' + stop.ref.id + ')">Plan a trip to this location</a>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.planFrom(' + stop.ref.id + ')">Plan a trip from this location</a>';
		text += '<br/>';
		text += '<br/>';
		text += '<a href="javascript:mdvOAKMapHelper.getScheduledDeps(' + stop.ref.id + ', \'0\')">Scheduled Departures from this location</a>';		
		
	return text;
};

MDVMapOAKRailSystems.prototype.onToolTip = function (id, msg, obj) {
	var stopNameDiv = document.getElementById('span_' + obj.stop.ref.id);
	
	if(stopNameDiv.offsetWidth > 282){
		
		stopNameDiv.innerHTML = stopNameDiv.innerHTML.substring(0,38) + '...'
	}

/*	if (!obj.isVisible() || !obj.stop)
		return; */

};

MDVMapOAKRailSystems.prototype.onToolTipCallback = function (response) {

	var target = document.getElementById('stop_' + this.stop.ref.id);
	if (!target)
		return;
		
	target.innerHTML = response.responseText;
	
};

MDVMapOAKRailSystems.prototype.execute = function() {
	var _params = {  };
		_params = $H(_params);
		_params = _params.toQueryString();
	
	var _ajax = new Ajax.Request(this.url['json'], { method: 'get', parameters: _params, onComplete: this.onJSONCallback.bind(this) });
	
	var inps = document.getElementsByTagName('input');

	for (var i=0; i < inps.length; i++) {

		if (inps[i].name.substring(0, 4) == 'grp_') {
			attachEventListener(inps[i], 'click', this.onGroup.bind(this), false);
		} else if (inps[i].name.substring(0, 5) == 'line_') {
			attachEventListener(inps[i], 'click', this.onLine.bind(this), false);
		}
		
	}
	
	var selectAll = document.getElementById('selectAll');
	var deselectAll = document.getElementById('deselectAll');
	
	if (selectAll)
		attachEventListener(selectAll, 'click', this.selectAll.bind(this), false);

	if (deselectAll)
		attachEventListener(deselectAll, 'click', this.deselectAll.bind(this), false);
};

MDVMapOAKRailSystems.prototype.onLine = function(e) {
	var src = e.srcElement ? e.srcElement : e.target;	
	var id = parseInt(src.name.substring(5));
	
	if (src.checked)
		this.touch(id);		
	else
		this.remove(id);

	this.draw();
};

MDVMapOAKRailSystems.prototype.clear = function() {
	this.deselectAll();
	this.draw();
};

MDVMapOAKRailSystems.prototype.draw = function () {
	this.helper.mdvMap.hideToolTips();
	
	if (this.current.length > 0)
		this.untouched = false;
	
	var that = this;
	function match(stop) {
		var id = stop.ref.id;
		for(var i=0; i < that.current.length; i++) {
			var c = that.current[i];
			var s = 0;
			var e = stop.lineIDs.length==null ? stop.lineIDs.id : stop.lineIDs[s];
			
			do {
				if (e == c) {
					for (var l=0; l < that.stops.length; l++) {
						if (that.stops[l].ref.id == id)
							return -1;
					}
					return c;
				}
				s++;
			} while (e = stop.lineIDs[s]);
		}
		
		return -1;
	}

	// Remove all segments
	var p = null;
	while (p = this.drawn.pop()) {
		this.layer.removePolyline(p);
	}
	
	// Remove all stations
	var s = null;
	while (s = this.stops.pop()) {
		if (s.marker) {
			this.layer.removeMarker(s.marker);
			s.marker = null;
		}		
	}

	// Clean!
	this.layer.removeAll();

	// Remove all dots
	var s = null;
	for(s in this.dots) {
		if (this.dots[s].img) {
			this.layer.removeMarker(this.dots[s]);
		}
	}
	
	// Construct "graph"
	for (var i=0; i < this.current.length; i++) {
		var mapIt = this.current[i];
		this.addLine(mapIt);
	}
	
	if (this.graph.length > 0) {
		// Check extends
		var max = { x: [], y: [] };
		for (var e=0; e < this.graph.length; e++) {
			var item = this.graph[e];
			
			var list = item.coordStr.split(' ');
			
			for (var i=0; i < list.length; i++) {
				var c = list[i].split(',');
				max.x.push(parseInt(c[0]));
				max.y.push(parseInt(c[1]));
			}
		}
		
		max.x.sort(function(a, b) { return a - b; });
		max.y.sort(function(a, b) { return a - b; });
		
		dist = { x: max.x[max.x.length-1] - max.x[0], y: max.y[max.y.length-1] - max.y[0] };
		
		var zls = this.helper.mdvMap.config.getZoomLevels();
		var vp  = this.helper.mdvMap.getViewportExtends();		
		var zt = 0;

		for (var z=0; z < zls.length; z++) {
			var width  = parseInt(zls[z].get('realWidth')) / parseInt(zls[z].get('numberOfTilesX'));
			var height = parseInt(zls[z].get('realHeight')) / parseInt(zls[z].get('numberOfTilesY'));
			
			var vwidth  = vp.width / parseInt(zls[z].get('tileSizeX')) * width;
			var vheight = vp.height / parseInt(zls[z].get('tileSizeY')) * height;
			
			if (vwidth < dist.x) {
				break;
			}

			if (vheight < dist.y) {
				break;
			}

			zt = z;
		}
		
		var update = true;
		
		if (arguments.length > 0)
			update = arguments[0];
		
		if (update) {
			var ctr = new MDVCoordinates('MTCV', (max.x[0] + max.x[max.x.length-1])/2, (max.y[0] + max.y[max.y.length-1])/2);
			this.helper.mdvMap.setZoomLevel(zt);
			this.helper.mdvMap.setCentre(ctr);
			this.helper.mdvMap.update();
		}
	}
	
	// Draw "graph" borders
	for (var i=this.graph.length-1; i >=0; i--) {
		var poly = this.graph[i];
		
		if (!poly)
			continue;
			
		var brdr = this.helper.mdvMap.createPolyline(poly.coordStr);
			brdr.add('colour', 'black');
			var w = document.all ? '4' : '5';
			brdr.add('weight', w);
			brdr.add('opacity', '1');
		
		this.layer.addPolyline(brdr, false);
		this.drawn.push(brdr);

		//this.layer.addPolyline(poly, false);
		//this.drawn[poly.pathID] = poly;
	}

	// Draw actual "graph"
	for (var i=this.graph.length-1; i >=0; i--) {
		var poly = this.graph[i];
		
		if (!poly)
			continue;

		this.layer.addPolyline(poly, false);
		this.drawn.push(poly);
	}
	
	var stationList = [];	

	// Watch out for stations and draw them.
	for (var s=0; s < this.data.stnList.length; s++) {
		var stop = this.data.stnList[s];
		var success = match(stop);
		if (success!=-1) {
			var line = this.getLine(success);
			var icon = 'fw/mdv/mot6.gif';
			
			if (line.color)
				icon = 'fw/mdv/stations/' + line.color + '.gif';
				
			var coords = stop.ref.coords.split(',');			

			if (parseInt(coords[0]) <= 0 || parseInt(coords[1]) <= 0)
				continue;

			stop.marker = this.helper.mdvMap.createMarker(new MDVCoordinates('MTCV', coords[0], coords[1]), new MDVPoint(0.5, 0.5), icon);
			var tt = this.helper.mdvMap.createToolTip(new MDVPoint(320, 202), this.getContent(stop, line));
				tt.stop = stop;				
			stop.marker.setToolTip(tt);
			this.layer.addMarker(stop.marker, false);
			//this.drawDots(stop);
			this.stops.push(stop);
			
			stationList.push( { name: stop.name, id: stop.ref.id, toString: function() { return this.name; } } );			
		}
	}	
	
	stationList.sort();
	stationList.marshal = function () {
		var ret = '';
		if (document.all)
			ret += '<select name="Stations" class="stationSelect" id="stationSelect">';

		if (this.length > 0)
			ret += '<option>Please select a station</option>';
		else
			ret += '<option>Please select a line below first</option>';

		for (var i=0; i < this.length; i++) {
			ret += '<option value="' + this[i].id + '">';
			ret += this[i].name;
			ret += '</option>';
		}
		
		if (document.all)
			ret += '</select>';
		
		return ret;
	};
	
	if(document.getElementById('stationSelect')) {
		if (document.all)
			document.getElementById('stationSelect').outerHTML = stationList.marshal();
		else
			document.getElementById('stationSelect').innerHTML = stationList.marshal();
		
		attachEventListener(document.getElementById('stationSelect'), 'change', this.onChange.bind(this), false);
	}

	// Empty "graph"
	this.graph = [];

	this.helper.mdvMap.update();	
};

MDVMapOAKRailSystems.prototype.onChange = function (e) {
	var src = e.srcElement ? e.srcElement : e.target;
	var	id = parseInt(src[src.selectedIndex].getAttribute('value'));
	
	for (var i=0; i < this.stops.length; i++) {
		var s = this.stops[i];
		
		if (s.marker && s.marker.toolTip && s.marker.toolTip.stop && s.marker.toolTip.stop.ref.id == id) {
			s.marker.toolTip.display();
			break;
		}		
	}
};

MDVMapOAKRailSystems.prototype.getDotCoords = function (target, align) {
	var delta  = new MDVPoint(11, -6);
	var size   = new MDVPoint(6, 6);
	var offset = new MDVPoint(0, 0);
	var factor = new MDVPoint(1.5, 0);
	var ret    = [];
	
	var length = target.lineIDs.length ? target.lineIDs.length : 1;
	
	switch (align) {
		case 'h-left':
			delta.x = -6 - ((size.x * factor.x) * length);
		break;
		
		case 'v-bottom':
			delta.x = -6;
			delta.y = 9;

			factor.x = 0;
			factor.y = 1.5;
		break;
		
		case 'v-top':
			factor.x = 0;
			factor.y = 1.5;
			
			delta.x = -6;
			delta.y = -8 - ((size.y * factor.y) * length);
		break;
	}
	
	var coords = target.marker.getCoords().clone();

	var zoomLevel 			= this.helper.mdvMap.config.getZoomLevel(this.helper.mdvMap.config.currentZoomLevelIndex);
	var pxWidthAll          = parseInt(zoomLevel.get('tileSizeX')) * parseInt(zoomLevel.get('numberOfTilesX'));
	var pxToRealRatioWidth  = pxWidthAll / parseInt(zoomLevel.get('realWidth'));
	var pxHeightAll         = parseInt(zoomLevel.get('tileSizeY')) * parseInt(zoomLevel.get('numberOfTilesY'));
	var pxToRealRatioHeight = pxHeightAll / parseInt(zoomLevel.get('realHeight'));
	
	delta.x /= pxToRealRatioWidth;
	delta.y /= pxToRealRatioHeight;
	
	coords.x += delta.x;
	coords.y += delta.y;	
	
	var i=0;
	var line = target.lineIDs[i] || target.lineIDs.id;
	
	do {
		offset.x = i * ((size.x * factor.x) / pxToRealRatioWidth);
		offset.y = i * ((size.y * factor.y) / pxToRealRatioHeight);
		
		var n = new MDVCoordinates(coords.mapName, coords.x + offset.x, coords.y + offset.y);
			
		ret.push({ id: line, coords: n, unique: target.ref.id + '_' + line });
		
		i++;
	} while(line = target.lineIDs[i]);	
	
	return ret;
};

MDVMapOAKRailSystems.prototype.getAlign = function(target) {
		if (target.display.direction && target.display.direction.zLevel)
			return target.display.direction.align;
		else {
			var d = 'h-right';
			for (var i=0; i < target.display.length; i++) {
				if (parseInt(target.display[i].zLevel) == -1)
					d = target.display[i].align;
				if (parseInt(target.display[i].zLevel) == this.helper.mdvMap.config.getZoomLevelIndex())
					return target.display[i].align;
			}
			return d;
		}
	}

MDVMapOAKRailSystems.prototype.drawDots = function (stop) {
	var align = this.getAlign(stop);
	var i = 0; var l = stop.lineIDs.id || stop.lineIDs[i];	
	
	var newDots = this.getDotCoords(stop, align);
	var d = null;

	while(d = newDots.pop()) {		
		var mrkr = this.helper.mdvMap.createMarker(d.coords, new MDVPoint(0, 0), 'fw/mdv/dots/dot_' + d.id + '.gif');
		this.dots[d.unique] = mrkr;
		this.layer.addMarker(mrkr, false);
	}
};

MDVMapOAKRailSystems.prototype.checkDots = function (id, msg, obj) {
	if (this.zoomLevel == obj.config.getZoomLevelIndex())
		return;
		
	for (var i=0; i < this.stops.length; i++) {
		var align = this.getAlign(this.stops[i]);
		var newDots = this.getDotCoords(this.stops[i], align);

		while(d = newDots.pop()) {					
			if (this.dots[d.unique]) {
				this.dots[d.unique].setCoords(d.coords);
			}
		}
		
	}	
	
	this.zoomLevel = obj.config.getZoomLevelIndex();
};

MDVMapOAKRailSystems.prototype.onGroup = function(e) {
	var src = e.srcElement ? e.srcElement : e.target;
	var id = parseInt(src.name.substring(4));
	
	var lines = this.getLines(id);
	
	for (var i=0; i < lines.length; i++) {
		var l = lines[i];
		
		if (src.checked) {
			this.touch(l);
			var c = document.getElementById('line_' + l);
			if (c) c.checked = true;
		} else {
			this.remove(l);
			var c = document.getElementById('line_' + l);
			if (c) c.checked = false;
		}
	}
	
	this.draw();
};

MDVMapOAKRailSystems.prototype.getLines = function(grp) {
	var lines = [];
	for (var i=0; i < this.data.lineList.length; i++) {
		var l = this.data.lineList[i];
		
		if (l.groupID == grp)
			lines.push(l.id);
	}
	
	return lines;
};

MDVMapOAKRailSystems.prototype.addLine = function(id) {
	var that = this;
	function match(id) {
		for (var i=0; i < that.graph.length; i++) {
			if (that.graph[i].pathID == id)
				return true;
		}
		
		return false;
	}

	var line = this.getLine(id);
	
	if (!line)
		return;
	
	var ps = [];
	
	if (line.pathIDs.id)
		ps.push(line.pathIDs.id);
	else
		ps = line.pathIDs;
	
	var pathes = this.getPathes(ps);
	
	for(var p=0; p < pathes.length; p++) {
		if (!match(pathes[p].id)) {	

			var poly = this.helper.mdvMap.createPolyline(pathes[p].coords);
				poly.add('colour', '#' + line.color);
				poly.add('opacity', '1');
				poly.coordStr = pathes[p].coords;
				poly.pathID = pathes[p].id;

			this.graph.push(poly);
		}
	}
};

MDVMapOAKRailSystems.prototype.touch = function (id) {	
	this.remove(id);
	this.current.unshift(id);
	mdvEventLog.trigger('SECTION1_RAIL_SYSTEM_MAP', 'index.html', '');
};

MDVMapOAKRailSystems.prototype.remove = function (id) {
	for (var i=0; i < this.current.length; i++) {
		if (this.current[i] == id) {
			this.current.splice(i, 1);
			return true;
		}
	}
	
	return false;
};

MDVMapOAKRailSystems.prototype.getPathes = function(ids) {
	function match (id) {
		for(var l=0; l < ids.length; l++) {
			if (ids[l] == id)
				return true;
		}
		return false;
	}
	
	var p = [];
	
	for (var i=0; i < this.data.pathList.paths.length; i++) {
		var path = this.data.pathList.paths[i];
		
		if (match(path.id))
			p.push(path);
	}
	
	return p;
};

MDVMapOAKRailSystems.prototype.getLine = function(id) {
	var line = null;
	
	for (var i=0; i < this.data.lineList.length; i++) {
		line = this.data.lineList[i];
		
		if (line.id == id)
			return line;
	}
	
	return null;
};	

MDVMapOAKRailSystems.prototype.onJSONCallback = function(response) {
	this.data = null;
	
	try {
		eval('this.data = ' + response.responseText + ';');
	} catch (e) {
		var error = e;
	}
	
	if (this.pre) {
		var temp = this.pre;
		
		try {			
			eval('this.pre = ' + temp + ';');
			this.restore();
		} catch (e) {
			var error = e;
		}
	}
};

MDVMapOAKRailSystems.prototype.restore = function () {
	if (this.pre && this.pre.rp && this.untouched) {
		// this.helper.mdvMap.setCentre(this.pre.rp.state.center);
		// this.helper.mdvMap.setZoomLevel(this.pre.rp.state.zoom);
		
		for (var line in this.pre.rp.lines) {
			if (typeof this.pre.rp.lines[line] == 'function')
				continue;
			
			this.touch(this.pre.rp.lines[line]);
			var c = document.getElementById('line_' + this.pre.rp.lines[line]);
			if (c) c.checked = true;
		}
		
		this.draw();
		this.untouched = true;
	}
};

MDVMapOAKRailSystems.prototype.selectAll = function () {	
	for (var i=0; i < this.data.lineList.length; i++) {
		var line = this.data.lineList[i];
		
		this.touch(line.id);
		var c = document.getElementById('line_' + line.id);
		if (c) c.checked = true;
	}
	
	for (var i=0; i < this.data.grpList.length; i++) {
		var grp = this.data.grpList[i];
		var c = document.getElementById('grp_' + grp.id);
		if (c) c.checked = true;
	}
	
	this.draw();
};

MDVMapOAKRailSystems.prototype.deselectAll = function () {
	for (var i=0; i < this.data.lineList.length; i++) {
		var line = this.data.lineList[i];
		
		this.remove(line.id);
		var c = document.getElementById('line_' + line.id);
		if (c) c.checked = false;
	}
	
	for (var i=0; i < this.data.grpList.length; i++) {
		var grp = this.data.grpList[i];
		var c = document.getElementById('grp_' + grp.id);
		if (c) c.checked = false;
	}

	this.draw();
};

function MDVRotator() {
	this.rep = [
		{ color: '#005F19', image: 'fw/mdv/1st.gif', id: null },
		{ color: '#E83D00', image: 'fw/mdv/2nd.gif', id: null },
		{ color: '#6A3523', image: 'fw/mdv/3rd.gif', id: null }
	];
}

MDVRotator.prototype.require = function (id) {
	this.free(id);
	
	for(var i=0; i < this.rep.length; i++) {
		var e = this.rep[i];
		if (!e.id) {
			e.id = id;
			return e;
		}
	}
	
	return null;
};

MDVRotator.prototype.free = function (id) {
	for(var i=0; i < this.rep.length; i++) {
		var e = this.rep[i];
		
		if (e.id == id) {
			e.id = null;
			return true;
		}
	}
	
	return false;
};

MDVRotator.prototype.isVacant = function () {
	for(var i=0; i < this.rep.length; i++) {
		var e = this.rep[i];
		
		if (e.id)
			return false;
			
	}

	return true;
};

function MDVMapOAKPrint(div, obj) {
	this.div = div;
	this.mdvMap = null;
	this.obj = null;
	this.obj = obj;
	
	this.markerOffset = [];
	this.markerOffset['planATrip'] 	= new MDVPoint(0.17, 0.69);
	this.markerOffset['nss'] 		= new MDVPoint(0.15, 0.7);

	this.red = [
			{ maxScale:     700, epsilon:   1 },
			{ maxScale:    1375, epsilon:   2 },
			{ maxScale:    2750, epsilon:   2 },
			{ maxScale:    5500, epsilon:   2 },
			{ maxScale:   11000, epsilon:   5 },
			{ maxScale:   22000, epsilon:   8 },
			{ maxScale:   44000, epsilon:  15 },
			{ maxScale:   88000, epsilon:  25 },
			{ maxScale:  176000, epsilon:  40 },
			{ maxScale:  352000, epsilon:  60 },
			{ maxScale:  704000, epsilon: 140 },
			{ maxScale: 1400000, epsilon: 300 }
		];
	
	MDVMapOAKPrint.prototype.applyConfig = MDVMapOAKHelper.prototype.applyConfig;
	
	this.execute();
}

MDVMapOAKPrint.prototype.execute = function () {
	var config = mdvMapConfig.clone();
	this.done = false;
	this.applyConfig(config);
	
	if (!this.div)
		return;
	
	this.mdvMap = new MDVMap(this.div);
	new MDVMapScale(this.mdvMap, {});
	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.setState);
	this.mdvMap.execute(config);
};

MDVMapOAKPrint.prototype.setState = function (id, msg, obj) {

	if (this.done)
		return;
		
	this.done = true;
		
	if (this.obj.tp) {
		var tp = this.obj.tp;
		
		if (tp.points.origin) {
			var origin = this.mdvMap.createMarker(tp.points.origin.coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_start.png');
			this.mdvMap.addMarker(origin, false);
		}

		if (tp.points.destination) {
			var destination = this.mdvMap.createMarker(tp.points.destination.coords, this.markerOffset['planATrip'].clone(), 'fw/mdv/pin_end.png');
			this.mdvMap.addMarker(destination, false);
		}

		this.mdvMap.setCentre(tp.state.center);
		this.mdvMap.setZoomLevel(tp.state.zoom);		
		this.mdvMap.update();
		
		if (tp.trips.sessionID && tp.trips.sessionID.length > 0) {
			var trips = new MDVMapEFATrips(this.mdvMap, { getMarker: getTripMarker, reductionList: this.red });
			trips.loadTrip(tp.trips.sessionID, tp.trips.requestID, tp.trips.routePos, false);
		}
		
		mdvEventLog.trigger('GENERAL_PRINTABLE_MAP', 'itinerary.html', '');
	}
	
	if (this.obj.nrs) {	
		var nrs = this.obj.nrs;
		
		if (nrs.stops && nrs.stops.length > 0) {
			for (var i=0; i < nrs.stops.length; i++) {
				var s = nrs.stops[i];
				
				var m = this.mdvMap.createMarker(s.coords, s.factor, s.img);
				this.mdvMap.addMarker(m, false);
			}
		}

		if (nrs.points && nrs.points.dm) {
			var dm = this.mdvMap.createMarker(nrs.points.dm.coords, this.markerOffset['nss'].clone(), 'fw/mdv/pin_nss.png');
			this.mdvMap.addMarker(dm, false);
		}
		
		this.mdvMap.setCentre(nrs.state.center);
		this.mdvMap.setZoomLevel(nrs.state.zoom);		
		this.mdvMap.update();

		if (nrs.routes && nrs.routes.length > 0) {
			var mapper = new MDVMapOAKObjectMapper(this);
			for (var i=nrs.routes.length-1; i >= 0; i--) {
				var r = nrs.routes[i];
				mapper.mapIt('0', r.type, r.line, '0');
			}
		}
		
		mdvEventLog.trigger('SECTION1_PRINTABLE_NEAR_BY_SERVICES_RESULTS', 'nearbyroutesandservices.html', '');
	}

	if (this.obj.rp) {
		var rp = this.obj.rp;
		
		this.mdvMap.setCentre(rp.state.center);
		this.mdvMap.setZoomLevel(rp.state.zoom);		
		this.mdvMap.update();	
		
		railSystems = new MDVMapOAKRailSystems(this);

		for (var i=0; i < rp.lines.length; i++) {
			railSystems.touch(rp.lines[i]);
		}
		
		window.setTimeout(function () {railSystems.draw(false);}, 2000);

		mdvEventLog.trigger('GENERAL_PRINTABLE_MAP', 'itinerary.html', '');
	}
};

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; 
}

function getObjectWidth(obj) {
	var elem = getRawObject(obj);
	var result = 0;

	if (elem.offsetWidth) {
		result = elem.offsetWidth;
	} else if (elem.clip && elem.clip.width) {
		result = elem.clip.width;
	} else if (elem.style && elem.style.pixelWidth) {
		result = elem.style.pixelWidth;
	}

	return parseInt(result);
}

function getObjectHeight(obj) {
	var elem = getRawObject(obj);
	var result = 0;

	if (elem.offsetHeight) {
		result = elem.offsetHeight;
	} else if (elem.clip && elem.clip.height) {
		result = elem.clip.height;
	} else if (elem.style && elem.style.pixelHeight) {
		result = elem.style.pixelHeight;
	}

	return parseInt(result);
}

function getParent (obj) {
	var p = obj.parentElement || obj.parentNode;
	
	return p;
}

function getTripMarker(type, usage, coords, alignment, pos) {
	var src = '';
	var last = false;
	
	if (this.response.trips.trip.legs.leg)
		last = true;
	else if (this.response.trips.trip.legs.length-1 == pos)
		last = true;

	if (usage == 'departure' && pos == 0) {
		src = new Image();
		src.src = 'fw/mdv/pin_start_map.png';
		alignment = new MDVPoint(0.18, 0.75);
	} else if (usage == 'arrival' && last) {
		src = new Image();
		src.src = 'fw/mdv/pin_end_map.png';
		alignment = new MDVPoint(0.18, 0.75);
	} else if (type >= 100 && this.imgs[type + '_' + usage] && this.imgs[type + '_' + usage].complete)
		src = this.imgs[type + '_' + usage];	
	else if (this.imgs[type])
		src = this.imgs[type];
	else
		src = this.imgs['stop'];
		
	var m = this.mdvMap.createMarker(coords, alignment, src.src);
			
	return m;
}

function populateMapInfo(id, msg, obj) {
	var vx = document.getElementById('x_value');
	var vy = document.getElementById('y_value'); 
	var vlat = document.getElementById('lat_value'); 
	var vlong = document.getElementById('long_value');
	
	if (vx && vy) {
		vx.value = obj.getCentre().x;
		vy.value = obj.getCentre().y;
	}
	
	if (vlat && vlong) {
		var wgs = obj.getWGS84(obj.getCentre());
		vlat.value = wgs.x;
		vlong.value = wgs.y;
	}
}

function jumpUTM(e) {
	var vx = document.getElementById('x_value');
	var vy = document.getElementById('y_value'); 
	var c = new MDVCoordinates('MTCV', vx.value, vy.value);
	mdvOAKMapHelper.mdvMap.setCentre(c);
	mdvOAKMapHelper.mdvMap.update();
}

function jumpWGS(e) {
	var vlat = document.getElementById('lat_value'); 
	var vlong = document.getElementById('long_value');
	var c = new MDVCoordinates('WGS84', parseFloat(vlat.value), parseFloat(vlong.value));
	mdvOAKMapHelper.mdvMap.setCentre(c);
	mdvOAKMapHelper.mdvMap.update();
}