MDVMapScale.prototype.setScale = function() {
	
	var level = this.levels[this.mdvMap.config.getZoomLevelIndex()];
	var bottomText = level.meterOut + ' ' + level.meterUnit;
	
	if (this.divScaleTextBottom) {
		this.divScaleTextBottom.innerHTML = bottomText; 
	}
	mdvLib.style([this.divScaleBar], {
		width: level.pxMeter + 'px',
		backgroundPosition: ((this.scaleImg.width - level.pxMeter) * -1)  + 'px 0'
	});
	
	this.divScaleTickBottom.style.left = level.pxMeter - 1 + 'px';
	
	return true;
}; 

MDVMapScale.prototype.createDivs = function() {

	  this.divScale = createDiv('divScale');
      this.divScaleLeft = createDiv('divScaleLeft_' + this.mdvMap.type);
      this.divScaleBar = createDiv('divScaleBar_' + this.mdvMap.type);
      this.divScaleTickTop = createDiv('divScaleTickTop_' + this.mdvMap.type);
      this.divScaleTickBottom = createDiv('divScaleTickBottom_' + this.mdvMap.type);
      this.divScaleTextTop = createDiv('divScaleTextTop_' + this.mdvMap.type);
      this.divScaleTextBottom = createDiv('divScaleTextBottom_' + this.mdvMap.type);
      
      mdvLib.style([this.divScale], {
            position: 'absolute',
            top: this.mdvMap.viewportHeight - 30 + 'px',
            left: '5px',
            zIndex: 999
      });
      
      mdvLib.style([this.divScaleBar, this.divScaleLeft, this.divScaleTextBottom,
            this.divScaleTextTop, this.divScaleTickBottom, this.divScaleTickTop], {
            position: 'absolute',
            display: 'inline'
      });
      
      mdvLib.style([this.divScaleBar, this.divScaleLeft, this.divScaleTickBottom, this.divScaleTickTop], {

            background: 'transparent',
            backgroundImage: 'url(' + this.scaleImg.src + ')',
            backgroundPosition: '0 0',
            backgroundRepeat: 'no-repeat'

      });
      
      mdvLib.style([this.divScaleLeft], {
            width: '4px',
            height: '18px'
      });
      
      mdvLib.style([this.divScaleBar], {
            width: '100px',
            height: '4px',
            left: '3px',
            top: '7px'
      });

      mdvLib.style([this.divScaleTickTop], {
            width: '4px',
            height: '12px',
            backgroundPosition: '-4px 0',
            top: '0px'
      });

      mdvLib.style([this.divScaleTickBottom], {
            width: '4px',
            height: '18px',
            backgroundPosition: '-8px 0',
            top: '0px'
      });

      mdvLib.style([this.divScaleTextTop], {
            width: '60px',
            left: '8px',
            top: '-2px',
            fontSize: '10px'
      });
      
      mdvLib.style([this.divScaleTextBottom], {
            width: '60px',
            left: '8px',
            top: '11px',
            fontSize: '10px'
      });

      this.divScale.appendChild(this.divScaleLeft);
      this.divScale.appendChild(this.divScaleBar);
      this.divScale.appendChild(this.divScaleTickTop);
      this.divScale.appendChild(this.divScaleTickBottom);

      if (this.displayYards)
            this.divScale.appendChild(this.divScaleTextTop);

      if (this.displayMeters)
            this.divScale.appendChild(this.divScaleTextBottom);

      this.mdvMap.viewport.appendChild(this.divScale);

      this.mdvMap.events.registerEvent(MDVEvent_ZOOM_CHANGED, this, this.setScale);

      this.init = true;

      this.setScale();
	  
      function createDiv(id) {
	  
		  if(document.getElementById(id)){
			var div = document.getElementById(id);
			return div;
		  }
		  else{
            var div = document.createElement('div');
            div.id = id;
            return div;
		}
      }     
};

MDVMapScale.prototype.updatePosition = function(viewportHeight) {

    if (this.divScale && viewportHeight) {
        this.divScale.style.top = parseInt(viewportHeight, 10) - 30 + 'px';
    }              
};

  MDVMapEFATrips.prototype.prefetchImgs = function () {
  	var ipath = 'images/';
  	if (this.mdvMap.config.get('imagePath'))
  		ipath = this.mdvMap.config.get('imagePath');

  	this.imgs['99'].src = ipath + 'mot99.gif';
  	this.imgs['99_follow'].src = ipath + 'mot99_follow.gif';
  	this.imgs['100'].src = ipath + 'mot100.gif';
  	this.imgs['100_follow'].src = ipath + 'mot100_follow.gif';
  	this.imgs['100_arrival'].src = ipath + 'mot100_arrival.gif';
  	this.imgs['100_departure'].src = ipath + 'mot100.gif';
  	this.imgs['101'].src = ipath + 'mot101.gif';
  	this.imgs['101_follow'].src = ipath + 'mot101_follow.gif';
  	this.imgs['101_arrival'].src = ipath + 'mot101_arrival.gif';
  	this.imgs['101_departure'].src = ipath + 'mot101_departure.gif';
  	this.imgs['102'].src = ipath + 'mot102.gif';
  	this.imgs['102_follow'].src = ipath + 'mot102_follow.gif';
  	this.imgs['102_arrival'].src = ipath + 'mot102_arrival.gif';
  	this.imgs['102_departure'].src = ipath + 'mot102_departure.gif';
  	this.imgs['103'].src = ipath + 'mot103.gif';
  	this.imgs['103_follow'].src = ipath + 'mot103_follow.gif';
  	this.imgs['103_arrival'].src = ipath + 'mot103_arrival.gif';
  	this.imgs['103_departure'].src = ipath + 'mot103_departure.gif';
  	this.imgs['104'].src = ipath + 'mot104.gif';
  	this.imgs['104_follow'].src = ipath + 'mot104_follow.gif';
  	this.imgs['104_arrival'].src = ipath + 'mot104_arrival.gif';
  	this.imgs['104_departure'].src = ipath + 'mot104_departure.gif';
  	this.imgs['105'].src = ipath + 'mot105.gif';
  	this.imgs['105_follow'].src = ipath + 'mot105_follow.gif';
  	this.imgs['105_arrival'].src = ipath + 'mot105_arrival.gif';
  	this.imgs['105_departure'].src = ipath + 'mot105_departure.gif';
  	this.imgs['106'].src = ipath + 'mot106.gif';
  	this.imgs['106_follow'].src = ipath + 'mot106_follow.gif';
  	this.imgs['106_arrival'].src = ipath + 'mot106_arrival.gif';
  	this.imgs['106_departure'].src = ipath + 'mot106_departure.gif';
  	this.imgs['107'].src = ipath + 'mot107.gif';
  	this.imgs['107_follow'].src = ipath + 'mot107_follow.gif';
  	this.imgs['107_arrival'].src = ipath + 'mot107_arrival.gif';
  	this.imgs['107_departure'].src = ipath + 'mot107_departure.gif';
  	this.imgs['stop'].src = ipath + 'stop.gif';
  	this.imgs['1'].src = ipath + 'mot1.gif';
  	this.imgs['1_follow'].src = ipath + 'mot1_follow.gif'
  	this.imgs['2'].src = ipath + 'mot2.gif';
  	this.imgs['2_follow'].src = ipath + 'mot2_follow.gif';
  	this.imgs['3'].src = ipath + 'mot3.gif';
  	this.imgs['3_follow'].src = ipath + 'mot3_follow.gif';
  	this.imgs['4'].src = ipath + 'mot4.gif';
  	this.imgs['4_follow'].src = ipath + 'mot4_follow.gif';
  	this.imgs['5'].src = ipath + 'mot5.gif';
  	this.imgs['5_follow'].src = ipath + 'mot5_follow.gif';
  	this.imgs['6'].src = ipath + 'mot6.gif';
  	this.imgs['6_follow'].src = ipath + 'mot6_follow.gif';
  	this.imgs['7'].src = ipath + 'mot7.gif';
  	this.imgs['7_follow'].src = ipath + 'mot7_follow.gif';
  	this.imgs['8'].src = ipath + 'mot8.gif';
  	this.imgs['8_follow'].src = ipath + 'mot8_follow.gif';
  	this.imgs['9'].src = ipath + 'mot9.gif';
  	this.imgs['9_follow'].src = ipath + 'mot9_follow.gif';
  	this.imgs['10'].src = ipath + 'mot10.gif';
  	this.imgs['10_follow'].src = ipath + 'mot10_follow.gif';
  	this.imgs['11'].src = ipath + 'mot11.gif';
  	this.imgs['11_follow'].src = ipath + 'mot11_follow.gif';
  	this.imgs['12'].src = ipath + 'mot12.gif';
  	this.imgs['12_follow'].src = ipath + 'mot12_follow.gif';
  	this.imgs['13'].src = ipath + 'mot13.gif';
  	this.imgs['13_follow'].src = ipath + 'mot13_follow.gif';
  	this.imgs['poi'].src = ipath + 'pin.gif'
  };

  MDVMapEFAInfoEx.prototype.createLayers = function() {
  
  	if (!this.stops) {
  		this.stops = this.mdvMap.createLayer('efa_stops');
  		this.stops.setZIndex(1);
  		this.mdvMap.addLayer(this.stops);
  	}

  	if (!this.poi) {
  		this.poi = this.mdvMap.createLayer('efa_poi');
  		this.poi.setZIndex(1);
  		this.mdvMap.addLayer(this.poi);
  	}
    
    
    
    if (this.mdvMap.config.get('info.stopLabels') === 'true') {
        
        if (!this.stopLabel) {
	  	    
	  	    if (typeof this.mdvMap.config.get('info.stopLabels.minLevel') === 'number') {
	  	    	minLevel = this.mdvMap.config.get('info.stopLabels.minLevel');
	  	    }
	  	    
	  	     this.stopLabel = this.mdvMap.createLayer('stopLabel', {
	                                                           'useOwnContainer': true,
	  	                                                       'minLevel': minLevel
  	                                                       });
	  	     this.mdvMap.addLayer(this.stopLabel);
	  	}
    }
  };
  
MDVLayer.prototype.addMarker = function(marker) {
	var update = true;
	for (var m=0; m < this.markers.length; m++) {
		if (this.markers[m].id == marker.id) {
			return false;
		}
	}
	
	if (arguments.length == 2)
		update = arguments[1];

	marker.layer = this;
	
	this.markers.push(marker);		
	marker.img.src = marker.imgSrc;
	
	if(marker.mode==1 | marker.mode==4){
		marker.img.style.zIndex = '10';

	}
	else if(marker.mode==2){
		marker.img.style.zIndex = '9';
	}
	else if(marker.mode==3 | marker.mode==5){
		marker.img.style.zIndex = '8';
	}
	else if(marker.mode==99){
		marker.img.style.zIndex = '2';
	}
	
	else if(marker.mode==100){
		marker.img.style.zIndex = '3';
	}
	
	else{
		marker.img.style.zIndex = '4';
		
		if(marker.imgSrc.indexOf('/dir/')!='-1' && 1==2){
		marker.img.style.width='18px';
		marker.img.style.height='18px';
		}
		
	}

	return true;
 };
  
  
 MDVMapEFATrips.prototype.processTrip = function(id, gName, efa) {
  	
  	if (gName != 'MDVMapEFATrips') {
  		return false;
  	}
  		
  	var hostUrl, _params, createPath, process, alignment = 0.5, leg = null;
  	var jsonServerURL = this.mdvMap.config.get('trips.jsonServerURL');
  		
  	if (this.options['alignment']) {
	  	alignment = this.options['alignment'];
  	}
  		
 	this.response = efa;
  	
  	this.clear();
	
	createPath = function(mode) {
		
		var l = 0, tripIsArr;
		var _response = mode === 'lite' ? this.response : this.responseJson;
		
		var maxLeg = this.response.trips.trip.legs.length -1;
		
		
		while (leg) {
			
			// JSON result does not contain points and mode info
			// so borrow it from the lite request
			if (mode === 'json') {
				tripIsArr = mdvLib.typeOf(this.response.trips.trip.legs) === 'array';
				leg.points = tripIsArr ? this.response.trips.trip.legs[l].points : this.response.trips.trip.legs.leg.points;
				leg.mode = tripIsArr ? this.response.trips.trip.legs[l].mode : this.response.trips.trip.legs.leg.mode;
				
			}
			
			var type = leg.mode.type;
			var points = leg.points;				
			var colour = this.getLegColour(type);
			var opacity = '0.5';
			var weight = 3;
			var p = null;
			
			var list = this.getReductionList(leg);
			list.sort(MDVMapEFATrips_ScaleSort);
			
			if (this.mdvMap.config.get('trips.polyline.opacity'))
				opacity = this.mdvMap.config.get('trips.polyline.opacity');
	
			if (this.mdvMap.config.get('trips.polyline.weight'))
				weight = this.mdvMap.config.get('trips.polyline.weight');
			
			// partial route info contains no path description
			if (!leg.path) {
				// do we have turn instructions? If so use these...
				if (leg.turnInst && leg.turnInst.length > 0) {
					
					var  pathStr = '';
					
					for(var i=0; i<leg.turnInst.length; i++) {
						for (var p in leg.turnInst[i]) {
							if(p==='coords') {
								pathStr += leg.turnInst[i][p] + ' ';
							}	
						}
					} 
					// remove trailing blank 
					pathStr = pathStr.substring(0, pathStr.length-1);	
				
				// ... if not, draw a direct line from point to point. 
				} else {
					
					var  pathStr = '';
					
					for(var i=0; i<leg.points.length; i++) {
						if (leg.points[i].ref) {
							for (var p in leg.points[i].ref) {
								if(p==='coords') {
									pathStr += leg.points[i].ref[p] + ' ';
								}	
							}
						}
					} 
					pathStr = pathStr.substring(0, pathStr.length-1);
				}
			} else {
			// we got a path description	
				var pathStr = leg.path.replace(/\.00000/gi, '');
			}		
			
			if (list.length > 0) {
				p = this.mdvMap.createPolyline(pathStr, { reductionList: list });
				this.polylines.push(p);
			} else {
				p = this.mdvMap.createPolyline(pathStr);
				this.polylines.push(p);
			}
			
			p.add('colour', colour);
			p.add('opacity', opacity);
			p.add('weight', weight);

			if (!p.markers['departure']) {
				var coords = p.getAllCoords();
				var m = this.getMarker(type, 'departure', coords[0], alignment, l);
					
				p.markers['departure'] = m;
				
				if(l!=0  && l <= maxLeg && leg.mode.type > '100'){
					p.markers['departure'].imgSrc = 'images/mdvMap/mot' + leg.mode.type + '_via.gif'
					p.markers['departure'].usage ='via'; 
				}
				
				p.markers['departure'].mode  = type;
				p.markers['departure'].point = points[0];
			}
	
			if (!p.markers['arrival']) {
				var coords = p.getAllCoords();
				var m = this.getMarker(type, 'arrival', coords[coords.length-1], alignment, l);
					
				p.markers['arrival'] = m;
				
				if(l!=0 && leg.mode.type > '100' && l < maxLeg){
					p.markers['arrival'].imgSrc = 'images/mdvMap/mot' + leg.mode.type + '_via.gif';
					p.markers['arrival'].usage ='via'; 
				}
				
				p.markers['arrival'].mode  = type;
				p.markers['arrival'].point = points[1];
			}
			
			p.leg = leg;
			this.layer.addPolyline(p, false);
			
			// Check for interchange
			if (leg.interchange) {
				
				var next = _response.trips.trip.legs[(l+1)];
				
				// if the mode is json, fetch next points from lite response
				var nextPoints = mode === 'lite' ? next.points : this.response.trips.trip.legs[l+1].points;
				
				var ic = this.mdvMap.createPolyline(leg.interchange.path);
				
					colour = this.getLegColour(99);
					ic.add('colour', colour);
					ic.add('opacity', opacity);
					ic.add('weight', weight);

				
					ic.leg = leg;
					ic.isInterchange = true;
			
				var m = this.getMarker(99, 'departure', coords[coords.length-1], alignment, l);
	
					ic.markers['departure'] 		= m;
					ic.markers['departure'].mode 	= 99;
					ic.markers['departure'].point	= points[1];
	
				var nextCoords = next.path.split(' ');
					nextCoords = nextCoords[0].split(',');
						
				var c = new MDVCoordinates(coords[coords.length-1].mapName, nextCoords[0], nextCoords[1]);
					m = this.getMarker(99, 'arrival', c, alignment, l);
	
					ic.markers['arrival'] 			= m;
					ic.markers['arrival'].mode  	= 99;
					ic.markers['arrival'].point 	= nextPoints[0];
				
				this.layer.addPolyline(ic, false);
				this.polylines.push(ic);
				
			}
			
			l++; leg = _response.trips.trip.legs[l];
		}
		
	}.bind(this);
	
	process = function(mode) {
		
		createPath(mode);
		
		if (this.doBeautify) {
			this.beautify();
		}
		this.processMarkers();
		
		this.mdvMap.update();
		
		this.processPolylines();
        
       // mdvJpMaps[currentMap].getProxPOIs();
        
	
	}.bind(this);
	
	// path description via lite request
	if (this.mdvMap.config.get('trips.useJsonForPath') !== 'true') {
		
		if (this.response.trips.trip.legs.leg && !this.response.trips.trip.legs.length) {
			leg = this.response.trips.trip.legs.leg;
		} else if (this.response.trips.trip.legs.length) {
			leg = this.response.trips.trip.legs[0];
		}
		process('lite');
		
		//we're done here.
		return true; 
	}
	
	// get path description via separate json request
	// get current EFA service and use it as URL
	
	if (typeof jsonServerURL !== 'undefined') {
		hostUrl = jsonServerURL;
	} else {
		hostUrl = /^\/(?:[\w\-%]+\/)*(\w+)\??/.exec(window.location.pathname);
		hostUrl = hostUrl && hostUrl[1];
		// usually 'XSLT_TRIP_REQUEST2'
	}
	
	_params = {
		sessionID: this.tripParams.sessionId,
		requestID: this.tripParams.requestId,
		command: 'tripCoordSeq:' + this.tripParams.tripIndex,
		filterEpsilon: this.tripParams.reductionList,
		output: 'JSON'
	}; 

	if (typeof hostUrl === 'string') {	
		
		mdvLib.ajax({ 
			host: hostUrl, 
			parameters: _params, 
			onComplete: function(r) { 
				
				var _response = r.responseText || r;
				_response = _response.replace(/\.00000/gi, '');
				eval('this.responseJson = ' + _response + ';');
				//invalid JSON?
				if (!this.responseJson) {
					return false;
				}
				if (this.responseJson.trips.trip.legs.leg && !this.responseJson.trips.trip.legs.length) {
					leg = this.responseJson.trips.trip.legs.leg;
				} else if (this.responseJson.trips.trip.legs.length) {
					leg = this.responseJson.trips.trip.legs[0];
				}
				
				process('json'); 
			
			}.bind(this)
		});
	} 
    else {
		//alert('ERROR:\nCould not retrieve hostUrl.');	
	}
  };

  
  MDVMapEFATrips.prototype.update = function (id, msg, obj) {

	if (this.polylines.length <= 0)
		return false;
		
		var skip = this.options['skipBoundaryCheck'] && this.options['skipBoundaryCheck'] == true;
		
		this.zoomLevel = obj.config.getZoomLevelIndex();
		
		this.mdvMap.getLayer('directions').removeAllMarkers();
        
        this.mdvMap.getLayer('nearInfo').update();
        
        
		
		// Reset them directly using the attribute as we don't want to force redrawing
		for (var p=0; p < this.polylines.length; p++) {
			if (this.polylines[p] && this.polylines[p].markers['departure'])
				this.polylines[p].markers['departure'].visible = false;
			if (this.polylines[p] && this.polylines[p].markers['arrival'])
				this.polylines[p].markers['arrival'].visible = false;

			// Reset directions
			for (var a=0; a < this.polylines[p].directions.length; a++) {
				//this.layer.removeMarker(this.polylines[p].directions[a]);
				this.mdvMap.getLayer('directions').removeMarker(this.polylines[p].directions[a]);
				//log.debug('reset dir' + [a]);
			} 
			
			
			var maxScale = 25000;
			if (this.mdvMap.config.get('trips.polyline.arrows.maxScale'))
				maxScale = parseInt(this.mdvMap.config.get('trips.polyline.arrows.maxScale'));
				
			var zl = this.mdvMap.config.getZoomLevel(this.zoomLevel);
			var displayArrows = zl.getScale() <= maxScale;
			
			if (this.mdvMap.config.get('useArrowsForEFATrips') && this.mdvMap.config.get('useArrowsForEFATrips') == 'true' && displayArrows) {
				this.polylines[p].arrows = this.polylines[p].getArrows();

				for (var a=0; a < this.polylines[p].arrows.length; a++) {
					var update = a == this.polylines[p].arrows.length-1 ? true : false;
					this.layer.addPolyline(this.polylines[p].arrows[a], update);
				}
			} 
			else if (this.mdvMap.config.get('useDirectionsForEFATrips') && this.mdvMap.config.get('useDirectionsForEFATrips') == 'true' && displayArrows) {
			
				this.mdvMap.getLayer('directions').polyNum = p;
				var r = this.polylines[p].getDirections();
				
				for (var d=0; d < r.length; d++) {
					var update = d == r.length-1 ? true : false;
					
					this.mdvMap.getLayer('directions').addMarker(r[d], update);
				} 
				
				this.polylines[p].directions = r;
			}
		}
		
		// Origin and destination of a journey are always visible.
		if (this.polylines[0].markers['departure'])
			this.polylines[0].markers['departure'].setVisibility(true);
		if (this.polylines[this.polylines.length-1].markers['arrival'])
			this.polylines[this.polylines.length-1].markers['arrival'].setVisibility(true);
			
		for (var i=this.polylines.length-1; i > 0 ; i--) {
			var current = this.polylines[i];
			var prev	= this.polylines[i-1];
			
			if (!current || !prev)
				continue;
			
			var temparr = [[i, 'departure', current.markers['departure']], [i, 'arrival', prev.markers['arrival']]];
			temparr.sort(MDVMapEFATrips_PrioritySort);

			temparr[0][2].setVisibility(true);
				
			if (!temparr[1][2].intersects(temparr[0][2]) || !temparr[0][2].isVisible() || skip) 
				temparr[1][2].setVisibility(true);
			else
				temparr[1][2].setVisibility(false);
		}
		
	this.updateWizard();
		
	return true;
	};
  
  
 MDVMapEFATrips.prototype.getMarker = function(type, usage, coords, alignment, pos) {
  	var src = '';
	
	if (type >= 100 && this.imgs[type + '_' + usage])
		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;
  };
  
   MDVToolTip.prototype.setCoords = function (coords) {
		if(this.mdvMap){
	   		coords = this.mdvMap.getInternalCoordinates(coords);
	   		this.coords = coords;
		}
   };
  
    // show context menu
   MDVMapContextMenu.prototype.oncontextmenu = function(e) {
   	e = e ? e : window.event;

   		var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
 		var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
 		var x = e.clientX + scrollLeft;
 		var y = e.clientY + scrollTop;

	    var mX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
	    var mY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));

	    var offsetL = 0;
	    var offsetT = 0;

	    var obj = this.mdvMap.viewport;

	    while(obj) {
	    	offsetL += obj.offsetLeft;
	    	offsetT += obj.offsetTop;

	    	obj = obj.offsetParent;
	    }

	    mX = mX - offsetL - 3;
	    mY = mY - offsetT - 3;
		
		if (this.mdvMap.config.get('contextMenu.size.width')
			&& this.mdvMap.config.get('contextMenu.size.height')) {
		
			var width = parseInt(this.mdvMap.config.get('contextMenu.size.width'));
			var height = parseInt(this.mdvMap.config.get('contextMenu.size.height'));
		
			if(mY +height > this.mdvMap.viewport.offsetHeight && mX +width > this.mdvMap.viewport.offsetWidth){
				x = x - width;
				y = y - height;
				
				this.contextMenu.div.className= "mapContextMenu mapContextMenuLeftTop";
			}
			
			else if(mX +width > this.mdvMap.viewport.offsetWidth){
				x = x - width;
				
				this.contextMenu.div.className= "mapContextMenu mapContextMenuLeft";
			}
			else if(mY +height > this.mdvMap.viewport.offsetHeight){
				y = y - height;
				
				this.contextMenu.div.className= "mapContextMenu mapContextMenuTop";
			}
			
			
			else{
				this.contextMenu.div.className= "mapContextMenu";
			}
			
			this.contextMenu.div.style.width= width + 'px';
			this.contextMenu.div.style.height= height + 'px';

		}

 		this.contextMenu.div.style.display = 'none';
 		this.contextMenu.div.style.left = x + 'px';
 		this.contextMenu.div.style.top = y + 'px';
 		this.contextMenu.div.style.display= 'block';

 		var mousePoint = new MDVPoint(mX, mY);
 		var mouseCoord = this.mdvMap.getCoordinates(mousePoint);
 		this.mdvMap.events.triggerEvent(MDVEvent_CONTEXT_MENU, true, mouseCoord);

   	return false;
   };
  
  
  
  MDVMapControl.prototype.populateContainers = function () {
  	if (!this.arrowContainer || !this.zoomContainer)
  		return false;

  	// Populate Arrow Container
  	var firstRow 	= this.createDiv();
  	var secondRow 	= this.createDiv();
  	var thirdRow	= this.createDiv();

  	this.arrowContainer.appendChild(firstRow);
  	this.arrowContainer.appendChild(secondRow);
  	this.arrowContainer.appendChild(thirdRow);

	// Top Left to Top Right
	var arrow_1_1 = this.createDiv();
		arrow_1_1.className = 'MDVMapControl_Arrow';
		arrowImg_1_1 = this.createImage();
		arrowImg_1_1.src = this.images['transparent'].src;
		arrow_1_1.appendChild(arrowImg_1_1);
	var arrow_2_1 = this.createDiv();
		arrow_2_1.className = 'MDVMapControl_Arrow';
		arrowImg_2_1 = this.createImage();
		arrowImg_2_1.hover = this.images['top_hover'];
		arrowImg_2_1.normal = this.images['top_normal'];
		arrowImg_2_1.alt = this.images['top_normal'].alt;
		arrowImg_2_1.title = this.images['top_normal'].title;
		arrowImg_2_1.onclick = this.goNorth;
		arrowImg_2_1.src = this.images['top_normal'].src;
		arrow_2_1.appendChild(arrowImg_2_1);
	var arrow_3_1 = this.createDiv();
		arrow_3_1.className = 'MDVMapControl_Arrow';
		arrowImg_3_1 = this.createImage();
		arrowImg_3_1.src = this.images['transparent'].src;
		arrow_3_1.appendChild(arrowImg_3_1);

	firstRow.appendChild(arrow_1_1);
	firstRow.appendChild(arrow_2_1);
	firstRow.appendChild(arrow_3_1);

	// Middle Left to Middle Right
	var arrow_1_2 = this.createDiv();
		arrow_1_2.className = 'MDVMapControl_Arrow';
		arrowImg_1_2 = this.createImage();
		arrowImg_1_2.hover = this.images['left_hover'];
		arrowImg_1_2.normal = this.images['left_normal'];
		arrowImg_1_2.alt = this.images['left_normal'].alt;
		arrowImg_1_2.title = this.images['left_normal'].title;
		arrowImg_1_2.onclick = this.goEast;
		arrowImg_1_2.src = this.images['left_normal'].src;
		arrow_1_2.appendChild(arrowImg_1_2);
	var arrow_2_2 = this.createDiv();
		arrow_2_2.className = 'MDVMapControl_Arrow MDVMapControl_Arrow_LastResult';
		arrowImg_2_2 = this.createImage();
		arrowImg_2_2.hover = this.images['centre_hover'];
		arrowImg_2_2.normal = this.images['centre_normal'];
		arrowImg_2_2.alt = this.images['centre_normal'].alt;
		arrowImg_2_2.title = this.images['centre_normal'].title;
		arrowImg_2_2.onclick = this.goBack;
		arrowImg_2_2.mapControl = this;
		arrowImg_2_2.src = this.images['centre_normal'].src;
		arrow_2_2.appendChild(arrowImg_2_2);
	var arrow_3_2 = this.createDiv();
		arrow_3_2.className = 'MDVMapControl_Arrow';
		arrowImg_3_2 = this.createImage();
		arrowImg_3_2.hover = this.images['right_hover'];
		arrowImg_3_2.normal = this.images['right_normal'];
		arrowImg_3_2.alt = this.images['right_normal'].alt;
		arrowImg_3_2.title = this.images['right_normal'].title;
		arrowImg_3_2.onclick = this.goWest;
		arrowImg_3_2.src = this.images['right_normal'].src;
		arrow_3_2.appendChild(arrowImg_3_2);

  	secondRow.appendChild(arrow_1_2);
  	secondRow.appendChild(arrow_2_2);
  	secondRow.appendChild(arrow_3_2);

  	// Lower Left to Lower Right
  	var arrow_1_3 = this.createDiv();
  		arrow_1_3.className = 'MDVMapControl_Arrow';
  		arrowImg_1_3 = this.createImage();
  		arrowImg_1_3.src = this.images['transparent'].src;
  		arrow_1_3.appendChild(arrowImg_1_3);
  	var arrow_2_3 = this.createDiv();
  		arrow_2_3.className = 'MDVMapControl_Arrow';
  		arrowImg_2_3 = this.createImage();
  		arrowImg_2_3.hover = this.images['bottom_hover'];
  		arrowImg_2_3.normal = this.images['bottom_normal'];
  		arrowImg_2_3.alt = this.images['bottom_normal'].alt;
  		arrowImg_2_3.title = this.images['bottom_normal'].title;
  		arrowImg_2_3.onclick = this.goSouth;
  		arrowImg_2_3.src = this.images['bottom_normal'].src;
  		arrow_2_3.appendChild(arrowImg_2_3);
  	var arrow_3_3 = this.createDiv();
  		arrow_3_3.className = 'MDVMapControl_Arrow';
  		arrowImg_3_3 = this.createImage();
  		arrowImg_3_3.src = this.images['transparent'].src;
  		arrow_3_3.appendChild(arrowImg_3_3);

  	thirdRow.appendChild(arrow_1_3);
  	thirdRow.appendChild(arrow_2_3);
  	thirdRow.appendChild(arrow_3_3);


  	// Populate Zoom Level Container
  	var zoomIn = this.createDiv();
	  	zoomIn.className = 'MDVMapControl_Zoom';
  		zoomInImg = this.createImage();
  		zoomInImg.hover = this.images['zoomIn_hover'];
  		zoomInImg.normal = this.images['zoomIn_normal'];
  		zoomInImg.alt = this.images['zoomIn_normal'].alt;
  		zoomInImg.title = this.images['zoomIn_normal'].title;
  		zoomInImg.src = this.images['zoomIn_normal'].src;
  		zoomInImg.onclick = this.zoomIn;
  		zoomIn.appendChild(zoomInImg);
  		this.zoomContainer.appendChild(zoomIn);


  	// Iterate for every Zoom Level
  	var zoomLevels = 0;
  	var zoomLevelArr = this.mdvMap.config.getZoomLevels();
  	if (zoomLevelArr)
  		zoomLevels = zoomLevelArr.length;

  	for (var z = 0; z < zoomLevels; z++) {
  		var level = zoomLevelArr[zoomLevels - z - 1];
  		if (level) {
	  		var tmpZL = this.createDiv();
	  			tmpZL.className = 'MDVMapControl_ZoomLevel';
	  			tmpZLImg = this.createImage();
	  			tmpZLImg.level = level.level;
	  			tmpZLImg.hover = this.images['zoomLevel_hover'];
	  			tmpZLImg.normal = this.images['zoomLevel_normal'];
	  			tmpZLImg.src = this.images['zoomLevel_normal'].src;
	  			tmpZLImg.alt = "1:" + level.getScale();
	  			tmpZLImg.title = tmpZLImg.alt;
	  			tmpZLImg.onclick = MDVMapControl_onclick;
	  			tmpZL.appendChild(tmpZLImg);
	  			this.zoomContainer.appendChild(tmpZL);
	  			this.zoomLevels.push(tmpZLImg);
  		}
  	}

  	var zoomOut = this.createDiv();
	  	zoomOut.className = 'MDVMapControl_Zoom';
  		zoomOutImg = this.createImage();
  		zoomOutImg.hover = this.images['zoomOut_hover'];
  		zoomOutImg.normal = this.images['zoomOut_normal'];
  		zoomOutImg.alt = this.images['zoomOut_normal'].alt;
  		zoomOutImg.title = this.images['zoomOut_normal'].title;
  		zoomOutImg.src = this.images['zoomOut_normal'].src;
  		zoomOutImg.onclick = this.zoomOut;
  		zoomOut.appendChild(zoomOutImg);
  		this.zoomContainer.appendChild(zoomOut);

  	return true;
  };
  
   
MDVPolyline.prototype.getDirection = function (pos, next) {
	var a 		= next.x - pos.x;
	var b 		= next.y - pos.y;
	var angle 	= Math.atan2(b, a);
	
	var deg 	= angle * 180 / Math.PI;
	var temp    = deg;
	
	if (deg < 0)
		deg = 360 + deg;

		deg	= Math.floor(0.5 + deg);
		
	// IMG Offset...
	deg += 90;
		
	while (deg >= 120)
		deg -= 120;
		
	var img = '';
		
		
	// Pick appropriate IMG
	switch (deg % 3) {
		case 0:
			img = deg + '.png';
		break;
		
		case 1:
			img = (deg-1) + '.png';
		break;

		case 2:
			if (deg+1 == 120)
				deg = -1;
			img = (deg+1) + '.png';
		break;
	}
	
	var colour = 'FF0000';
	if (this.attributes['colour'] && this.attributes['colour'].indexOf('#') > -1) {
		colour = this.attributes['colour'].substring(this.attributes['colour'].indexOf('#')+1);
	}			
	
	var ipath = 'images/';
	if (this.mdvMap.config.get('imagePath'))
		ipath = this.mdvMap.config.get('imagePath');
		
	
	
	var m = this.mdvMap.createMarker(pos, new MDVPoint(0.5, 0.5), ipath + 'dir/' + colour + '/' + img);
	
	//bugfix ie
	m.img.style.width = '18px'
	m.img.style.height = '18px'
					
	return m;
 };
  
 MDVPolyline.prototype.getDirections = function () {
	  	var coordSeq = this.getAllCoords();
	  	var max		 = 20;
	  	var arrows	 = new Array();
	  	var counter	 = 0;
	  	var iter	 = 0;
	  	
	  	if (this.mdvMap.config.get('trips.polyline.arrows.max'))
	  		max = parseInt(this.mdvMap.config.get('trips.polyline.arrows.max'));
  	
		var zoomLevel = this.mdvMap.config.getZoomLevel(this.mdvMap.config.currentZoomLevelIndex);
		var pxWidthAll          = parseInt(zoomLevel.get('tileSizeX')) * parseInt(zoomLevel.get('numberOfTilesX'));
		var realToPxRatioWidth  = pxWidthAll / parseInt(zoomLevel.get('realWidth'));
		
		var polyNum= this.mdvMap.getLayer('directions').polyNum +10;
		
		switch (zoomLevel.level){
			case '0':	max =16;
					break;
			case '1':	max =31;
					break;
			case '2':	max =51;
					break;
			case '3':	max =81;
					break;
			case '4':	max =91;
					break;
			case '5':	max =111;
					break;
			default: max = 151;
		}
		
	  	while (counter <= 0 && iter < 9) {
	  	
		  	for (var c=0; c < coordSeq.length-1; c++) {
		  		if (!coordSeq[c] || !coordSeq[c+1])
		  			return null;
		  			
	  			var vec = new MDVPoint(coordSeq[c+1].x - coordSeq[c].x, 
	  				coordSeq[c+1].y - coordSeq[c].y);
	  				
	  			var dist = Math.sqrt(Math.pow(vec.x, 2) + Math.pow(vec.y, 2));
	  				dist *= realToPxRatioWidth;
	
	  			if (dist > max) {
				
	  				arrows.push( this.getDirection(new MDVCoordinates(coordSeq[c].mapName, coordSeq[c].x + vec.x / 2, coordSeq[c].y + vec.y / 2), coordSeq[c+1].clone()) ); 
	  				counter++;
	  			}   			
		  	}
		  	
		  	max -= 5;
		  	iter++;
	  	}
		
		return arrows;
};

 MDVPolyline.prototype.getDirectionsNetPath = function () {
	  	var coordSeq = this.getAllCoords();
	  	var max		 = 20;
	  	var arrows	 = new Array();
	  	var counter	 = 0;
	  	var iter	 = 0;
	  	
	  	if (this.mdvMap.config.get('trips.polyline.arrows.max'))
	  		max = parseInt(this.mdvMap.config.get('trips.polyline.arrows.max'));
  	
		var zoomLevel = this.mdvMap.config.getZoomLevel(this.mdvMap.config.currentZoomLevelIndex);
		var pxWidthAll          = parseInt(zoomLevel.get('tileSizeX')) * parseInt(zoomLevel.get('numberOfTilesX'));
		var realToPxRatioWidth  = pxWidthAll / parseInt(zoomLevel.get('realWidth'));
		
		var polyNum= this.mdvMap.getLayer('directions').polyNum +10;
		
		if(coordSeq.length > 2000){
			max =200;
		}
		else if(coordSeq.length > 1500){
			max =150;
		}
		else if(coordSeq.length > 1000){
			max =130;
		}
		
		else if(coordSeq.length > 800){
			max =100;
		}
		else if(coordSeq.length > 650){
			max =90;
		}
		else if(coordSeq.length > 500){
			max =80;
		}
		else{
			max =70;
		}
		
		for (var c=0; c < coordSeq.length-1; c++) {
			if (!coordSeq[c] || !coordSeq[c+1])
				return null;
				
			var vec = new MDVPoint(coordSeq[c+1].x - coordSeq[c].x, 
				coordSeq[c+1].y - coordSeq[c].y);
				
			var dist = Math.sqrt(Math.pow(vec.x, 2) + Math.pow(vec.y, 2));
				dist *= realToPxRatioWidth;
			
			if (c % max == 0) {
			
				arrows.push( this.getDirection(new MDVCoordinates(coordSeq[c].mapName, coordSeq[c].x + vec.x / 2, coordSeq[c].y + vec.y / 2), coordSeq[c+1].clone()) ); 
				counter++;
			}   	
		}

		
		return arrows;
};
  
  function MDVVMLRenderer(mdvMap, container) {
	this.mdvMap 	= mdvMap;
	this.container 		= container; 
	this.max			= null;
	this.min			= null;
	this.border			= 50;
	this.offset			= new MDVPoint(0, 0);
	this.boundingBox	= null;
	this.group			= null;
	
	document.namespaces.add("v", "urn:schemas-microsoft-com:vml");     	
	var style = document.createStyleSheet();

	style.addRule('v\\: *', "behavior: url(#default#VML);");
	style.addRule('v\\:shape', "behavior: url(#default#VML);");
	style.addRule('v\\:stroke', "behavior: url(#default#VML);");
	
	
	this.group = document.createElement('v:group');
	this.container.appendChild(this.group);
	
	// Inherit from MDVRenderer
	for (var method in MDVRenderer.prototype) {

	if (!MDVVMLRenderer.prototype[method])
	  MDVVMLRenderer.prototype[method] = MDVRenderer.prototype[method];
	}
  }
  
  MDVVMLRenderer.prototype.drawPolyline = function (polyline) {
	if (!polyline)
		return false;
		
	var pathStr = 'm';
	var coords = polyline.getAllCoords();
	for (var i=0; i < coords.length; i++) {      			
		var point = this.mdvMap.getPoint(coords[i]);					
		
		var x = point.x - this.offset.x;
		var y = point.y - this.offset.y;
		
		pathStr += x + ',' + y;

		if (i < coords.length-1)
			pathStr += ' ';
		if (i == 0)
			pathStr += 'l';
	}
	pathStr += ' e'; 
	
	var width  = this.boundingBox[1].x - this.boundingBox[0].x;
	var height = this.boundingBox[1].y - this.boundingBox[0].y;
	var left = this.boundingBox[0].x;
	var top  = this.boundingBox[0].y;
	
	var colour = polyline.get('colour');
	if (!colour)
		colour = 'red';

	var weight = polyline.get('weight');
	if (!weight)
		weight = '4px';
		
	var opacity = polyline.get('opacity');
	if (!opacity)
		opacity = '0.5';
		
	if (!polyline.append) {
		
		var shape = document.createElement("v:shape");
			shape.style.position = 'relative';
			shape.style.top = '0px';
			shape.style.left = '0px';
			shape.style.width = width;
			shape.style.height = height;
			
			shape.setAttribute('filled', 'false');
			shape.setAttribute('stroked', 'true');
			shape.setAttribute('strokecolor', colour);
			shape.setAttribute('strokeweight', weight);
			shape.setAttribute('path', pathStr);
			
		var stroke = document.createElement("v:stroke");
			stroke.setAttribute('opacity', opacity);
			stroke.setAttribute('joinstyle', 'round');
			stroke.setAttribute('endcap', 'round');
			
			shape.appendChild(stroke);	      		
		this.group.appendChild(shape);
		shape.parentPolyline = polyline;
		polyline.element = shape;
		polyline.element.mdvMap = this.mdvMap;
		polyline.append = true;
		
	} else if (polyline.element.path.value != pathStr) {
		polyline.element.path.value = pathStr;
	}
	
	if (polyline.toolTip)
		polyline.setToolTip(polyline.toolTip);
	
	return true;
  };
  
 MDVVMLRenderer.prototype.removePolyline = function (polyline) {
	if (!polyline || !polyline.append || polyline.element == null)
		return false;

		this.group.removeChild(polyline.element);
		polyline.element.onmousedown = null;
		polyline.element.onmousemove = null;
		polyline.element.onmouseout = null;
		polyline.element.onmouseover = null;
		polyline.element.onmouseup = null;

		if (polyline.element.toolTip)
			polyline.element.toolTip = null;

		if (polyline.element.mdvMap)
			polyline.element.mdvMap = null;

		polyline.element = null;
		polyline.append = false;
	
	return true;
 };
  
  MDVVMLRenderer.prototype.setBoundingBox = function () {
		var width  = this.boundingBox[1].x - this.boundingBox[0].x;
		var height = this.boundingBox[1].y - this.boundingBox[0].y;
		
		var left = this.boundingBox[0].x;
		var top  = this.boundingBox[0].y;
	
		this.offset = new MDVPoint(left, top);
		
		this.group.style.behavior = 'url(#default#VML)';
		this.group.style.width  = width + 'px';
		this.group.style.height = height + 'px';
		this.group.style.position = 'absolute'
		this.group.style.left = left + 'px';
		this.group.style.top = top + 'px';
		this.group.setAttribute('coordsize', width + ',' + height);
		this.group.coordsize.value = width + ',' + height;
	
		return true;			
  };
  
    MDVMapEFAInfoEx.prototype.fetchPins = function() {
	// Get Pins for current position & zoom level.
  	if (this.mdvMap.config.get('efaURL')) {

  		var host   = this.mdvMap.config.get('efaURL');
        var purpose   = this.mdvMap.config.get('purpose') != null ? this.mdvMap.config.get('purpose') : '';
  		var centre = this.mdvMap.getCentre();
  		var language = this.mdvMap.config.get('language') != null ? this.mdvMap.config.get('language') : 'en';
  		var zoomLevel = this.mdvMap.config.getZoomLevel(this.mdvMap.config.getZoomLevelIndex());
  		var isLast = this.mdvMap.config.getZoomLevel(parseInt(this.mdvMap.config.getZoomLevelIndex())+1) == null;
  		var isOneBeforeLast = this.mdvMap.config.getZoomLevel(parseInt(this.mdvMap.config.getZoomLevelIndex())+2) == null && this.mdvMap.config.getZoomLevel(parseInt(this.mdvMap.config.getZoomLevelIndex())+1) != null;

  		var showStops = zoomLevel.get('showSTOP') == "true" && this.stops.visible ? 1 : 0;
  		var showPOI   = zoomLevel.get('showPOI') == "true" && this.poi.visible ? 1 : 0;
  		
  		var poiArea = this.mdvMap.config.get('poiArea') =="true";
  		var poiPoint = this.mdvMap.config.get('poiPoint')=="false";  		  		
  		
  		var vpReal = this.mdvMap.getViewportRealExtends();
  		var radius = Math.floor(0.5 + Math.sqrt((Math.pow(vpReal.width/2, 2) 
  			+ Math.pow(vpReal.height/2, 2))));

		var _params = { language: language, coord: Math.floor(centre.x + 0.5) + ':' + Math.floor(centre.y + 0.5) + ':' 
			+ centre.mapName, inclFilter: 1, purpose: purpose, max: -1, coordListFormat: 'STRING', 
			language: 'en', itdLPxx_mdvMapName: 'mdvMap_' + this.mdvMap.getName(), coordListOutputFormat: 'STRING' };
		
		var ifilter = 1;
		
		if (showStops) {
			var temp = '';
			
			if (zoomLevel.get('showSTOP.majorMeans')) {
				temp = zoomLevel.get('showSTOP.majorMeans');
			}
			
			_params['type_' + ifilter] = 'STOP';
			_params['radius_' + ifilter] = radius;
			_params['inclDrawClasses_' + ifilter] = temp;
			
			ifilter++;

			if ((isLast || isOneBeforeLast) && !this.stopsOnly) {
				temp = '';
				
				if (isLast) {
					_params['type_' + ifilter] = 'ENTRANCE';
					_params['radius_' + ifilter] = radius;
					_params['inclDrawClasses_' + ifilter] = temp;
					ifilter++;
				}
				
				temp = '';
	
				_params['type_' + ifilter] = 'BUS_POINT';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = temp;
	
				ifilter++;
			}
		}
		
		if (showPOI) {
			var temp = '';

			// All POI DrawClasses
			for (var ii=39; ii <= 80; ii++) {
				temp += ii + ':';
			}
			
			
			if(poiArea){
			
				temp ='';
				_params['type_' + ifilter] = 'POI_AREA';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = temp;
                _params['inclPOIH_' + ifilter] = selSubCat;

				ifilter++;
			}
			
			
			if(!poiPoint){
			
				temp ='';
				_params['type_' + ifilter] = 'POI_POINT';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = temp;
                _params['inclPOIH_' + ifilter] = selSubCat;

				ifilter++;
			}
			
			if (this.options && this.options.pools) {
				for (pl in this.options.pools) {
					_params['type_' + ifilter] = pl;
					_params['radius_' + ifilter] = radius;
	
					if (this.options.pools[pl].inclDrawClasses && this.options.pools[pl].inclDrawClasses.length > 0)
						_params['inclDrawClasses_' + ifilter] = this.options.pools[pl].inclDrawClasses;
	
					if (this.options.pools[pl].exclLayers && this.options.pools[pl].exclLayers.length > 0)
						_params['exclLayers_' + ifilter] = this.options.pools[pl].exclLayers;
					
					ifilter++;
				}
				
			}
			
		}
		
		var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVMapEFAInfoEx_onAjaxComplete });
  	}
  };
  
 