// ================================= golbal variables ===============================================================
mdv.map = {
    config: null,
    miniConfig: null,
    mdvMap: new Array(),
    enableMiniMap: true,
    mdvMiniMap: new Array(),
    text: {},
    vars: {},
    ctxCoords: null,
    reductionList: new Array(),
    onclick: true,
    service: new Array()
};

// service colors
mdv.map.service['001'] = '#E2001A';
mdv.map.service['002'] = '#006AB4';
mdv.map.service['003'] = '#976D21';
mdv.map.service['004'] = '#FFCC00';
mdv.map.service['005'] = '#0EBAEA';
mdv.map.service['006'] = '#8ABA16';
mdv.map.service['008'] = '#EF7F01';
mdv.map.service['010'] = '#00935C';
mdv.map.service['011'] = '#00935C';
mdv.map.service['012'] = '#A763A0';
mdv.map.service['014'] = '#A10944';
mdv.map.service['015'] = '#F19C99';
mdv.map.service['016'] = '#2C1E42';
mdv.map.service['017'] = '#006AB4';
mdv.map.service['019'] = '#F7BBA1';
mdv.map.service['031'] = '#009790';
mdv.map.service['032'] = '#009790';
mdv.map.service['041'] = '#A10944';
mdv.map.service['051'] = '#F19C99';
mdv.map.service['052'] = '#F19C99';
mdv.map.service['903'] = '#009790';
mdv.map.service['931'] = '#A10944';


// ================================= map configuration =====================================================================

mdv.map.initConfig = function() {
    var overlay, overlayLayer, prop, settings = {
        'transparentImg': mdv.map.vars.imgPath + 'efa_map/transparent.gif',
        'serverURL': mdv.map.vars.tiles,
        'efaURL': mdv.map.vars.efaURL,
        'tripURL': mdv.map.vars.tripURL,
        'defaultScale': mdv.map.vars.defaultScale,
        'network': mdv.map.vars.net,
        'xCenterReal': mdv.map.vars.xCenter,
        'yCenterReal': mdv.map.vars.yCenter,
        'imagePath': mdv.map.vars.imgPath + 'efa_map/',
        'mapName': mdv.map.vars.mapName,
        'block': '100',
        'zoomOnDoubleClick': 'true',
        'useMagnifyGlass': 'true',
        'hotspotOnMouseWheel': 'true',
        'useBubbleForEFAInfo': 'true',
        'useBubbleOverflowForEFAInfo': 'true',
        'useBubblePinForEFAInfo': 'false',
        'useJsonForPath': 'true',
        'info.stopLabels': 'true',
        'info.stopLabels.minLevel': 7,
        'info.stop.only': 'true',
        'info.stop.size.width': '235',
        'info.stop.size.height': '180',
        'info.poi.size.width': '235',
        'info.poi.size.height': '180',
        'poiArea': 'true',
        'poiPoint': 'true',
        // mot colours 	
        'trips.useJsonEx': 'true',
        'trips.polyline.opacity': '1',
        'trips.polyline.weight': '4',
        'trips.marker.size.height': '100',
        'trips.marker.size.width': '235',
        'trips.polyline.size.height': '100',
        'trips.polyline.size.width': '235',
        'motColour_0': '#0000FF',
        'motColour_1': '#27dee7',	// u-bahn
        'motColour_2': '#009261',	// s-bahn
        'motColour_3': '#85188f',	// bus
        'motColour_4': '#FF0000',   // tram 
        'motColour_5': '#85188f',	// lowfloor bus
        'motColour_6': '#605d5c',	// train
        'motColour_7': '#0000FF',
        'motColour_8': '#6c513d',	// taxi
        'motColour_9': '#85188f',
        'motColour_10': '#000000',	// ship
        'motColour_11': '#0000FF',
        'motColour_12': '#85188f',	// sev
        'motColour_15': '#009261',	// s-bahn
        'motColour_16': '#6c513d',	// taxi
        'motColour_20': '#6c513d',	// taxi
        'motColour_98': '#ea6f14',  // walk
        'motColour_99': '#ea6f14',	// walk
        'motColour_100': '#ea6f14',	// walk
        'motColour_101': '#1db89d',	// bike
        'motColour_102': '#1db89d',	// bike
        'motColour_103': '#6c513d',	// car
        'motColour_104': '#6c513d',	// car
        'motColour_105': '#6c513d',	// taxi
        'motColour_106': '#6c513d',	// car
        'motColour_107': '#1db89d',	// bike
        'motColour_108': '#0000FF'
    };
    
    // coordinate reduction
	reductionList = [
		{ maxScale:   2500, epsilon:   3 },
		{ maxScale:   5200, epsilon:   5 },
		{ maxScale:  11000, epsilon:   10 },          
		{ maxScale:  23000, epsilon:  30 },
		{ maxScale:  50000, epsilon:  40 },
		{ maxScale: 100000, epsilon:  50 },
		{ maxScale: 210000, epsilon: 50 }
	]; 

    
    mdv.map.config = mdvMapConfig;
    if (mdv.map.enableMiniMap) {
        mdv.map.miniConfig = mdvMiniMapConfig;
    }
    
    for (prop in settings) {
        mdv.map.config.add(prop, settings[prop]);
           if (mdv.map.enableMiniMap) {
            mdv.map.miniConfig.add(prop, settings[prop]);
           }
    }
}


// ================================= map common functionality ======================================

mdv.map.onLoadHandler = function(id, sessionID, requestID, routeIdx, center) {
    if (!mdvLib.$(id)) {
        mdv.map.onUnloadMapHandler(id);
        return;
    }
    mdv.map.mdvMap[id] = new MDVMap(mdvLib.$(id));
    if (mdvLib.$('mini_' + id)) {
        mdv.map.mdvMiniMap[id] = new MDVMap(mdvLib.$('mini_' + id));
    }
    else {
        mdv.map.enableMiniMap = false;
    }
    if (!mdv.map.mdvMap[id] || (!mdv.map.mdvMiniMap[id] && mdv.map.enableMiniMap)) {
        return;
    }
    
    mdv.map.initConfig();
    
    mdv.map.mdvMap[id].id = id;
    if (mdv.map.enableMiniMap) {
        mdv.map.mdvMiniMap[id].id = id;
    }
    
     // adjust size
     if(jQuery('#itdLPxx_view') && jQuery('#itdLPxx_view').attr('value') === 'printMap' && jQuery('#itdLPxx_tripSelector').length > 0 && jQuery('#itdLPxx_tripSelector').attr('value') != '') {
        jQuery('#karte_druck').css('height', '675px');
        jQuery('#karte_druck #karte_rechts_map').css('width', '665px');
        jQuery('#karte_druck #karte_rechts_map').css('height', '665px');
     }
         
    if (mdv.map.enableMiniMap) {
        // point selection
        new MDVMapSelector(mdv.map.mdvMap[id]);
        // mouse navigation
        new MDVMapNavigator(mdv.map.mdvMap[id]);
        new MDVMapNavigator(mdv.map.mdvMiniMap[id]);
    
        // navigation elements
        var controlText = new Array();
        controlText['goNorth'] = mdv.map.text.goNorth;
        controlText['goWest'] = mdv.map.text.goWest;
        controlText['goEast'] = mdv.map.text.goEast;
        controlText['goSouth'] = mdv.map.text.goSouth;
        controlText['lastResult'] = mdv.map.text.lastResult;
        controlText['zoomIn'] = mdv.map.text.zoomIn;
        controlText['zoomOut'] = mdv.map.text.zoomOut;
        
        new MDVMapControl(mdv.map.mdvMap[id], controlText);

        mdv.map.mdvMap[id].events.registerEvent(MDVEvent_OBJECT_CLICKED, this, mdv.map.onObjectClicked);
        mdv.map.mdvMap[id].events.registerEvent(MDVEvent_TOOLTIP, this, mdv.map.onToolTip);
    }

    
    new MDVMapEFAInfoEx(mdv.map.mdvMap[id], {getMOTImage: mdv.map.getMOTImage, imagePath: mdv.map.vars.imgPath + 'efa_map/', alignment: new MDVPoint(0.5, 0.5)} );
    mdv.map.mdvMap[id].trips = new MDVMapEFATrips(mdv.map.mdvMap[id], { reductionList: mdv.map.reductionList });
    
    mdv.map.mdvMap[id].execute(mdv.map.config);
    if (mdv.map.enableMiniMap) {
        mdv.map.mdvMiniMap[id].execute(mdv.map.miniConfig);
        this.sync = new MDVMapSyncBound(mdv.map.mdvMap[id], mdv.map.mdvMiniMap[id]);
        mdv.map.mdvMap[id].registerGadget(this.sync);
        mdv.efa.attachEventListener(document, 'mouseup', mdv.map.mdvMap[id].release.bind(mdv.map.mdvMap[id]), false);
        mdv.efa.attachEventListener(document, 'mouseup', mdv.map.mdvMiniMap[id].release.bind(mdv.map.mdvMiniMap[id]), false);
    }
    // display service 
    if (jQuery('#itdLPxx_service').length > 0 && jQuery('#itdLPxx_service').attr('value') != '') { 
        this.mdvMapper = new mdv.map.MDVMapObjectMapper(id);		
        this.mdvMapper.mapIt(jQuery('#itdLPxx_service').attr('value'), true);
    }
    // initialise map
    if (sessionID && requestID && routeIdx) {
        mdv.map.displayJourney(id, sessionID, requestID, routeIdx, center);
        if(center) {
            mdv.map.initialiseMap(id);
        }
    }
    else {
        mdv.map.initialiseMap(id);
    }  
}

mdv.map.onUnloadMapHandler = function(id) {
	if (mdv.map.mdvMap[id]) {
		mdv.map.mdvMap[id].destroy();
		mdv.map.mdvMiniMap[id].destroy();
		mdv.map.mdvMap[id] = null;
        mdv.map.mdvMiniMap[id] = null;
    }
}


// Initialise map
mdv.map.initialiseMap = function (id) {
    var x = jQuery('#itdLPxx_mapCenterX').attr('value');
    var y = jQuery('#itdLPxx_mapCenterY').attr('value');
    var zl = jQuery('#itdLPxx_mapZoomLevel').attr('value');
    // center for print map
    if(jQuery('#itdLPxx_view').length > 0 && jQuery('#itdLPxx_view').attr('value') === 'printMap') {
        x = jQuery('#itdLPxx_print_mapX').attr('value');
        y = jQuery('#itdLPxx_print_mapY').attr('value');
        zl = jQuery('#itdLPxx_print_mapZL').attr('value');
    }
    // set center and zoom level
    mdv.map.setMapCenter (id, parseInt(x,10), parseInt(y,10), zl); 
    // set marker
    mdv.map.setMapMarker(mdv.map.vars.usage, id);
    mdv.map.setMapMarker('destination', id);
    // update
    mdv.map.mdvMap[id].update();
}


// Store map center 
mdv.map.storeMapCenter = function (id) {
    var mc = mdv.map.mdvMap[id].getCentre();
    mdvLib.$('itdLPxx_mapCenterX').value = parseInt(mc.x, 10);
    mdvLib.$('itdLPxx_mapCenterY').value = parseInt(mc.y, 10);
    mdvLib.$('itdLPxx_mapZoomLevel').value = mdv.map.mdvMap[id].config.getZoomLevelIndex();
} 


// Set map center and zoom level
mdv.map.setMapCenter = function (id, x, y, zl) {
    if (id && x && y && zl) {
        var nc = new MDVCoordinates(mdv.map.vars.mapName, parseInt(x, 10), parseInt(y, 10));
        mdv.map.mdvMap[id].setCentre(nc);
        mdv.map.mdvMap[id].setZoomLevel(zl);
        mdv.map.mdvMap[id].update();
    }
} 


// Set map marker
mdv.map.setMapMarker = function (usage, id) {
    if (jQuery('#itdLPxx_mapMarker_' + usage).length > 0 && jQuery('#itdLPxx_mapMarker_' + usage).attr('value') != '' && jQuery('#itdLPxx_mapMarker_' + usage).attr('value').indexOf(':') > -1) {
        var coord = jQuery('#itdLPxx_mapMarker_' + usage).attr('value').split(':');
        var mc = new MDVCoordinates(mdv.map.vars.mapName, parseInt(coord[0],10), parseInt(coord[1],10));
        mdv.map.marker = mdv.map.mdvMap[id].createMarker(mc, new MDVPoint(0.5, 0.75), mdv.map.getImage(usage));
        mdv.map.marker.img.style.zIndex = '99';//'490'; 
		mdv.map.mdvMap[id].addMarker(mdv.map.marker);
    }
}
      

// Get marker image.
mdv.map.getImage = function (usage) {
	var img = mdv.map.vars.imgPath + 'efa_ico/karte_start.png';
    
    if (usage === 'destination') {
        img = mdv.map.vars.imgPath + 'efa_ico/karte_ziel.png';
    }

	var i = new Image();
    i.src = img;

	return img;
}


// Determine POI icons by draw class. 
mdv.map.getMOTImage = function (mot, type, pin) {
    var img = '';
    // poi
    if((type =='POI_POINT' || type == 'POI_AREA') && pin.attrs[1].value){
        // ticket counter
        if (pin.attrs[1].value === 'TicketCounter'){
            img = mdv.map.vars.imgPath + 'efa_ico/karte_vvk.png';
        }
        // poi standard icon
        else {
            img = mdv.map.vars.imgPath + 'efa_map/poi.gif';	
        }
    }
    // stop
    else {
		img = mdv.map.vars.imgPath + 'efa_map/mot' + mot + '.gif';		
    }
    return img;
}


// ================================= map navigation ================================================

// Return to inital map view
mdv.map.resetView = function (id) {
    // initial map center and zoomlevel
    mdv.map.setMapCenter (id, mdv.map.vars.xCenter, mdv.map.vars.yCenter, mdv.map.vars.defaultScale);
    // close netplan legend and delete services
    if(jQuery('#mapLVP').is(':visible')) {
        mdv.map.toggleLVPFunc ('', id);
    }
    // close legend
    if (jQuery('#mapLegend').is(':visible')) {
        mdv.map.toggleLegend('');
    }
}

// Toggle map legend.
mdv.map.toggleLegend = function (id) {
    jQuery("#legendTab" + id).toggleClass('active');
    if (jQuery("#mapLegend" + id).is(":hidden")) {
        if (jQuery("#mapLVP" + id).is(":not(:hidden)")) {
            jQuery("#lvpTab" + id).toggleClass('active');
            jQuery("#mapLVP" + id).slideUp("slow");
        }
        jQuery("#mapLegend" + id).slideDown("slow");
    } 
    else {
        jQuery("#mapLegend" + id).slideUp("slow");
    }
}

// Toggle map LVP functionality.
mdv.map.toggleLVPFunc = function (id, mapID) {
    this.id = id;
    jQuery("#lvpTab" + id).toggleClass('active');
    if ($("#mapLVP" + id).is(":hidden")) {
        var URL = mdv.map.vars.lvpURL + '&mergeProj=1&itdLPxx_mapID=' + mapID + '&language=' + mdv.efa.language + '&hideBannerInfo=1&hideGeneralInfo=1&lineListBranchCode=09&lineListBranchCode=21&lineListBranchCode=22&lineListBranchCode=29&lineListSubnetwork=kvv&mergeDir=1&reqType=8&itdLPxx_mapId=' + id;
        if (jQuery("#mapLegend" + id).is(":not(:hidden)")) {
            jQuery("#legendTab" + id).toggleClass('active');
            jQuery("#mapLegend" + id).slideUp("slow");
        }
		jQuery.ajax({ url: URL, success: lineFinder_onAjaxComplete.bind(this)});
    } 
    else {
        jQuery("#mapLVP" + id).slideUp("slow");
        if(mdv.map.mdvMapper && mdv.map.mdvMapper.layer) {
            mdv.map.mdvMapper.layer.removeAllPolylines();
        }
    }
}

// Get lines for map LVP functionalit.
function lineFinder_onAjaxComplete (response) { 
    jQuery('#linefinderContainer_' + this.id).html(response);
    jQuery("#mapLVP" + this.id).slideDown("slow");
    jQuery('.active_service').click();
}

// Print map.
mdv.map.printMap = function (id) {
    var mc = mdv.map.mdvMap[id].getCentre();
    if (id != 'karte_rechts_map') {
        var tripIdx = id.substring(15);
        jQuery('#itdLPxx_tripSelector').attr('value', tripIdx);
     }
     if (jQuery('#itdLPxx_view').attr('value') === 'printMapshowStop') {
        jQuery('#itdLPxx_view').attr('value', 'printMap');
     }
    jQuery('#itdLPxx_print_mapX').attr('value', parseInt(mc.x,10));
    jQuery('#itdLPxx_print_mapY').attr('value',parseInt(mc.y,10));
    jQuery('#itdLPxx_print_mapZL').attr('value',mdv.map.mdvMap[id].config.getZoomLevelIndex());
    document.forms['EFAPrintIMap'].submit();
}

// ================================= display service ===============================================

// Toggle service on map.
mdv.map.toggleLine = function (checkbox, mapID) {
    if (!this.mdvMapper || this.mdvMapper == null) {
		this.mdvMapper = new mdv.map.MDVMapObjectMapper(mapID);	
	}
    jQuery('#itdLPxx_service').attr('value', checkbox.value);
    this.mdvMapper.mapIt(checkbox.value, checkbox.checked);	
}

// Mapper.
mdv.map.MDVMapObjectMapper = function (mapID) {
    this.mdvMap = mdv.map.mdvMap[mapID]
	this.routes  = []; 
    this.layer = this.mdvMap.createLayer('services');
    this.mdvMap.addLayer(this.layer);
}

// Display or remove service.
mdv.map.MDVMapObjectMapper.prototype.mapIt = function (line, state) {
    // display service
    if(state) {
        this.fetch (line);
    }
}

// Request service.
mdv.map.MDVMapObjectMapper.prototype.fetch = function (line) {
    var URL = mdv.map.vars.geoURL + '&itdLPxx_line=' + line + '&hideBannerInfo=1&filterEpsilon=5.0&returnSinglePath=1&outputFormat=JSON&line=' + line + '&language=' + mdv.efa.language;
    jQuery.ajax({ url: URL, success: toggleLine_onAjaxComplete.bind(this)});
}


// Display/remove service on map.
function toggleLine_onAjaxComplete (response) {	
    var efa = null;
    
	eval('efa = ' + response + ';');
    
    // remove old polylines
    mdv.map.mdvMapper.layer.removeAllPolylines();
	
	if (!efa || !efa.geoObjects || 
        !efa.geoObjects.items ||
        !efa.geoObjects.items[0] || 
		!efa.geoObjects.items[0].item.paths || 		
        !efa.geoObjects.items[0].item.paths[0] ||
        !efa.geoObjects.items[0].item.paths[0].path ||
		!efa.geoObjects.items[0].item.mode.diva) {
			return;
    }
    
    var j = 0;
    var i=0;
    var colour = '#6E6F71';
    var p = efa.parameters[0] || efa.parameters;
	var line ='';
    var coordList = { x: [], y: [] };
        
    do {
		i++;
		if (p && p.name == 'line') {
			line = p.value;
		}
	} while (p = efa.parameters[i]);
    
    for (j=0; j < efa.geoObjects.items.length; j++) {
        if(j > 0 && (!efa.geoObjects.items[j].item.paths || 		
            !efa.geoObjects.items[j].item.paths[0] ||
            !efa.geoObjects.items[j].item.paths[0].path ||
            !efa.geoObjects.items[j].item.mode.diva)){
            return;
        }
        var service = efa.geoObjects.items[j].item.mode.diva.line;
        var pointLength = Math.round(efa.geoObjects.items[j].item.points.length / 2);
        var path = efa.geoObjects.items[j].item.paths[0];
    
        if (mdv.map.service[service]) {
            colour = mdv.map.service[service];
        }

        var item = {id: line, line: efa.geoObjects.items[j].item.mode.diva.toString(), polylines: []};
    
        // add polyline
        i = 0;
        do {
            i++;
            path = path.path;
            var p = this.mdvMap.createPolyline(path);
            
            p.add('colour', colour);
            p.add('opacity', '1.0');
            
            mdv.map.mdvMapper.layer.addPolyline(p, efa.geoObjects.items[j].item.paths[i]==null);
            
            if (item) {
                item.polylines.push(p);
            }
            
        } while (path = efa.geoObjects.items[j].item.paths[i]);
        this.beautify(efa.geoObjects.items[j].item);
        mdv.map.mdvMapper.routes.push(item);
     }
    this.mdvMap.update();
}

mdv.map.MDVMapObjectMapper.prototype.beautify = function (item) {
	var coords = this.mdvMap.getPolylineCoords();
	var x = coords[0];
	var y = coords[1];
	
	x.sort(MDVMap_NumSort);
	y.sort(MDVMap_NumSort);
	
	var width  = x[x.length-1] - x[0];
	var height = y[y.length-1] - y[0];
	var newX   = parseInt(x[0]) + Math.floor(0.5 + width/2);
	var newY   = parseInt(y[0]) + Math.floor(0.5 + height/2);     	
	
	var centre = new MDVCoordinates(this.mdvMap.config.get('mapName'),
		newX, newY);
		
	var zoom = 0;
	var extd = this.mdvMap.getViewportExtends();
	
	var zls = this.mdvMap.config.getZoomLevels();
	for (var i=zls.length-1; i >= 0; i--) {
		var zl = zls[i];
		var bWidth = false;
		var bHeight = false;
		
		var vpTiles = new MDVPoint(extd.width / parseInt(zl.get('tileSizeX')),
			extd.height / parseInt(zl.get('tileSizeY')));
		
		var numTiles = new MDVPoint(zl.get('numberOfTilesX'), zl.get('numberOfTilesY'));
		var realExtends = new MDVPoint(zl.get('realWidth'), zl.get('realHeight'));
		
		var tileSize = new MDVPoint(Math.floor(0.5 + realExtends.x / numTiles.x),
			Math.floor(0.5 + realExtends.y / numTiles.y));
			
		var real = new MDVPoint(tileSize.x * vpTiles.x, tileSize.y * vpTiles.y);    		
		
		if (real.x > (width*1.15) && !bWidth) {
			zoom = i;
			bWidth = true;
		}		

		if (real.y > (height*1.15) && !bHeight) {
			zoom = i;
			bHeight = true;
		}
		
		if (bWidth && bHeight)
			break;
	}

	this.mdvMap.setCentre(centre);
	this.mdvMap.setZoomLevel(zoom);
};


// ================================= map input =====================================================

// Submit stop or poi.
mdv.map.submitObject = function (id, type, omc, usage, mapID) {
    var prefix = '';
    
	if (type == 'POI_POINT' || type == 'POI_AREA') {
		type= 'poiID';
    }
	else if (type == 'STOP') { 
		prefix = 'stopID:';
    }
		
	switch (type) {
		case 'coord':
			jQuery('#nameInfo_' + usage).attr('value', id); 
			jQuery('#typeInfo_' + usage).attr('value', 'coord');
			break;
		case 'poiID':
			id = id.substr(id.indexOf('-') + 1);
            jQuery('#placeInfo_' + usage).attr('value', omc + ':-1');
            // do default
		default:	
			jQuery('#typeInfo_' + usage).attr('value', type);
			jQuery('#nameInfo_' + usage).attr('value', prefix + id);
	}
    
    if(jQuery('#selectAssignedStops').length > 0) {
        jQuery('#selectAssignedStops').attr('value', '0');
    }
     if(jQuery('#deleteAssignedStops').length > 0) {
        jQuery('#deleteAssignedStops').attr('value', '1');
    }
    
    jQuery('#name_' + usage).attr('value', name);
    jQuery('#execInst').attr('value', 'verifyOnly');
    
    mdv.map.storeMapCenter(mapID);
    
	document.getElementById('EFA-Form').submit();
}

// Remove marker on stop or poi.
mdv.map.onObjectClicked = function(id, msg, obj) {
    if (obj.right && obj.mdvMap && obj.mdvMap.id) { 	
        var img = obj.marker.img.src;
        
        // remove marker
        obj.marker.toolTip.setVisibility(false);
        mdv.map.mdvMap[obj.mdvMap.id].removeMarker(obj.marker);
        
        // empty layout parameter
        if(img.indexOf('start') > -1) {
            mdvLib.$('itdLPxx_mapMarker_' + mdv.map.vars.usage).value = '';
        }
        else if (img.indexOf('ziel') > -1) {
            mdvLib.$('itdLPxx_mapMarker_destination').value = '';
        }
    }
}


// ================================= tooltip =======================================================

// Handle the tootltip.
mdv.map.onToolTip = function(id, msg, obj) {
	if (obj.isFixed()) {
		return;
    }
	if (obj.isVisible()) {
		if (!obj.helper) {
			obj.helper = new mdv.map.toolTipHelper(obj, obj.mdvMap.id);
        }
		obj.helper.execute(obj);
	}
	else if (obj.invisibleContent && obj.helper) {
		obj.helper.destroyContent(obj);
	}
}


// Create tooltip.
mdv.map.toolTipHelper = function (toolTip, mapID) {
	this.toolTip = toolTip;
	this.processed = false;
    this.mapID = mapID;
}


// Tooltip bubble.
mdv.map.toolTipHelper.prototype.execute = function(tooltip) {
	var id = tooltip.getParent().id;
    var body = '<div id="' + id + '" class="karte_meldung">';
    var type = '';
	var omc = '';
    var size = new MDVPoint(205, 180);
    var link ='';
    var addr1 = '';
    var addr2 = '';
    var i = 0;
    
	if (tooltip.getParent().objectId) {
		id = tooltip.getParent().objectId.id;
        type = tooltip.getParent().objectId.type;
        omc = tooltip.getParent().objectId.omc;
    }
    
    // get address and link
    if (tooltip.getParent().objectId && tooltip.getParent().objectId.attrs) {
        var a;
        for(i=0; i < tooltip.getParent().objectId.attrs.length; i++) {
            a = tooltip.getParent().objectId.attrs[i];
            if(a.name === 'LINK') {
                var url = a.value;
                var url2 = a.value;
                if (url.indexOf('http://') < 0) {
                    url = 'http://' + url;
                }
                if (url2.indexOf('http://') > -1) {
                    url2 = url2.substring(7);
                }
                link = '<br/><a href="' + url + '" target=_blank">' + url2 + '</a>';
             }
             if(a.name === 'POI_ADDRESS') {
                addr1 = '<br/>' + a.value;
             }
             if(a.name === 'POI_TEXT3') {
                addr2 = '<br/>' + a.value;
             }
        }
     }

    // process tooltip
	if (!this.processed) {	
        // service on output map
        if (tooltip.parentMarker && tooltip.parentMarker.leg && tooltip.parentMarker.leg.mode) {
            var motType = tooltip.parentMarker.leg.mode.type;
            if (motType === '100' || motType === '99') {
                body = '<strong>' + mdv.map.text.walk + '</strong>';
            }
            if (motType === '101' || motType === '102' || motType === '106') {
                body = '<strong>' + mdv.map.text.taxi + '</strong>';
            }
            if (motType === '103' || motType === '104' || motType === '105' || motType === '107') {
                body = '<strong>' + mdv.map.text.bike + '</strong>';
            }
            else if (tooltip.parentMarker.leg.mode.name) {
                body = '<strong>' + tooltip.parentMarker.leg.mode.name + '</strong><br/> ' + mdv.map.text.direction +' ' + tooltip.parentMarker.leg.mode.destination;
            }
        }
		// submit stop, poi tooltip (enquiry screen)
		else if (tooltip.getParent() && tooltip.getParent().objectId) { 
            // locality
            if (tooltip.getParent() && tooltip.getParent().objectId.loc && tooltip.getParent().objectId.loc != '' && (type === 'POI_POINT' || type === 'POI_AREA')) {
                body = body.concat('<p><strong>', mdv.map.text.place, ':</strong> ',tooltip.getParent().objectId.loc ,'</p>');
            }
			// marker 
			if (type === 'coord') {
                // marker of journey on output map
                if (tooltip.innerHTML != '') {
                    body = tooltip.innerHTML;
                }
                else if (tooltip.title != undefined && tooltip.title !='') {
                    body = tooltip.title;
                }
			}
            // poi 
            else if (type === 'POI_POINT' || type === 'POI_AREA') {
                body = body.concat('<p><strong>', tooltip.getParent().objectId.desc, '</strong>', addr1, addr2, link, '</p>');
            }
			// stop 
			else {
                body = body.concat('<p><strong>', mdv.map.text.stop, ':</strong> ', tooltip.getParent().objectId.desc, '</p>');
            }
            // set origin/destination
            if (type != 'coord' && jQuery('#resultScreen').length === 0) {
                body = body.concat('<a class="button-trans" href="javascript:this.mdv.map.submitObject(\'', id, '\',\'', type, '\',\'', omc, '\', \'', mdv.map.vars.usage, '\',\'', this.mapID, '\');" title="', mdv.map.text.fromHere, '"><span>', mdv.map.text.fromHere, '</span></a>');
                body = body.concat('<div class="clear">&nbsp;</div>');
                if (mdv.map.vars.usage === 'origin') { 
                    body = body.concat('<a class="button-trans" href="javascript:this.mdv.map.submitObject(\'', id, '\',\'', type, '\',\'', omc, '\', \'destination\',\'', this.mapID, '\');" title="', mdv.map.text.toHere, '"><span>', mdv.map.text.toHere, '</span></a>');
                    body = body.concat('<div class="clear">&nbsp;</div>');
                }
            }
            else if (type != 'coord') {
                body = body.concat('<div class="clear">&nbsp;</div><p>&nbsp;</p>');
            }
            // departure monitor
            if (type === 'STOP') {
                var ttbURL = mdv.map.vars.ttbURL + '&type_ttb=stopID&name_ttb=' + id + '&lsShowTrainsExplicit=1&useAllStops=1&mode=odv&sessionID=0';
                body = body.concat('<p> <a class="button-grau" href="', ttbURL, '" title="', mdv.map.text.requestTTB, '" target="_blank"><span>', mdv.map.text.requestTTB, '</span></a></p><div class="clear">&nbsp;</div>');
            }
		}
		this.processed = true;
        body = body.concat('</div>');
        this.toolTip.setInnerHTML(body);
	}
    // size
    if (tooltip.parentMarker && tooltip.parentMarker.leg && tooltip.parentMarker.leg.mode) {
        size = new MDVPoint(205, 80);
    }
    else if (tooltip.getParent() && tooltip.getParent().objectId && type === 'coord') {
        if (tooltip.title != undefined && tooltip.title !='') {
            size = new MDVPoint(205, 100);
        }
        else {
            size = new MDVPoint(205, 60);
        }  
    }
    else if (type === 'POI_POINT' || type === 'POI_AREA') {
        size = new MDVPoint(205, 170);
    }
    else if ((type === 'STOP' && jQuery('#resultScreen').length === 0)) {
        size = new MDVPoint(205, 140);
    }
    this.toolTip.container.setSize(size);
    this.toolTip.container.updateBubble();
    this.toolTip.update();
}


// Destroys the content of the tooltip bubble.
mdv.map.toolTipHelper.prototype.destroyContent = function(tooltip) {
	var name = 'name_' + tooltip.id;
	var body = '<div id="' + name + '">';
	body += '</div>';
	this.toolTip.setInnerHTML(body);
	this.processed = false;
}


// ================================= output map ====================================================

// Displays a journey on the map.
mdv.map.displayJourney = function (id, sessionID, requestID, tripIndex, center) {
    if (tripIndex === 'null') {
        return;
    }
    var beautify = true;
    if(center) {
        beautify = false;
    }
	mdv.map.mdvMap[id].trips.loadTrip(sessionID, requestID, tripIndex, beautify);
}


// Clear journeys and lines on the map. 
mdv.map.clearMap = function (id, routeIdx) {
    mdv.map.mdvMap[id].trips.clear();
     // close netplan legend and delete services
    if(jQuery('#mapLVP' + routeIdx).is(':visible')) {
        mdv.map.toggleLVPFunc (routeIdx, id);
    }
    // remove services
    else {
        mdv.map.mdvMapper.layer.removeAllPolylines();
    }
    // close legend
    if (jQuery('#mapLegend' + routeIdx).is(':visible')) {
        mdv.map.toggleLegend(routeIdx);
    }
}


// ================================= overridden map functionality ==================================

// ====================================================================================
// Set origin/destination marker on right mouse click.
// Remove marker if right clicked. 
// Use markers as origin/destination for trip computation. 
// ====================================================================================

/**
* MDVMapSelector
* @base MDVGadgetBase
* @param {MDVMap} mdvMap
* @constructor
*/  
function MDVMapSelector(mdvMap) {
	/**
	 * This field stores a reference to the parent {@link MDVMap} instance
	 * @type MDVMap
	 * @private
	 */ 
	this.mdvMap 		= mdvMap;
	
	this.markers		= new Array();
    this.markers['origin'] = null;
    this. markers['destination'] = null;
	
	this.layer		= null;
	
	// Inherit from MDVGadgetBase
	for (var method in MDVGadgetBase.prototype) {
		if (!MDVMapSelector.prototype[method])
		     MDVMapSelector.prototype[method] = MDVGadgetBase.prototype[method];
	}
	
 	this.mdvMap.registerGadget(this);	
	this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.onObjectClicked);
	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.init);
}

MDVMapSelector.prototype.init = function (id, msg, obj) {
	if (this.layer == null) {
		this.layer = this.mdvMap.createLayer('selectors');
		this.mdvMap.addLayer(this.layer);
	}
};

MDVMapSelector.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;
	mY = mY - offsetT;

	var source = new MDVPoint(mX, mY);	    
	var target = this.mdvMap.getCoordinates(source);
    var tooltip;
    var size = new MDVPoint(120, 50);

	if (this.markers['origin'] === null && (jQuery('#itdLPxx_mapMarker_' + mdv.map.vars.usage).length > 0  && jQuery('#itdLPxx_mapMarker_' + mdv.map.vars.usage).attr('value') === '')) {
		this.markers['origin'] = this.mdvMap.createMarker(target, new MDVPoint(0.5, 0.75), mdv.map.vars.imgPath + 'efa_ico/karte_start.png');
        tooltip = this.mdvMap.createToolTip(size, '<b>' + mdv.map.text.origin + '</b>');
		this.layer.addMarker(this.markers['origin']);
		if (jQuery('#nameInfo_' + mdv.map.vars.usage).length > 0 && jQuery('#typeInfo_' + mdv.map.vars.usage).length > 0) {
			jQuery('#nameInfo_' + mdv.map.vars.usage).attr('value', target.x + ':' + target.y + ':' + target.mapName + ':' + mdv.map.text.mapLoc);
			jQuery('#itdLPxx_mapMarker_' + mdv.map.vars.usage).attr('value', target.x + ':' + target.y + ':' + target.mapName + ':' + mdv.map.text.mapLoc);
			jQuery('#typeInfo_' + mdv.map.vars.usage).attr('value', 'coord');	
            if (jQuery('#name_' + mdv.map.vars.usage).length > 0) {
                jQuery('#name_' + mdv.map.vars.usage).attr('value', mdv.map.text.mapLoc);
            }
		}
	}
	else if (this.markers['destination'] == null && (document.getElementById('itdLPxx_mapMarker_destination') && document.getElementById('itdLPxx_mapMarker_destination').value=='')) {
		this.markers['destination'] = this.mdvMap.createMarker(target, new MDVPoint(0.5, 0.75), mdv.map.vars.imgPath + 'efa_ico/karte_ziel.png');
        this.markers['destination'].img.style.zIndex = '99';//'490'; 
		this.layer.addMarker(this.markers['destination']);
		if (('#nameInfo_destination').length > 0 && jQuery('#typeInfo_destination').length > 0) {
			jQuery('#nameInfo_destination').attr('value', target.x + ':' + target.y + ':' + target.mapName + ':' + mdv.map.text.mapLoc);
			jQuery('#itdLPxx_mapMarker_destination').attr('value', target.x + ':' + target.y + ':' + target.mapName + ':' + mdv.map.text.mapLoc);
			jQuery('#typeInfo_destination').attr('value', 'coord');
            if (jQuery('#name_destination').length > 0) {
                jQuery('#name_destination').attr('value', mdv.map.text.mapLoc);
            }
		}
	}  
    return false;
}

MDVMapSelector.prototype.onObjectClicked = function (id, msg, obj) {
    var i = 0;
    var usg = mdv.map.vars.usage;
	if (obj.right) {    
		this.layer.removeMarker(obj.marker);
		if(this.markers['origin']){
			if (this.markers['origin'].id == obj.marker.id) {
				this.markers['origin'] = null;
				if (jQuery('#nameInfo_' + mdv.map.vars.usage).length > 0 && jQuery('#typeInfo_' + mdv.map.vars.usage).length > 0) {
					jQuery('#nameInfo_' + mdv.map.vars.usage).attr('value', 'invalid');
					jQuery('#typeInfo_' + mdv.map.vars.usage).attr('value', 'invalid');
                    jQuery('#itdLPxx_mapMarker_' + mdv.map.vars.usage).attr('value', '');
					if (jQuery('#name_' + mdv.map.vars.usage).length > 0) {
						jQuery('#name_' + mdv.map.vars.usage).attr('value', '');
                    }
				}
			}
		}
		if(this.markers['destination']){
			if (this.markers['destination'].id == obj.marker.id) {
				this.markers['destination'] = null;
				if (jQuery('#nameInfo_destination').length > 0 && jQuery('#typeInfo_destination').length > 0) {
					jQuery('#nameInfo_destination').attr('value', 'invalid');
					jQuery('#typeInfo_destination').attr('value', 'invalid');
                    jQuery('#itdLPxx_mapMarker_destination').attr('value', '');
					if (jQuery('#name_destination').length > 0) {
						jQuery('#name_destination').attr('value', '');
                    }
				}
			}
		}
        for (i=0; i < this.mdvMap.layers.length; i++) {
            if (this.mdvMap.layers[i].name === 'mdvMarkers') {
                this.mdvMap.layers[i].removeMarker(obj.marker);  
                if (obj.marker.imgSrc.indexOf('start') < 0) {
                    usg = 'destination';
                }
                if (jQuery('#nameInfo_' + usg).length > 0 && jQuery('#typeInfo_' + usg).length > 0) {
					jQuery('#nameInfo_' + usg).attr('value', 'invalid');
					jQuery('#typeInfo_' + usg).attr('value', 'invalid');
                    jQuery('#itdLPxx_mapMarker_' + usg).attr('value', '');
					if (jQuery('#name_' + usg).length > 0) {
						jQuery('#name_' + usg).attr('value', '');
                    }
				}
            }
        }
	}
}


MDVMapEFATrips.prototype.loadTrip = function (sessionID, requestID, tripIndex) {
  	if (!this.mdvMap.config.get('tripURL')) {
  		this.mdvMap.events.triggerEvent(MDVEvent_ERROR, 'No tripURL specified.');
  		return false;
  	}
  	
  	this.tripParams = {
  		sessionId: sessionID,
  		requestId: requestID,
  		tripIndex: tripIndex
  	};
  	
  	if (arguments.length == 4)
  		this.doBeautify = arguments[3];
  		
	this.tripParams.reductionList = '';
  	// Check whether we need to use reduction...
  	if (this.options['reductionList']) {
  		for (var r=0; r < this.options['reductionList'].length; r++) {
  			if (this.options['reductionList'][r].maxScale) {
  				this.tripParams.reductionList += this.options['reductionList'][r].epsilon + ':';
  			}
  		}
  	}
  	
  	var language = this.mdvMap.config.get('language') != null ? this.mdvMap.config.get('language') : 'en';
  	
  	var host = this.mdvMap.config.get('tripURL');
	var mapN = this.mdvMap.config.get('mapName');
  	var selector = ('tripSelector' + tripIndex);
    var jsonEx = this.mdvMap.config.get('trips.useJsonEx');
    var _params = {};

    if(jsonEx=='true'){
        _params = { 
            language: language, 
            sessionID: sessionID, 
            requestID: requestID, 
            coordListOutputFormat: 'STRING', 
            command: 'tripCoordSeq:' + this.tripParams.tripIndex, 
            output: 'JSON', 
            itdLPxx_mdvMapName: this.mdvMap.getName(), 
            filterEpsilon: this.tripParams.reductionList };
    }
    else{
       _params = { language: language, 
        sessionID: sessionID, 
        requestID: requestID, 
        coordListOutputFormat: 'STRING', 
        command: 'formatToXSLT', 
        tripSelection: 'on', 
        coordOutputFormat: mapN,
      	itdLPxx_mdvMap: 'MDVMapEFATrips', 
        itdLPxx_mdvMapName: this.mdvMap.getName(), 
        showItdPathCoordinates: '1', 
        filterEpsilon: this.tripParams.reductionList, itdLPxx_hideNotes: '1' };
        
      	_params[selector] = 'on';
  	
    }
    
	_params['action'] = 'XSLT_TRIP_REQUEST2';
    if (!mdv.map.vars.formAction) {
        _params['itdLPxx_debug'] = 'true';
    }
	
	var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVMapEFATrips_onAjaxComplete });
  	
  	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 x = Math.floor(centre.x + 0.5);
        var y = Math.floor(centre.y + 0.5);

		var _params = { language: language, outputFormat: 'JSON', itdLPxx_x: x, itdLPxx_y: y, itdLPxx_mapName: centre.mapName,
            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;

				ifilter++;
			}
			
			// only car sharing, church, ticket counter
			if(!poiPoint){
                // car sharing
				_params['type_' + ifilter] = 'POI_POINT';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = '20';

				ifilter++;
                
                // church
				_params['type_' + ifilter] = 'POI_POINT';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = '48';

				ifilter++;
                
                // ticket counter
				_params['type_' + ifilter] = 'POI_POINT';
				_params['radius_' + ifilter] = radius;
				_params['inclDrawClasses_' + ifilter] = '74';

				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++;
				}
				
			}
			
		}
        
        _params['action'] = 'XSLT_COORD_REQUEST';
        if (!mdv.map.vars.formAction) {
            _params['itdLPxx_debug'] = 'true';
        }
		
		var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVMapEFAInfoEx_onAjaxComplete });
  	}
 };
 
 // Content padding in bubble overwritten.
 MDVToolTipBubble.prototype.updateBubble = function () {
		var size = this.size;

	  	var ipath = 'images/';
	  	if (this.mdvMap.config.get('imagePath'))
	  		ipath = this.mdvMap.config.get('imagePath');

		// upper left corner

		this.complex['upperLeftCorner'].style.position = 'absolute';
		this.complex['upperLeftCorner'].style.overflow = 'hidden';
		this.complex['upperLeftCorner'].style.width = 30 + 'px';
		this.complex['upperLeftCorner'].style.height = 30 + 'px';
		this.complex['upperLeftCorner'].style.left = 0 + 'px';
		this.complex['upperLeftCorner'].style.top = (0 + this.innerOffset.y) + 'px';

		// end upper left corner

		// upper border

		this.complex['upperBorder'].style.position = 'absolute';
		this.complex['upperBorder'].style.overflow = 'hidden';
		this.complex['upperBorder'].style.width = (size.x - 2*28) + 'px';
		this.complex['upperBorder'].style.height = 30 + 'px';
		this.complex['upperBorder'].style.left = 30 + 'px';
		this.complex['upperBorder'].style.top = (0 + this.innerOffset.y) + 'px';

		// end upper border

		// upper right corner

		this.complex['upperRightCorner'].style.position = 'absolute';
		this.complex['upperRightCorner'].style.overflow = 'hidden';
		this.complex['upperRightCorner'].style.width = 30 + 'px';
		this.complex['upperRightCorner'].style.height = 30 + 'px';
		this.complex['upperRightCorner'].style.left = (size.x - 26) + 'px';
		this.complex['upperRightCorner'].style.top = (0 + this.innerOffset.y) + 'px';
		
		// end upper right corner

		// left border & body background

		this.complex['leftBorderBody'].style.position = 'absolute';
		this.complex['leftBorderBody'].style.overflow = 'hidden';
		this.complex['leftBorderBody'].style.width = size.x + 'px';
		this.complex['leftBorderBody'].style.height = (size.y - (this.pointerSize.y - 1 - this.innerOffset.y) - 2*30) + 'px';
		this.complex['leftBorderBody'].style.left = 0 + 'px';
		this.complex['leftBorderBody'].style.top = (30 + this.innerOffset.y) + 'px';
		
		// end left border & body background

		// lower right corner

		this.complex['lowerRightCorner'].style.position = 'absolute';
		this.complex['lowerRightCorner'].style.overflow = 'hidden';
		this.complex['lowerRightCorner'].style.width = 30 + 'px';
		this.complex['lowerRightCorner'].style.height = 30 + 'px';
		this.complex['lowerRightCorner'].style.left = (size.x - 28) + 'px';
		this.complex['lowerRightCorner'].style.top = (size.y - (this.pointerSize.y - 1 - this.innerOffset.y) - 30) + 'px';
		
		// end lower right corner
		
		// right border

		this.complex['rightBorder'].style.position = 'absolute';
		this.complex['rightBorder'].style.overflow = 'hidden';
		this.complex['rightBorder'].style.width = 2 + 'px';
		this.complex['rightBorder'].style.height = (size.y - (this.pointerSize.y - 1 - this.innerOffset.y) - 30) + 'px';
		this.complex['rightBorder'].style.left = (size.x) + 'px';
		this.complex['rightBorder'].style.top = (0 + this.innerOffset.y) + 'px';
		
		// end right border
		
		// end lower left corner

		this.complex['lowerLeftCorner'].style.position = 'absolute';
		this.complex['lowerLeftCorner'].style.overflow = 'hidden';
		this.complex['lowerLeftCorner'].style.width = 30 + 'px';
		this.complex['lowerLeftCorner'].style.height = 30 + 'px';
		this.complex['lowerLeftCorner'].style.left = 0 + 'px';
		this.complex['lowerLeftCorner'].style.top = (size.y - (this.pointerSize.y - 1 - this.innerOffset.y) - 30) + 'px';

		// lower left corner
		
		// lower border

		this.complex['lowerBorder'].style.position = 'absolute';
		this.complex['lowerBorder'].style.overflow = 'hidden';
		this.complex['lowerBorder'].style.width = (size.x - 2*28) + 'px';
		this.complex['lowerBorder'].style.height = 30 + 'px';
		this.complex['lowerBorder'].style.left = 30 + 'px';
		this.complex['lowerBorder'].style.top = (size.y - (this.pointerSize.y - 1 - this.innerOffset.y) - 30) + 'px';
		
		// end lower border
		
		// body
		
	
		// overwritten padding	
		this.complex['body'].style.position = 'absolute';
		this.complex['body'].style.width = (size.x-16) + 'px';
		this.complex['body'].style.height = (size.y - 31) + 'px';
		this.complex['body'].style.left = 8 + 'px';
		this.complex['body'].style.top = (8 + this.innerOffset.y) + 'px';


		// end body

		// pointer
		this.innerOffset.y >= this.pointerSize.y-1;
		var pointerTop = this.innerOffset.y >= this.pointerSize.y-1 ? 0 : this.size.y - this.pointerSize.y;

		this.complex['pointer'].style.position = 'absolute';
		this.complex['pointer'].style.overflow = 'hidden';
		this.complex['pointer'].style.width = this.pointerSize.x + 'px';
		this.complex['pointer'].style.height = this.pointerSize.y + 'px';
		this.complex['pointer'].style.left = this.pointerBorder.x + 'px';
		this.complex['pointer'].style.top = pointerTop + 'px';
		
		if (this.complex['pointer'].firstChild)
				this.complex['pointer'].firstChild.style.left = this.pointerState * -64 + 'px';

		// end pointer
		
		// pin
		var hasPin = (this.getParent() && this.getParent().toolTip && this.getParent().toolTip.hasPin());

		if (this.complex['pin'].firstChild) {
			this.complex['pin'].firstChild.src = hasPin ? (ipath + 'bubble.png') : this.mdvMap.transparent.src;
			this.complex['pin'].firstChild.onclick = hasPin ? MDVToolTipBubble_OnPinClick : null;
			this.complex['pin'].firstChild.style.top = -701 + 'px';
		}
		this.complex['pin'].style.position = 'absolute';
		this.complex['pin'].style.overflow = 'hidden';
		this.complex['pin'].style.width = '19px';
		this.complex['pin'].style.height = '18px';
		this.complex['pin'].style.left = (size.x - 29) + 'px';
		this.complex['pin'].style.top = (10 + this.innerOffset.y) + 'px';
		// end pin
    };
    

MDVMapEFATrips.prototype.getMarker = function(type, usage, coords, alignment, pos) {
  	var src = '';
	var last = false;
    var align = alignment;

    if (!this.imgs['origin'] && !this.imgs['destination']) {
        this.imgs['origin'] = new Image();
        this.imgs['origin'].src = mdv.map.vars.imgPath + 'efa_ico/karte_start.png';
        this.imgs['destination'] = new Image();
        this.imgs['destination'].src = mdv.map.vars.imgPath + 'efa_ico/karte_ziel.png';
    }
	
	if (this.response.trips.trip.legs.leg) {
		last = true;
    }
	else if (this.response.trips.trip.legs.length-1 == pos) {
		last = true;
    }

        
     if (usage == 'arrival' && last) {
		src = this.imgs['destination'];
        align = new MDVPoint (0.5, 0.7);
     }
     else if (usage == 'departure' && pos == 0) { 	
		src = this.imgs['origin'];
        align = new MDVPoint (0.5, 0.7);
     }
  	
	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, align, src.src);
			
  	return m;
};
  


