﻿// ==================================================================
// Global variables
// ==================================================================
// the map
var mdvJpMaps = {};
// coordinate reduction list
var reductionList = new Array();
// coordinates of the right mouse click
var ctxCoords = null;

// ==================================================================
// Common map functionality
// ==================================================================
// This function loads and initializes the map when the site is loaded.
function onLoadMapHandler(type, usage, fullTrip, selector) {
    
    var initiator;
    
    // change headline in overlay mode, if 3rd arg is a DOM Element, not boolean   
    if (arguments.length===3 && typeof arguments[2]==='object') {
        initiator = arguments[2];
        $('#ui-dialog-title-np-dialog').text($(initiator).text());
    }
    
	initMdvMapConfig(type);
	currentMap = type +':' + usage;
		
	if(type!='aerial' && mdvJpMaps['aerial'  + ':' +  usage]!= null){
		onUnloadMapHandler('aerial', usage);
		changeMapStyles(type, 'aerial', usage)
	}
    
	if(type!='tube' && mdvJpMaps['tube'  + ':' +  usage]!= null){
		onUnloadMapHandler('tube', usage);
		changeMapStyles(type, 'tube', usage)
	}
    
	if(type!='navteq' && mdvJpMaps['navteq'  + ':' +  usage]!= null){
		onUnloadMapHandler('navteq', usage);
		changeMapStyles(type, 'navteq', usage)
	}
    
	if(type!='city' && mdvJpMaps['city'  + ':' +  usage]!= null){
		onUnloadMapHandler('city', usage);
		changeMapStyles(type, 'city', usage)
	}
	
	if (mdvJpMaps[type + ':' +  usage] == null){
		mdvJpMaps[type + ':' +  usage] = new MDVMapHelper(type, usage);
		$('itdLPxx_currentMap').value= type +':' + usage;
	}
	
	if(usage.indexOf('detail')!='-1'){
		var tripSelector = usage.split('_')[1];
		var sessionID = $('#sessionID').val();
		var requestID = $('#requestID').val();	
		
		mdvJpMaps[type + ':' +  usage].displayJourney(sessionID, requestID, tripSelector, false);
	} 
    else if(usage.indexOf('overview')!='-1'){
		var tripSelector = selector || currentRoute;
		var sessionID = $('#sessionID').val();
		var requestID = $('#requestID').val();	
		
		mdvJpMaps[type + ':' +  usage].displayJourney(sessionID, requestID, tripSelector, true);
	}

};

// This function unloads the map when the site is unloaded.
function onUnloadMapHandler(type, usage) {
    var key = type + ':' +  usage;
    if (mdvJpMaps[key]) {
        if (type !== 'tube') {
            mdvJpMaps[key].storeMapCentreAndZoomlevel(type);
        }
        mdvJpMaps[key].destroy(type, usage);
    }
};

function changeMapStyles(current, last, usage){

    $('button[id="' + current +'Button_' + usage+'"]').attr('class', 'btDep selected');
    $('button[id="' + last +'Button_' + usage+'"]').attr('class', 'btDep');

	if($('#' + current+'Hint_' + usage).length > 0){
		$('#' + current+'Hint_' + usage)[0].className= 'mapHint';
		$('#' + last+'Hint_' + usage)[0].className= 'hideMapHint';
	}
	
	if($('#aerialLabels_' + usage)){
		if(current == 'aerial'){
			$('#aerialLabels_' + usage).css('display', 'block');
		}
		else{
			$('#aerialLabels_' + usage).css('display', 'none');
		}
	}
}

// ==================================================================
// Common map functionality
// ==================================================================

// This function loads the map
function MDVMapHelper(type, usage) {
	this.mdvMap = null;
	this.markerLayer = null;
	this.type = type;
	this.usage = usage;
	this.marker = null;
	this.scale = null;
	
	// output map functionality
	this.viewport = document.getElementById('mdvMap_' + this.usage);
	this.trips = null;
	this.mdvMapTripsLoaded = false;
	
	// initialize map and register events
	if (this.mdvMap == null) {
		this.mdvMap = new MDVMap(document.getElementById('mdvMap_' + this.usage));
		
		// correct the map control alt texts
		if(mapLanguage =='de'){
			var controlText = new Array();
			controlText['goNorth'] = 'Norden';
			controlText['goWest'] = 'Westen';
			controlText['goEast'] = 'Osten';
			controlText['goSouth'] = 'Süden';
			controlText['lastResult'] = 'Letztes Ergebnis';
			controlText['zoomIn'] = 'Vergrößern';
			controlText['zoomOut'] = 'Verkleinern';
		}
		
		if(this.type=='aerial'){
			this.overlay = this.mdvMap.createOverlay('captions', mapServerURL + 'Luftbilder/Text/');		
			this.overlay.setFileType('.png');
			this.mdvMap.addOverlay(this.overlay); 
		}
		
        this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.checkLayers);

        
		// vvs context menu only on enquiry page 
		if(currentPage!='result'){
			if(this.type==='tube'){
				this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.submitTubePoint);
			}
			else{
                this.ctxMenuArr = new Array();

                var setOrigin = 'Startpunkt übernehmen';
                var setDestination = 'Zielpunkt übernehmen';	
            
                this.ctxMenuArr[0] = new MDVMapMenuItem(setOrigin, this.setOrigCoordinates.bind(this));
                this.ctxMenuArr[1] = new MDVMapMenuItem(setDestination, this.setDestCoordinates.bind(this)); 
                
                this.ctxMenu = new MDVMapMenu(this.ctxMenuArr);
                
                new MDVMapContextMenu(this.mdvMap, this.ctxMenu);
                
                this.mdvMap.events.registerEvent(MDVEvent_CONTEXT_MENU, this, this.ContextMenuHandler);
			
				this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.submitPoint);
                
                this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.checkLayers);

                this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
        
			}
		}
        
        new MDVMapNavigator(this.mdvMap);
        
        if(this.type!=='tube'){
            
            var imgPath = 'images/mdvMap/stopSymbols/'
            
            if(this.type=='aerial'){
                imgPath = 'images/mdvMap/aerialSymbols/';
            }
            
            new MDVMapEFAInfoEx(this.mdvMap, { imagePath: imgPath, alignment: new MDVPoint(0.5, 0.5) });	
				
            this.trips = new MDVMapEFATrips(this.mdvMap, { reductionList: reductionList });

        }

		new MDVMapControl(this.mdvMap, controlText);
				
		this.mdvMap.type = type;
		
		if(this.type!='tube'){
			this.scale = new MDVMapScale(this.mdvMap, {});
		}
    }
	
	this.execute();
	
    this.markerLayer = this.mdvMap.createLayer('vvsMarkers',{ 'useOwnContainer': true });
    
    this.markerLayer_drawn = {};
    this.mdvMap.addLayer(this.markerLayer);
    
	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.setListMarker);
    // MDVEvent_MAP_INITIALISED already fired, so trigger setListMarker  
    this.setListMarker.apply(this);
	// map does not move if it is grabbed and the mouse moved over the borders of the map
	attachEventListener(document, 'mouseover', this.mdvMap.release.bind(this.mdvMap), false);
};

// This function destroys the map and clears the cache.
MDVMapHelper.prototype.destroy = function(type, usage) {
    
    $('div[class=MDVMapControl]').remove();
	$('div[class=mapContextMenu]').remove();
	$('div[id=divScale]').remove();
	
 	$('div[id="mdvMap_'+usage+'_mdvMap_'+usage+'_mapper0_mapTiles"]').remove();
	$('div[id="mdvMap_' + usage+ '_mdvMarkers"]').remove();
	$('div[id="mdvMap_' + usage+ '_mapper0"]').remove();
	$('div[id="mdvMap_' + usage+ '_mapper1"]').remove(); 

	mdvJpMaps[type + ':' +  usage].mdvMap.destroy();
	mdvJpMaps[type + ':' +  usage].mdvMap = null;
	mdvJpMaps[type + ':' +  usage] = null;
};

//  resize map function 
MDVMapHelper.prototype.resizeMap = function() {

	var mh = $('#' + this.viewport.id).height() 

	var myh=(mh > 333)?333:560;

    $('#' + this.viewport.id).animate({
        height: myh + "px"
    }, 1000 );

	var time=(mh > 333)?900:100;

	window.setTimeout(

	function(){
        mdvJpMaps[currentMap].setViewport(myh);

	},time)
}

MDVMapHelper.prototype.checkLayers = function(id, msg, obj) {
	var zl = this.mdvMap.config.currentZoomLevelIndex;
    
    if(zl > 4){
        $('#mdvMap_' + this.usage + ' .stopNamesBox').css('display', 'block');
    }
    else{
        $('#mdvMap_' + this.usage + ' .stopNamesBox').css('display', 'none');
    }
    
}

MDVMapHelper.prototype.stopSeq = function(obj) {

    if(obj==true){
        this.mdvMap.config.params['trips.polyline.stopSeq'] = 'true';
    }
    else{
        this.mdvMap.config.params['trips.polyline.stopSeq'] = 'false';
    }
    
	var sessionID = $('#sessionID').val();
	var requestID = $('#requestID').val();	
    
    this.trips.loadTrip(sessionID, requestID, this.tripIndex)
};


MDVMapHelper.prototype.stopNames = function(obj) {

    if(obj==true){
        this.mdvMap.config.params['info.stopLabels'] = 'true';
    }
    else{
        this.mdvMap.config.params['info.stopLabels'] = 'false';
        $('.stpLbl').remove();
    }
    
    this.mdvMap.update();

};


// resize map and update position of the scale 
MDVMapHelper.prototype.setViewport = function(size) {
	this.scale.updatePosition(size);
}

MDVMapHelper.prototype.execute = function () {

	// execute map
	 if (this.mdvMap) {
		if(this.type=='aerial'){
			this.mdvMap.execute(mdvSatelliteMapConfig);	
		}
		else if(this.type=='tube'){
			this.mdvMap.execute(mdvNetplanConfig);	
		}
		else if(this.type=='city'){
			this.mdvMap.execute(mdvCityMapConfig);		
		}
		else{
			this.mdvMap.execute(mdvMapConfig);	
		}
	} 
    
    if (this.type!=='tube') {
        this.restoreMapPos();
    }
    
};


var markerListCenter = '';

// Set marker for odv select list entries 
MDVMapHelper.prototype.setListMarker = function(id, msg, map) {
    
    var that = this,
        size = new MDVPoint(270, 120),
        usageImg = 'von.png',
        offset = { x: 0.5, y: 0.5 },
        usage, odvs, len, selected, selOdv, i,
        curOdv, x, y, display, tool, mc, m;
        
    
    $("select[id^='name_']").each(function(index) {

        usage = this.id.split('_')[1];
        odvs =$('option', this);
        
        // set map centre with selected odv's coords
        if (markerListCenter==='') {
            selected = $('option:selected', this).attr('id');
            selOdv =  selected.split('$');
            markerListCenter = selOdv[0]+':' +selOdv[1];
            that.zoomCoord(selOdv[0], selOdv[1])
        }
        
        // draw markers
        for (i=0, len=odvs.length; i<len; i++) {
            // curOdv format: node odvNameElem, {@x}${@y}${.}${@stateless}${@sortByQu}${@anyType}
            curOdv =  odvs[i].id.split('$');
            x = parseInt(curOdv[0], 10);
            y = parseInt(curOdv[1], 10);
            
            // draw marker only once
            if (that.markerLayer_drawn[usage.charAt(0) + curOdv[3]]===true) {
                continue;
            }
            
            // no coords provided
            if (x>0===false || y>0===false) {
                continue;
            }
            // outside of viewport
            if (that.mdvMap.inBounds({'x': x, 'y': y})===false) {
                continue;
            }
            
            if (usage==='destination') {
                usageImg = 'nach.png';
            }
            else if (usage==='via') {
                usageImg = 'via.png';
            }
            
            display = '<strong>' + curOdv[2] + '</strong>';

            if(curOdv[5]==='stop'){
                size = new MDVPoint(300, 255);
            }
            
            tool = that.mdvMap.createToolTip(size, display);
            tool.setOverflow(true);
            tool.setPin(true);
            
            mc = new MDVCoordinates(that.mdvMap.config.params.mapName, x, y);
        
            m = that.mdvMap.createMarker(mc,  offset, that.getImage(usageImg));
            m.objectId.type = curOdv[5];
            m.objectId.id = curOdv[3];
            m.objectId.desc = curOdv[2]
            m.setToolTip(tool);
            m.stateless = curOdv[3];
            m.usage = usage;
            that.markerLayer.addMarker(m);
            that.markerLayer_drawn[usage.charAt(0) + curOdv[3]]=true;
        }
    });

};

MDVMapHelper.prototype.zoomCoord = function (coordX, coordY) {

    var coord = new MDVCoordinates(this.mdvMap.config.params.mapName, coordX, coordY);
	this.mdvMap.setCentre(coord);
    this.mdvMap.setZoomLevel(5);
	this.mdvMap.update()
}

// store map centre and zoomlevel
MDVMapHelper.prototype.storeMapCentreAndZoomlevel = function(last_type) {
        
    var mapCentre = this.mdvMap.getCentre(),
        data = [mapCentre.mapName,
                mapCentre.x, 
                mapCentre.y, 
                this.mdvMap.config.currentZoomLevelIndex,
                last_type].join(':');
                
    $.cookie('mapState', data, { 'path': '/' });
    
};

MDVMapHelper.prototype.restoreMapPos = function () {
    
    var c, zl, data, last_type, 
        cookie = $.cookie('mapState');
        
    if (cookie) {
        data = cookie.split(':');
        c = new MDVCoordinates(data[0], data[1], data[2]);
        this.mdvMap.setCentre(c);
        zl = data[3];
        last_type = data[4];
        
        if (this.type=='aerial' && last_type=='navteq') {
            zl+=1;
        }
        else if (this.type=='navteq' && last_type=='aerial') {
             zl-=1;
        }
        else if (this.type=='aerial' && last_type=='city') {
            zl+=2;
        }
        else if (this.type=='city' && last_type=='aerial') {
            zl-=2;
        }
        else if (this.type=='city' && last_type=='navteq') {
            zl-=1;
        }
        else if (this.type=='navteq' && last_type=='city') {
            zl+=1;
        }
        
        if(zl < 0) {
            zl = 0;
        }
    
        this.mdvMap.setZoomLevel(zl);
        this.mdvMap.update();
    }
};

// This function sets the origin/destination marker
MDVMapHelper.prototype.setMarker = function(obj, usage) {
	
	var mc = new MDVCoordinates(obj.mapName, parseInt(obj.x), parseInt(obj.y));
	var text;

	var offset = { x: 0.5, y: 0.5 };
	
	if(this.usage.indexOf('destination')!='-1') {
		if (document.getElementById('name_destination') && document.getElementById('name_destination').value!='')
			text = document.getElementById('name_destination').value;
		else
			text =  obj.name;
	}
	else {
		if (document.getElementById('name_origin') && document.getElementById('name_origin').value!='')
			text = document.getElementById('name_origin').value;
		else
			text = obj.name;
			usage= 'origin';
	}
	
	this.marker = this.mdvMap.createMarker(mc,  offset, this.getImage(usage));
	var tool = this.mdvMap.createToolTip('<b>' + text + '</b>');
	this.marker.setToolTip(tool);
	this.mdvMap.addMarker(this.marker);
	this.mdvMap.update();
};

// This function returns the marker image.
MDVMapHelper.prototype.getImage = function(usage) {
	var img = 'images/mdvMap/transparent.gif';
	
	 if(!usage){
		usage= 'transparent';
	} 

	switch(usage) {
		case 'origin':
			img = 'images/mdvMap/origin.gif';
			break;
		case 'destination':
			img = 'images/mdvMap/destination.gif';
			break;
		case 'via':
			img = 'images/mdvMap/via.gif';
			break;
		default:
		img = 'images/mdvMap/'+ usage;
	}
	
	var i = new Image();
	i.src = img;

	return img;
};

//this function create a tooltip
MDVMapHelper.prototype.onToolTip = function(id, msg, obj) {

	if (obj.isFixed()){
		return;
	}
	if (obj.isVisible()) {
		if (!obj.helper){
			obj.helper = new MDVToolTipHelper(obj);
		}
        
        // ouput map - line tooltips
        if(obj.parentMarker.leg){
            obj.helper.executeLine(obj);
        }
        else{
            obj.helper.executePoint(obj);
        }
	} 
};

// MDVToolTipHelper
function MDVToolTipHelper(toolTip) {
	this.toolTip = toolTip;
	this.processed = false;
	this.type = currentMap;	
};

// This function creates the tooltip bubble.
MDVToolTipHelper.prototype.executePoint = function(tooltip) {

	if (!this.processed) {
	
		var wait = '';
	
		if (mapLanguage =='en'){
			wait = 'Please wait while loading...';
		}
		else{
			wait = 'Bitte warten....'
		}
        
		// ROP - STOPS with Departure Monitor
		if (tooltip.getParent().objectId && this.type.indexOf('rop')!='-1' && tooltip.stop) {
			tooltip.setInnerHTML('<b>'
				+ tooltip.stop.name
				+ '</b><br><br><div class="dmDiv" id="div_'
				+ tooltip.stop.ref.id
				+ '">'
				+ wait
				+'</div>'); 

			tooltip.dm = new MDVEFADepartureMonitor(tooltip.stop.ref.id, 'XSLT_DM_REQUEST');
			tooltip.dm.getDepartures(tooltip.stop.ref.id);
		} 
		
		// STOPS with Departure Monitor
		if (tooltip.getParent().objectId && tooltip.getParent().objectId.type.toLowerCase()=='stop') {
			tooltip.setInnerHTML('<div class="tthead"><img src="images/bg.tt.hs.png" alt=""/> '
				+ tooltip.getParent().objectId.desc
				+ '</div><div class="dmDiv" id="div_'
				+ tooltip.getParent().objectId.id
				+ '">'
				+ wait
				+'</div>'); 

			tooltip.dm = new MDVEFADepartureMonitor(tooltip.parentMarker.objectId.id, 'XSLT_DM_REQUEST');
			tooltip.dm.getDepartures(tooltip.getParent().objectId.id);
		} 
        
		// POIS with Links and Address
		if (tooltip.getParent().objectId && tooltip.getParent().objectId.type && tooltip.getParent().objectId.type.toLowerCase()=='poi_area' 
				|| tooltip.getParent().objectId && tooltip.getParent().objectId.type.toLowerCase()=='poi_point' 
				|| tooltip.getParent().objectId && tooltip.getParent().objectId.type.toLowerCase()=='poi') {
		
			var link ='';
            
            if(tooltip.getParent().getObjectId().attrs){
	
                for (var i=0; i < tooltip.getParent().getObjectId().attrs.length; i++) {
                    var a = tooltip.getParent().getObjectId().attrs[i];

                    if (a.name == 'POI_LINK') { 		
                        link = link + '<a href="' + a.value.substring(a.value.indexOf('$') +1) 
                               + '" target="_blank">' 
                               + a.value.substring(0, a.value.indexOf('$')) + '</a><br/>';
                    }
                } 
                
                for (var i=0; i < tooltip.getParent().getObjectId().attrs.length; i++) {
                    var a = tooltip.getParent().getObjectId().attrs[i];

                    if (a.name == 'POI_ADDRESS') {
                        link += 'Adresse: ' + a.value;
                    }							
                }	
            
            }
			
			tooltip.setInnerHTML('<div class="tthead"><img src="images/bg.tt.ziel.png" alt=""/> '
				+ tooltip.getParent().objectId.desc
				+ '</div><div class="poiDiv">'
				+ link + ' </div>'
				+''); 
		} 
	}
    else if (tooltip.dm) {
        tooltip.dm.getDepartures(tooltip.getParent().objectId.id);
    }	
};


// This function creates the tooltip bubble.
MDVToolTipHelper.prototype.executeLine = function(obj) {

   if(obj.parentMarker.leg.mode.type=='100' || obj.parentMarker.leg.mode.type=='99'){
        var newTool = 'Fußweg';
        obj.setInnerHTML(newTool); 
    }
    else if(obj.parentMarker.leg.mode.type=='97'){
        var newTool = 'Sitzenbleiber';
        obj.setInnerHTML(newTool); 
    }
    else if(obj.parentMarker.leg.mode.type=='105'){
        var newTool = 'Taxifahrt';
        obj.setInnerHTML(newTool); 
    }
    else if(obj.parentMarker.leg.mode.type=='107'){
        var newTool = 'Fahrrad';
        obj.setInnerHTML(newTool); 
    }
    else if(obj.parentMarker.leg.mode.diva && obj.parentMarker.leg.mode.diva.operator){
    
        var newTool = obj.parentMarker.leg.mode.name;
        
        obj.setInnerHTML(newTool); 
    }
    else if(obj.parentMarker.leg.mode.name){
        var newTool = obj.parentMarker.leg.mode.name;
        obj.setInnerHTML(newTool); 
    }
}

// this function submit a point from the list map
MDVMapHelper.prototype.submitPoint = function(id, msg, obj) {

    // submit only list points  obj.marker.layer.name == 'vvsMarkers' && 
    var stateless = obj.stateless || obj.marker.stateless || null;
    var usage = tmpUsage || obj.marker.usage || null;

    if(stateless && usage){
        $('#nameInfo_' + usage).val(stateless);
        $('#typeInfo_' + usage).val('any');
        
        submitEFAForm();
    }
};

// submit a point from a tube map 
MDVMapHelper.prototype.submitTubePoint = function(id, msg, obj) {

    if(this.usage=='overlay'){
        this.usage = tmpUsage;
    }

	if(this.id != 'dm' && this.id != 'stt' && this.id != 'rop'){
        $('#execInst').val('verifyOnly')
    }

    $('#nameInfo_' + this.usage).val(obj[0]);
    $('#typeInfo_' + this.usage).val('any');
	
	submitEFAForm();
};

// ==================================================================
// Trip request context menu functions.
// ==================================================================
// The context menu handler gets the mouse coordinates and the centre coordinates 
MDVMapHelper.prototype.ContextMenuHandler = function(id, status, obj) {
    
	if(status == true){
		ctxCoords = obj;
	}
}

// This context menu functions submits a selected point.
MDVMapHelper.prototype.setOrigCoordinates = function() {
    this.setCoordinates('origin');
};

// This context menu functions submits a selected point.
MDVMapHelper.prototype.setDestCoordinates = function() {
	this.setCoordinates('destination');
};

// this function set the coordinates form the context menu 
MDVMapHelper.prototype.setCoordinates = function(usage) {

    // store coordinates and type
    $('#nameInfo_' + usage).val(parseInt(ctxCoords.x) + ':' + parseInt(ctxCoords.y) + ':' + ctxCoords.mapName + ':'); 
    $('#typeInfo_' + usage).val('coord');
    $('#nameState_' + usage).val('notidentified');
    $('placeState_' + usage).val('notidentified');
    $('placeInfo_' + usage).val('');
    
    this.mdvMap.mapper.style.cursor = 'wait';
        
    $('#execInst').val('verifyOnly');
    submitEFAForm();

};	

// ==================================================================
// Map output functions.
// ==================================================================

// This function displays a journey on the map.
MDVMapHelper.prototype.displayJourney = function(sessionID, requestID, tripIndex, fullTrip) {

	if(!sessionID){
		sessionID = document.getElementById('sessionID').value
	}
	
	if(!requestID){
		requestID = document.getElementById('requestID').value
	}
	
	if(!tripIndex){
		tripIndex ='1'
	}
    
    this.tripIndex = tripIndex;
	
	this.trips.loadTrip(sessionID, requestID, tripIndex, fullTrip);
    this.trips.update();
	this.mdvMapTripsLoaded = true;
}

// This function displays a journey on the map.
MDVMapHelper.prototype.tripDetailView = function(x, y) {
	this.mdvMap.setCentre(new MDVCoordinates(this.mdvMap.config.params.mapName,x,y));	
	this.mdvMap.setZoomLevel(4);		
	this.mdvMap.update();	
}

MDVMapHelper.prototype.mapIt = function (id, type, line, coords) {
	if (this.mdvMapper == null)
		this.mdvMapper = new MDVMapObjectMapper(this);	
		
	var lineAll = line.replace('$dir$', 'H');
	var id =1;

    this.clear();
    
	this.mdvMapper.mapIt(id, type, lineAll, coords);	
};


function MDVMapObjectMapper(helper) {
	this.helper = helper;
	this.mdvMap = this.helper.mdvMap;
	this.routes  = [];
	
	// new layer for routes
	this.layer  = this.mdvMap.createLayer('routes');
	this.layer.setZIndex(5);
	this.mdvMap.addLayer(this.layer);
}

MDVMapHelper.prototype.clear = function () {

	if(this.mdvMapper){
		this.mdvMapper.layer.removeAll();
	}
};

MDVMapObjectMapper.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.id == id)
		{
			this.remove(route);
			this.routes.splice(r, 1);
			return;
		}			
	}

	this.fetch(id, type, line, coords);	
};

MDVMapObjectMapper.prototype.fetch = function (id, type, line, coords) {
	var _param = { line: line, 
				hideBannerInfo: 1, 
				coordListOutputFormat: 'STRING', 
				filterEpsilon: '5.0',
				returnSinglePath: '1',
				itdLPxx_id: id,
				itdLPxx_type: type,
				itdLPxx_coords: coords,
                command:'bothdirections',
                outputFormat: 'JSON'                
                };
		
	var _ajax = mdvLib.ajax({ host: 'XSLT_GEOOBJECT_REQUEST', method: 'post', parameters: _param, onComplete: this.onRouteCallback.bind(this)});
};

MDVMapObjectMapper.prototype.onRouteCallback = function (request) {

	var json, efa, p, coords, geoObjItems, color, 
        path, item, code, coordList, c, len, stop, 
        cs, stopName, marker, tt, size, i=0;
	
    if (request && request.responseText)	{
 		json = request.responseText;
 	} else if (request) {
 		json = request;
 	}
	
	eval('efa = ' + json + ';');
	
	if (!efa || !efa.geoObjects || 
		!efa.geoObjects.items || 		
		!efa.geoObjects.items[0].item.paths ||
		!efa.geoObjects.items[0].item.mode.diva) {
			return;
	}
    
	geoObjItems = efa.geoObjects.items[0];
	
    color = {
        '3': '#ED1C24',
        '1': '#14A3FF',
        '2': '#58AF41',
        '0': '#939598',
        '6': '#939598',
        '9': '#14A3FF',
        '11': '#14A3FF'
    };
	
    item = {
        polylines: [], 
        stops: []
    };
	
    $(geoObjItems.item.paths).each(function(idx, elem) {
        p = this.mdvMap.createPolyline(elem.path);
        code = geoObjItems.item.mode.code;
        p.add('colour', color[code] || '#939598');
		p.add('opacity', '1');
		this.layer.addPolyline(p, false);
		item.polylines.push(p); 
    }.bind(this));
    
    
	coordList = { x: [], y: [] };
	
	for (i=0; i < item.polylines.length; i++) {
		p = item.polylines[i];
		coords = p.getAllCoords();
		for (c=0, len=coords.length; c < len; c++) {
            coordList.x.push(coords[c].x);
			coordList.y.push(coords[c].y);
		}
	}
	
	coordList.x.sort(function(a, b) { return a - b; });
	coordList.y.sort(function(a, b) { return a - b; });
    stop = geoObjItems.item.points[0] || geoObjItems.item.points;	
	coords = new MDVCoordinates('NBWT', coordList.x[1], coordList.y[1]);
    i = 0;
	
    do {
		i++;
		cs = stop.ref.coords.split(',');
		stopName = stop.name;
		coords = new MDVCoordinates('NBWT', cs[0], cs[1]);
		marker = null;
		if (coords.x > 0 && coords.y > 0) {
            marker = this.mdvMap.createMarker(coords, new MDVPoint(0.5, 0.5), this.getIcon(geoObjItems.item.mode.code));
			size = new MDVPoint(270, 150);
			tt = this.mdvMap.createToolTip(size, stopName);
			tt.stop = stop;
			tt.setOverflow(true);
			tt.setPin(true);
			marker.setToolTip(tt); 
			this.layer.addMarker(marker, geoObjItems.item.points[i]==null);
		}		
		if (marker) {
			item.stops.push(marker);
		}
		stop = geoObjItems.item.points[i];
	} while (stop);  
	
	this.routes.push(item);
    
    MDVMapEFATrips.prototype.beautify.apply(this);
    this.mdvMap.update();
};

MDVMapObjectMapper.prototype.getIcon = function (mot) {
	var ext = mot;

	return 'images/mdvMap/mot' + ext + '.gif';
};

/**
* MDVEFADepartureMonitor
*/
function MDVEFADepartureMonitor(id, url) {
	this.id 	= id;
	this.url 	= url;
}

MDVEFADepartureMonitor.prototype.getDepartures = function(identifier) {

	var _params = { 
        itdLPxx_id: identifier, 
        name_dm: this.id, 
        type_dm: 'stopID', 
        mode: 'direct', 
        limit: '5', 
        deleteAssignedStops_dm: '1', 
        useRealtime: '1',
        itdLPxx_page: 'tooltip'
    };
    
	var _ajax = mdvLib.ajax({ host: this.url, parameters: _params, onComplete: MDVEFADepartureMonitor_onAjaxComplete.bind(this)});
	
};

function MDVEFADepartureMonitor_onAjaxComplete(request) {

	if (request) {
		var id =this.id;
		var text = request.responseText;
		if(document.getElementById('div_' + id)){
			var target = document.getElementById('div_' + id);
				target.innerHTML = text;
		}
	}
}

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.divScaleBar = createDiv('divScaleBar');
      this.divScaleTickTop = createDiv('divScaleTickTop');
      this.divScaleTickBottom = createDiv('divScaleTickBottom');
      this.divScaleTextTop = createDiv('divScaleTextTop');
      this.divScaleTextBottom = createDiv('divScaleTextBottom');

	  var color = '#000000';

	  if(this.mdvMap.config.params.scaleColor){
		color = this.mdvMap.config.params.scaleColor;
	  }
      
      mdvLib.style([this.divScale], {
            position: 'absolute',
            top: this.mdvMap.viewportHeight - 30 + 'px',
            left: '5px',
			color: color,
            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';
    }              
};


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{
		marker.img.style.zIndex = '3';
	}
	
	return true;
 }; 
 
function trigger_wizard() {
    var elem, map; 
    for (elem in mdvJpMaps) {
        if (mdvJpMaps[elem] !== null) {
            map = mdvJpMaps[elem];
            break;
        }
    }
    if (map) {
        map.trips.launchWizard();
    }
}
