var mdvMapsArr = new Array();
var ctxCoords = null;

var roccasMapHistory = new Array();
var roccasMapHistoryPtr = 0;

var rMapNavigator = new rMapNavigatorClass();
var rTimer = new rTimerClass();

function rTimerClass() {
	this.timers = new Array();
	this.id = 0;
}
rTimerClass.prototype.fnAdd = function(pmClass, pmFunction, pmTimeout) {
	var id = this.id++;
	this.timers[id] = new Array();
	this.timers[id]["class"] = pmClass;
	this.timers[id]["function"] = pmFunction;
	window.setTimeout("fnTimer('" + id + "')", pmTimeout);
}
rTimerClass.prototype.fnExec = function(pmId) {
	var obj = this.timers[pmId]["class"];
	eval("obj." + this.timers[pmId]["function"] + "()");
}

function fnTimer(pmId) {
	if(typeof(rTimer) == 'undefined') {
		return;
	}
	rTimer.fnExec(pmId);
}

function rMapNavigatorClass() {
	this.fnSetScale = rMapNavigatorClass_SetScale;
}

function rMapNavigatorClass_SetScale(pmScale, pmId) {
	if(pmId.substring(0, 7) == 'mdvMap_') {
		var ps = pixelPerMeter / pmScale;
		var scales = new Array(10000, 5000, 2500, 1250, 500, 250, 125, 50, 25);
		
		for(var i in scales) {
			var w = ps * scales[i];
			if(w < 31) {
				break;
			}
		}
			
		var content = "";
		content += '<img src="/ib/site/elements/efa/ajaxmap/lyMassstab_hell.gif" height="3" width="' + Math.round(w) + '">';
		content += '<img src="/ib/site/elements/efa/ajaxmap/lyMassstab_dunkel.gif" height="3" width="' + Math.round(w*2-Math.round(w)) + '">';
		content += '<img src="/ib/site/elements/efa/ajaxmap/lyMassstab_hell.gif" height="3" width="' + Math.round(w) + '">';
		content += '<img src="/ib/site/elements/efa/ajaxmap/lyMassstab_dunkel.gif" height="3" width="' + Math.round(w*2-Math.round(w)) + '">';
		content += '<div style="width:'  + Math.round(w*4) + '; text-align:right">';
		if(scales[i]*4 >= 1000) {
			content += scales[i]*4/1000 +" km";
		}
		else {
			content += scales[i]*4 +" m";
		}
		content += '</div>';
		
		document.getElementById("map_NavigationArea_" + pmId.substring(7) + "_Scale").innerHTML = content;
	}
}

function roccasMapTooltip(pmMapHelper) {
 	if (!pmMapHelper)
 		return;

	// Name of gadget
 	this.name = 'roccasTooltip';
	this.mapHelper = pmMapHelper;
 	this.mdvMap = this.mapHelper.mdvMap;
	
 	this.mdvMap.registerGadget(this);

	// Inherit from MDVGadgetBase
    for (var method in MDVGadgetBase.prototype) {
        if (!roccasMapTooltip.prototype[method])
            roccasMapTooltip.prototype[method] = MDVGadgetBase.prototype[method];
    }
}

roccasMapTooltip.prototype.onmousemove = function(e) {
	var div = document.getElementById("map_TooltipHelper_" + this.mdvMap.name.substring(7));
	if(typeof(div) == "undefined" || div == null) {
		return true;
	}
	
	if(typeof(div.tooltip) == "undefined" || div.tooltip == null) {
		fnToolTip(div, {html:'Doppelklicken Sie, um Haltestellen und wichtige Punkte an dieser Stelle einzublenden.'});
	}
	else {
		var mouseX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
		var mouseY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
		
		if(typeof(div.tooltip.mouseX) != "undefined" && div.tooltip.mouseX != null) {
			if(Math.abs(mouseX - div.tooltip.mouseX) > 5 || Math.abs(mouseY - div.tooltip.mouseY) > 5) {
				div.tooltip.hideTimer = rTimer2.fnAdd(div.tooltip, "fnHide", 500);
				if(typeof(div.tooltip.displayTimer) != "undefined" && div.tooltip.displayTimer != null) {
					rTimer2.fnCancel(div.tooltip.displayTimer); // cancel display
				}
				div.tooltip.displayTimer = rTimer2.fnAdd(div.tooltip, "fnDisplay", 1500);
				div.tooltip.fnPrepareDisplay(e);
			}
			else {
				if(typeof(div.tooltip.hideTimer) != "undefined" && div.tooltip.hideTimer != null) {
					rTimer2.fnCancel(div.tooltip.hideTimer); // cancel hide
				}
				div.tooltip.hideTimer = rTimer2.fnAdd(div.tooltip, "fnHide", 1000);
			}
		}
	}
	if(parseInt(this.mdvMap.config.getZoomLevelIndex()) >= 5)
		div.tooltip.html = "Klicken Sie mit der rechten Maustaste, um innerhalb von Ortschaften einen beliebigen Punkt auszuw&auml;hlen.";
	else
		div.tooltip.html = "Doppelklicken Sie, um Haltestellen und wichtige Punkte an dieser Stelle zu suchen.";

	return true;
}
roccasMapTooltip.prototype.onmouseout = function(e) {
	var div = document.getElementById("map_TooltipHelper_" + this.mdvMap.name.substring(7));
	if(typeof(div) == "undefined" || div == null)
		return true;

	if(typeof(div.tooltip.displayTimer) != "undefined" && div.tooltip.displayTimer != null) {
		rTimer2.fnCancel(div.tooltip.displayTimer); // cancel display
	}
	div.tooltip.hideTimer = rTimer2.fnAdd(div.tooltip, "fnHide", 500);
}


function roccasMapNavigator(pmMapHelper) {
 	if (!pmMapHelper)
 		return;

	// Name of gadget
 	this.name = 'roccasMapNavigator';
	this.mapHelper = pmMapHelper
	

	var div = document.createElement('div');
	div.style.position = 'absolute';
	div.style.zIndex = 10;
	div.className = 'MapControl_Rect';
	div.style.cursor = 'move';
	var img = new Image();
	img.src="/ib/site/elements/lyLeer.gif";
	img.style.width="30px";
	img.style.height="30px";
	img.galleryimg = "no";
	img.style.cursor="move";
	img.style.visibility="hidden";
	div.appendChild(img);
	this.mapHelper.mdvMiniMap.viewport.appendChild(div);

 	// Reference to div object
 	this.div = div;
 	this.img = img;
 	// Reference to navigator object
 	this.div.navigator = this;


 	// Reference to mdvMap object
 	this.mdvMap = this.mapHelper.mdvMap;
	this.mdvMiniMap = this.mapHelper.mdvMiniMap;

 	this.navigator = this;

 	// Indicates whether dragging is active or not
 	this.mouseDown = false;
 	// Store the previous Centre Coords
 	this.centre;
 	// Mouse positions
 	this.mouseLast  = new MDVPoint(-1, -1);
 	this.mouseStart = new MDVPoint(-1, -1);


	this.div.onmousedown = this.onmousedown_div;
	// We don't want IE to handle drag events which are related to the mouse in our mapper:
	this.div.ondragstart = new Function([], 'var e=e?e:event;e.cancelBubble=true;e.returnValue=false;return false;');
	//this.div.selectstart = new Function([], 'var e=e?e:event;e.cancelBubble=true;e.returnValue=false;return false;');


	this.div.onmouseup = function(e) {
		e = e ? e : window.event;
		this.navigator.mdvMiniMap.mapper.onmouseup(e);
	};
	this.div.onmousemove = function(e) {
		e = e ? e : window.event;
		this.navigator.mdvMiniMap.mapper.onmousemove(e);
	};

	this.div.onmouseout = this.onmouseup;
 	this.mdvMiniMap.registerGadget(this);

	// Inherit from MDVGadgetBase
    for (var method in MDVGadgetBase.prototype) {

        if (!roccasMapNavigator.prototype[method])
            roccasMapNavigator.prototype[method] = MDVGadgetBase.prototype[method];

    }
 	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED, this, this.update);
}
  
roccasMapNavigator.prototype.update = function() {
	var h = this.mdvMap.viewportRealHeight / this.mdvMiniMap.viewportRealHeight * this.mdvMiniMap.viewportHeight;
	var w = this.mdvMap.viewportRealWidth / this.mdvMiniMap.viewportRealWidth * this.mdvMiniMap.viewportWidth;

	this.div.style.top  = (parseInt(this.mdvMiniMap.viewportHeight) / 2 - h / 2) + "px";
	this.div.style.left = (parseInt(this.mdvMiniMap.viewportWidth) / 2 - w / 2) + "px";
	this.img.style.width = w + "px";
	this.img.style.height = h + "px";
}

roccasMapNavigator.prototype.onmousedown_div = function(e) {
	e = e ? e : window.event;

	if ((e.button == 0 && !window.event) || (e.button == 1 && window.event))
	{
	    var mX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
	    var mY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));

	    this.navigator.mouseLast.x  = mX;
	    this.navigator.mouseLast.y  = mY;

	    this.navigator.mouseStart.x = this.navigator.mouseLast.x;
	    this.navigator.mouseStart.y = this.navigator.mouseLast.y;

	    if (!this.navigator.mouseDown) {
			if (this.navigator.mdvMap.config.get('cursorMove')) {
				if (document.all) {
					this.navigator.div.style.cursor = 'url(\'' + this.navigator.mdvMap.config.get('cursorMove') + '\')';
					this.navigator.mdvMiniMap.mapper.style.cursor = 'url(\'' + this.navigator.mdvMap.config.get('cursorMove') + '\')';
				}
				else {
					this.navigator.div.style.cursor = '-moz-grabbing';
					this.navigator.mdvMiniMap.mapper.style.cursor = '-moz-grabbing';
				}
	    	}
			else {
				this.navigator.div.style.cursor = 'auto';
				this.navigator.mdvMiniMap.mapper.style.cursor = 'auto';
			}
	    }

		this.navigator.centre = new MDVCoordinates(this.navigator.mdvMiniMap.getCentre().mapName,
			this.navigator.mdvMiniMap.getCentre().x,
			this.navigator.mdvMiniMap.getCentre().y);

		this.navigator.mouseDown = true;

	    return true;
	} else {
		return true;
	}
};

roccasMapNavigator.prototype.onmouseup = function(e) {
	e = e ? e : window.event;
  	if (this.navigator.mouseDown) {
		if (this.navigator.mdvMap.config.get('cursorIdle')) {
			if (document.all) {
				this.navigator.div.style.cursor = 'url(\'' + this.mdvMap.config.get('cursorIdle') + '\')';
				this.navigator.mdvMiniMap.mapper.style.cursor = 'url(\'' + this.mdvMap.config.get('cursorIdle') + '\')';
			}
			else {
				this.navigator.div.style.cursor = '-moz-grab';
				this.navigator.mdvMiniMap.mapper.style.cursor = '-moz-grab';
			}
		}
		else {
			this.navigator.div.style.cursor = 'move';
			this.navigator.mdvMiniMap.mapper.style.cursor = 'auto';
		}

		var centre = this.navigator.mdvMap.getCentre();
		this.navigator.mdvMiniMap.setCentre(centre);

		rTimer.fnAdd(this.navigator.mdvMap, "update", 2);
		rTimer.fnAdd(this.navigator.mdvMiniMap, "update", 2);
  	}

  	this.navigator.mouseDown = false;

	fnMap_AppendHistory(this.navigator.mdvMap); //roccas append history
	
  	return true;
};

roccasMapNavigator.prototype.onmousemove = function(e) {
	e = e ? e : window.event;

    if(!this.navigator.mouseDown) {
		return;
	}

	var mouseX = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
	var mouseY = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));

	this.navigator.div.style.left = parseInt(this.navigator.div.style.left) + mouseX - this.navigator.mouseLast.x;
	this.navigator.div.style.top = parseInt(this.navigator.div.style.top) + mouseY - this.navigator.mouseLast.y;

	
/*
    var offsetL = 0;
    var offsetT = 0;

	var obj = this.navigator.div;

    while(obj) {
    	offsetL += obj.offsetLeft;
    	offsetT += obj.offsetTop;

    	obj = obj.offsetParent;
    }



    mouseX = mouseX - (offsetL);
    mouseY = mouseY - (offsetT);

	var centrePoint  = new MDVPoint(mouseX, mouseY);
	var centreCoords = this.navigator.mdvMiniMap.getCoordinates(centrePoint);

	this.navigator.mdvMap.events.triggerEvent(MDVEvent_MOUSE_MOVED, 'MDVMap noticed a mouse movement.', centreCoords);
*/

	if (this.navigator.mouseDown) {
		if (this.navigator.mdvMap.config.get('cursorMove')) {
			if (document.all) {
				//this.navigator.div.style.cursor = 'url(\'' + this.navigator.mdvMap.config.get('cursorMove') + '\')';
				//this.navigator.mdvMiniMap.mapper.style.cursor = 'url(\'' + this.navigator.mdvMap.config.get('cursorMove') + '\')';
			}
			else {
				this.navigator.div.style.cursor = '-moz-grabbing';
				this.navigator.mdvMiniMap.mapper.style.cursor = '-moz-grabbing';
			}
		}
		else {
			this.navigator.div.style.cursor = 'auto';
			this.navigator.mdvMiniMap.mapper.style.cursor = 'auto';
		}


		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 zoomLevelMM = this.navigator.mdvMiniMap.config.getZoomLevel(this.navigator.mdvMiniMap.config.currentZoomLevelIndex);
		var zoomLevel = this.navigator.mdvMap.config.getZoomLevel(this.navigator.mdvMap.config.currentZoomLevelIndex);
		var pxWidthAll     = parseInt(zoomLevelMM.get('tileSizeX')) * parseInt(zoomLevelMM.get('numberOfTilesX'));
		var realToPxRatio  = parseInt(zoomLevelMM.get('realWidth')) / pxWidthAll;

		var realOffset = new MDVPoint((-(mX - this.navigator.mouseLast.x) * realToPxRatio),
			-(mY - this.navigator.mouseLast.y) * realToPxRatio);

		var newCentre = new MDVCoordinates(this.navigator.mdvMap.config.get('mapName'), this.navigator.mdvMap.real.x - realOffset.x, this.navigator.mdvMap.real.y - realOffset.y);

		this.navigator.mdvMap.setCentre(newCentre);


	    var tl = new MDVPoint(parseInt(this.navigator.mdvMap.mapper.style.left), parseInt(this.navigator.mdvMap.mapper.style.top));
		this.navigator.mdvMap.mapper.style.left = (tl.x - zoomLevelMM.scale/zoomLevel.scale*(mX - this.navigator.mouseLast.x)) + 'px';
		this.navigator.mdvMap.mapper.style.top  = (tl.y - zoomLevelMM.scale/zoomLevel.scale*(mY - this.navigator.mouseLast.y)) + 'px';

		this.navigator.mouseLast.x = mX;
		this.navigator.mouseLast.y = mY;

		//rTimer.fnAdd(this.navigator.mdvMap, "_checkWrap", 10);
		return true;
	}
	else {
		return true;
	}
};


function fnMap_AppendHistory(pmMap) {

	var newMap = { zoom: pmMap.config.currentZoomLevelIndex, x: pmMap.getCentre().x, y: pmMap.getCentre().y };
	
	if(pmMap.name.substring(0, 7) != 'mdvMap_')
		return;
	
	var name = pmMap.name.substring(7);
	
	if(roccasMapHistoryPtr > 0) {
		var lastMap = roccasMapHistory[roccasMapHistoryPtr-1];
		if(lastMap.zoom == newMap.zoom && Math.abs(lastMap.x-newMap.x) < 10 && Math.abs(lastMap.y-newMap.y) < 10) {
			if(roccasMapHistoryPtr < roccasMapHistory.length) {
				fnButton_enable("bnNaechster", name);
			}
			else {
				fnButton_disable("bnNaechster", name);
			}
			if(roccasMapHistoryPtr < 2) {
				fnButton_disable("bnAusgangspunkt", name);
				fnButton_disable("bnVorheriger", name);
			}
			else {
				fnButton_enable("bnAusgangspunkt", name);
				fnButton_enable("bnVorheriger", name);
			}
			return;
		}
	}

	roccasMapHistory[roccasMapHistoryPtr] = newMap;
	roccasMapHistoryPtr++;
	if(roccasMapHistoryPtr < roccasMapHistory.length) {
		roccasMapHistory = roccasMapHistory.slice(0, roccasMapHistoryPtr);
	}
	if(roccasMapHistoryPtr > 1) {
		fnButton_enable("bnAusgangspunkt", name);
		fnButton_enable("bnVorheriger", name);
	}
	fnButton_disable("bnNaechster", name);
}
function fnButton_enable(pmId, pmUsage) {
	var img = document.getElementById("map_" + pmId + "_" + pmUsage);
	img.src = "/ib/site/elements/efa/ajaxmap/" + pmId + "_a.gif";
}
function fnButton_disable(pmId, pmUsage) {
	var img = document.getElementById("map_" + pmId + "_" + pmUsage);
	img.src = "/ib/site/elements/efa/ajaxmap/" + pmId + "_d.gif";
}

function fnMap_First(pmName) {
	var map = mdvMapsArr[pmName].mdvMap;
	if(roccasMapHistoryPtr < 2)
		return;
	roccasMapHistoryPtr = 1;
	var lastMap = roccasMapHistory[roccasMapHistoryPtr-1];
	nc = new MDVCoordinates("NAV4", lastMap.x, lastMap.y);
	map.setZoomLevel(lastMap.zoom);
	map.setCentre(nc);
	map.update();
}
function fnMap_Prev(pmName) {
	var map = mdvMapsArr[pmName].mdvMap;
	if(roccasMapHistoryPtr < 2)
		return;
	roccasMapHistoryPtr --;
	var lastMap = roccasMapHistory[roccasMapHistoryPtr-1];
	nc = new MDVCoordinates("NAV4", lastMap.x, lastMap.y);
	map.setZoomLevel(lastMap.zoom);
	map.setCentre(nc);
	map.update();
}
function fnMap_Next(pmName) {
	var map = mdvMapsArr[pmName].mdvMap;
	if(roccasMapHistoryPtr >= roccasMapHistory.length)
		return;
	var lastMap = roccasMapHistory[roccasMapHistoryPtr];
	roccasMapHistoryPtr++;
	nc = new MDVCoordinates("NAV4", lastMap.x, lastMap.y);
	map.setZoomLevel(lastMap.zoom);
	map.setCentre(nc);
	map.update();
}		

function fnMap_Print(pmName) {
	var m = mdvMapsArr[pmName].mdvMap;
	var param = "zoom=" + m.config.currentZoomLevelIndex;
	param += "&x=" + m.getCentre().x;
	param += "&y=" + m.getCentre().y;
	openWindow('karte', '/komfortauskunft/karte/?'+param, 'A6B3A0F2-7284-4B37-9027-4CC366608934')
}



function onUnloadMapHandler() {
	if (mdvMapsArr['origin'])
		mdvMapsArr['origin'].destroy();
	if (mdvMapsArr['destination'])
		mdvMapsArr['destination'].destroy();
	if (mdvMapsArr['via'])
		mdvMapsArr['via'].destroy();
	if (mdvMapsArr['dm'])
		mdvMapsArr['dm'].destroy();
	if (mdvMapsArr['stt'])
		mdvMapsArr['stt'].destroy();
	if (mdvMapsArr['ttb'])
		mdvMapsArr['ttb'].destroy();
	if (mdvMapsArr['sf'])
		mdvMapsArr['sf'].destroy();
}

function onLoadMapHandler(form) {
	//alert(form.elements.length);
	for (var i=0; i < form.length; i++) {
		if (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);
				//alert(value);
			}
		}
	}
}

function ContextMenuHandler(id, status, obj) {
	if (status)
		ctxCoords = obj;
}

/* Highlights a preselected stop or poi*/
function hightlightStop(id, msg, layer) {
	// 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(':');


	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='solid #FF0000 3px;';
							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; //comment for no mm

	this.input = document.getElementById('itdLPxx_mdvMap_' + id);

	this.value = value;

	this.marker = null;

	this.sync = null;

	this.ctxMenuArr = new Array();
	if(mapLanguage =='en')
		this.ctxMenuArr[0] = new MDVMapMenuItem("Set origin/destination", this.setCoordinates);
	else
		this.ctxMenuArr[0] = new MDVMapMenuItem("Punkt &uuml;bernehmen", 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 = '/ib/site/elements/efa/ajaxmap/address.gif';

	switch(this.id) {
		case 'origin':
			img = '/ib/site/elements/efa/ajaxmap/origin.gif';
			break;
		case 'destination':
			img = '/ib/site/elements/efa/ajaxmap/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, { type: 'coord', name: 'Map origin/destination', x: parseInt(ctxCoords.x), y: parseInt(ctxCoords.y), mapName: ctxCoords.mapName });
		else {
//			mdvMapsArr[name].onObjectClicked(-1, { type: 'coord', name: 'Gewählter Punkt aus Karte', x: parseInt(ctxCoords.x), y: parseInt(ctxCoords.y), mapName: ctxCoords.mapName });
			mdvMapsArr[name].onObjectClicked(-1, { type: 'coord', name: ctxCoords.pointName, omc: ctxCoords.pointOMC, 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';

			//var T1 = (new Date()).getTime();
			this.mdvMap.execute(mdvMapConfig[this.id]);
			//alert(((new Date()).getTime() - T1) / 1000);


// ff comment for no mm
			this.mdvMiniMap.execute(mdvMiniMapConfig[this.id]);

			if (this.mdvMap && this.mdvMiniMap)
				this.sync = new MDVMapSync(this.mdvMap, this.mdvMiniMap);
// end comment for no mm
		}
	}
	else if (value.length <= 0) {
		var mdvMapTarget = document.getElementById('mdvMap_' + this.id);

		if (mdvMapTarget)
			mdvMapTarget.style.display = 'none';
	}

	if (value.length > 0 && nameState == 'identified')
		this.doIdentified();
	else if (value.length > 0 && nameState == 'list')
		this.doPlace();
	else if (value.length > 0 && placeState == 'list')
		this.onChange(null)
	else if (value.length > 0 && placeState == 'identified')
		this.doPlace();
	else if (value.length > 0 && (this.getCommand() == 'changeRequest' || this.getCommand() == 'tripRetoure'))
		this.doNotIdentified();
};

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() {
	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 MDVMapEFAInfo(this.mdvMap);
		new MDVMapNavigator(this.mdvMap);
		new roccasMapTooltip(this);
		new MDVMapControl(this.mdvMap);

		if (!mdvMapConfig[this.id].get('xCenterReal') &&
			!mdvMapConfig[this.id].get('yCenterReal') &&
			!mdvMapConfig[this.id].get('mapName')) {

			mdvMapConfig[this.id].add('xCenterReal', values[0]);
			mdvMapConfig[this.id].add('yCenterReal', values[1]);
			mdvMapConfig[this.id].add('mapName', values[2]);

			if (values[3]) {
				mdvMapConfig[this.id].add('defaultScale', values[3]);
			} else {
				mdvMapConfig[this.id].add('defaultScale', '2');
			}
		}

		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);
	}

	if (this.mdvMiniMap == null) {
		this.mdvMiniMap = new MDVMap(document.getElementById('mdvMiniMap_' + this.id));

		if (!mdvMiniMapConfig[this.id].get('xCenterReal') &&
			!mdvMiniMapConfig[this.id].get('yCenterReal') &&
			!mdvMiniMapConfig[this.id].get('mapName')) {
				new roccasMapNavigator(this);
				new MDVMapNavigator(this.mdvMiniMap);

				mdvMiniMapConfig[this.id].add('xCenterReal', values[0]);
				mdvMiniMapConfig[this.id].add('yCenterReal', values[1]);
				mdvMiniMapConfig[this.id].add('mapName', values[2]);

				if (values[3]) {
					mdvMiniMapConfig[this.id].add('defaultScale', values[3]);
				}
		}
	}
};

MDVMapHelper.prototype.onToolTip = function(id, obj) {
	var text = obj.getInnerHTML();
		text = text.replace(/Landmark: /, '');
		text = text.replace(/Stop: /, '');
	obj.setInnerHTML(text);
};

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(8);

		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;

	if (x <= 0 || y <= 0)
		return;

	var nc = new MDVCoordinates(mapName, parseInt(x), parseInt(y));
	this.mdvMap.setCentre(nc);
	this.mdvMap.setZoomLevel(8);
	
//	this.setMarker({ type: this.getType(), name: display, mapName: mapName, x: x, y: y });
	this.setMarker({ type: 'address', 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('/efa9/efa94/roccas/XML_STOPFINDER_REQUEST', { method: 'post', parameters: params, onComplete: MDVMapHelper_AjaxCallback });
}

MDVMapHelper.prototype.doCoordinates = function(obj) {
	var nc = null;

	var zl = 8;

	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) {
		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(obj.name);
		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(obj.name);
	}


};

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('/efa9/efa94/roccas/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('/efa9/efa94/roccas/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 parts=document.getElementById('placeOMC_'+this.id).value.split(":");
		omc=parts[0];
		placeID=parts[1];
		//omc = document.getElementById('placeOMC_' + this.id).value;
	} 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: '6' };
	params = $H(params).toQueryString();

	var _ajax = new Ajax.Request('/efa9/efa94/roccas/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';
	/* Auskommentiert, da die Ortsliste bei geöffneter Karte nicht verifiziert wurde.
	   Bsp VOR: gföhl, hauptplatz -> karte -> geföhl(krems) wählen, anfordern
	   => ort wird nicht verifiziert

	if (placeState);
		placeState.value = 'invalid'; */
};

MDVMapHelper.prototype.onObjectClicked = function(id, 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) {
		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 = '';
			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 = '';
			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 = obj.omc + ':-1';
			//alert(document.forms.efaform.id);
			//place.value = '';
			if(this.id != 'dm' && this.id != 'stt')
				execInst.value = 'verifyOnly';
			this.mdvMap.mapper.style.cursor = 'wait';
			this.input.value = ''; //obj.x + ':' + obj.y + ':' + obj.mapName + ':' + this.mdvMap.config.currentZoomLevelIndex;
			break;
	}
	if(this.id=='ttb' && document.forms[1])
		document.forms[1].submit();
	else
		document.forms.efaform.submit();

};

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 MDVMapSync(mdvMap, mdvMiniMap) {
	this.mdvMap 		= mdvMap;
	this.mdvMiniMap 	= mdvMiniMap;

	this.lastMap 	    = null;
	this.lastMiniMap    = null;

	this.mdvMap.events.registerEvent(MDVEvent_MAP_INITIALISED,   this, this.updateMiniMap);
	this.mdvMiniMap.events.registerEvent(MDVEvent_MAP_INITIALISED,   this, this.updateMap);
}

MDVMapSync.prototype.updateMiniMap = function (id, msg, mdvMap) {
	if (this.lastMiniMap && this.lastMiniMap.centre.equals(mdvMap.getCentre()) && this.lastMiniMap.zoomLevel == mdvMap.config.getZoomLevelIndex())
		return false;

	this.mdvMiniMap.setCentre(mdvMap.getCentre().clone());
	this.mdvMiniMap.setZoomLevel(mdvMap.config.getZoomLevelIndex());

	this.lastMiniMap = { centre: this.mdvMiniMap.getCentre(), zoomLevel: this.mdvMiniMap.config.getZoomLevelIndex() };

	return this.mdvMiniMap.update();

};

MDVMapSync.prototype.updateMap = function (id, msg, mdvMiniMap) {
	if (this.lastMap && this.lastMap.centre.equals(mdvMiniMap.getCentre()) && this.lastMap.zoomLevel == mdvMiniMap.config.getZoomLevelIndex())
		return false;

	this.mdvMap.setCentre(mdvMiniMap.getCentre().clone());
	this.mdvMap.setZoomLevel(mdvMiniMap.config.getZoomLevelIndex());

	this.lastMap = { centre: this.mdvMap.getCentre(), zoomLevel: this.mdvMap.config.getZoomLevelIndex() };

	return this.mdvMap.update();

};
