
var theX, theY;
var x1, y1, x2, y2;
var zleft,zright,ztop,zbottom;
var zmapminx,zmapmaxx,zmapmaxy,zmapminy;
var mtop,mleft,mwidth,mheight,mborder;
var mapDivId;
var activeTool="zoomin";
var beforeactiveTool="zoomin";

var blnMouseover = false;
var dragging = false;
var panning = false;
var waitingForResponse = false;
var mouseX=0;
var mouseY=0;
var arrSelObjectid=new Array();
var currentMeasure=0;
var currentArea=0;

var dtext="";
var totalMeasure=0;
var totalArea=0;

var meterpropixelX;
var meterpropixelY;
var mapX=0;
var mapY=0;
var sendidfsmmX=-1;
var sendidfsmmY=-1;

var theButton=-1;
var cleftbutton=1;
var crightbutton=2;

var intTimeleftMousetip = 2; // maptip anzeigen nach n sekunden
var aktiv_mt=false;
aktiv_mt = window.setTimeout("setTimeMousetip(" + intTimeleftMousetip + ")",500);

function setTimeMousetip(intTimeleftMousetip){
	if (blnMaptipAnzeigen && LayerBerechtigung[maptip_layerid]!=0){
		if (maptip_layerid>-1 && (mouseX!=sendidfsmmX) && 
		   (mouseY!=sendidfsmmY) && (mouseX>=0) && (mouseX<mwidth) && (mouseY>=0) && (mouseY<mheight) && (!panning) && (!dragging) && (!isWorking) && (!isMoving)){
			if(aktiv_mt) { 
				window.clearTimeout(aktiv_mt); 
			}
			intTimeleftMousetip--;
			if(intTimeleftMousetip > 0) { 
				aktiv_mt = window.setTimeout("setTimeMousetip(" + intTimeleftMousetip + ")",500); 
			}
			if(intTimeleftMousetip <= 0) {
				sendMaptipRequest(maptip_layerid);
			}
		}
	}
}


function setMapDivProperties(top, left, width, height, border, mapId) {
	mtop = top;//+border;
	mleft = left;//+border;
	mwidth = width;//-(2*border);
	mheight = height;//-(2*border);
	mborder = border;
	mapDivId = mapId;
}

function createZoomBoxDivs(){
	createLayer("zoomboxTop",mleft,mtop,mwidth,mheight,false,"");
	createLayer("zoomboxBottom",mleft,mtop,mwidth,mheight,false,"");
	createLayer("zoomboxLeft",mleft,mtop,mwidth,mheight,false,"");
	createLayer("zoomboxRight",mleft,mtop,mwidth,mheight,false,"");
	setLayerBackgroundColor("zoomboxTop","blue");
	setLayerBackgroundColor("zoomboxBottom","blue");
	setLayerBackgroundColor("zoomboxLeft","blue");
	setLayerBackgroundColor("zoomboxRight","blue");
}
function createIdResultDiv(){
	  document.writeln('<div id="IdResult" style="position:absolute; overflow:auto; left:0px; top:0px; width:500px; height:460px; background-color:White; border-style:ridge;visibility:hidden;">');
	  document.writeln('</div>');
}


function highlightTool(tool){
	if (tool){
		document.images["zoomInTool"].src = "images/ims/zoomin.gif";
		document.images["zoomOutTool"].src = "images/ims/zoomout.gif";
		document.images["panTool"].src = "images/ims/pan.gif";
		document.images["idTool"].src = "images/ims/identify.gif";
		document.images["fsnachweisTool"].src = "images/ims/albu.gif";
		document.images["measureTool"].src = "images/ims/messen_mu.gif";
		document.images["measureToolm2"].src = "images/ims/messen_m2u.gif";
		document.images["textTool"].src = "images/ims/textu.gif";
		document.images["prop"].src = "images/ims/propertiesu.gif";
		document.images["selByEnvTool"].src = "images/ims/select_rect_1.gif";
		document.images["bufferTool"].src = "images/ims/buffer_1.gif";
		switch (tool){
			case "prop":
				document.images["prop"].src = "images/ims/propertiesD.gif";
				break;
			case "zoomin":
				document.images["zoomInTool"].src = "images/ims/zoominD.gif";
				break;
			case "zoomout":
				document.images["zoomOutTool"].src = "images/ims/zoomoutD.gif";
				break;
			case "pan":
				document.images["panTool"].src = "images/ims/panD.gif";
				break;
			case "identify":
				document.images["idTool"].src = "images/ims/identifyD.gif";
				break;
			case "hyperlink":
				//document.images["hyperlinkTool"].src = "images/ims/hyperD.gif";
				break;
			case "fsnachweis":
				document.images["fsnachweisTool"].src = "images/ims/albD.gif";
				break;
			case "measure":
				document.images["measureTool"].src = "images/ims/messen_md.gif";
				break;
			case "measurepoly":
				document.images["measureToolm2"].src = "images/ims/messen_m2d.gif";
				break;
			case "text":
				document.images["textTool"].src = "images/ims/textd.gif";
				break;
			case "selenv":
				document.images["selByEnvTool"].src = "images/ims/selectrectd.gif";
				break;
			case "buffer":
				document.images["bufferTool"].src = "images/ims/bufferd.gif";
				break;
			default:
		}
	}
}

function deActivateTool(){
	writeProtokoll("deActivateTool");
	if (document.getElementById("divProp").style.visibility=="visible"){
		setProperties();
	}
	hideLayer("divMsg");
	hideLayer("divShowLen");
	hideLayer("divShowPuf");
	hideLayer("divShowText");
	hideLayer("id");
	if (wininfo){
		if (!wininfo.closed){
			wininfo.close();
		}
	}
	var layer = document.getElementById("mapContainer");
	layer.onmousedown=null;
	layer.onclick=null;
	//layer.onmousemove=setMouseXY;
	document.onmousemove=setMouseXY;
	
	layer.ondblclick=null;
	layer.onmouseout=setMouseoverFalse;
	layer.onmouseover=setMouseoverTrue;

}
function setMouseoverFalse(){
	blnMouseover=false;
	window.status="";
}
function setMouseoverTrue(){
	blnMouseover=true;
	window.status="";
}
function setActiveTool(tool){
	finishPolyline();
	deActivateTool();
	if (activeTool!="print"){
		beforeactiveTool=activeTool;
	}
	activeTool = tool;
	writeProtokoll("setActiveTool "+activeTool);
	var layer = document.getElementById("mapContainer");
	if(activeTool == "selenv") {
		strPrtUserText="";
		layer.onmousedown= startDragging;
		layer.style.cursor = "crosshair";
	}
 	if(activeTool == "zoomin" || activeTool == "zoomout") {
		layer.onmousedown=startDragging;
		layer.style.cursor = "crosshair";
	}
 	else if(activeTool == "pan") {
		layer.onmousedown= startMapDragging;
 		layer.style.cursor = "move";
 	}
	else if(activeTool == "identify") {
		layer.style.cursor = "crosshair";
		layer.onmousedown= pointClick;
	}
	else if(activeTool == "fsnachweis") {
		layer.onmousedown= pointClick;
		layer.style.cursor = "crosshair";
	}
	else if(activeTool == "testTool") {
		layer.onmousedown=pointClick;
		//layer.onmousedown=pointClick;
		layer.style.cursor = "crosshair";
		//document.getElementById("divMessenInfo").style.visibility="visible";
	
	}
	else if(activeTool == "text") {
		layer.onmousedown=pointClick;
		layer.style.cursor = "crosshair";
		showLayer("divShowText");
		showLayer("divText");
		deactivateRubberband();
		
		//showtext();
	}
	else if(activeTool == "measure" || activeTool == "measurepoly" || activeTool == "measurecircle") {
		layer.onmousedown=pointClick;
		layer.ondblclick=finishPolyline;
		//layer.onmousedown=pointClick;
		layer.style.cursor = "crosshair";
		showLayer("divShowLen");
	}
	/*
	else if(activeTool == "buffer") {
		showLayer("divShowPuf");
	}
	*/
	else if(activeTool == "print") {
		layer.onmousedown=null;
		showprinterdialog();
	}
 }

function startDragging(e){
	if (!e) e=window.event;
	if (isIE){
		theButton=window.event.button;
	}else{
		theButton=e.which;
	}
	if (theButton==cleftbutton) {
		panning=false;
		if(!dragging){
			if(activeTool=="selenv" && (!getLayerVisibility(ActiveLayerIndex))){
				alert("Auswahl nicht möglich,\nLayer ist nicht sichtbar oder kein Layer aktiv !");
			}else{
				dragging = true;
				x1=mouseX;
				y1=mouseY;
				x2=x1+1;
				y2=y1+1;
				showZoomBox(x1,y1,x2,y2);	
				var layer = document.getElementById("mapContainer");
		 		layer.onmousemove = updateDragging;
				layer.onmouseup = stopDragging;
			}	
		}
		return false;
	}else{
		document.getElementById("mapContainer").style.cursor = "move";
 		startMapDragging();
	}
	
	
}

function startMapDragging(e) {
	dragging = false;
	if (!panning) {
		panning = true;
		x1=mouseX;
		y1=mouseY
		x2=x1+1;
		y2=y1+1;
		var layer = document.getElementById("mapContainer");
		layer.onmousemove = updateMapDragging;
		layer.onmouseup = stopMapDragging;
	}
	return false;
}
function writeText(){
	var text = document.maptext.text.value;
	if (text==null||text==""){
		showLayer('divShowText');
	}else{
		dtext=text;
		drawText();
	}
		
}
function pointClick(e) {
	//settime_mt(intTimeleftMousetip);
	if (isIE){
		theButton=window.event.button;
	}else{
		theButton=e.which;
	}
	if (mouseX>-1&&mouseY>-1) {
		if (theButton==cleftbutton) {
			var x1 = mouseX;
			var y1 = mouseY;
			if(activeTool == "fsnachweis"){
				openFsNachweis(mapX, mapY);
			}
			if((activeTool == "measure"||activeTool == "measurepoly"||activeTool == "text"||activeTool == "measurecircle")){
				clickAddPoint(e);
			}
			if(activeTool == "zoomInTool" || activeTool == "zoomOutTool"){
				setClip();
				// adjust for offsets
				zoom(zmapminx,zmapminy,zmapmaxx,zmapmaxy);
			}
			if(activeTool == "identify") {
				var isopen=false;
				setIdDiv(mouseX,mouseY);
				showLayer('loading');
				if (wininfo && !wininfo.closed){
					wininfo.document.formflurstliste.frmfsliste.value="";
					wininfo.document.getElementById("divifr").innerHTML="";
					wininfo.document.getElementById("divinfo").innerHTML="";
				}else{
					openInfoWindow();
				}
				hideLayer('loading');
				getLayerXYInfo(mapX,mapY);
			}
		}else{
			finishPolyline();
			//if (!activate_rb){
 				document.getElementById("mapContainer").style.cursor="move";
 				startMapDragging();
 			//}
		}
	}
}
function setIdDiv(x,y){
	var layer = document.getElementById("id").style;
	layer.top=y-10;
	layer.left=x-10;
	layer.visibility="visible";

}
function resetClick() {
	txtQuery="";
	if (activeTool == "measure"){
		document.dialogmsg.gesamt.value="";
		document.dialogmsg.segment.value="";
		clickmaplinexstr="";
		clickmaplineystr="";
		resetPolyline();
	}else if (activeTool == "measurepoly"){
		document.dialogmsg.gesamt.value="";
		document.dialogmsg.segment.value="";
		clickmappolyxstr="";
		clickmappolyystr="";
		resetPolygon();
	}else if (activeTool == "measurecircle"){
		deactivateRubberband();
		currentMeasure=0;
		totalMeasure=0;
		document.dialogmsg.gesamt.value="";
		document.dialogmsg.segment.value="";
		resetCircle();
		activecircle=0;
	}else if (activeTool == "text"){
		resetText();
	}else if (activeTool == "selenv"){
		UnselectSelectedByEnvAll();
		UnselectSelectedByAttributeAll();
		getAllMaps(true);
	}else{
		clickPointGKX.length=0;
		clickPointGKY.length=0;
		UnselectSelectedFeatures();
		getAllMaps(true);
	}
}
function UnselectSelectedFeatures(){
	intCntSelFeature=0;
	bufferinm=0;
	strPrtUserText="";
	selenvminx=0;
	selenvminy=0;
	selenvmaxx=0;
	selenvmaxy=0;
	UnselectSelectedByAttributeAll();
	UnselectSelectedByEnvAll();
	UnselectSelectedByBufferAll();
}

function UnselectSelectedByAttributeAll(){
	intCntSelFeature=0;
	for (var i=0;i<LayerID.length;i++) {
		LayerSelAttr[i]="";
	}
		
}
function UnselectSelectedByEnvAll(){
	arrSelObjectid.length=0;
	intCntSelFeature=0;
	for (var i=0;i<LayerID.length;i++) {
		LayerSelEnv[i]="";
	}	
}
function UnselectSelectedByBufferAll(){
	for (var i=0;i<LayerID.length;i++) {
		LayerSelBuffer[i]="";
	}	
}
function deleteClickPoint() {
	if (activeTool == "measure"){
		deactivateRubberband();
		if (clickdivlinex[clickdivlinex.length-1]==-1){
			clickmaplinex.pop();
			clickmapliney.pop();
			clickdivlinex.pop();
			clickdivliney.pop();
		}
		if (clickdivlinex.length>1){
			clickmaplinex.pop();
			clickmapliney.pop();
			clickdivlinex.pop();
			clickdivliney.pop();
		}
		lastclicklinex=clickdivlinex[clickdivlinex.length-1]
		lastclickliney=clickdivliney[clickdivliney.length-1]
		drawgraphics();
		updateMeasurebox();
		if (clickdivlinex.length>1){
			activateRubberband();
		}
	}else if (activeTool == "measurepoly"){
		deactivateRubberband();
		if (clickdivpolyx[clickdivpolyx.length-1]==-1){
			clickmappolyx.pop();
			clickmappolyy.pop();
			clickdivpolyx.pop();
			clickdivpolyy.pop();
		}
		if (clickdivpolyx.length>1){
			clickmappolyx.pop();
			clickmappolyy.pop();
			clickdivpolyx.pop();
			clickdivpolyy.pop();
		}
		lastclickpolyx=clickdivpolyx[clickdivpolyx.length-1]
		lastclickpolyy=clickdivpolyy[clickdivpolyy.length-1]
		drawgraphics();
		updateMeasurebox();
		if (clickdivpolyx.length>1){
			activateRubberband();
		}
	}else if (activeTool == "measurecircle"){
		if(clickPointCircleX.length>1){
			clickPointCircleX.pop();
			clickPointCircleY.pop();
			drawgraphics();
			activecircle=0;
		}else{
			resetClick();
		}
	}else if (activeTool == "text"){
		if (clickdivtextx.length>0){
			clickmaptextx.pop();
			clickmaptexty.pop();
			clickmaptext.pop();
			clickdivtextx.pop();
			clickdivtexty.pop();
		}
		drawgraphics();
	}else if (activeTool == "selenv"){
		if (LayerSelEnv[ActiveLayerIndex]!=""){
			var selenvtab=LayerSelEnv[ActiveLayerIndex].split("|");
			selenvtab.pop();
			LayerSelEnv[ActiveLayerIndex]="";
			if (selenvtab.length>0){
				LayerSelEnv[ActiveLayerIndex]=selenvtab.join("|");
			}
			getAllMaps(false,intActiveMapservice);
		}
	}
}
function clickAddPoint(e){
	if (mouseX>-1 && mouseY>-1) {
		if (!activate_rb){
			activateRubberband();
		}
		if (activeTool=="measure"){
			if (clickdivlinex.length==0){
				clickdivlinex[clickdivlinex.length]=-1;
				clickdivliney[clickdivliney.length]=-1;
				clickmaplinex[clickmaplinex.length]=-1;
				clickmapliney[clickmapliney.length]=-1;
			}
			clickdivlinex[clickdivlinex.length]=mouseX;
			clickdivliney[clickdivliney.length]=mouseY;
			lastclicklinex=mouseX;
			lastclickliney=mouseY;
			clickmaplinex[clickmaplinex.length]=mapX;
			clickmapliney[clickmapliney.length]=mapY;
			pl.drawRect((mouseX-1),(mouseY-1),3,3);
			if (clickdivlinex.length>2){
				var l=clickdivlinex.length;
				if (clickdivlinex[l-2]!=-1){
					pl.drawPolyline(clickdivlinex.slice(l-2,l),clickdivliney.slice(l-2,l));
					pl.paint();
					if (showLength){
						displayLength(pllb,clickdivlinex.slice(l-2,l),clickdivliney.slice(l-2,l),currentMeasure);
						pllb.paint();
					}
				}
			}
		
		}else if(activeTool=="measurepoly"){
			if (clickdivpolyx.length==0){
				clickdivpolyx[clickdivpolyx.length]=-1;
				clickdivpolyy[clickdivpolyy.length]=-1;
				clickmappolyx[clickmappolyx.length]=-1;
				clickmappolyy[clickmappolyy.length]=-1;
			}
			if (clickdivpolyx[clickdivpolyx.length-1]==-1){
				startclickx=mouseX;
				startclicky=mouseY;
				startclickmapx=mapX;
				startclickmapy=mapY;
			}
			clickdivpolyx[clickdivpolyx.length]=mouseX;
			clickdivpolyy[clickdivpolyy.length]=mouseY;
			lastclickpolyx=mouseX;
			lastclickpolyy=mouseY;
			lastclickmapx=mapX;
			lastclickmapy=mapY;
			clickmappolyx[clickmappolyx.length]=mapX;
			clickmappolyy[clickmappolyy.length]=mapY;
			pg.drawRect((mouseX-1),(mouseY-1),3,3);
			if (clickdivpolyx.length>2){
				var l=clickdivpolyx.length;
				if (clickdivpolyx[l-2]!=-1){
					pg.drawPolyline(clickdivpolyx.slice(l-2,l),clickdivpolyy.slice(l-2,l));
					pg.paint();
					if (showLength){
						displayLength(pglb,clickdivpolyx.slice(l-2,l),clickdivpolyy.slice(l-2,l),currentMeasure);
						pglb.paint();
					}
				}
			}

		}else if(activeTool=="measurecircle"){
			drawCircle(e);
		}else if(activeTool=="text"){
			clickmaptextx[clickmaptextx.length]=mapX;
			clickmaptexty[clickmaptexty.length]=mapY;
			clickdivtextx[clickdivtextx.length]=mouseX;
			clickdivtexty[clickdivtexty.length]=mouseY;
			clickmaptext[clickmaptext.length]=document.maptext.text.value;
			lbl.drawString2(clickmaptext[clickmaptext.length-1],clickdivtextx[clickdivtextx.length-1],clickdivtexty[clickdivtexty.length-1]);
			lbl.paint();

		}else{
		}
	}
	
}

function isValidPolygon(cpx,cpy)
{
	if (cpx.length < 3 || cpy.length < 3)
	{
		return false;
	}

	//anastasia slope list and y-intercept list
	var mList = new Array();
	var bList = new Array();
	var x1Line = new Array();
	var y1Line = new Array();
	var x2Line = new Array();
	var y2Line = new Array();
	mList.length=0;
	bList.length=0;
	x1Line.length=0;
	y1Line.length=0;
	x2Line.length=0;
	y2Line.length=0;

	for (var ix=1; ix < cpx.length; ix++)
	{
		lastPtX = cpx[ix-1];
		lastPtY = cpy[ix-1];
		currPtX = cpx[ix];
		currPtY = cpy[ix];
		var deltaY = currPtY - lastPtY;
		var deltaX = currPtX - lastPtX;
		var slope = parseFloat( eval(deltaY/deltaX) );
		if (lastPtX == currPtX)
			slope = 99999999999999999;
		var yintercept = parseFloat( eval(lastPtY - (slope*lastPtX)) );
		//alert("ix = " + ix + " Last Point=(" + lastPtX + "," + lastPtY +") Curr Point=(" + currPtX + "," + currPtY + ")\nSlope=" + slope + "Y Intercept= " + yintercept);
		mList[ix-1] = slope;
		bList[ix-1] = yintercept;
		x1Line[ix-1] = lastPtX ;
		y1Line[ix-1] = lastPtY ;
		x2Line[ix-1] = currPtX ;
		y2Line[ix-1] = currPtY ;
	}
	lastPtX = cpx[ cpx.length-1 ];
	lastPtY = cpy[ cpy.length-1 ];
	currPtX = cpx[0];
	currPtY = cpy[0];
	var deltaY = currPtY - lastPtY;
	var deltaX = currPtX - lastPtX;
	var slope = parseFloat( eval(deltaY/deltaX) );
	var yintercept = parseFloat( eval(lastPtY - (slope*lastPtX)) );
	mList[mList.length] = slope;
	bList[bList.length] = yintercept;
	x1Line[x1Line.length] = lastPtX ;
	y1Line[y1Line.length] = lastPtY ;
	x2Line[x2Line.length] = currPtX ;
	y2Line[y2Line.length] = currPtY ;
	//alert("Connecting to First Point, Last Point=(" + lastPtX + "," + lastPtY +") Curr Point=(" + currPtX + "," + currPtY + ")\nSlope=" + slope + "Y Intercept= " + yintercept);
	//alert("we will have " + mList.length + " lines and slopes to compare.");

	for (var ix=0; ix < mList.length; ix++)
	{
		for (var jx=ix+1; jx < mList.length; jx++)
		{ 
			if (ix == jx)   continue;
			if (ix+1 == jx) continue;
			if (ix == jx+1) continue;
			//alert("Comparing line " + ix + " with " + jx);
			var anX =  parseFloat( eval( (bList[jx]-bList[ix])/(mList[ix]-mList[jx]) ) );
			var intanX = Math.floor(anX);
			//alert (" calc x is " + intanX);
			//alert ("Point " + ix + ", Min of " + x1Line[ix] + " and " + x2Line[ix] + " is = " + Math.min( x1Line[ix], x2Line[ix]) );
			//alert ("Point " + jx + ", Min of " + x1Line[jx] + " and " + x2Line[jx] + " is = " + Math.min( x1Line[jx], x2Line[jx]) );
			var minLineFromX = Math.min( x1Line[ix], x2Line[ix]) ;
			var maxLineFromX = Math.max( x1Line[ix], x2Line[ix]) ;
			var minLineToX = Math.min( x1Line[jx], x2Line[jx]);
			var maxLineToX = Math.max( x1Line[jx], x2Line[jx]);
 
			if ( intanX > minLineFromX && intanX < maxLineFromX && intanX > minLineToX && intanX < maxLineToX )
			{
				writeProtokoll( "line number " + ix + " intersects with line " + jx);
				return false;
			}
						 
		}
	}

	return true;
}



function updateDragging(e){
	if (dragging) {
		x2=mouseX;
		y2=mouseY;
		//var inside = true;
		/*
		if (x2 < mleft) {
			x2 = mleft;
			//inside = false;
		}
		if (x2 >  mleft + mwidth ) {
			x2 = mleft + mwidth ;
			//inside = false;
		}
		if (y2 < mtop ) {
			y2 = mtop;
			//inside = false;	
		}
		if (y2 > mtop + mheight) {
			y2 = mtop +  mheight ;
			//inside = false;
		}
		*/
		setClip();
	}
	return false
}

function updateMapDragging(e) {
	if (panning) {
		x2 = mouseX;
		y2 = mouseY;
		/*
		if (x2 < mleft) x2 = mleft;
		if (x2 > mleft + mwidth) x2 = mleft + mwidth;
		if (y2 < mtop) y2 = mtop;
		if (y2 > mtop + mheight) y2 = mtop + mheight; 
		*/
		var dx = x2-x1;
		var dy = y2-y1;
				
		var cLeft = - dx;
		var cTop = - dy;
		var cRight = mwidth;
		var cBottom = mheight;
		if (dx>0) {
			cLeft = 0;
			cRight = mwidth - dx;
		}
		if (dy>0) {
			cTop = 0;
			cBottom = mheight - dy;
		}
				
		moveLayer(mapDivId,dx ,dy);
		panClipLayer(mapDivId,cLeft,cTop,cRight,cBottom);
		
	}
	return false;
}

function stopDragging(e){
	if (dragging){
		dragging = false;
		if (activeTool != "selenv"){
			var layer = document.getElementById("mapContainer");
	 		layer.onmousemove=null;
			layer.onmouseup = null;
			hideZoomBox();
			setClip();
			// adjust for offsets
			zoom(zmapminx,zmapminy,zmapmaxx,zmapmaxy);
		}else{
			if (getLayerVisibility(ActiveLayerIndex)){
				var layer = document.getElementById("mapContainer");
		 		layer.onmousemove = null;
				layer.onmouseup = null;
				hideZoomBox();
				var lbpoint = returnMapXY(zleft, zbottom);
				var rtpoint = returnMapXY(zright, ztop);
				bufferinm=0;
				
				setLayerinfoXY(ActiveLayerIndex,zmapminx,zmapminy,zmapmaxx,zmapmaxy);
				var axl = '<?xml version="1.0" encoding="UTF-8"?>';
				axl += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';
				axl += 'envelope="false" skipfeatures="false" beginrecord="0" featurelimit="' + intMaxFeaturInfo + '">\n'; 
				axl += '<LAYER id="' + LayerID[ActiveLayerIndex] + '"/>';
				axl += '<SPATIALQUERY>';
				axl += '<SPATIALFILTER relation="area_intersection" subfields="OBJECTID FID">';
				var env='<ENVELOPE minx="' + idMinX + '" maxx="' + idMaxX + '" miny="' + idMinY + '" maxy="' + idMaxY + '" />';
				env=replacePointByComma(env);
				axl += env;//'<ENVELOPE maxy="' + idMaxY + '" maxx="' + idMaxX + '" miny="' + idMinY + '" minx="' + idMinX + '" />';
				
				axl += '</SPATIALFILTER>';
				axl += '</SPATIALQUERY>';
				axl += '</GET_FEATURES>';
				axl += '</REQUEST>';
				axl += '</ARCXML>';
				var queryUrl = 	MsListUrl[LayerMS[ActiveLayerIndex]] + "&CustomService=Query";
				var deferred = dojo.rawXhrPost({
				url:    queryUrl,
				handleAs: "text",
				timeout: 3000,
				postData:axl,
				handle: function(response, ioArgs){
					var xx="";
					var cx="";
					var z1=true;
					var p1=this.postData.toUpperCase().indexOf("LAYERID=");
					if (p1<0){
						p1=this.postData.toUpperCase().indexOf("LAYER ID=");
						p1+=10;
					}else{
						p1+=9;
					}
					var p2=this.postData.indexOf(">",p1);
					var l=this.postData.substring(p1,p2-2);
					p1=this.url.search(/servicename=/i);
					p2=this.url.indexOf("&",p1);
					var sname=this.url.substring(p1+12,p2);
					var sid=getServiceIdByName(sname);
					var layeridx=getLayerIndexByServiceID(sid,l);
					
					if (response instanceof Error){
						if(response.dojoType == "cancel"){
							writeProtokoll("sendIdRequest.Canceled\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex])
						}else if(response.dojoType == "timeout"){
							writeProtokoll("sendIdRequest.TimeOut\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex]);
						}else{
							writeProtokoll("sendIdRequest.Error\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex]+"\n"+response);
						}
					}else{
						var arrTmp=new Array();
						var arrTmp2=new Array();
						var p3=response.search(/fields/i);
						var strObjectid="OBJECTID";
						if (response.search(/OBJECTID/i)<0){
							strObjectid="FID";
						}
						while (p3>-1){
							var cx="";
							var p4=response.indexOf("/>",p3)-2;
							var fieldlist = response.substring(p3+7,p4).split('" ');
							for (var h=0;h<fieldlist.length;h++) {
								var f2=fieldlist[h].split('="');
								if (strObjectid=="OBJECTID"){
									if (f2[0].search(/OBJECTID/i)>-1){
										arrTmp[arrTmp.length]=f2[1];
									}
								}else{
									if (f2[0].search(/FID/i)>-1){
										arrTmp[arrTmp.length]=f2[1];
									}
								}
							}
							p3=response.indexOf("FIELDS",p4);
						}
						var blnDrin=false
						for (var h=0;h<arrTmp.length;h++) {
							blnDrin=false;
							for (var k=0;k<arrSelObjectid.length;k++) {
								if (arrSelObjectid[k]==arrTmp[h]){
									blnDrin=true;
									arrSelObjectid[k]=-1;
								}
							}
							if (!blnDrin){
								arrTmp2[arrTmp2.length]=arrTmp[h];
							}
						}
						var arrTmp3 = arrSelObjectid.concat(arrTmp2);
						arrSelObjectid.length=0
						for (var k=0;k<arrTmp3.length;k++) {
							if (arrTmp3[k]>-1){
								arrSelObjectid[arrSelObjectid.length]=arrTmp3[k]
							}
						}
						LayerSelAttr[ActiveLayerIndex]=strObjectid+" IN ("+arrSelObjectid+")|";
						if (arrSelObjectid.length==0){
							LayerSelAttr[ActiveLayerIndex]="";
						}
						intActiveMapservice=LayerMS[ActiveLayerIndex];
						getAllMaps(false,intActiveMapservice);

						if (arrSelObjectid.length>0){
							if (wininfo && !wininfo.closed){
								wininfo.document.formflurstliste.frmfsliste.value="";
								wininfo.document.getElementById("divifr").innerHTML="";
								wininfo.document.getElementById("divinfo").innerHTML="";
							}else{
								openInfoWindow();
							}
							axl = '<?xml version="1.0" encoding="UTF-8"?>';
							axl += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES geometry="false" outputmode="xml" checkesc ="true" ';
							axl += 'envelope="true" skipfeatures="false" beginrecord="0" featurelimit="' + intMaxFeaturInfo + '">\n'; 
							axl += '<LAYER id="' + LayerID[ActiveLayerIndex] + '"/>';
							
							axl += '<QUERY subfields="#ALL#" where="'+LayerSelAttr[ActiveLayerIndex].substring(0,LayerSelAttr[ActiveLayerIndex].length-1)+'">';
							axl += '</QUERY>';
							axl += '</GET_FEATURES>';
							axl += '</REQUEST>';
							axl += '</ARCXML>';
							var queryUrl = 	MsListUrl[LayerMS[ActiveLayerIndex]] + "&CustomService=Query";
							var deferred = dojo.rawXhrPost({
								url:    queryUrl,
								handleAs: "text",
								timeout: 2000,
								postData:axl,
								handle: function(response, ioArgs){
									var xx="";
									var cx="";
									var z1=true;
									var p1=this.postData.toUpperCase().indexOf("LAYERID=");
									if (p1<0){
										p1=this.postData.toUpperCase().indexOf("LAYER ID=");
										p1+=10;
									}else{
										p1+=9;
									}
									var p2=this.postData.indexOf(">",p1);
									var l=this.postData.substring(p1,p2-2);
									p1=this.url.search(/servicename=/i);
									p2=this.url.indexOf("&",p1);
									var sname=this.url.substring(p1+12,p2);
									var sid=getServiceIdByName(sname);
									var layeridx=getLayerIndexByServiceID(sid,l);
									
									if (response instanceof Error){
										if(response.dojoType == "cancel"){
											writeProtokoll("sendIdRequest.Canceled\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex])
										}else if(response.dojoType == "timeout"){
											cx += "<table border='0' cellpadding='0' cellspacing='1' width='100%'>";
											cx += "<tr class='headerRow'>";
											cx += "<td  class='headerRow'>" + LayerAliasname[ActiveLayerIndex] + "</td>";
											cx += "</tr>";
											cx += "</table>";
											cx += "<div style='overflow:auto;border-width:1px;'>";
											cx += "<table width='100%' cellpadding='1' cellspacing='2'>";
											cx += "<colgroup><col width='40%'><col width='60%'></colgroup>";
											cx += "<Table><tr><td class='oddRow'>&nbsp;</td><td class='oddRow'>keine Daten erhalten (Zeit&uuml;berschreitung)</td></tr></table></div>";
											wininfo.document.getElementById("divinfo").innerHTML+=cx;
											cx="";
											writeProtokoll("sendIdRequest.TimeOut\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex]);
										}else{
											writeProtokoll("sendIdRequest.Error\n"+this.url+"\n"+LayerAliasname[ActiveLayerIndex]+"\n"+response);
										}
									}else{
										intCntSelFeature=0;
										wininfo.document.getElementById("divinfo").innerHTML="";
										setInfoTable(ActiveLayerIndex,response);
									}
									getxml++;
									
								}
							});
						}else{
							if (wininfo &&  !wininfo.closed){
								wininfo.close();
							}
						}
					}
				}
				});
				
				
			
			}
		}
		return false;
	}
}
function stopMapDragging(e){
	if (panning) {
		panning = false;
		var ixOffset = x1-mouseX;
		var iyOffset = mouseY-y1;
		pan(ixOffset, iyOffset);
		if (theButton!=cleftbutton){
			setActiveTool(activeTool);
		}
		return false;
	}
}

function resetAfterPan(){
	moveLayer(mapDivId,0,0);
	clipLayer2(mapDivId,0,0,mwidth,mheight);
	//document.getElementById('theImage0').onload = null;
}

function createLayer(name, inleft, intop, width, height, visible, content) {
	  var layer;
	    document.writeln('<div id="' + name + '" style="position:absolute; overflow:hidden; left:' + inleft + 'px; top:' + intop + 'px; width:' + width + 'px; height:' + height + 'px;' + ';z-index:2010;visibility:' + (visible ? 'visible;' : 'hidden;') +  '">');
	    document.writeln(content);
	    document.writeln('</div>');
}
function createMapContainer(name, content, itop, ileft, iwidth, iheight, border, mapclass, zindex){
 	if (zindex==null) 
		var zindex=99;
	if(!isIE){
		iwidth = iwidth - (2*border);
		iheight = iheight - (2*border);
	}
	document.writeln('<div id="' + name + '" class="' + mapclass + '" style="position:absolute; z-index:' + zindex + ';overflow:hidden; left:' + ileft + 'px; top:' + itop + 'px; width:' + iwidth + 'px; height:' + iheight + 'px;' + ';z-index:'+zindex+';visibility:hidden;border-width:' +border +'px;">');
	document.writeln(content);
	document.writeln('</div>');
}
function createTocContainer(name, content, itop, iright, iwidth, iheight, border, mapclass,zi){
	if(!isIE){
		iwidth = iwidth - (2*border);
		iheight = iheight - (2*border);
	}
	document.writeln('<div id="' + name + '" class="' + mapclass + '" style="position:absolute; overflow:scroll; right:' + iright + 'px; top:' + itop + 'px; width:' + iwidth + 'px; height:' + iheight + 'px;' + ';visibility:visible;border-width:' +border +'px;z-index:'+zi+'">');
	document.writeln(content);
	document.writeln('</div>');
}



function getDiv(name) {
	var theObj = document.getElementById(name);
	if (theObj!=null) {
		return theObj.style
	 }  else {
	    return(null);
	 }
}
		


function getXY(e) {
		theX=mouseX;
		theY=mouseY;
	
	/*
	if (!e) e=window.event;
	if (isIE) {
		theX=e.clientX + document.body.scrollLeft;
		theY=e.clientY + document.body.scrollTop;
	} else {
		theX=e.pageX;
		theY=e.pageY;
	}
	*/
	return false;
}
function showZoomBox(left, top, right, bottom){
	clipLayer("zoomboxTop",left,top,right,bottom);
	clipLayer("zoomboxLeft",left,top,right,bottom);
	clipLayer("zoomboxRight",left,top,right,bottom);
	clipLayer("zoomboxBottom",left,top,right,bottom);
	showLayer("zoomboxTop");
	showLayer("zoomboxLeft");
	showLayer("zoomboxRight");
	showLayer("zoomboxBottom");
	zmapminx=Math.round(mapX*1000)/1000;
	zmapminy=Math.round(mapY*1000)/1000;
}
function hideZoomBox(){
	writeProtokoll("hideZoomBox");
	window.scrollTo(0,0);
	hideLayer("zoomboxTop");
	hideLayer("zoomboxLeft");
	hideLayer("zoomboxRight");
	hideLayer("zoomboxBottom");
	zmapmaxx=Math.round(mapX*1000)/1000;
	zmapmaxy=Math.round(mapY*1000)/1000;
	var x;
	if (zmapmaxx<zmapminx){
		x=zmapmaxx;
		zmapmaxx=zmapminx;
		zmapminx=x;
	}
	if (zmapmaxy<zmapminy){
		x=zmapmaxy;
		zmapmaxy=zmapminy;
		zmapminy=x;
	}
}


function moveLayer(name, x, y) {		
  	var layer = getDiv(name);		
    layer.left = x + "px";
   	layer.top  = y + "px";
}


function setLayerBackgroundColor(name, color) {		
  	var layer = getDiv(name);		
	layer.backgroundColor = color;
}


function hideLayer(name) {
  	var layer = getDiv(name);
  	layer.visibility = "hidden";
}

function showLayer(name) {
  	var layer = getDiv(name);		
  	layer.visibility = "visible";
}


function clipLayer2(name, clipleft, cliptop, clipright, clipbottom) {		
	  var layer = getDiv(name);		
	  layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
}

function resizeLayer(name, clipleft, cliptop, clipwidth,clipheight) {		
	var layer = getDiv(name);
	layer.top	= cliptop  + "px";
	layer.left	= clipleft + "px";
	layer.height = clipheight + "px";
	layer.width	= clipwidth + "px";
}
function resizetoc() {		
	moveLayer("divTocContainer",mouseX ,mouseY);
//	var layer = getDiv("divTocContainer");
//	layer.left	= mouseX + "px";
//	layer.width	= clipwidth + "px";
}

function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {		
	  var layer = getDiv(name);
	  var newWidth = clipright - clipleft;
		var newHeight = clipbottom - cliptop;
		layer.height = newHeight;
		layer.width	= newWidth;
		layer.top	= cliptop  + "px";
		layer.left	= clipleft + "px";

}
function panClipLayer(name, clipleft, cliptop, clipright, clipbottom) {		
	var layer = getDiv(name);
	if (layer!=null) {
		layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	} 
	return false;
}
function setClip() {
	var inSize = 3;
	var lSize = parseInt(inSize) - 1;
	if (lSize < 1) lSize = 1;
	var tempX=x1;
	var tempY=y1;
	
	if (x1>x2) {
		zright=x1;
		zleft=x2;
	} else {
		zleft=x1;
		zright=x2;
	}
	if (y1>y2) {
		zbottom=y1;
		ztop=y2;
	} else {
		ztop=y1;
		zbottom=y2;
	}
	if ((x1 != x2) && (y1 != y2)) {
		clipLayer("zoomboxTop",zleft,ztop,zright,ztop+lSize);
		clipLayer("zoomboxLeft",zleft,ztop,zleft+lSize,zbottom);
		clipLayer("zoomboxRight",zright-lSize,ztop,zright,zbottom);
		clipLayer("zoomboxBottom",zleft,zbottom-lSize,zright,zbottom);
	}
	return false;
}

var isMoving = false;
var idx, idy;
var idLayer;

function startMove(e, divId) {
	if(activeTool == "measure" || activeTool == "measurepoly"){
		document.getElementById("mapContainer").onmousedown=null;
	}
	idLayer = document.getElementById(divId);
	isMoving = true;
	idx = mouseX - idLayer.offsetLeft;
	idy = mouseY - idLayer.offsetTop;
	document.getElementById("mapContainer").onmousemove = updateMove;
	document.getElementById("mapContainer").onmouseup = stopMove;
}
function startResizeEW(e, divId) {
	idLayer = document.getElementById(divId);
	isMoving = true;
	idx = mouseX - idLayer.offsetLeft;
	document.onmousemove = updateResizeEW;
	document.onmouseup = stopResizeEW;
}
function updateMove(e) {
	if(!isMoving || (idLayer == null)) return;
	idLayer.style.left = mouseX - idx;
	idLayer.style.top = mouseY - idy;
	if (idLayer.offsetLeft < 0)
		idLayer.style.left = 0;
	if (idLayer.offsetTop < 0)
		idLayer.style.top = 0;
}
function updateResizeEW(e) {
	if(!isMoving || (idLayer == null)) return;
	idLayer.style.width = width - mouseX;
	if (idLayer.offsetLeft < 0)
		idLayer.style.left = 0;
}
function stopMove() {
	if(activeTool == "measure" || activeTool == "measurepoly"){
		document.getElementById("mapContainer").onmousedown=pointClick;
	}
	if(!isMoving || (idLayer == null)) return;
	idLeft = idLayer.offsetLeft;
	idTop = idLayer.offsetTop;
	isMoving = false;
	idLayer = null;
	document.getElementById("mapContainer").onmousemove=setMouseXY;
	
}
function stopResizeEW() {
	if(!isMoving || (idLayer == null)) return;
	idLeft = idLayer.offsetLeft;
	var x = document.getElementById("divTocLeft");
	//x.left=idLayer.left;
	isMoving = false;
}
function setMouseXY(e) {
	mouseX=-1; 
	mouseY=-1;
	if (!e)
    	e = window.event;
	if (isIE){  
		mouseX=event.clientX + document.body.scrollLeft; 
		mouseY=event.clientY + document.body.scrollTop
	}else{
		mouseX=e.pageX; 
		mouseY=e.pageY;
	}
	// subtract offsets from page left and top
	mouseX = mouseX-left-1;
	mouseY = mouseY-top-1;
	mouseStuff();
	setTimeMousetip(intTimeleftMousetip);
}
function getMapXY(imageX,imageY){
	meterpropixelX = (maxx-minx) / mwidth;
	meterpropixelY = (maxy-miny) / mheight;
	mapX = meterpropixelX * mouseX + minx;
	var theY = mheight - mouseY;
	mapY = meterpropixelY * theY + miny;
}
function mouseStuff() {
	document.getElementById("tip").style.visibility="hidden";
	if (blnMouseover){
		getMapXY(mouseX,mouseY);
				
		var gkr= Math.round(mapX * 100)/100;
		var gkh= Math.round(mapY * 100)/100;
		
		if (gkr != "NaN" && gkh != "NaN") {
			var stat = "GK R " + gkr + "   H " + gkh;
			if (blnDebugOn){
				stat+= " (mouseX "+mouseX+" mouseY "+mouseY+";   ratioX "+Math.round(meterpropixelX*10000)/10000+" ratioY "+Math.round(meterpropixelY*10000)/10000+")";
			}
			window.status=stat;
			//document.zwischenspeicher.zp.innerText = String(mapX).substring(0,7)+ " " +String(mapY).substring(0,7);
		}
		if ((activeTool == "measure" || activeTool == "measurepoly"  || activeTool == "measurecircle")) {
			if (activate_rb){
				updateMeasurebox();
				drawRubberband();
			}
		}
	}
}
function setstatusnull(){
	window.status="";
}
function rettotalMeasure(xlist,ylist){
	var s=0;
	var t=0;
	for (var i=xlist.length-1; i >0 ; i--){
		t=calcDistance(xlist[i-1],ylist[i-1],xlist[i],ylist[i]);
		s+=t;
	}
	return s;
}



//MeasureArea return number of mapunits per scalebar unit
function invertUnits(sUnits,mUnits) { 
	var mDistance = 0; 
	if (mUnits == "FEET") { 
		if (sUnits=="MILES") { 
			mDistance = 5280; 
		} else if (sUnits == "METERS") { 
			mDistance = 3.280833; 
		} else if (sUnits == "KILOMETERS") { 
			mDistance = 3280.833; 
		} else if (sUnits == "FEET") { 
			mDistance = 1.0; 
		} 
	} else { //METERS 
		if (sUnits=="MILES") { 
			mDistance = 1609; 
		} else if (sUnits == "FEET") { 
			mDistance = 0.304800609601; 
		} else if (sUnits == "KILOMETERS") { 
			mDistance = 000304800609601; 
		} else if (sUnits == "METERS") { 
			mDistance = 1.0; 
		} 
	} 
	return mDistance; 
} 		
function updateMeasurebox(){
	currentMeasureP=0;
	if (activeTool == "measure" && clickmaplinex.length>0){
		var lmaplinex=new Array();
		var lmapliney=new Array();
		var x=true;
		var i=clickmaplinex.length-1;
		while (x){
			if (clickmaplinex[i]!=-1 && clickmapliney[i]!=-1){
				lmaplinex[lmaplinex.length]=clickmaplinex[i];
				lmapliney[lmapliney.length]=clickmapliney[i];
			}else{
				x=false;
			}
			i--;
			if (i<0){
				x=false;
			}
		}
		lmaplinex.unshift(mapX);
		lmapliney.unshift(mapY);
		totalMeasure=rettotalMeasure(lmaplinex,lmapliney);		
		currentMeasure = calcDistance(clickmaplinex[clickmaplinex.length-1],clickmapliney[clickmaplinex.length-1],mapX,mapY);
		currentMeasure=Math.round(currentMeasure*10)/10;
		document.dialogmsg.segment.value = " ca. "+String(currentMeasure) + " m";
		totalMeasure=Math.round(totalMeasure*10)/10;
		document.dialogmsg.gesamt.value = String(totalMeasure) +" m";
	}else if (activeTool == "measurepoly" && clickmappolyx.length>0) {
		currentMeasure = calcDistance(clickmappolyx[clickmappolyx.length-1],clickmappolyy[clickmappolyx.length-1],mapX,mapY);
		var workarea = 0;
		var lmappolyx=new Array();
		var lmappolyy=new Array();
		var dblMapX=mapX;
		var dblMapY=mapY;
		var x=true;
		var i=clickmappolyx.length-1;
		while (x){
			if (clickmappolyx[i]!=-1 && clickmappolyy[i]!=-1){
				lmappolyx[lmappolyx.length]=clickmappolyx[i];
				lmappolyy[lmappolyy.length]=clickmappolyy[i];
			}else{
				x=false;
			}
			i--;
			if (i<0){
				x=false;
			}
		}
		lmappolyx.reverse();
		lmappolyy.reverse();
		lmappolyx[lmappolyx.length]=dblMapX;
		lmappolyy[lmappolyy.length]=dblMapY;
		lmappolyx[lmappolyx.length]=lmappolyx[0];
		lmappolyy[lmappolyy.length]=lmappolyy[0];
		
		if (lmappolyx.length>2){
			document.dialogmsg.segment.value = " ca. "+String(currentMeasure) + " m";
			totalArea=rettotalArea(lmappolyx,lmappolyy);		
			document.dialogmsg.gesamt.value = " ca."+String(totalArea) +" m²";
				
		}
	}else if (activeTool == "measurecircle" && clickPointCircleX.length>activecircle) {
		currentMeasure = calcDistance(clickPointCircleX[activecircle],clickPointCircleY[activecircle],mapX,mapY);
		if (activate_rb){
			//divmsg.value = "Segment ca. " +currentMeasure + " m,  GesamtlÃ¤nge ca. " + parseInt((totalMeasure+currentMeasure)*10)/10 +" m";
			document.dialogmsg.segment.value = " ca. "+String(currentMeasure) + " m";
//			divmsg.gesa.value =parseInt((totalMeasure+currentMeasure)*10)/10 +" m";
		}	
	
	}else{
		//divmsg.value = "";
	}
}
function calcDistance(vX,vY,bX,bY) {
	// Note: decimal are not hard coded to allow use with locales using commas instead of points.
	var xD = Math.abs(vX - bX);
	var yD = Math.abs(vY - bY);
	var mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
	var u = Math.pow(10,1);
	var distance = parseInt(mDistance*u+(5/10))/u;
	return distance;
}
function rettotalArea(x,y){
	var xt=String(x).split(",");
	var yt=String(y).split(",");
	var total=0;
	var cai=xt.length-1;
	var xc=xt.length;
	var caj = 0;
	while (caj < xc) {
		xjyi = xt[caj] * yt[cai];
		xiyj = xt[cai] * yt[caj];
		xydiff = (xjyi - xiyj);
		total+=xydiff;
		cai = caj;
		caj++;  
	}
	total = total / 2 ;
	total = parseInt((total * 10) + 0.5) / 10;
	if (total < 0){
		total=total*-1;
	}
	return total;
}




