var mdvMapsArr = new Array();
var mdvMapConfigs = new Array();
var mdvMiniMapConfigs = new Array();
var ctxCoords = null;

function onUnloadMapHandler() {
    
    if (mdvMapsArr['origin'])
		mdvMapsArr['origin'].destroy();
		
	if (mdvMapsArr['destination'])
		mdvMapsArr['destination'].destroy();
}

function onLoadMapHandler(usage) {
	
	if(!document.getElementById('mdvMap_'+usage)) {
		return true;
	}
	
	var form = document.forms[0];
	
	var form1 = document.forms[1];
	
    initMdvMapConfig();
	
	if(usage){
		
		var dest, orig, value;
		
		// swap if tripRetoure
		// don't change identifiedOdv values
		// in case both maps are opened   
		if(identifiedOdv.command && identifiedOdv.command === 'tripRetoure') {
			dest = identifiedOdv.origin;
			orig = identifiedOdv.destination;
		} else {
			dest = identifiedOdv.destination;
			orig = identifiedOdv.origin;
		}
		
		switch (usage) {
			case 'origin':		value = orig;  
								break;
			case 'destination':	value = dest;  
								break;
			case 'via':			value = identifiedOdv.via;  
								break;
			default:			value = usage;
								break;
		}

		if (value !== '::' && value !== '') {
		
			if (mdvMapsArr[usage] == null) {
				mdvMapsArr[usage] = new MDVMapHelper(usage, value);
			}
			
			return true;
		}
		

		for (var i=0; i < form.length; i++) {
			if (form[i].name && form[i].name== 'itdLPxx_mdvMap_'+ usage) {
				var name = form[i].name.substring(15, form[i].name.length);
				var value = form[i].value;

				if (mdvMapsArr[name] == null) {
					mdvMapsArr[name] = new MDVMapHelper(name, value);
				}
			}
		}


		if(form1){
			for (var i=0; i < form1.length; i++) {
				if (form[i].name && form[i].name.substring(0, 15) == 'itdLPxx_mdvMap_') {
					var name = form1[i].name.substring(15, form1[i].name.length);
					var value = form1[i].value;


					if (mdvMapsArr[name] == null) {
						mdvMapsArr[name] = new MDVMapHelper(name, value);
					}
				}
			}
		}
	
	}
	else{
	
	
		for (var i=0; i < form.length; i++) {
			if (form[i].name && form[i].name.substring(0, 15) == 'itdLPxx_mdvMap_') {
				var name = form[i].name.substring(15, form[i].name.length);
				var value = form[i].value;


				if (mdvMapsArr[name] == null) {
					mdvMapsArr[name] = new MDVMapHelper(name, value);
				}
			}
		}


		if(form1){
			for (var i=0; i < form1.length; i++) {
				if (form1[i].name && form1[i].name== 'itdLPxx_mdvMap_'+ usage) {
					var name = form1[i].name.substring(15, form1[i].name.length);
					var value = form1[i].value;


					if (mdvMapsArr[name] == null) {
						mdvMapsArr[name] = new MDVMapHelper(name, value);
					}
				}
			}
		}
	
	
	
	
	}
		
}


function ContextMenuHandler(id, status, obj) {
	if (status)
		ctxCoords = obj;
}

/* Highlights a preselected stop or poi*/
function hightlightStop(id, msg, layer) {
	
    // handle only stop layer
	if (msg.indexOf('efa_stops') === -1) {
		return;
	}
    var usage = layer.mdvMap.name.slice(7);
    
    // highlight stop
	var ids_origin;
	var idArr = new Array();
	if(document.getElementById('itdLPxx_id_origin'))
		ids_origin = document.getElementById('itdLPxx_id_origin').value;
	else if(document.getElementById('itdLPxx_id_dm'))
		ids_origin = document.getElementById('itdLPxx_id_dm').value;
	else if(document.getElementById('itdLPxx_id_stt'))
		ids_origin = document.getElementById('itdLPxx_id_stt').value;
	else if(document.getElementById('itdLPxx_id_ttb'))
		ids_origin = document.getElementById('itdLPxx_id_ttb').value;
	if(document.getElementById('itdLPxx_id_destination')) {
		var ids_destination;
		ids_destination = document.getElementById('itdLPxx_id_destination').value;
		idArr[1] = ids_destination.split(':');
	}
	if(document.getElementById('itdLPxx_id_via')) {
		var ids_via;
		ids_via = document.getElementById('itdLPxx_id_via').value;
		idArr[2] = ids_via.split(':');
	}
	// Substitute with column (':') separated list of ids.
	idArr[0] = ids_origin.split(':');
    
     if (idArr.length < 2) {
        return;
    }
    
    if (idArr[0].length > 2 && (usage==='origin' || usage==='dm' || usage==='stt' || usage==='ttb')) {
        return;
    }
    
    if (idArr[1].length > 2 && usage==='destination') {
        return;
    }

        if (idArr[2].length > 2 && usage==='via') {
        return;
    }
        
        
   
    

	var marked = 0;

	if (layer) {
		var markers = layer.getMarkers();

		for (var m = 0; m < markers.length; m++) {
			var marker = markers[m];
			var object = marker.getObjectId();
			for (var j=0; j<idArr.length; j++){
				for (var i = 0; i < idArr[j].length - 1; i++) {
					if(document.getElementById('odvNameList_' + idArr[j][idArr[j].length - 1])){
						if(document.getElementById('odvNameList_' + idArr[j][idArr[j].length - 1]).options[i] && document.getElementById('listElem_' + idArr[j][idArr[j].length - 1] + '_' + i)) {
							if (document.getElementById('odvNameList_' + idArr[j][idArr[j].length - 1]).options[i].selected && object.id == document.getElementById('listElem_' + idArr[j][idArr[j].length - 1] + '_' + i).value) {
								var img = marker.getImage();
								// Give it a nice red border...
								img.style.border='solid #FF0000 3px;';
								marked++;
								// List is ought to be unique. No need to continue iteration cycle. Leave...
								break;
							}
						}
					}
					else{
						if (object.id == idArr[j][i]) {
                            var img = marker.getImage();
							// Give it a nice red border...
							img.style.border='3px solid red';
							marked++;
							// List is ought to be unique. No need to continue iteration cycle. Leave...
							break;
						}
					}

				}

				if (marked >= idArr.length) {
					// Leave iteration as soon as required count of markers have been highlighted.
					break;
				}
			}

		}
	}
}

function MDVMapHelper(id, value) {
	this.id = id;
	this.mdvMap = null;
	this.mdvMiniMap = null;

	this.input = document.getElementById('itdLPxx_mdvMap_' + id);

	this.value = value;

	this.marker = null;

	this.sync = null;

	this.ctxMenuArr = new Array();
	
	if(mapLanguage =='en')
		if(id=='origin'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Set origin", this.setCoordinates);
		}
		else if(id=='destination'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Set destination", this.setCoordinates);
		}
		else{
		this.ctxMenuArr[0] = new MDVMapMenuItem("Set point", this.setCoordinates);
		}
	else if(mapLanguage=='fr')
		if(id=='origin'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Startpunkt setzen", this.setCoordinates);
		}
		else if(id=='destination'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Zielpunkt setzen", this.setCoordinates);
		}
		else{
		this.ctxMenuArr[0] = new MDVMapMenuItem("Punkt setzen", this.setCoordinates);
		}
	else
		if(id=='origin'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Startpunkt setzen", this.setCoordinates);
		}
		else if(id=='destination'){
		this.ctxMenuArr[0] = new MDVMapMenuItem("Zielpunkt setzen", this.setCoordinates);
		}
		else{
		this.ctxMenuArr[0] = new MDVMapMenuItem("Punkt setzen", this.setCoordinates);
		}
		
		
		
	this.ctxMenu = new MDVMapMenu(this.ctxMenuArr);

	this.execute();
}

MDVMapHelper.prototype.destroy = function() {

	this.mdvMap.destroy();
	this.mdvMiniMap.destroy();

	this.mdvMap = null;
	this.mdvMiniMap = null;
};

MDVMapHelper.prototype.getImage = function() {


	var img = 'images/address.gif';

	switch(this.id) {
		case 'origin':
			img = 'images/mdvMap/origin.gif';
			break;
		case 'destination':
			img = 'images/mdvMap/destination.gif';
			break;
	}

	var i = new Image();
		i.src = img;

	return img;
};

MDVMapHelper.prototype.setCoordinates = function() {
	var name = this.mdvMap.name.substring(this.mdvMap.name.lastIndexOf('_')+1);
	if (mdvMapsArr[name])
		if(this.id == 'stt' || this.id == 'dm') {
			if(document.getElementById('itdLPxx_mdvMap_stt'))
				document.getElementById('itdLPxx_mdvMap_stt').value='';
			if(document.getElementsByName('sessionID')[0])
				document.getElementsByName('sessionID')[0].value='0';
			if(document.getElementsByName('requestID')[0])
				document.getElementsByName('requestID')[0].value='0';
		}
		if(mapLanguage =='en')
			mdvMapsArr[name].onObjectClicked(-1, null, { type: 'coord', name: 'Map origin/destination', x: parseInt(ctxCoords.x), y: parseInt(ctxCoords.y), mapName: ctxCoords.mapName });
		else if(mapLanguage =='fr')
			mdvMapsArr[name].onObjectClicked(-1, null, { type: 'coord', name: 'Gewählter Punkt aus Karte', x: parseInt(ctxCoords.x), y: parseInt(ctxCoords.y), mapName: ctxCoords.mapName });
		else
			mdvMapsArr[name].onObjectClicked(-1, null, { type: 'coord', name: 'Gewählter Punkt aus Karte', x: parseInt(ctxCoords.x), y: parseInt(ctxCoords.y), mapName: ctxCoords.mapName });
};

MDVMapHelper.prototype.execute = function () {
	var value = this.value;
	
	var nameState = this.getNameState();
	var placeState = this.getPlaceState();
	
    this.doDefault();

	if (value.length > 0 && this.mdvMap && this.mdvMiniMap) {
		var mdvMapTarget = document.getElementById('mdvMap_' + this.id);

		if (mdvMapTarget) {
		
			mdvMapTarget.style.display = 'block';
			
			this.mdvMap.execute(mdvMapConfigs[this.id]);
			this.mdvMiniMap.execute(mdvMiniMapConfigs[this.id]);
			if (this.mdvMap.config.get('infoEx.useGeneralStopIcon')) {
                this.infoEx.getMOTImage = this.getStopImg;
            }
			if (this.mdvMap && this.mdvMiniMap)
				this.sync = new MDVMapSync(this.mdvMap, this.mdvMiniMap);
		}
	}
	else if (value.length <= 0) {
		var mdvMapTarget = document.getElementById('mdvMap_' + this.id);

		//if (mdvMapTarget)
		//	mdvMapTarget.style.display = 'none';
	}

	if (nameState == 'identified')
		this.doIdentified();
	else if (nameState == 'list')
		this.doPlace();
	else if (placeState == 'list')
		this.onChange(null)
	else if (placeState == 'identified')
		this.doPlace();
	else if ((this.getCommand() == 'changeRequest' || this.getCommand() == 'tripRetoure'))
		this.doNotIdentified();
	else if (nameState == 'empty')
		this.doEmpty();
};

MDVMapHelper.prototype.getCommand = function() {
	var command = document.getElementById('itdLPxx_command');

	if (command)
		return command.value;
	return '';
};

MDVMapHelper.prototype.getType = function() {
	var typeSelectors = document.getElementsByName('type_' + this.id);

	if (typeSelectors.length == 1)
		return typeSelectors[0].value;
	else if (typeSelectors.length > 1) {
		for (var i=0; i < typeSelectors.length; i++) {
			var temp = typeSelectors[i];
			if (temp.checked)
				return temp.value;
		}
	} else {
		return '';
	}
};

MDVMapHelper.prototype.getNameState = function() {
	var state = document.getElementById('nameState_' + this.id);
	if (state)
		return state.value;
	else
		return '';
};

MDVMapHelper.prototype.getPlaceState = function() {
	var state = document.getElementById('placeState_' + this.id);
	if (state)
		return state.value;
	else
		return '';
};

MDVMapHelper.prototype.onNewCentre = function (id, msg, obj) {
	var centre = obj.getCentre();
	this.input.value = centre.x + ':' + centre.y + ':' + centre.mapName + ':' + obj.config.getZoomLevelIndex();
};

MDVMapHelper.prototype.doDefault = function() {


	if(mapLanguage =='de'){
	
	var text = new Array();
	text['goNorth'] = 'Norden';
	text['goWest'] = 'Westen';
	text['goEast'] = 'Osten';
	text['goSouth'] = 'Süden';
	text['lastResult'] = 'Letztes Ergebnis';
	text['zoomIn'] = 'Vergrößern';
	text['zoomOut'] = 'Verkleinern';
	
	}


	var values = this.value.split(':');
	if (this.mdvMap == null) {
		this.mdvMap = new MDVMap(document.getElementById('mdvMap_' + this.id));
		

		
		
		new MDVMapContextMenu(this.mdvMap, this.ctxMenu);
		new MDVMapNavigator(this.mdvMap);
        this.infoEx = new MDVMapEFAInfoEx(this.mdvMap);
		new MDVMapControl(this.mdvMap, text);

		if (!mdvMapConfigs[this.id].get('xCenterReal') &&
			!mdvMapConfigs[this.id].get('yCenterReal') &&
			!mdvMapConfigs[this.id].get('mapName')) {

			mdvMapConfigs[this.id].add('xCenterReal', values[0]);
			mdvMapConfigs[this.id].add('yCenterReal', values[1]);
			mdvMapConfigs[this.id].add('mapName', values[2]);
			
			//alert('zoomlevel ' + values[3])

			if (values[3]) {
				mdvMapConfigs[this.id].add('defaultScale', values[3]);
			}
			else {
				mdvMapConfigs[this.id].add('defaultScale', '2');
			}
		}
		
	
		//this.mdvMap.events.registerEvent(MDVEvent_ERROR, null, errorFunction);
		this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.onNewCentre);
		this.mdvMap.events.registerEvent(MDVEvent_OBJECT_CLICKED, this, this.onObjectClicked);
		this.mdvMap.events.registerEvent(MDVEvent_TOOLTIP, this, this.onToolTip);
		this.mdvMap.events.registerEvent(MDVEvent_CONTEXT_MENU, null, ContextMenuHandler);
		this.mdvMap.events.registerEvent(MDVEvent_LAYER_UPDATED, null, hightlightStop);
		this.mdvMap.events.registerEvent(MDVEvent_LAYER_UPDATED, this, this.setCoords);
		
	}

	if (this.mdvMiniMap == null) {
		this.mdvMiniMap = new MDVMap(document.getElementById('mdvMiniMap_' + this.id));
						  new MDVMapNavigator(this.mdvMiniMap);


		if (!mdvMiniMapConfigs[this.id].get('xCenterReal') &&
			!mdvMiniMapConfigs[this.id].get('yCenterReal') &&
			!mdvMiniMapConfigs[this.id].get('mapName')) {				

				mdvMiniMapConfigs[this.id].add('xCenterReal', values[0]);
				mdvMiniMapConfigs[this.id].add('yCenterReal', values[1]);
				mdvMiniMapConfigs[this.id].add('mapName', values[2]);

				if (values[3]) {
					mdvMiniMapConfigs[this.id].add('defaultScale', values[3]);
				}
				else {
					mdvMiniMapConfigs[this.id].add('defaultScale', '2');
				} 
		}
	}
};



MDVMapHelper.prototype.setCoords = function(id, msg, obj) {

// alert(document.getElementById("itdLPxx_mdvMap_" + this.id).value);



};

MDVMapHelper.prototype.onToolTip = function(id, msg, obj) {
	/* var text = obj.getInnerHTML();
		text = text.replace(/Landmark: /, '');
		text = text.replace(/Stop: /, '');
	obj.setInnerHTML(text); */
	
	var wait = '';
	
	if (mapLanguage =='en'){
		wait = 'Please wait while loading...';
	}
	else{
		wait = 'Bitte warten....'
	}
	
	switch (obj.getParent().objectId.type.toLowerCase()) {
			
			case 'poi_area':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML(dmPOI + ': <b>'
					+ obj.getParent().objectId.desc
					+ '</b><br/><br/>Klicken Sie, um diesen wichtigen Punkt auszuwählen.'); 
				} 
			break;
			
			case 'poi_point':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML(dmPOI + ': <b>'
					+ obj.getParent().objectId.desc
					+ '</b><br/><br/>Klicken Sie, um diesen wichtigen Punkt auszuwählen.'); 
				} 
			break;
			
			case 'poi':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML(dmPOI + ': <b>'
					+ obj.getParent().objectId.desc
					+ '</b><br/><br/>Klicken Sie, um diesen wichtigen Punkt auszuwählen.'); 
				} 
			break;
			
			case 'address':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML('Adresse: <b>'
					+ obj.getParent().objectId.desc
					+ '</b>'); 
				} 
			break;
			
			case 'coord':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML('<b>Punkt aus Karte '
					+ obj.getParent().objectId.desc
					+ '</b>'); 
				} 
			break;
			
			case 'stop':
	  			if (obj && obj.isVisible()) {
				obj.setInnerHTML(dmStop + ': <b>'
					+ obj.getParent().objectId.desc
					+ '</b><br><br><div id="'
					+ obj.getParent().objectId.id
					+ '">'
					+ wait
					+'</div>'); 

				obj.dm = new MDVEFADepartureMonitor(obj.parentMarker.objectId.id, '../dm/XML_DM_REQUEST');
				obj.dm.getDepartures(obj.getParent().objectId.id);
				}  
			break;
			
			default:
			if (obj && obj.isVisible()) {
				obj.setInnerHTML('<b>'
					+ obj.getParent().objectId.desc
					+ '</b><br/><br/>Klicken Sie, um diesen Punkt auszuwählen.'); 
				} 
		}
};



MDVMapHelper.prototype.doEmpty = function() {


		
	var values = document.getElementById('itdLPxx_mdvMap2_' + this.id).value.split(':');


	if (values.length >= 4) {
		var mapName = values[2];
		var x = values[0];
		var y = values[1];

		var nc = new MDVCoordinates(mapName, parseInt(x), parseInt(y));
		this.mdvMap.setCentre(nc);
		this.mdvMap.setZoomLevel(values[3]);
		
	

	//	this.setMarker({ type: this.getType(), name: display, mapName: mapName, x: x, y: y });
	}

	this.mdvMap.update();

};




MDVMapHelper.prototype.doNotIdentified = function() {

	var values = this.value.split(':');

	var display = document.getElementById('nameDisplay_' + this.id).value;

	if (values.length >= 3) {
		var mapName = values[2];
		var x = values[0];
		var y = values[1];

		var nc = new MDVCoordinates(mapName, parseInt(x), parseInt(y));
		this.mdvMap.setCentre(nc);
		this.mdvMap.setZoomLevel(4);
		
	

		this.setMarker({ type: this.getType(), name: display, mapName: mapName, x: x, y: y });
	}

	this.mdvMap.update();

};

MDVMapHelper.prototype.doIdentified = function() {
	var mapName = document.getElementById('nameMapName_' + this.id).value;
	var x = document.getElementById('nameX_' + this.id).value;
	var y = document.getElementById('nameY_' + this.id).value;
	var display = document.getElementById('nameDisplay_' + this.id).value;
	var type = document.getElementById('type_' + this.id).value;

	if (x <= 0 || y <= 0)
		return;


	var nc = new MDVCoordinates(mapName, parseInt(x), parseInt(y));
	this.mdvMap.setCentre(nc);
	this.mdvMap.setZoomLevel(5);
	

	this.setMarker({ type: type, name: display, mapName: mapName, x: x, y: y });

	this.mdvMap.update();
};


MDVMapHelper.prototype.doAddress = function(obj) {
	var params = { name_sf: 'streetID:' + obj.streetID + ':' + obj.houseNumber + ':' + obj.omc, type_sf: 'address', itdLPxx_usage: this.id, 'itdLPxx_zoomLevel': 8 };
	params = $H(params).toQueryString();

	var _ajax = new Ajax.Request('XML_STOPFINDER_REQUEST', { method: 'post', parameters: params, onComplete: MDVMapHelper_AjaxCallback });
}

MDVMapHelper.prototype.doCoordinates = function(obj) {
	var nc = null;

	var zl = 7;

	if (obj && obj.x && obj.y)
		nc = new MDVCoordinates(obj.mapName, parseInt(obj.x), parseInt(obj.y));
	else if (obj && obj.firstChild) {
		var target = obj.getElementsByTagName('odvNameElem');
		if (target.length == 1)
			nc = new MDVCoordinates(target[0].getAttribute('mapName'), parseInt(target[0].getAttribute('x')), parseInt(target[0].getAttribute('y')));
		else {
			for (var i=0; i < target.length; i++) {
				if(target[i].getAttribute('streetID') && parseInt(target[i].getAttribute('streetID')) == 0) {
					nc = new MDVCoordinates(target[i].getAttribute('mapName'), target[i].getAttribute('x'), target[i].getAttribute('y'));
					break;
				}
			}
		}
		var itdLayoutParams = obj.getElementsByTagName('itdLayoutParam');
		for (var i=0; i < itdLayoutParams.length; i++) {
			if (itdLayoutParams[i].getAttribute('name') == 'zoomLevel') {
				zl = itdLayoutParams[i].getAttribute('value');
				break;
			}
		}
	}

	if (nc && nc.x > 0 && nc.y > 0) {
		this.mdvMap.setCentre(nc);
		this.mdvMap.setZoomLevel(parseInt(zl));

		if (obj && obj.type && (obj.type == 'address' || obj.type == 'crossing'))
			this.setMarker(obj);

		this.mdvMap.update();
	}

};

MDVMapHelper.prototype.setMarker = function(obj) {
	var mc = new MDVCoordinates(obj.mapName, parseInt(obj.x), parseInt(obj.y));

	if (this.marker == null && obj.type != 'stop' && obj.type != 'poi') {
		this.marker = this.mdvMap.createMarker(mc, 0, this.getImage());
		var tool = this.mdvMap.createToolTip('<b>' + obj.name + '</b>');
		this.marker.setToolTip(tool);
		this.mdvMap.addMarker(this.marker);
	} else if (this.marker && obj.type != 'stop' && obj.type != 'poi') {
		this.marker.setCoords(mc);
		this.marker.toolTip.setInnerHTML('<b>' + obj.name + '</b>');
	}


};

MDVMapHelper.prototype.doPOI = function(obj) {
	var params = { name_sf: obj.poiID, type_sf: 'poiID', place_sf: 'placeID:'+obj.omc+':'+obj.placeID, itdLPxx_usage: this.id };
	params = $H(params).toQueryString();

	var _ajax = new Ajax.Request('XML_STOPFINDER_REQUEST', { method: 'post', parameters: params, onComplete: MDVMapHelper_AjaxCallback });
};

MDVMapHelper.prototype.doStop = function(obj) {
	var params = { name_sf: obj.stopID, type_sf: 'stopID', itdLPxx_usage: this.id };
	params = $H(params).toQueryString();

	var _ajax = new Ajax.Request('XML_STOPFINDER_REQUEST', { method: 'post', parameters: params, onComplete: MDVMapHelper_AjaxCallback });
};

MDVMapHelper.prototype.doPlace = function(obj) {
	var omc = 0; var placeID = -1;

	if (obj == null) {
		var placeValArr = document.getElementById('place_' + this.id).value.split(':')
		placeID = placeValArr[1];
//		omc = document.getElementById('placeOMC_' + this.id).value;
		omc = placeValArr[0];
		placeID = placeValArr[1];
	}
	else {
		omc = obj.omc;
		placeID = obj.placeID;
	}

	var params = { omc: omc, placeID: placeID, itdLPxx_usage: this.id, createImage: 0, pinTypeStop: 0, pinTypePOI: 0, itdLPxx_zoomLevel: '7' };
	params = $H(params).toQueryString();

	var _ajax = new Ajax.Request('XML_MAP_REQUEST', { method: 'post', parameters: params, onComplete: MDVMapHelper_AjaxCallback });
};

MDVMapHelper.prototype.onChange = function(obj) {
	if (this.value <= 0)
		return;

	this.resetInfo();

	var selectedIndex = 0;
	if (obj != null) {
		selectedIndex = obj.selectedIndex;
	}

	var temp = odv[this.id][selectedIndex];

	switch (temp.type) {
		case 'place':
			this.doPlace(temp);
			break;
		case 'stop':
			this.doStop(temp);
			break;
		case 'poi':
			this.doPOI(temp);
			break;
		case 'address':
			if (temp.x == '' && temp.y == '' && temp.streetID > 0) {
				this.doAddress(temp);
				break;
			}
		default:
			this.doCoordinates(temp);
			break;
	}
};

MDVMapHelper.prototype.resetInfo = function() {
	var name 		= document.getElementById('nameInfo_' + this.id);
	var place 		= document.getElementById('placeInfo_' + this.id);
	var placeState 	= document.getElementById('placeState_' + this.id);
	var type 		= document.getElementById('typeInfo_' + this.id);

	if (name)
		name.value = 'invalid';
	if (place)
		place.value = 'invalid';
	if (type)
		type.value = 'invalid';
};

MDVMapHelper.prototype.getStopImg = function(mot, type, pin) {
    
    var typ = type.toUpperCase();
    
    switch (typ) {
        // do not discern Stops by MOT
        // context (this) is infoEx object 
        case 'STOP':        return this.stopImg.src;
        case 'BUS_POINT':   return this.mdvMap.transparent.src || '';
        case 'ENTRANCE':	return this.entranceImg.src;
        case 'POI_POINT':	return this.poiImg.src;
        case 'POI_AREA':	return this.poiImg.src;
        default:        	return this.stopImg.src;    
	}
};

MDVMapHelper.prototype.onObjectClicked = function(id, msg, obj) {

	var name 		= document.getElementById('nameInfo_' + this.id);
	var place 		= document.getElementById('placeInfo_' + this.id);
	var placeState 	= document.getElementById('placeState_' + this.id);
	var type 		= document.getElementById('typeInfo_' + this.id);
	var execInst 	= document.getElementById('execInst');

	if(this.id == 'stt' || this.id == 'dm') {
		if(document.getElementById('itdLPxx_mdvMap_stt'))
			document.getElementById('itdLPxx_mdvMap_stt').value='';
		if(document.getElementsByName('sessionID')[0])
			document.getElementsByName('sessionID')[0].value='0';
		if(document.getElementsByName('requestID')[0])
			document.getElementsByName('requestID')[0].value='0';
	}
	
	switch (obj.type.toLowerCase()) {
		case 'stop':
			name.value = obj.id;
			type.value = 'stopID';
			placeState.value = 'empty';
			place.value = '';
			if (this.marker)
				this.mdvMap.removeMarker(this.marker);
			if(this.id != 'dm' && this.id != 'stt')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = '';
			document.getElementById("itdLPxx_mapState_" + this.id).value="close";
			document.forms[0].submit();
			break;
		case 'poi':
			place.value = obj.omc + ':-1';
			name.value = obj.id;
			type.value = 'poiID';
			if (this.marker)
				this.mdvMap.removeMarker(this.marker);
			if(this.id != 'dm' && this.id != 'stt')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = '';
			document.getElementById("itdLPxx_mapState_" + this.id).value="close";
			document.forms[0].submit();
			break;
			
		case 'poi_point':
			place.value = obj.omc + ':-1';
			name.value = /.+-(\d+)/.exec(obj.id)[1] || obj.desc; //obj.id.substring(4,20);
			type.value = 'poiID';
			if (this.marker)
				this.mdvMap.removeMarker(this.marker);
			if(this.id != 'dm' && this.id != 'stt' && this.id != 'rop')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = '';
			document.getElementById("itdLPxx_mapState_" + this.id).value="close";
			document.forms[0].submit();
			break;
			
		case 'poi_area':
			place.value = obj.omc + ':-1';
			name.value = /.+-(\d+)/.exec(obj.id)[1] || obj.desc;//obj.id.substring(4,20);
			type.value = 'poiID';
			if (this.marker)
				this.mdvMap.removeMarker(this.marker);
			if(this.id != 'dm' && this.id != 'stt' && this.id != 'rop')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = '';
			document.getElementById("itdLPxx_mapState_" + this.id).value="close";
			document.forms[0].submit();
			break;
			
			
		case 'coord':
			if (obj.id)
				return;
			name.value = obj.x + ':' + obj.y + ':' + obj.mapName + ':' + obj.name;
			type.value = 'coord';
			placeState.value = 'empty';
			place.value = '';
			if(this.id != 'dm' && this.id != 'stt')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = '';
			document.getElementById("itdLPxx_mapState_" + this.id).value="close";
			document.forms[0].submit();
			break;
	}
};

function MDVMapHelper_AjaxCallback(request) {
	var usage = request.responseXML.getElementsByTagName('itdLayoutParam');
	for (var i=0; i < usage.length; i++) {
		if (usage[i].getAttribute('name') == 'usage') {
			mdvMapsArr[usage[i].getAttribute('value')].doCoordinates(request.responseXML);
			break;
		}
	}
}

function doTripRetoure() {
	var origin = document.getElementById('itdLPxx_mdvMap_origin');
	var destination = document.getElementById('itdLPxx_mdvMap_destination');

	if (origin && destination) {
		var temp = destination.value;
		destination.value = origin.value;
		origin.value = temp;
	}
}


function errorFunction(){


}


/**
* MDVEFADepartureMonitor
*/
function MDVEFADepartureMonitor(id, url) {
	this.id 	= id;
	this.url 	= url;
}

MDVEFADepartureMonitor.prototype.getDepartures = function(identifier) {
	var _params = { itdLPxx_id: identifier, name_dm: this.id, type_dm: 'stopID', mode: 'direct', limit: '5', language: curLanguage };
		_params = $H(_params);
		_params = _params.toQueryString();

	var ajax = new Ajax.Request(this.url, { method: 'post', parameters: _params, onComplete: MDVEFADepartureMonitor_onAjaxComplete });
};

function MDVEFADepartureMonitor_onAjaxComplete(request) {
	if (request) {
		MDVEFADepartureMonitor_populateTable(request);
	}
}

function MDVEFADepartureMonitor_populateTable(request) {
	if (request.responseXML) {

		var firstChild = request.responseXML.firstChild;

		while (firstChild.nodeType != 1) {
			firstChild = firstChild.nextSibling;
		}

		var id = firstChild.getAttribute('id');
		var text = request.responseText;

		var target = document.getElementById(id);
			target.innerHTML = text;
	}
}



function MDVMarker_onload (e) {
   		e = e ? e : window.event;   	
   		
  		// We need to wait for the onload event in Firefox as it doesn't provide proper values for img width and height, if we don't wait.
		if (this.marker) {
			this.marker.update();
			if (!this.marker.append && this.marker.layer) {
				this.mdvMap.markerObjects.appendChild(this);
				this.marker.append = true;
				
			}
		}
  }
  
  attachEventListener(window, 'unload', onUnloadMapHandler, false);
