// ================================= golbal variables ===============================================================
mdv.map = {
    config: null,
    mdvMap: null,
    mdvLiveMap: null,
    initLiveMap: false,
    currentSession: {
        'mapType': 'street'
    },
    dynText: {},
    dynVal: {},
    ctxCoords: null,
    reductionList: new Array(),
    trips: null,
    mapInput: true
};


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

// Scale bar
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: '10px',
			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';
    }              
}

// Display trips
MDVMapEFATrips.prototype.loadTrip = function (zope_command, epsilon) {
  	if (!this.mdvMap.config.get('tripURL')) {
  		this.mdvMap.events.triggerEvent(MDVEvent_ERROR, 'No tripURL specified.');
  		return false;
  	}
  	
  	if (arguments.length == 3) {
  		this.doBeautify = arguments[2];
    }
  	
  	var host = this.mdvMap.config.get('tripURL');
  	var _params = {
        zope_command: zope_command,
        zope_epsilon: epsilon || '',
        itdLPxx_mdvMapName: mdv.map.mdvMap.getName(),
        coordListOutputFormat: 'STRING'
    };
  		
	// Get trip...
	var _ajax = mdvLib.ajax({ host: host, parameters: _params, onComplete: MDVMapEFATrips_onAjaxComplete });
  	
  	return true;  		
};
  
  
// ================================= map handler =====================================================================

mdv.map.initConfig = function() {
    var overlay, overlayLayer, prop, settings = {
        'transparentImg': '/begWR/img/mdvMap/transparent.gif',
        'efaURL': '/coordinfo',
        'tripURL': '/generate',
        'backgroundColour': '#F1EEE8',
        'defaultScale': '1',
        'network': 'bay',
        'xCenterReal': '4416512',
        'yCenterReal': '718219',
        'imagePath': '/begWR/img/mdvMap/',
        'mapName': 'NAV4',
        'block': '100',
        'zoomOnDoubleClick': 'true',
        'useMagnifyGlass': 'true',
        'hotspotOnMouseWheel': 'true',
        'useBubbleForEFAInfo': 'true',
        'useBubbleOverflowForEFAInfo': 'true',
        'useBubblePinForEFAInfo': 'true',
        //'useTooltipLayer': 'true', 
        'useJsonForPath': 'true',
        //'trips.useJsonEx', 'true',
        'useTooltipLayer': 'true',
        'info.stopLabels': 'true',
        // mot colours 	
        'trips.polyline.opacity': '1',
        'trips.polyline.weight': '4',
        'trips.marker.size.height': '80',
        'trips.marker.size.width': '250',
        'trips.polyline.size.height': '80',
        'trips.polyline.size.width': '250',
        'motColour_0': '#0000FF',
        'motColour_1': '#27dee7',	// u-bahn
        'motColour_2': '#00FF00',	// s-bahn
        'motColour_3': '#0000FF',	// bus
        'motColour_4': '#FF0000',   // tram 
        'motColour_5': '#0000FF',	// lowfloor bus
        'motColour_6': '#000000',	// train
        'motColour_7': '#0000FF',
        'motColour_8': '#6c513d',	// taxi
        'motColour_9': '#0000FF',
        'motColour_10': '#000000',	// ship
        'motColour_11': '#0000FF',
        'motColour_12': '#85188f',	// sev
        'motColour_15': '#00FF00',	// 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 = (mdv.map.currentSession.mapType === 'ortho' || mdv.map.currentSession.mapType === 'hybrid') ? mdvMapConfigOrtho : mdvMapConfig;
    mdv.map.miniConfig = (mdv.map.currentSession.mapType === 'ortho' || mdv.map.currentSession.mapType === 'hybrid') ? mdvMiniMapConfigOrtho : mdvMiniMapConfig;
    if (mdv.map.config instanceof MDVMapConfig === false) {
        mdv.map.mdvMap.events.triggerEvent(MDVEvent_ERROR, 'MDVEvent_ERROR: Invalid map settings file.');
        return;
    }
    if (mdv.map.miniConfig instanceof MDVMapConfig === false) {
        mdv.map.mdvMiniMap.events.triggerEvent(MDVEvent_ERROR, 'MDVEvent_ERROR: Invalid mini map settings file.');
        return;
    }
    for (prop in settings) {
        mdv.map.config.add(prop, settings[prop]);
        mdv.map.miniConfig.add(prop, settings[prop]);
    }
    overlay = mdv.map.config.get('overlay');
    if (overlay && overlay.tileUrl && mdv.map.currentSession.mapType === 'hybrid') {
        overlayLayer = mdv.map.mdvMap.createOverlay(overlay.name ? overlay.name : 'captions', overlay.tileUrl);
        overlayLayerMini = mdv.map.mdvMiniMap.createOverlay(overlay.name ? overlay.name : 'captions', overlay.tileUrl);
        if (overlay.fileType) {
            overlayLayer.setFileType(overlay.fileType);
            overlayLayerMini.setFileType(overlay.fileType);
        }
        mdv.map.mdvMap.addOverlay(overlayLayer);
        mdv.map.mdvMiniMap.addOverlay(overlayLayerMini);
    }
}

mdv.map.onLoadHandler = function() {
    
    var liveMapCbx = mdvLib.$('liveMapToggle');
    
    mdv.map.mdvMap = new MDVMap(mdvLib.$('mdvMap'));
    mdv.map.mdvMiniMap = new MDVMap(mdvLib.$('mdvMiniMap'));
    if (!mdv.map.mdvMap || !mdv.map.mdvMiniMap) {
        return;
    }

    // delete journeys on map
    if (!mdvLib.$('itdRouteList')) {
        mdv.map.deleteCookie('c_routeIdx');
    }
    //delete departures on map
    if (!mdvLib.$('itdDepartureList')) {
        mdv.map.deleteCookie('c_dmLine0');
        mdv.map.deleteCookie('c_dmLine1');
        mdv.map.deleteCookie('c_dmLine2');
        mdv.map.deleteCookie('c_dmPos0');
        mdv.map.deleteCookie('c_dmPos1');
        mdv.map.deleteCookie('c_dmPos2');
        mdv.map.deleteCookie('c_dmColors');
    }
    // set map type
    var c_mapType = mdv.map.readCookie('c_mapType');
    if (c_mapType) {
        mdv.map.currentSession.mapType = c_mapType;
    }
    mdv.map.initConfig();
    
    // context menu for enquiry screen
    
    if (mdv.map.dynVal.usage != '') {
        mdv.map.mdvMap.ctxMenuArr = new Array();
        mdv.map.mdvMap.ctxMenuArr[0] = new MDVMapMenuItem(mdv.map.dynText.coordFromHere, mdv.map.setCoordinatesOrigin);
        if (mdv.map.dynVal.usage === 'origin') {
            mdv.map.mdvMap.ctxMenuArr[1] = new MDVMapMenuItem(mdv.map.dynText.coordToHere, mdv.map.setCoordinatesDestination);
            mdv.map.mdvMap.ctxMenuArr[2] = new MDVMapMenuItem(mdv.map.dynText.coordViaHere, mdv.map.setCoordinatesVia);
        }
        mdv.map.mdvMap.ctxMenu = new MDVMapMenu(mdv.map.mdvMap.ctxMenuArr);
        new MDVMapContextMenu(mdv.map.mdvMap, mdv.map.mdvMap.ctxMenu);
        mdv.map.mdvMap.events.registerEvent(MDVEvent_CONTEXT_MENU, null, mdv.map.ContextMenuHandler);
    }
    
    mdv.map.mdvMap.events.registerEvent(MDVEvent_LAYER_UPDATED, this, mdv.map.highlightPoints);
    mdv.map.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, null, mdv.map.mapInitialised);
    mdv.map.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, mdv.map.onToolTip);
    mdv.map.mdvMap.events.registerEvent(MDVEvent_MOUSE_UP, this, mdv.sug.closeSuggest);
    mdv.map.mdvMap.events.registerEvent(MDVEvent_ZOOM_CHANGED, this, function(idx, msg, zoomIdx) { 
        var zi = parseInt(zoomIdx, 10);
        var lml = mdvLib.$('mdvMap_ownContainer_liveMapLayer');
        
        if (mdvLib.typeOf(lml) === 'null') {
            return;
        }
         
        if (zi < 10) {
            liveMapCbx.disabled = true;
            if (mdv.map.mdvMap.liveMapLayer !== undefined) {
                mdv.map.mdvMap.liveMapLayer.removeAll()
            }
            lml.style.display = 'none';    
        } else {
            liveMapCbx.disabled = false;
            lml.style.display = 'block';
        }   
     });
    
    var dyntext = [];
		dyntext['goNorth'] = mdv.map.dynText.navGoNorth;
		dyntext['goWest'] = mdv.map.dynText.navGoWest;
		dyntext['goEast'] = mdv.map.dynText.navGoEast;
		dyntext['goSouth'] = mdv.map.dynText.navGoSouth;
        dyntext['zoomIn'] = mdv.map.dynText.navZoomIn;
		dyntext['zoomOut'] = mdv.map.dynText.navZoomOut;
    
    // copyright
    if (mdv.map.currentSession.mapType === 'ortho') {
        mdvLib.$('copyrightNavteq').style.display = 'none';
        mdvLib.$('copyrightHybrid').style.display = 'none';
        mdvLib.$('copyrightOrtho').style.display = '';
        document.getElementById('streetMapButton').className='';
        document.getElementById('satelliteMapButton').className='activeMap';
        document.getElementById('hybridMapButton').className='';
    }
    else if (mdv.map.currentSession.mapType === 'hybrid') {
        mdvLib.$('copyrightNavteq').style.display = '';
        mdvLib.$('copyrightHybrid').style.display = '';
        mdvLib.$('copyrightOrtho').style.display = '';
        document.getElementById('streetMapButton').className='';
        document.getElementById('satelliteMapButton').className='';
        document.getElementById('hybridMapButton').className='activeMap';
    }
    else {
        mdvLib.$('copyrightNavteq').style.display = '';
        mdvLib.$('copyrightHybrid').style.display = 'none';
        mdvLib.$('copyrightOrtho').style.display = 'none';
        document.getElementById('streetMapButton').className = 'activeMap';
        document.getElementById('satelliteMapButton').className='';
        document.getElementById('hybridMapButton').className='';
    }

   
    // rectangle zoom
    mdv.map.mdvMap.rectZoom = new MDVRectZoom(mdv.map.mdvMap, {
        opacity: 0.3,
        border: '3px solid #23409C',
        useButton: true,
        buttonImg: 'pan/panBtn.png',
        buttonImgOver: 'pan/panBtn_rollover.png',
        buttonImgActive: 'pan/panBtn_rollover.png',
        buttonPosLeft: '13px',
        buttonPosTop: '265px',
        title: mdv.map.dynText.rectZoomClick,
        titleActive: mdv.map.dynText.rectZoomDraw 
    });
    
    // mouse navigation
    new MDVMapNavigator(mdv.map.mdvMap);
    new MDVMapNavigator(mdv.map.mdvMiniMap);
    
    // graphical navigation elements
    new MDVMapControl(mdv.map.mdvMap, {
        text: dyntext,
        posTop: '28px',
        posLeft: '10px'
    });
    mdv.map.mdvMap.scale = new MDVMapScale(mdv.map.mdvMap, {});
    
    new MDVMapEFAInfoEx(mdv.map.mdvMap, {imagePath: '/begWR/img/mdvMap/', alignment: new MDVPoint(0.5, 0.5)} );
    mdv.map.trips = new MDVMapEFATrips(mdv.map.mdvMap, { reductionList: mdv.map.reductionList });

    
    mdv.map.mdvMap.execute(mdv.map.config);
    mdv.map.mdvMiniMap.execute(mdv.map.miniConfig);
    
    // synchronize map and minimap
    this.sync = new MDVMapSyncBound(mdv.map.mdvMap, mdv.map.mdvMiniMap);
    mdv.map.mdvMap.registerGadget(this.sync);
    
    // layer   
    mdv.map.mdvMap.begMarkerLayer = mdv.map.mdvMap.createLayer('begMarkerLayer', {'useOwnContainer': true});
    mdv.map.mdvMap.addLayer(mdv.map.mdvMap.begMarkerLayer);
    
    // slider (zoom)
    var mdvMapSlider = new MDVMapSlider(mdv.map.mdvMap, {
		sliderOffsetTop: 80,
		sliderOffsetLeft: 20,
        tickOffsetLeft: 9,
        text: dyntext
	});	
    
    mdv.common.attachEventListener(document, 'mouseup', mdv.map.mdvMap.release.bind(mdv.map.mdvMap), false);
	mdv.common.attachEventListener(document, 'mouseup', mdvMapSlider.onKnobUp.bind(mdvMapSlider), false);
 
    mdv.map.doIdentified();
    mdv.beg.setDimensions();
    mdv.map.restoreMapView();
    
    // fix postion of "more" submenu
    if (document.getElementById('moreMapSubmenu') && mdv.beg.dynVal.language === 'en') {
        document.getElementById('moreMapSubmenu').style.right = '194px';
    }
    
    // display ics messages (ics message screen only)
    if (jQuery('#icsMsgScreen').length > 0) {
        var ts = new Date().getTime();
        var params = '?outputFormat=JSON&amp;AIXMLReduction=removeCreationTime&amp;AIXMLReduction=removeExpirationDateTime&amp;AIXMLReduction=removeModificationTime&amp;AIXMLReduction=removePublication&amp;AIXMLReduction=removeSourceSystem' 
                        + '&amp;itdLPxx_ts=' + ts
                        + '&amp;filterInfoType=stopInfo&filterInfoType=stopBlocking';
        var ajax = mdvLib.ajax({ host: '/addinfo' + params, parameters: null, method: 'get', onComplete: addInfo_onAjaxComplete });
    }
}

mdv.map.onUnloadHandler = function(caller) {
    if (mdv.map.mdvMap) {
        mdv.map.saveMapState();
        mdv.map.destroy(caller);
    }
}

mdv.map.mapInitialised = function() {
    if (document.getElementById('centreX')) document.getElementById('centreX').value = mdvMap.getCentre().x;
    if (document.getElementById('centreY')) document.getElementById('centreY').value = mdvMap.getCentre().y;
    var zlSelect = document.getElementById('zoomLevel');
    if (zlSelect) {
        for (var i = 0; i < zlSelect.length; i++) {
            if (i == mdv.map.mdvMap.config.getZoomLevelIndex()) {
                zlSelect.selectedIndex = i;
                break;
            }
        }
    }
}

mdv.map.setMapType = function(type) {
    function _triggerChangeMap() {
        mdv.map.onUnloadHandler('setMapType');
        mdv.map.currentSession.mapType = (type === 'ortho') ? 'ortho' : ((type === 'hybrid') ? 'hybrid' : 'street');
        mdv.map.onLoadHandler();
    }
    if (mdv.map.currentSession.mapType === type) {
        return;
    }
    
    mdv.map.currentSession.mapType = type;
    mdv.map.setCookie('c_mapType', type);
    
    _triggerChangeMap();
}

mdv.map.changeMapType = function(type) {
    // reset old center and take new center if map view is changed
    if (mdvLib.$('itdLPxx_center_map')) {
        mdvLib.$('itdLPxx_center_map').value = 'false';
    }
    // set buttons 
    if (type === 'street') {
        document.getElementById('streetMapButton').className = 'activeMap';
    }
    else {
        document.getElementById('streetMapButton').className='';
    }
    if (type === 'ortho') {
        document.getElementById('satelliteMapButton').className='activeMap';
    }
    else {
        document.getElementById('satelliteMapButton').className='';
    }
    if (type === 'hybrid') {
        document.getElementById('hybridMapButton').className='activeMap';
    }
    else {
        document.getElementById('hybridMapButton').className='';
    }
    // set map type
    mdv.map.setMapType(type);
}

mdv.map.saveMapState = function(id, msg, obj) {
    var centre, zoomlevel, c, i;
    c = mdv.map.mdvMap.getCentre();
    centre = parseInt(c.x, 10) + ':' + parseInt(c.y, 10) + ':' + c.mapName;
    zoomlevel = mdv.map.mdvMap.config.getZoomLevelIndex();
    mdv.map.setCookie('c_mapCentre', escape(centre));
    mdv.map.setCookie('c_mapZoomLevel', zoomlevel);
    
    mdv.map.deleteCookie('c_dmLine0');
    mdv.map.deleteCookie('c_dmLine1');
    mdv.map.deleteCookie('c_dmLine2');
    mdv.map.deleteCookie('c_dmPos0');
    mdv.map.deleteCookie('c_dmPos1');
    mdv.map.deleteCookie('c_dmPos2');
    if (mdv.map.mdvMapper) {
        mdv.map.setCookie('c_dmColors', mdv.map.mdvMapper.colors);
        for (i=0; i<mdv.map.mdvMapper.routes.length; i++) {
            if (mdv.map.mdvMapper.routes[i]) {
                mdv.map.setCookie('c_dmLine' + i, mdv.map.mdvMapper.routes[i].ln);
                mdv.map.setCookie('c_dmPos' + i, mdv.map.mdvMapper.routes[i].id + ':' + i);
            }
        }
    }
    return true;
}

mdv.map.restoreMapView = function() {
    var c_centre, c_zoomlevel, c_tripIdx, c_dmLine0, c_dmLine1, c_dmLine3, c_dmPos0, c_dmPos1, c_dmPos3, c_liveMap, centreArr,  c_mapType, c_mapWidth, nc;
    c_centre = unescape(mdv.map.readCookie('c_mapCentre'));
    c_zoomlevel = mdv.map.readCookie('c_mapZoomLevel');
    c_mapWidth = mdv.map.readCookie('c_mapWidth');
    c_routeIdx = mdv.map.readCookie('c_routeIdx');
    c_dmLine0 = mdv.map.readCookie('c_dmLine0');
    c_dmLine1 = mdv.map.readCookie('c_dmLine1');
    c_dmLine2 = mdv.map.readCookie('c_dmLine2');
    c_dmPos0 = mdv.map.readCookie('c_dmPos0');
    c_dmPos1 = mdv.map.readCookie('c_dmPos1');
    c_dmPos2 = mdv.map.readCookie('c_dmPos2');
    c_liveMap = mdv.map.readCookie('c_liveMap');
    
    centreArr = c_centre.split(':');
    nc = new MDVCoordinates(centreArr[2], parseInt(centreArr[0], 10), parseInt(centreArr[1], 10));
    mdv.map.mdvMap.setCentre(nc);
    mdv.map.mdvMap.setZoomLevel(parseInt(c_zoomlevel, 10));
    if (c_mapWidth) {
        if (c_mapWidth === 'true') {
            mdv.map.extendMap(true);
        }
        else {
            mdv.map.extendMap(false);
        }
    }
    
    // display journeys
    if((location.href.indexOf('fahrtplanauskunft') > -1 || location.href.indexOf('tripplanner') > -1) && c_routeIdx) {
        mdv.map.displayJourney(c_routeIdx, null, null, false);
    }
    mdv.map.mdvMap.update();
    
    // display departures
    if (location.href.indexOf('abfahrtstafel') > -1) {
        if (c_dmLine0 && c_dmPos0) {
            mdv.map.mapService(c_dmLine0, c_dmPos0);
        }
        if (c_dmLine1 && c_dmPos1) {
            mdv.map.mapService(c_dmLine1, c_dmPos1);
        }
        if (c_dmLine2 && c_dmPos2) {
            mdv.map.mapService(c_dmLine2, c_dmPos2);
        }
    }
    
    // display live map
    if (c_liveMap) {
        mdv.map.toggleLiveMap (c_liveMap); 
        mdvLib.$('liveMapToggle').checked = true;
        if (parseInt(mdv.map.mdvMap.config.getZoomLevelIndex(), 10) < 10) {
            mdvLib.$('liveMapToggle').disabled = true;    
        }
    }
}

mdv.map.setCookie = function(n, w) {
    jQuery.cookie(n, w, {path: '/'});
}

mdv.map.deleteCookie = function(n) {
    jQuery.cookie(n, null);
}

mdv.map.readCookie = function(searchName) {
    return jQuery.cookie(searchName);
}

mdv.map.destroy = function(caller) {
    function _removeDivs(map, caller) {
        var i, j, elem, vp = map.viewport,
            re = /MDVMapControl|MDVMapSync|mdvMarkers|divSlider|divScale/;
            
        walkDomTree(vp, function (node) {
            for (i = node.childNodes.length-1; i >= 0; i--) {
                elem = node.childNodes[i];
                if (elem.nodeType === 1 && (re.test(elem.id) || re.test(elem.className))) {
                    node.removeChild(elem);
                }
            }
        });
        if (typeof caller !== 'string') {
            for (j = 0; j < map.mappers.length; j++) {
                vp.removeChild(map.mappers[j]);
            }
            return;
        }
        timeout = window.setTimeout(function() {
            for (j = 0; j < map.mappers.length; j++) {
                vp.removeChild(map.mappers[j]);
            }
            timeout = null;
        }, 2000);
    }
    if (mdv.map.liveMap) {
        mdv.map.liveMap.clear();
        mdv.map.liveMap = null;
        mdv.map.initLiveMap = false;
    }
    mdv.map.mdvMap.destroy();
    mdv.map.mdvMiniMap.destroy();
    _removeDivs(mdv.map.mdvMap, caller);
    _removeDivs(mdv.map.mdvMiniMap, caller);
    mdv.map.mdvMap = null;
    mdv.map.mdvMiniMap = null;
    mdv.map.mdvMapper = null;
}

var walkDomTree = function _walk(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        _walk(node, func);
        node = node.nextSibling;
    }
}


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

// Extend/withdraw map.
mdv.map.extendMap = function (state) {
    // left column
    mdv.common.toggleElem2(mdvLib.$('leftColumn'), !state);
    // buttons
    mdv.common.toggleElem2(mdvLib.$('map_extend'), !state);
    mdv.common.toggleElem2(mdvLib.$('map_withdraw'), state);
    // cookie
    mdv.map.setCookie('c_mapWidth', state);
    // reset layout dimensions
    mdv.beg.setDimensions();
    
    if (mdv.map.mdvMap.rectZoom) {
         mdv.map.mdvMap.rectZoom.oMapPos['left'] = state ? 35 : 552;
    }
}

// Toggle mini map.
mdv.map.toggleMiniMap = function (state) {
    if (mdvLib.$('mdvMiniMap')) {
        if (state) {
            // sliding does not work well for IE
            if (mdv.common.getIEVersion() > -1) {
                mdvLib.$('mdvMiniMapScroll').style.width = 150 + 'px';
                mdvLib.$('mdvMiniMapScroll').style.height = 150 + 'px';
                mdvLib.$('mdvMiniMap').style.top = 0 + 'px';
                mdvLib.$('mdvMiniMap').style.left = 0 + 'px';
                mdvLib.$('mdvMiniMap').style.display = 'block';
                mdv.common.toggleElem(mdvLib.$('mini_map_opener'));
            }
            // slide in
            else {
                jQuery("#mdvMiniMapContainer").scrollTo( '+=155', 600 );
                mdv.common.toggleElem(mdvLib.$('mini_map_opener'));
            }
        }
        // sliding does not work well for IE
        else {
            if (mdv.common.getIEVersion() > -1) {
                mdvLib.$('mdvMiniMapScroll').style.width = 150 + 'px';
                mdvLib.$('mdvMiniMapScroll').style.height = 150 + 'px';
                mdvLib.$('mdvMiniMap').style.top = 0 + 'px';
                mdvLib.$('mdvMiniMap').style.left = 0 + 'px';
                mdv.common.toggleElem(mdvLib.$('mdvMiniMap'));
                mdv.common.toggleElem(mdvLib.$('mini_map_opener'));
            }
            // slide out
            else {
                jQuery("#mdvMiniMapContainer").scrollTo( '-=155', 600 );
                timeout = window.setTimeout(function() {
                    mdv.common.toggleElem(mdvLib.$('mini_map_opener'));
                    timeout = null;
                }, 1000);
            }
        }
    }
}

// Sets the origin/destination/via markers 
mdv.map.doIdentified = function () {
    var usages = new Array;
    var i, coord, marker, img, m, imgName;
    usages[0] = mdv.map.dynVal.usage;
    if (mdv.map.dynVal.usage === 'origin') { 
        usages[1] = 'destination';
        usages [2] = 'via';
    }
    for (i=0; i < usages.length; i++) {
        if (mdvLib.$('itdLPxx_coord_' + usages[i])) {
            imgName = usages[i];
            if (imgName != 'via' && imgName != 'destination') {
                imgName = 'origin';
            }
            coord = mdvLib.$('itdLPxx_coord_' + usages[i]).value.split(':');
            if(coord[0] != '' && coord[1] != '' && coord[2] != '') {
                marker = new MDVCoordinates(coord[2], parseInt(coord[0], 10), parseInt(coord[1], 10));
                img = '/begWR/img/mdvMap/' + imgName + '.gif';
                mdv.map.setMarker(marker, img);
                // center map on marker
                if (usages.length === 1 && mdvLib.$('itdLPxx_center_map') && mdvLib.$('itdLPxx_center_map').value==='true') {
                    mdv.map.setMapCenter(coord[2], parseInt(coord[0], 10), parseInt(coord[1], 10), 20)
                }
            }
        }
    }
    mdv.map.mdvMap.update();
}

// Sets a marker.
mdv.map.setMarker = function(coord, img) {
	var marker = mdv.map.mdvMap.createMarker(coord, 0, img);
    marker.img.style.zIndex = '490'; 
	mdv.map.mdvMap.begMarkerLayer.addMarker(marker);
}

// Set map center.
mdv.map.setMapCenter = function(mapName, x, y, zl) {
    var centre = parseInt(x, 10) + ':' + parseInt(y, 10) + ':' + mapName;
    mdv.map.mdvMap.setCentre(new MDVCoordinates(mapName, parseInt(x, 10), parseInt(y, 10)));
    mdv.map.mdvMap.setZoomLevel(parseInt(zl, 10));
    mdv.map.setCookie('c_mapCentre', escape(centre));
    mdv.map.setCookie('c_mapZoomLevel', zl);
    mdv.map.mdvMap.update();
}

// resize map and map components 
mdv.map.resizeMapComponents = function () {
    mdv.map.mdvMap.resize();

    if (mdv.map.mdvMap.rectZoom) {
        //re-initialize rectZoom after resizing of viewport
        var imgTp = mdvLib.$('bilderleiste') ? mdv.beg.heightImgHeader : 0;
        var tp = mdv.beg.heightHeader + mdv.beg.heightMenu + imgTp;
        mdv.map.mdvMap.rectZoom.oMapPos = { left: 552, top: tp };
        mdv.map.mdvMap.rectZoom._setDimensions();
    }
    
    if(mdv.map.mdvMap.scale) {
        var size = mdvLib.$('mdvMap').clientHeight;
        // update scale bar after resizing of viewport
        mdv.map.mdvMap.scale.updatePosition(size);
    }
}


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

// Submit stop or poi.
mdv.map.submitObject = function (id, type, omc, usage) {
    var prefix = '';
    
	if (type == 'POI_POINT' || type == 'POI_AREA') {
		type= 'poiID';
    }
	else if (type == 'STOP') { 
		prefix = 'stopID:';
    }
		
	switch (type) {
		case 'coord':
			mdvLib.$('nameInfo_' + usage).value = id; 
			mdvLib.$('typeInfo_' + usage).value = 'coord';
			break;
		case 'poiID':
			id = id.substr(id.indexOf('-') + 1);
            mdvLib.$('placeInfo_' + usage).value = omc + ':-1';
            // do default
		default:	
			mdvLib.$('typeInfo_' + usage).value = type;
			mdvLib.$('nameInfo_' + usage).value = prefix + id;
	}
    if(mdvLib.$('mode_ttb')) {
        mdvLib.$('mode_ttb').value = 'odv';
    }
    if(mdvLib.$('mode')) {
        mdvLib.$('mode').value = '';
    }
	document.forms['efaRequest'].submit();
}


// ================================= context menu =====================================================================

// Context menu handler
mdv.map.ContextMenuHandler = function (id, status, obj) {
	if(status) {
		mdv.map.ctxCoords = obj;
	}
}

// Submit origin coordinate.
mdv.map.setCoordinatesOrigin = function () {
    mdv.map.setCoordinates(mdv.map.dynVal.usage);
}

// Submit destination coordinate. 
mdv.map.setCoordinatesDestination = function () {
    mdv.map.setCoordinates('destination');
}

// Submit via coordinate. 
mdv.map.setCoordinatesVia = function () {
    mdv.map.setCoordinates('via');
}

// Submit coordinate. 
mdv.map.setCoordinates = function(usage) { 
    mdvLib.$('nameInfo_' + usage).value = parseInt(mdv.map.ctxCoords.x) + ':' + parseInt(mdv.map.ctxCoords.y) + ':' + mdv.map.ctxCoords.mapName; 
    mdvLib.$('typeInfo_' + usage).value = 'coord';
    mdvLib.$('placeInfo_' + usage).value = '';
    
    mdv.map.mdvMap.mapper.style.cursor = 'wait';
    if(mdvLib.$('mode_ttb')) {
        mdvLib.$('mode_ttb').value = 'odv';
    }
    if(mdvLib.$('mode')) {
        mdvLib.$('mode').value = '';
    }
    if(mdvLib.$('selectAssignedStops_' + usage)) {
        mdvLib.$('selectAssignedStops_' + usage).value = 1;
    }
    if(mdvLib.$('deleteAssignedStops_' + usage)) {
        mdvLib.$('deleteAssignedStops_' + usage).value = 0;
    }
    document.forms['efaRequest'].submit();
}


// ================================= 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.helper.execute(obj);
	}
	else if (obj.invisibleContent && obj.helper) {
		obj.helper.destroyContent(obj);
	}
}


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


// Tooltip bubble.
mdv.map.toolTipHelper.prototype.execute = function(tooltip) {
	
	var par = tooltip.getParent();
	
	if (mdvLib.typeOf(par) !== 'object' || this.toolTip.getInnerHTML().indexOf('add_info') > -1) {
	    return;
	}

	var id = par.id;
    var body = '<div id="' + id + '">';
    var type = par.objectId && par.objectId.type;
	var omc = par.objectId && par.objectId.omc;
    var size = new MDVPoint(300, 90);
    var txt = this.toolTip.getInnerHTML();
    
	if (par.objectId) {
		id = par.objectId.id;
    }
    
    if (this.toolTip.parentMarker && this.toolTip.parentMarker.leg) {
         size = new MDVPoint(220, 80);
    }
    
	if (!this.processed) {	
        // correct MOT text
        if (this.toolTip.parentMarker && this.toolTip.parentMarker.leg) {
            if (txt === '100' || txt === '99') {
                body += mdv.map.dynText.mot100;
            }
            else if (this.toolTip.parentMarker.leg.mode && this.toolTip.parentMarker.leg.mode.name) {
                body += this.toolTip.parentMarker.leg.mode.name;
            }
            size = new MDVPoint(220, 80);
        }
        else {
            body += this.toolTip.getInnerHTML();
        }
		// submit stop, poi tooltip (enquiry screen)
		if (par && par.objectId && !document.getElementById('tripSelector')) { 
			// marker
			if (type=='coord') {
				size = new MDVPoint(300, 80);
			}
			// stop, poi
			else {
				body += '<br/>';
                if (mdv.map.mapInput) {
                    body += '<div class="mapInputLinks"><a href="javascript:this.mdv.map.submitObject(\'' + id + '\',\'' + type + '\',\'' + omc + '\', \'' + mdv.map.dynVal.usage + '\')">' + mdv.map.dynText.fromHere + '</a>';
                    if (mdv.map.dynVal.usage === 'origin') {
                        body += ' | ';
                        body += '<a href="javascript:mdv.map.submitObject(\'' + id + '\',\'' + type + '\',\'' + omc + '\', \'destination\')">' + mdv.map.dynText.toHere  + '</a>';
                        body += ' | ';
                        body += '<a href="javascript:mdv.map.submitObject(\'' + id + '\',\'' + type + '\',\'' + omc + '\', \'via\')">' + mdv.map.dynText.viaHere  + '</a>';
                    }
                    body += '</div>';
                }
            }
            // departure monitor for stops
            if (par.objectId.type == 'STOP') {
                size = new MDVPoint(300, 200);
                body += '<div id=\'dmLoading_' + id +'\'>';
                body += '<br/>';
                body += mdv.map.dynText.dmLoading;
                body += '</div>';
                tooltip.dm = new mdv.map.departureMonitor(id, '/dmAjax');
                tooltip.dm.getDepartures(id);
            }
		}
		this.processed = true;
        body += '</div>';
        this.toolTip.container.updateBubble();
        this.toolTip.setInnerHTML(body);
	}
	// reload departure monitor
	else { 
        if (tooltip.dm) {
            this.toolTip.dm.getDepartures(id);
            size = new MDVPoint(300, 200);
        }
        if (!mdv.map.mapInput) {
           jQuery('.mapInputLinks').css('display','none'); 
        }
        else {
            jQuery('.mapInputLinks').css('display','');
        }
	}
    this.toolTip.container.setSize(size);
    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;
}


// ================================= departure monitor (bubble) ===========================================================

// Departure monitor
mdv.map.departureMonitor = function(id, url) {
	this.id 		= id;
	this.url 		= url;
}


// Request departure monitor.
// Parmeter:	identifier - id of the tooltip content container
mdv.map.departureMonitor.prototype.getDepartures = function(identifier) {
	var _params = { useRealtime: 1, 
                    language: mdv.beg.dynVal.language, 
                    name_dm: this.id,
                    type_dm: 'stopID', 
                    mode: 'direct', 
                    limit: mdv.map.dynVal.dmBubbleDeps, 
                    hideBannerInfo: 1,
                    deleteAssignedStops_dm: 1,
                    useProxFootSearch: 0,
                    itdLPxx_mode: 'bubble',
                    itdLPxx_id: identifier,
                    ts: new Date().getTime()};
	var ajax = mdvLib.ajax({ host: this.url, parameters: _params, method: 'get', onComplete: departureMonitor_onAjaxComplete });
}


// Create departure monitor. 
function departureMonitor_onAjaxComplete(request) {
    
    if (request && request.responseText) {
		var text = request.responseText;
		var id = text.substring(text.indexOf('depTable_')+ 9,text.length);
            id = id.substring(0,id.indexOf('_'));
		var target = mdvLib.$('dmLoading_' + id);
		if (target) {
			target.innerHTML = text; 
        }
		else {
			target = mdvLib.$(id);
			if (target) {
				target.innerHTML += '<br/>' + text; 
            }
		}
	}
}


// ================================= map buttons =====================================================================

mdv.map.showMapLayerInclusion = function () {
    // toggle more menu
    mdv.common.toggleElem(mdvLib.$('moreMapSubmenu'));
    // toggle button
    if (mdvLib.$('moreMapSubmenu').style.display === 'block') {
        mdvLib.$('moreMapButton').className = 'standardButtonActive';
    }
    else {
        mdvLib.$('moreMapButton').className = 'standardButton';
    }
    
}


// ================================= live map =====================================================================

// Toggle live map. Initialize if necessary. 
mdv.map.toggleLiveMap = function (state) {
    // show live map
    if (state) {
        // initialize live map
        if (!mdv.map.initLiveMap) {
            mdv.map.liveMap = new MDVLiveMap(mdv.map.mdvMap);
            mdv.map.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, mdv.map.liveMap, mdv.map.liveMap.getAdditionalInfo);
            mdv.map.initLiveMap = true;
        }
        mdv.map.liveMap.startTimer();
        mdv.map.setCookie('c_liveMap', true);
    }
    // hide live map
    else {
        mdv.map.liveMap.clear();
        mdv.map.deleteCookie('c_liveMap');
    }   
}


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

// Displays a journey on the map.
mdv.map.displayJourney = function(routeIdx, count, epsilon, beautify) {
    if (!routeIdx) {
        return;
    }
    
    var zope_epsilon = epsilon ? epsilon : '1.0:1.5:2.5:5.0:10.0:20.0.100.0';
    var doBeautify = true; 
    
    var zope_command = 'getRoutePath:' + routeIdx + ':json';
    
    if (arguments.length == 4) {
  		doBeautify = arguments[3];
    }
  	
    if(count) {
        mdv.map.clearJourneys(count);
    }
    
    mdv.map.setCookie('c_routeIdx', routeIdx);
    
    mdv.map.trips.loadTrip(zope_command, zope_epsilon, doBeautify);
    mdv.common.toggleElem2(mdvLib.$('displayTripInactive_' + routeIdx), true);
    mdv.common.toggleElem2(mdvLib.$('displayTripActive_' + routeIdx), false);
}


// Clears all journeys on the map.
mdv.map.clearJourneys = function(count) {
    mdv.map.deleteCookie('c_routeIdx');
    // toggle buttons
    for (var i = 1; i <= count; i++) {
        mdv.common.toggleElem2(mdvLib.$('displayTripActive_' + i), true);
        mdv.common.toggleElem2(mdvLib.$('displayTripInactive_' + i), false);
    }
    // clear all journeys
	mdv.map.trips.clear();
}


// ================================= dm map =====================================================================

// Create mapper to display service. 
mdv.map.mapService = function(line, pos, coord) {
    if (this.mdvMapper == null) {
		this.mdvMapper = new mdv.map.MDVMapObjectMapper();	
	}
	this.mdvMapper.mapIt(line, pos);	
    // set center and zoom on departure stop
    if (coord) {
        var c = coord.split(':');
        mdv.map.mdvMap.setCentre(new MDVCoordinates(c[2], c[0], c[1]));
        mdv.map.mdvMap.setZoomLevel(18);
    }
}

// Mapper.
mdv.map.MDVMapObjectMapper = function () {
    var c_dmColors = mdv.map.readCookie('c_dmColors');
    
	this.routes  = [];
    if (c_dmColors) {
        this.colors = c_dmColors.split(',');
    }
    else {
        this.colors = new Array('#FF0000', '#00FF00', '#0000FF');
    }
    
	// new layer for services  
    this.layer = mdv.map.mdvMap.createLayer('begDMLayer', {'useOwnContainer': true});
    mdv.map.mdvMap.addLayer(this.layer);
}


// Display or remove service.
mdv.map.MDVMapObjectMapper.prototype.mapIt = function (line, pos) {
    var r;
    var c = this.routes.length;

    // remove service
    for (r=0; r < c; r++) {
		var route = this.routes[r];
        var routePos = pos.toString().indexOf(':') > -1 ? pos.toString().split(':')[0] : pos; 
		if (route && route.id.toString() === routePos) {
			this.remove(route);
			this.routes.splice(r, 1);
            this.colors.push(this.colors[r]);
            this.colors.splice(r, 1);
            mdv.map.mdvMap.update(); 
			return;
		}			
	}
    
    // display service
	this.fetch (line, pos);	  
}

// Remove service on map.
mdv.map.MDVMapObjectMapper.prototype.remove = function (item) {
	if (!item) {
		return false;
    }
    
	var p, id;

    // remove polyline
	while (p = item.polylines.pop()) {
		this.layer.removePolyline(p);
	}

    // remove legend
    id = item.id;
    if (mdvLib.$('mapIt_' + id)) {
        mdvLib.$('mapIt_' + id).style.backgroundColor = 'transparent';
        mdvLib.$('mapIt_' + id).style.width = '0px';
        mdvLib.$('mapIt_' + id).style.height = '0px';
        mdvLib.$('mapIt_' + id + '_open').style.display = '';
        mdvLib.$('mapIt_' + id + '_close').style.display = 'none';
    }
    
    return true;
}


// Request service.
mdv.map.MDVMapObjectMapper.prototype.fetch = function (line, pos) {
    var url = '/geoobject'
    var _params = { coordListOutputFormat: 'STRING', 
                    filterEpsilon: '5.0', 
                    hideBannerInfo: 1, 
                    returnSinglePath: 1,
                    line: line,
                    itdLPxx_pos: pos,
                    itdLPxx_line: line};
	var ajax = mdvLib.ajax({ host: url, parameters: _params, method: 'get', onComplete: mapService_onAjaxComplete });
}


// Display service on map. 
function mapService_onAjaxComplete(request) {
	var json, efa;
	
 	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.item.paths ||
		!efa.geoObjects.items.item.mode.diva) {
			return;       
    }

    var i, id, item, line, col;
    var stop = efa.geoObjects.items.item.points[0] || efa.geoObjects.items.item.points;	
    var p = efa.parameters[0] || efa.parameters;
    var coordList = { x: [], y: [] };
    var path = efa.geoObjects.items.item.paths[0] || efa.geoObjects.items.item.paths.path;
    var idx = mdv.map.mdvMapper.routes.length > 2 ? 2 : mdv.map.mdvMapper.routes.length;

    // get service id
    i = 0;
    do {
		i++;
		if (p && p.name == 'pos') {
            var idPos = p.value.toString();
            if (idPos.indexOf(':') > -1) {
                id = idPos.split(':')[0];
                idx = idPos.split(':')[1];
            }
            else {
                id = p.value;
                // switch colors
                if (mdv.map.mdvMapper.routes.length > 2) {
                    mdv.map.mdvMapper.colors.push(mdv.map.mdvMapper.colors[0]);
                    mdv.map.mdvMapper.colors.shift();
                }
            }
		}
        else if (p && p.name == 'line') {
			line = p.value;
		}
	} while (p = efa.parameters[i]);
    
    item  = {   id: id,
                line: efa.geoObjects.items.item.mode.diva.toString(), 
                polylines: [],
                stops: [],
                ln: line}
    
    col = mdv.map.mdvMapper.colors[idx];
    
    // create polyline
    i = 0;
    do {
		var pl;
        i++;
		pl = mdv.map.mdvMap.createPolyline(path);
		pl.add('opacity', '1.0');
        pl.add('colour', col);
        mdv.map.mdvMapper.layer.addPolyline(pl, efa.geoObjects.items.item.paths[i]==null);
        
		if (item) {
           item.polylines.push(pl);
        }	
	} while (path = efa.geoObjects.items.item.paths[i]);
    
    // highlight stops
	i = 0;
	do {
		i++;
		item.stops.push(stop.ref.id);
		stop = efa.geoObjects.items.item.points[i];
	} while (stop);
   
    // do not display more than 3 services
    if (mdv.map.mdvMapper.routes.length > 2) {
        mdv.map.mdvMapper.remove(mdv.map.mdvMapper.routes[0]);
        mdv.map.mdvMapper.routes.shift();
    }
    
    mdv.map.mdvMapper.routes[idx] = item;
    mdv.map.mdvMap.update(); 
  
    // create legend
    if (mdvLib.$('mapIt_' + id) ) {
        mdvLib.$('mapIt_' + id).style.backgroundColor = col;
        mdvLib.$('mapIt_' + id).style.width = '15px';
        mdvLib.$('mapIt_' + id).style.height = '15px';
        mdvLib.$('mapIt_' + id + '_open').style.display = 'none';
        mdvLib.$('mapIt_' + id + '_close').style.display = '';
    }
}

mdv.map.highlightPoints = function(id, msg, layer) {
    if (layer && layer.name === 'efa_stops' && mdv.map.mdvMapper && mdv.map.mdvMapper.routes) {
        var i, j, m, img, routes = mdv.map.mdvMapper.routes;
        var markers = layer.getMarkers();
        for (m = 0; m < markers.length; m++) {
            var object = markers[m].getObjectId();
            for (i=0; i<routes.length; i++) {
                if (routes[i]) {
                    for (j=0; j < routes[i].stops.length; j++) {
                        if (object.id === routes[i].stops[j]) { 
                            img = markers[m].getImage();
                            img.style.border = '2px solid #00FF00'; 
                        }
                    }
                }
            }
        }
    }
}


// ================================= add info map ======================================================================

function addInfo_onAjaxComplete (response) {
    var json = null;
 	var efa = null;

 	if (response && response.responseText)	{
 		json = response.responseText;
 	} 
    else if (response) {
 		json = response;
 	}
    else {
        return false;
    }

 	eval('efa = ' + json + ';'); 
    
    // no messages available
    if (!efa.additionalInformation || !efa.additionalInformation.travelInformations || !efa.additionalInformation.travelInformations.travelInformation) {
        return false;
    }
    
    var msg = efa.additionalInformation.travelInformations.travelInformation;
    var size = new MDVPoint(300, 200);
    var i = 0;
    var j = 0;
    
    for (i=0; i < msg.length; i++) {
        // stop blockings and stop informations
        if ((msg[i].type === 'stopBlocking' || msg[i].type === 'stopInfo') && msg[i].concernedStops.length > 0 && (msg[i].valid === '1' || msg[i].valid === '0')) {
           var stops = msg[i].concernedStops;
           var img = '/begWR/img/icsMsg/information.gif';
           var title = '<b>' + msg[i].infoLink.subject;
           if (msg[i].type === 'stopBlocking') {
               img = '/begWR/img/icsMsg/blocking.gif';
           }
           if (msg[i].infoLink.subject === '') {
               title = msg[i].infoLink.subtitle;
           }
           title = title.concat('</b><br/>', msg[i].infoLink.content);
           
           for (j=0; j < stops.length; j++) {
               if (stops[j].coords && stops[j].coords.x != '' && stops[j].coords.y != '' && stops[j].coords.x != '-0.0' && stops[j].coords.y != '-0.0') {
                   var marker = new MDVCoordinates(stops[j].coords.mapName, parseInt(stops[j].coords.x, 10), parseInt(stops[j].coords.y, 10));
                   var tool = mdv.map.mdvMap.createToolTip(size,'<b>' + title + '</b>');
                   mdv.map.setMarker(marker, img);
               }
           }
        }
    }
    
}

// ================================= event listener =====================================================================

mdv.common.attachEventListener(window, 'load', mdv.map.onLoadHandler, null);
mdv.common.attachEventListener(window, 'unload', mdv.map.onUnloadHandler, null);
