// setup test for Nav 4.0
var isIE = false;
var isNav = (navigator != null);
if (isNav) isNav = (navigator.appName.indexOf("Netscape")>=0);
var isNav4 = false;
var isIE4 = false;
var is5up = false;
var theBrowser = navigator.appVersion;
var fullDHTML = false;
var mouseX;
var mouseY;

var selectingBox=false;
var selectBoxX = 0;
var selectBoxY = 0;
var selectBoxX1 = 0;
var selectBoxY1 = 0;
var moveBoxX = 0;
var moveBoxY = 0;
var objectOffsetX = 0;
var objectOffsetY = 0;
var centerX = 0;
var centerY = 0;
var cDiv = 2;
var selectBox = new Array();
var moveBox = new Array();
var ACTION_MODE_NONE = 0;
var ACTION_MODE_SELECTBOX = 1;
var ACTION_MODE_MOVE = 2;
var ACTION_MODE_POINT = 3;
var ACTION_MODE_MEASURING = 4;
var ACTION_MODE_COORD_INFO = 5;
var ACTION_MODE_SELECTPOLYGON = 6;

var DEFAULT_MAIN_MAP_LAYER_NAME = 'mainMapLayer';
var DEFAULT_MAIN_MAP_CLICK_LAYER_NAME = 'mainMapClickLayer';

var activeToolbarModeImage = "";
var activeToolbarMode = "jsp.components.statusmessage.notoolselected";

var measuringActive = new Array();
var measuringNorthWidthLength = new Array();
var measuringSouthWidthLength = new Array();
var measuringHeightLength = new Array();
var measuringImageWidth = new Array();
var measuringImageHeight = new Array();
var measuringX = new Array();
var measuringY = new Array();
var measuringXPrev = new Array();
var measuringYPrev = new Array();
var measuringLastDistance = new Array();
var measuringTotalDistance = new Array();
var measuringUnit = new Array();

var measuringJsGraphics = new Array();

var selectPolygonActive = new Array();
var selectPolygonJsGraphics = new Array();

var selectPolygonisFirstSet = new Array();
var selectPolygonXFirst = new Array();
var selectPolygonYFirst = new Array();
var selectPolygonYCoords = new Array();

var measuringTotalText;
var measuringSegmentText;
var measuringCurrentSegmentText;

var m_xScale = 0.0;
var m_yScale = 0.0;

var m_minX = 0.0;
var m_maxY = 0.0;
var toolBarModesLanguageArray = new Array();
xMousePos = 0;
yMousePos = 0;
xImagePos = 0;
yImagePos = 0;
isDebug = false;
sliderWasActive=false;
sliderInAction=false;
currentInstNr = -1;

var toolBarModesArray = new Array(
        "jsp.components.statusmessage.notoolselected",
        "zoomIn",
        "zoomOut",
        "zoomInAtRect",
        "zoomOutAtRect",
        "selectAtRect",
        "selectAtPolygon",
        "centeredPan",
        "freehandPan",
        "coordInfo",
        "distanceMeasuring",
        "dataSearch",
        "selectRouteStartPoint",
        "selectRouteEndPoint");

if (isNav) {
  if (parseFloat(navigator.appVersion)<5) {
    isNav4=true;
  } else {
    is5up = true;
  }
} else {
  isIE4=true;
  isIE=true;
  if ((navigator.appVersion.indexOf("MSIE 5")>0) || (navigator.appVersion.indexOf("MSIE 6")>0) || (navigator.appVersion.indexOf("MSIE 7")>0)) {
    isIE4 = false;
    is5up = true;
  }
}

if ((theBrowser.indexOf("MSIE 5")!=-1) || (theBrowser.indexOf("MSIE 6")!=-1) || (theBrowser.indexOf("MSIE 7")!=-1) ||
    (theBrowser=="Netscape")) fullDHTML = true;

function setCoordValues(xScale,yScale,minX,maxY) {
    m_xScale = xScale;
    m_yScale = yScale;

    m_minX = minX;
    m_maxY = maxY;
}

function showCoord(x,y) {
    var xCoord = (x * m_xScale) + m_minX;
    var yCoord = (-y * m_yScale) + m_maxY;
    window.status = xCoord +" / "+yCoord;
}

function mouseMovedToCoord() {
    getImageXY();
    showCoord(mouseX,mouseY);
}

function dualClick(instNr){
   getImageXY();
   myParentForm=getParentForm(instNr);
   if (myParentForm != null) {
       paramsToAdd = '&x=' + mouseX + '&y=' + mouseY;
       myParentForm.action = myParentForm.action + paramsToAdd;
       myParentForm.submit();
   }
}

function quadClick(instNr){
    getImageXY();
    myParentForm=getParentForm(instNr);
    if (myParentForm != null) {
      paramsToAdd = '&x1=' + mouseX + '&y1=' + mouseY +
                    '&x2=' + mouseX + '&y2=' + mouseY;
      myParentForm.action = myParentForm.action + paramsToAdd;

      myParentForm.submit();
    }
}



/**
 * This function generates the main map layer name depending on the instance number
 */
function getMainMapLayerName(instNr) {
  return DEFAULT_MAIN_MAP_LAYER_NAME+instNr;
}

/**
 * Die Methode erstellt einen DHTML-Layer.
 * @param name      Name des Layers
 * @param left      Startkoordinate links
 * @param top       Startkoordinate oben
 * @param width     Breite des Layers
 * @param height    H\u00f6he des Layers
 * @param visible   TRUE, wenn der Layer sichtbar sein soll
 * @param bgColor   Hintergrundfarbe des Layers
 * @param index     Index des Layers (nur IE)
 * @param font      Name der Schrift-Familie
 * @param fontSize  Schriftgr\u00f6\u00dfe
 * @param content   HTML, das innerhalb des Layers erstellt werden soll
 */

function createBox(name,left,top,width,height,visible,bgColor,index,font,fontSize,content) {
  if (isNav4) {
    document.writeln('<layer name="' + name + '" left=' + left + ' top=' + top +
                      ' width=' + width + ' height=' + height +
                      ' visibility=' + (visible ? '"show"' : '"hide"') +
                      ' bgcolor=' + bgColor + '>');
    document.writeln('<span style="font-family:' + font + ';font-size:' + fontSize + 'px>');
    document.writeln(content);
    document.writeln('</span></layer>');
  } else {
    document.writeln('<div id="' + name + '" style="position:absolute; overflow:hidden; width:' +
      width + 'px; height:' + height + 'px;' + ' visibility:' +
          (visible ? 'visible;' : 'hidden;') +  'z-index:' + index + ';font-family:' +
          font + ';font-size:' + fontSize + 'px;background-color:' + bgColor +
          '; top:' + top + 'px; left:' + left + 'px;">');
    document.writeln(content);
    document.writeln('</div>');
  }
}



/**
 * Gibt das Layer- Objekt mit dem Namen "name" zur\u00fcck
 * @param name      Name des Layers, der zur\u00fcckgegeben werden soll
 * @return          Layer- Objekt mit dem Namen "name" oder NULL
 */


function getLayer(name) {
  if (isNav4)
    return(document.layers[name]);
  else {
    if (isIE4) {
      layer = eval('document.all.' + name + '.style');
      return(layer);
    } else {
      if (is5up) {
        var theObj = document.getElementById(name);
        if (theObj != null) return theObj.style;
        else return(null);
      }
      else  return(null);
    }
  }
}




function getEle(id) {
  var ele;
   if (isNav4) {
     ele = document.layers[id];
   } else if (isIE) {
     ele = document.all[id];
   } else {
     ele = document.getElementById(id);
   }
   return ele;
}


/**
 * Die Funktion setzt den Layer mit dem Namen "name" auf unsichtbar
 * @param name      Name des Layers
 */
function hideLayer(name) {
  var layer = getLayer(name);
  if (isNav4)
    layer.visibility = "hide";
  else
    layer.visibility = "hidden";
}



/**
 * Die Funktion setzt den Layer mit dem Namen "name" auf sichtbar
 * @param name      Name des Layers
 */

function showLayer(name) {
  var layer = getLayer(name);
  if (isNav4)
    layer.visibility = "show";
  else
    layer.visibility = "visible";
}



/**
 * Die Funktion gibt TRUE zur\u00fcck, wenn der Layer Layer mit dem Namen "name"
 * unsichtbar ist.
 * @param name      Name des Layers
 * @return TRUE, wenn der Layer unsichtbar ist
 */

function isHideLayer(name) {
  var layer = getLayer(name);
  if (layer == null) return false;
  if (isNav4)	return(layer.visibility == "hide");
  else return(layer.visibility == "hidden");
  return false;
}



/**
 * Die Funktion setzt das Attribute "visible" des Layers mit dem Namen "name"
 * auf "visible" bzw. "hide". (Umschaltfunktion)
 * @param name  Name des Layers
 */

function toggleLayer(name) {
  if (isHideLayer(name))
    showLayer(name);
  else
    hideLayer(name);
}



/**
 * Die Funktion verschiebt den Layer mit dem Namen "name" auf
 * die \u00fcbergebene Position.
 * @param name    Name des Layers
 * @param x       X-Koord. (links oben) der neuen Position
 * @param y       Y-Koord. (links oben) der neuen Position
 */

function moveLayer(name, x, y) {
  var layer = getLayer(name);
  if (isNav4)
    layer.moveTo(x, y);
  else {
    layer.left = x + "px";
    layer.top  = y + "px";
  }
}



/**
 * Die Funktion speichert die akt. Position des Mauszeigers in
 * mouseX und mouseY ab.
 */

function getImageXY() {
	mouseX=xImagePos;
	mouseY=yImagePos;
}



/**
 * Die Funktion speichert die akt. Position des Mauszeigers in
 * mouseX und mouseY ab.
 */

function getAbsoluteImageXY() {
	mouseX=xMousePos;
	mouseY=yMousePos;
}

function getInstanceNumberFromElementName(name) {
	var instNr = -1;

	if ( name && name.substr(0,10)=="clickImage" ) {
		var inst=name.substr(10,name.length - 10);
		instNr = parseInt(inst);
	}
	return instNr;
}


// function to handle the mouseDown events.

function startMouseMove(e) {
	var eventObj=(window.event)?  window.event.srcElement : e.target;

	currentInstNr = getInstanceNumberFromElementName(eventObj.name);

	if( currentInstNr >= 0 )
	{
		if (activeToolbarMode=="zoomInAtRect" || activeToolbarMode=="zoomOutAtRect" || activeToolbarMode=="selectAtRect" )
		{
			startSelectBox(currentInstNr);
		}
		else if (activeToolbarMode=="freehandPan")
		{
			startMoveBox(currentInstNr);
		}
		return false;
	}
	else if(eventObj.name && eventObj.name=="sliderBand")
	{
		startSlider();
		return false;
	}
	return true;
}


// function to handle the mouseUp events.

function stopMouseMove(e, onSubmit) {
	if( currentInstNr >= 0 )
	{
		var isMoveBox = moveBox[currentInstNr];
		if ( isMoveBox != null ) {
			if ( isMoveBox ) {
				if (onSubmitFunction!=null)
					stopMoveBox(currentInstNr,onSubmitFunction);
				else
					stopMoveBox(currentInstNr,onSubmit);
			}
		}
		var isSelectBox = selectBox[currentInstNr];
		if (isSelectBox != null) {
			if ( isSelectBox ) {
				if (onSubmitFunction!=null)
					stopSelectBox(currentInstNr,onSubmitFunction);
				else
					stopSelectBox(currentInstNr,onSubmit);
			}
		}
		currentInstNr = -1;
		return false;
	}
	if ( sliderInAction || sliderWasActive) {
		stopSlider();
		return false;
	}
	return true;
}

/*
 * Function to handle mouse moves within none Microsoft Browser
 * Drag and Drop events are Windows IE5+ only methods!!!!
 */

function captureMouseMove(e) {
	var eventObj;
	if (document.layers) {
		eventObj=e.target;

		xMousePos = e.screenX;
		yMousePos = e.screenY;
		xImagePos = e.layerX;
		yImagePos = e.layerY;
	} else if (document.all) {
		eventObj = window.event.srcElement;

		xMousePos = window.event.clientX;
		yMousePos = window.event.clientY;
		if ( document.body.scrollLeft )
			xMousePos += document.body.scrollLeft;
		if ( document.body.scrollLeft )
			yMousePos += document.body.scrollTop;
		xImagePos = window.event.offsetX;
		yImagePos = window.event.offsetY;
	} else if (document.getElementById) {
		eventObj=e.target;

		xMousePos = e.screenX;
		yMousePos = e.screenY;
		xImagePos = e.layerX;
		yImagePos = e.layerY;
	}

	// Check, if we moved the mouse out of the slider
	if( eventObj.name) {
		if ( eventObj.name=="sliderZoomContainer" || eventObj.name=="sliderBand" ) {
			resumeSlider();
		} else {
			waitSlider();
			// Check if an action is active and if the mouse is still over our image
			if (currentInstNr >= 0 && getInstanceNumberFromElementName( eventObj.name ) >= 0) {
				var isMoveBox = moveBox[currentInstNr];
				if ( isMoveBox != null ) {
					if ( isMoveBox ) {
						moveTheBox(currentInstNr);
						return false;
					}
				}
				var isSelectBox = selectBox[currentInstNr];
				if (isSelectBox != null) {
					if ( isSelectBox ) {
						drawSelectBox(currentInstNr);
						return false;
					}
				}
			}
		}
	} else {
		waitSlider();
	}
	if ( sliderInAction ) {
		moveSlider();
		return false;
	}
	return true;
}



/**
 * Die Funktion startet die Anzeige der Selectbox
 */

function startSelectBox(instNr) {
  var isSelectBox = selectBox[instNr];
  if (isSelectBox == null) {
    selectBox[instNr] = false;
    isSelectBox = false;
  }
  if (isSelectBox) {
    stopSelectBox(instNr);
  } else {
    getImageXY();
    selectBoxX = mouseX;// - cDiv;
    selectBoxY = mouseY;// - cDiv;
    moveLayer("zoomSelectBox"+instNr,selectBoxX,selectBoxY);
    selectBox[instNr] = true;
    drawSelectBox(instNr);
    showLayer("zoomSelectBox"+instNr);
    if ( isDebug ) window.status = "Inst[" + instNr + "]: Start zooming";
  }
}



/**
 * Die Funktion stoppt die Anzeige der Selectbox.
 * Ist die Variable boxEvent (Name des zu sendenden Formulares) definiert,
 * so werden die Koordinaten der Selectbox (x1,y1,x2,y2) an die Action angeh\u00e4ngt
 * und das Formular wird per SUBMIT gesendet.
 * @param onSubmit optionaler Parameter: Funktion, die vor dem Abschicken
 *                 des Formulars ausgef\u00fchrt werden soll
 */

function stopSelectBox(instNr, onSubmit)
{
  hideLayer("zoomSelectBox"+instNr);
  selectBox[instNr] = false;
  if ( isDebug) window.status = "Inst[" + instNr + "]: Stopped zooming";
  var layer = getLayer("zoomSelectBox"+instNr);
  selectBoxX = parseInt(layer.left);
  selectBoxY = parseInt(layer.top);
  selectBoxX1 = selectBoxX + parseInt(layer.width);
  selectBoxY1 = selectBoxY + parseInt(layer.height);

  myParentForm=getParentForm(instNr);

  if(myParentForm != null && eval(onSubmit) != false)
  {
    paramsToAdd = '&x1=' + selectBoxX + '&y1=' + selectBoxY +
                  '&x2=' + selectBoxX1 + '&y2=' + selectBoxY1;
    myParentForm.action = myParentForm.action + paramsToAdd;
    myParentForm.submit();
  }
}



/**
 * Die Funktion zeichnet die Selectbox anhand der aktuellen Koord. des Cursor
 */

function drawSelectBox(instNr) {
  var isSelectBox = selectBox[instNr];
    if (isSelectBox == null) {
      selectBox[instNr] = false;
      isSelectBox = false;
      zooming = false;
    }
    if (isSelectBox) {
      var layer = getLayer("zoomSelectBox"+instNr);
      getImageXY();

      var width=0;
      var height=0;

      if (mouseX < selectBoxX) {
        layer.left = mouseX + cDiv+"px";
        width = selectBoxX - mouseX - cDiv;
      } else {
        layer.left = selectBoxX+"px";
    	width = mouseX - selectBoxX - cDiv;
      }
      if (mouseY < selectBoxY) {
        layer.top = mouseY + cDiv+"px";
        height = selectBoxY - mouseY - cDiv;
      } else {
        layer.top = selectBoxY+"px";
    	height = mouseY - selectBoxY - cDiv;
      }
      if ( height < 0 ) height = 0;
      if ( width < 0 ) width = 0;
      layer.height = height+'px';
      layer.width = width+'px';
      if ( isDebug ) window.status = "Inst[" + instNr + "]: " + width + " / " + height;
    }
}


function startMoveBox(instNr) {
  var isMoveBox = moveBox[instNr];
  if (isMoveBox == null) {
    isMoveBox = false;
    moveBox[instNr] = false;
  }
  if (isMoveBox) {
    stopMoveBox(instNr);
  } else {
    var layer = getEle(getMainMapLayerName(instNr));
    var objX=layer.style.left;
    var objY=layer.style.top;
    moveBox[instNr] = true;
    isMoving = true;
    getAbsoluteImageXY();

    centerX = parseInt(layer.style.left) + (parseInt(layer.style.width) / 2);
    centerY = parseInt(layer.style.top) + (parseInt(layer.style.height) / 2);

    // Needed to recalculate left and top of the layer
    objectOffsetX=mouseX - parseInt(objX); // .substr(0, objX.length-2);
    objectOffsetY=mouseY - parseInt(objY); // .substr(0, objY.length-2);

    moveBoxX = mouseX;
    moveBoxY = mouseY;
    moveBox[instNr] = true;

    if ( isDebug ) window.status = "Inst[" + instNr + "]: Start moving";
  }
}



/**
 * Die Funktion verschiebt den Layers der Hauptkarte anhand der akt. Cursorpos.
 */

function moveTheBox(instNr) {
  var isMoveBox = moveBox[instNr];
  if (isMoveBox == null) {
    isMoveBox = false;
    moveBox[instNr] = false;
  }
  if (isMoveBox) {
    getAbsoluteImageXY();
    moveLayer(getMainMapLayerName(instNr), (mouseX - objectOffsetX),(mouseY - objectOffsetY));
    if ( isDebug ) {
      var mapLayer = getEle(getMainMapLayerName(instNr));
      window.status = "Inst[" + instNr + "]: " + mapLayer.style.left + " / " + mapLayer.style.top;
    }
  }
}



/**
 * Die Funktion stoppt das Verschieben des Layers der Hauptkarte.
 * Ist die Variable boxEvent (Name des zu sendenden Formulares) definiert,
 * so werden die Koordinaten des  Mittelpunktes des Layers der Hauptkarte (x,y)
 * an die Action angeh\u00e4ngt und das Formular wird per SUBMIT gesendet.
 * @param onSubmit optionaler Parameter: Funktion, die vor dem Abschicken
 *                 des Formulars ausgef\u00fchrt werden soll
 */

function stopMoveBox(instNr, onSubmitt)
{
  moveBox[instNr] = false;
  var layer = getEle(getMainMapLayerName(instNr));
  if ( isDebug ) window.status = "Inst[" + instNr + "]: Stopped moving";
  dx = parseInt(layer.style.left) + (parseInt(layer.style.width) / 2) - centerX;
  dy = parseInt(layer.style.top) + (parseInt(layer.style.height) / 2) - centerY;
  newCenterX = centerX - dx;
  newCenterY = centerY - dy;
  myParentForm=getParentForm(instNr);

  if(myParentForm != null && eval(onSubmitt) != false)
  {
    paramsToAdd = '&x=' + newCenterX.toFixed(0) + '&y=' + newCenterY.toFixed(0);
    paramsToAdd = '&x1='+moveBoxX+'&y1='+moveBoxY+'&x2='+mouseX+'&y2='+mouseY;
    myParentForm.action = myParentForm.action + paramsToAdd;
    myParentForm.submit();
  }
}


/**
 * this function marks a selected Point
 */
function measuringDrawSelectionPoint(instNr, X, Y) {
 measuringJsGraphics[instNr].drawEllipse(X-1, Y-1, 2, 2);
 measuringJsGraphics[instNr].paint();
}



/**
 *
 */

function computeMeasuringDistance(instNr, X1, Y1, X2, Y2) {
    // +1 because we measure from Pixel to Pixel (only if pixels are different)!!!
    xDelta = Math.abs(X1 - X2)+(X1 != X2 ? 1 : 0);
    yDelta = Math.abs(Y1 - Y2)+(Y1 != Y2 ? 1 : 0);

    measuringYmiddle = (Y1 + Y2)/2;
    measuringImageHeightProcent = Math.round(measuringYmiddle/measuringImageHeight[instNr]*100)/100; // format #0,##

    measuringWidthLength = measuringNorthWidthLength[instNr] + measuringImageHeightProcent*(measuringSouthWidthLength[instNr]-measuringNorthWidthLength[instNr]);

    xLength = xDelta*measuringWidthLength/measuringImageWidth[instNr];
    yLength = yDelta*measuringHeightLength[instNr]/measuringImageHeight[instNr];

    //setMeasuringMessage(X2+'/'+Y2+' -> '+X1+'/'+Y1+' xLength='+xLength+' yLength='+yLength+' measuringYmiddle='+measuringYmiddle+' measuringImageHeightProcent='+measuringImageHeightProcent+' measuringWidthLength='+measuringWidthLength);
    return Math.sqrt(xLength*xLength+yLength*yLength);
}



/**
 * This function handles the distance masuring to a new selected point.
 * It computes the new last and total distance an draw a line form
 * the last selected point to the new one.
 */

function measuringToNextPoint(instNr, X, Y) {
    if (measuringX[instNr] != measuringXPrev[instNr] || measuringY[instNr] != measuringYPrev[instNr]) {
      measuringXPrev[instNr] = measuringX[instNr];
      measuringYPrev[instNr] = measuringY[instNr];
      measuringX[instNr] = X;
      measuringY[instNr] = Y;

      measuringLastDistance[instNr] = computeMeasuringDistance(instNr, measuringX[instNr], measuringY[instNr], measuringXPrev[instNr], measuringYPrev[instNr]);
      measuringTotalDistance[instNr] += measuringLastDistance[instNr];
      setMeasuringMessage(measuringTotalText+roundWithDecimalPlaces(measuringTotalDistance[instNr], 3)+measuringUnit[instNr]+' '+measuringSegmentText+roundWithDecimalPlaces(measuringLastDistance[instNr], 3)+measuringUnit[instNr]);

      measuringJsGraphics[instNr].drawLine(measuringX[instNr], measuringY[instNr], measuringXPrev[instNr], measuringYPrev[instNr]);
    }
}

/**
 * This function start or continues distance measuring on the main map layer
 */
function startContinueMeasuring(instNr) {


  getImageXY();

  if (measuringActive[instNr]) {
    measuringToNextPoint(instNr, mouseX, mouseY);
  }
  else {
  	measuringJsGraphics[instNr] = new jsGraphics(getMainMapLayerName(instNr));
  	measuringJsGraphics[instNr].setColor('#ff0080');

    measuringX[instNr] = mouseX;
    measuringY[instNr] = mouseY;
    measuringXPrev[instNr] = 0;
    measuringYPrev[instNr] = 0;
    measuringLastDistance[instNr] = 0;
    measuringTotalDistance[instNr] = 0;

    //setMeasuringMessage('instance['+instNr+'] starting distance measuring '+measuringX[instNr]+'/'+measuringY[instNr]);
    measuringActive[instNr] = true;
    measuringJsGraphics[instNr].clear();
    setMeasuringMessage(' ');
  }

  measuringDrawSelectionPoint(instNr, mouseX, mouseY);

  return true;
}

/**
 * This function displays distance measuring if mouse moves over the main map layer
 */
function mouseMovedForMeasuring(instNr) {
  getImageXY();

  //setMeasuringCoord(' measuringNorthWidthLength='+measuringNorthWidthLength+' measuringSouthWidthLength='+measuringSouthWidthLength+' measuringHeightLength='+measuringHeightLength+' '+measuringImageWidth+';'+measuringImageHeight+' '+mouseX+'/'+mouseY);
  if (measuringActive[instNr]) {
    measuringLength = computeMeasuringDistance(instNr, mouseX, mouseY, measuringX[instNr], measuringY[instNr]);

    //setMeasuringCoord(measuringCurrentSegmentText+measuringLength+' '+mouseX+'/'+mouseY+' '+mainMapLayer.className+' '+mainMapLayer.tagName+' '+mainMapLayer.offsetTop+'/'+mainMapLayer.offsetLeft+' z='+mainMapLayer.style.zIndex);
    setMeasuringCoord(measuringCurrentSegmentText+roundWithDecimalPlaces(measuringLength, 3)+measuringUnit[instNr]);
  }
  else {
    setMeasuringCoord(' ');
  }
  //window.status = mouseX +" / "+mouseY;

  return true;
}

/**
 * This function stops distance measuring on the main map layer
 */
function stoppingMeasuring(instNr) {
  measuringActive[instNr] = false;

  getImageXY();

  //measuringToNextPoint(instNr, mouseX, mouseY);

  alert(measuringTotalText+roundWithDecimalPlaces(measuringTotalDistance[instNr], 3)+measuringUnit[instNr]);

  measuringX[instNr] = 0;
  measuringY[instNr] = 0;
  measuringXPrev[instNr] = 0;
  measuringYPrev[instNr] = 0;
  measuringLastDistance[instNr] = 0;
  measuringTotalDistance[instNr] = 0;

  measuringJsGraphics[instNr].clear();
  setMeasuringMessage(' ');

  return false;
}

/**
 * this function marks a selected Point
 */
function selectPolygonDrawSelectionPoint(instNr, X, Y) {
 selectPolygonJsGraphics[instNr].drawEllipse(X-1, Y-1, 2, 2);
 selectPolygonJsGraphics[instNr].paint();
}

/**
 * This function handles the distance masuring to a new selected point.
 * It computes the new last and total distance an draw a line form
 * the last selected point to the new one.
 */
function selectPolygonToNextPoint(instNr, X, Y) {
    measuringXPrev[instNr] = measuringX[instNr];
    measuringYPrev[instNr] = measuringY[instNr];

    measuringX[instNr] = X;
    measuringY[instNr] = Y;

    if (!(measuringXPrev[instNr]==-10000)) {
      selectPolygonJsGraphics[instNr].drawLine(measuringX[instNr], measuringY[instNr],
                                             measuringXPrev[instNr], measuringYPrev[instNr]);
    }
    selectPolygonDrawSelectionPoint(instNr, X, Y);
}


/**
 * This function start or continues distance measuring on the main map layer
 */
function startContinueSelectPolygon(instNr) {
  getImageXY();

  if (!selectPolygonActive[instNr]) {
    selectPolygonJsGraphics[instNr] = new jsGraphics(getMainMapLayerName(instNr));
    selectPolygonJsGraphics[instNr].setColor('#ff0080');

    measuringX[instNr] = -10000;
    measuringY[instNr] = -10000;
    measuringXPrev[instNr] = -10000;
    measuringYPrev[instNr] = -10000;

    selectPolygonActive[instNr] = true;
    selectPolygonJsGraphics[instNr].clear();
  }
  selectPolygonToNextPoint(instNr, mouseX, mouseY);

  if (!selectPolygonisFirstSet[instNr]){
  	selectPolygonisFirstSet[instNr] = true;
  	selectPolygonXFirst[instNr] = mouseX;
    selectPolygonYFirst[instNr] = mouseY;
    selectPolygonYCoords[instNr]="";
  }
  selectPolygonYCoords[instNr] = selectPolygonYCoords[instNr]+mouseX+","+mouseY+",";
//  window.status = selectPolygonYCoords[instNr];


  return true;
}

/**
 * This function stops distance measuring on the main map layer
 */
function stoppingSelectPolygon(instNr) {
  getImageXY();

  selectPolygonYCoords[instNr] = selectPolygonYCoords[instNr]+selectPolygonXFirst[instNr]+","+selectPolygonYFirst[instNr];

  selectPolygonToNextPoint(instNr, selectPolygonXFirst[instNr], selectPolygonYFirst[instNr]);
  selectPolygonDrawSelectionPoint(instNr, mouseX, mouseY);

  selectPolygonActive[instNr] = false;

  measuringX[instNr] = 0;
  measuringY[instNr] = 0;
  measuringXPrev[instNr] = 0;
  measuringYPrev[instNr] = 0;

  selectPolygonisFirstSet[instNr]=false;
  selectPolygonXFirst[instNr] = 0;
  selectPolygonYFirst[instNr] = 0;
  myParentForm=getParentForm(instNr);

  if (myParentForm != null) {
       myParentForm.action = myParentForm.action + "&tuples=\""+selectPolygonYCoords[instNr]+"\"";
       myParentForm.submit();
  }


  selectPolygonYCoords[instNr]="";

  return false;
}


function roundWithDecimalPlaces(value, decimalPlaces) {
  tenPowdecimalPlaces = Math.pow(10, decimalPlaces);

  newValue = Math.round(value * tenPowdecimalPlaces) / tenPowdecimalPlaces;

  return newValue;
}

/**
 * This function changes the distance measuring info message
 */
function setMeasuringMessage(message) {
  if (document.getElementById('measuringInfoSpan')!=null)
  	document.getElementById('measuringInfoSpan').firstChild.nodeValue=message;

  return true;
}

/**
 * This function changes the distance measuring coordinates
 */
function setMeasuringCoord(message) {
  if (document.getElementById('measuringInfoSpan')!=null)
  	document.getElementById('measuringCoordSpan').firstChild.nodeValue=message;

  return true;
}

/**
 * This function shows the clicked Coordinates in a popup-window
 * @param instNr instance Number
 */
function showCoordInfo(caller,instNr)
{
  getImageXY();
  windowname='PegaView2ShowCoord'+instNr;
  destination='coordTransform.do';
  paramsToAdd='?caller='+caller+'&instanceNumber='+instNr+'&x=' + mouseX + '&y=' + mouseY;
  window.open(destination+paramsToAdd,
              windowname,
              'width=200,height=100,resizable=yes,scrollbars=yes,left=0,top=0,status=false,toolbar=false,menuebar=false');
}



/**
 * This function gets the index of the given Array that equals with
 * the given string
 * @param toolname The toolname that is searched
 * @param toolArray The Array in witch searched
 * @return the index of the Array if found otherwise 0
 */
function getIndexOfArray(toolname,toolArray) {
	for(var i=0;i<toolArray.length;i++) {
		if (toolname == toolArray[i]){
			return i;
		}
	}
	return 0;
}

function getParentForm(instNr) {
    if ( isIE ) {
        return eval("document.all.mainMapForm"+instNr);
    } else {
        return eval("document.getElementById('mainMapForm"+instNr + "')");
    }
}


function createLayerText(name, left, top, width, height, zidx, visible, content, events) {
  var text='';

  if (isNav4) {
    text = '<layer name="' + name + '" left=' + left + ' top=' + top +
           ' width=' + width + ' height=' + height +
           ' visibility=' + (visible ? '"show"' : '"hide"') +
           ' ' + events + '>\n';
    text += '  ' + content + '\n';
    text += '</layer>\n';
  } else {
    text = '<div id="' + name + '" name="' + name +'" style="position:absolute; overflow:hidden; width:' +
           width + 'px; height:' + height + 'px;' +
           ' top:' + top + 'px; left:' + left + 'px; visibility:' +
           (visible ? 'visible;' : 'hidden;') +  '" ' + events +'>\n';
    text += '  ' + content + '\n';
    text += '</div>\n';
  }
  return text;
}


function createZoomSelectionBoxText(instNr) {
  var text='';

  // zoom/selection box
  if (isNav4) {
    text ='<layer name="zoomSelectBox"+instNr width=0 height=0 visibility="hide" />';
  } else {
    text = '<div id="zoomSelectBox'+instNr+'"' +
           ' style="position:absolute;overflow:hidden; width:0px;' +
           ' top:0px; left:0px;' +
           ' height:0px; visibility:hidden;' +
           ' border-width:2px; border-style:dotted; border-color:#000000">\n'
    text += '</div>\n';
  }
  return text;
}


/************************************************************************
 *
 * FUNCTIONS FOR THE NEW CLICK LAYER
 *
 * Andreas Homa
 *
 ************************************************************************/



/*
 * This function generates the main map click layer name depending on the instance number
 */

function getMainMapClickLayerName(instNr) {
  return DEFAULT_MAIN_MAP_CLICK_LAYER_NAME+instNr;
}



/*
 * This functions creates HTML code for the click layer within the javascript
 */

function createMainMapLayerText(caller, instNr, width, height, content, actionMode, onSubmit) {
  // Which mouse events shall be react on
  var mouseEvents = createLayerEvents(caller, instNr, actionMode, onSubmit);

  // get the layer name of this instance
  var mapLayerName = getMainMapLayerName(instNr);

  // Create the HTML text for the clickLayer!
  var layerText = createLayerText(mapLayerName,0,0,width,height,1,true,content,mouseEvents);

  return layerText;
}


/*
 * This functions creates HTML code for the click layer within the javascript
 */

function createClickLayerText(caller, instNr, width, height, imagePath, actionMode, onSubmit) {
  // Which mouse events shall be react on
  var mouseEvents = createLayerEvents(caller, instNr, actionMode, onSubmit);

  // get the layer name of this instance
  var clickLayerName = getMainMapClickLayerName(instNr);

  var cursorStyle = "cursor:crosshair";
  if(actionMode == 2) cursorStyle ="cursor:move";
  var content = '<img id="clickImageID" name="clickImage' + instNr + '" src="' + imagePath + '" border=0 width=' + width + ' height=' + height + ' style="'+cursorStyle+'">';

  // Create the HTML text for the clickLayer!
  var layerText = createLayerText(clickLayerName,0,0,width,height,3,true,content,mouseEvents);

  return layerText;
}



/*
 * Create the HTML/Javascript code for the mouse events which should be added to the layer
 *
 */
function createLayerEvents(caller, instNr, actionMode, onSubmit)
{
  var events = '';

  switch(actionMode)
  {
    // Zoom \u00fcber Gummiband
    case ACTION_MODE_SELECTBOX:
      // need no mouse events for the main map
      // mouse events will be handled by the global event handler
      if (isIE)
      	events = 'ondragstart="event.returnValue = false;"';
      else
      	events = '';
      break;
    // Verschieben frei Hand
    case ACTION_MODE_MOVE:
      // need no mouse events for the main map
      // mouse events will be handled by the global event handler
      if (isIE)
      	events = 'ondragstart="event.returnValue = false;"';
      else
      	events = '';
      break;
    case ACTION_MODE_POINT:
      events = 'onClick="dualClick('+instNr+')"';
      break;
    case ACTION_MODE_MEASURING:
      // need no mouse events for the main map
      // mouse events will be handled by the transparent layer because of
      // problems with the wz_jsgraphics.js lib (see MainMap.jsp)
      events = '';
      break;
    case ACTION_MODE_SELECTPOLYGON:
      // need no mouse events for the main map
      // mouse events will be handled by the transparent layer because of
      // problems with the wz_jsgraphics.js lib (see MainMap.jsp)
      events = '';
      break;
    case ACTION_MODE_COORD_INFO:
      params="'"+caller+"','"+instNr+"'";
      events = 'onClick="showCoordInfo('+params+')"';
  }

  return events;
}

/**
 * This function changes the mode of the toolbar
 * @param imageID The id defined in jsp
 */
function selectImageFkt(myimageID,mytoolName) {
    var imageCompOff = eval(''+myimageID+'[0]');
    var id;
    var Ausgabetext = '';

    id = getEle(myimageID);
    var imageCompChange = eval(id);
    imageCompChange.src = imageCompOff.src;

    if (activeToolbarModeImage.length != 0 &&
        activeToolbarModeImage != myimageID) {
      var imageOff = eval(''+activeToolbarModeImage+'[1]');
      id = getEle(activeToolbarModeImage);
      var imageChange = eval(id);
      imageChange.src = imageOff.src;
    }

  	//deselect static tools.
  	if (getEle('selectAtPolygonImg')!=null)
  		getEle('selectAtPolygonImg').src = selectAtPolygonImg.src;
  	if (getEle('distanceMeasuringImg')!=null)
  		getEle('distanceMeasuringImg').src = distanceMeasuringImg.src;

    setMeasuringMessage(' ');
    setMeasuringCoord(' ');


    activeToolbarModeImage=myimageID;
    activeToolbarMode=mytoolName;

    var index = getIndexOfArray(activeToolbarMode,toolBarModesArray);
    if (getEle('toolBarInfo')!=null)
      getEle('toolBarInfo').innerText = toolBarModesLanguageArray[index];

    if (mytoolName=="zoomInAtRect" ||mytoolName=="zoomOutAtRect" ||mytoolName=="selectAtRect") {
      var innerText = createMainMapLayerText(myCaller,myInsNumber,mWidth,mHeight,content,ACTION_MODE_NONE,'wait()');
      innerText += createZoomSelectionBoxText(myInsNumber);
      innerText += createClickLayerText(myCaller,myInsNumber,mWidth,mHeight,clickImagePath,ACTION_MODE_SELECTBOX);

      Ausgabetext ='<form method="post" action="'+toolBarModesActionArray[index]+'" id="mainMapForm'+myInsNumber+'">\n';
      Ausgabetext += innerText + '\n';
      Ausgabetext += '</form>\n';
    } else if (mytoolName=="selectAtPolygon"){
      var innerText = createMainMapLayerText(myCaller,myInsNumber,mWidth,mHeight,content,ACTION_MODE_SELECTPOLYGON,'wait()');
      innerText +=createLayerText(transparentLayerName,0,0,mWidth,mHeight,true,contentTranspa,mouseEvents4Poly);

      Ausgabetext ='<form method="post" action="' +toolBarModesActionArray[index] +'" id="mainMapForm'+myInsNumber+'">\n';
      Ausgabetext += innerText + '\n';
      Ausgabetext += '</form>\n';
    } else if (mytoolName=="freehandPan") {
      var innerText = createMainMapLayerText(myCaller,myInsNumber,mWidth,mHeight,content,ACTION_MODE_NONE,'wait()');
      innerText += createClickLayerText(myCaller,myInsNumber,mWidth,mHeight,clickImagePath,ACTION_MODE_MOVE);

      Ausgabetext ='<form method="post" action="' + toolBarModesActionArray[index]+ '" id="mainMapForm'+myInsNumber+'">\n';
      Ausgabetext += innerText + '\n';
      Ausgabetext += '</form>\n';
    } else if (mytoolName=="coordInfo") {
      var innerText = createMainMapLayerText(myCaller,myInsNumber,mWidth,mHeight,content,ACTION_MODE_COORD_INFO,'wait()');

      Ausgabetext ='<form method="post" action="' + toolBarModesActionArray[index] + '" id="mainMapForm'+myInsNumber+'">\n';
      Ausgabetext += innerText + '\n';
      Ausgabetext +='</form>\n';
    } else if (mytoolName=="distanceMeasuring") {
      var innerText = createMainMapLayerText(myCaller,myInsNumber,mWidth,mHeight,content,ACTION_MODE_MEASURING,'wait()');
      innerText +=createLayerText(transparentLayerName,0,0,mWidth,mHeight,true,contentTranspa,mouseEvents4Meas);

      Ausgabetext ='<form method="post" action="' + toolBarModesActionArray[index] + '" id="mainMapForm'+myInsNumber+'">\n';
      Ausgabetext += innerText + '\n';
      Ausgabetext +='</form>\n';

    } else if (mytoolName=="zoomIn" || mytoolName=="zoomOut" || mytoolName=="centeredPan" || mytoolName=="dataSearch"
      ||mytoolName=="selectRouteStartPoint" ||mytoolName=="selectRouteEndPoint") {
      var innerText = '<input type="image" src="'+mainMapImageUrl+'" border="0" alt="'+mainMapAltStr+'" title="">';

      Ausgabetext +='<form method="post" action="'+toolBarModesActionArray[index]+'" id="mainMapForm'+myInsNumber+'">';
      Ausgabetext += innerText + '\n';
      Ausgabetext += '</form>\n';
    } else {
      Ausgabetext ='<input type="image" src="'+mainMapImageUrl+'" border="0" alt="'+mainMapAltStr+'" title="">';
    }

    id = getEle('meinAbsatz');
    id.innerHTML=Ausgabetext;

    return false;
}

function moveSlider() {
  ySliderPos = ySliderStart + (yMousePos - ySliderOffset);

  if ( ySliderPos > ySliderMax ) ySliderPos = ySliderMax;
  if ( ySliderPos < ySliderMin ) ySliderPos = ySliderMin;


  if (sliderInAction){
    getLayer('sliderBand').top=ySliderPos - halfSliderHeight + additionalY;
    sliderValue = ( ySliderPos / (ySliderMax - ySliderMin)) * 100;
  }
  if ( isDebug ) window.status = "ySliderStart: " + ySliderStart + " / ySliderOffset: " + ySliderOffset + " / ySliderPos: " + ySliderPos + " / value: " + sliderValue;
}

function waitSlider(){
  if ( sliderInAction ) {
    sliderWasActive = true;
    sliderInAction = false;
  }
}

function resumeSlider(){
  if ( sliderWasActive ) {
    sliderWasActive = false;
    sliderInAction = true;
  }
}

function startSlider(){
  ySliderOffset=yMousePos;
  sliderInAction=true;
  sliderWasActive=false;
}

function clickSlider(e){
  sliderValue=(event.y /(sliderValueImageHeigth/100)) + additionalY;
  var value=100-sliderValue;
  if (value>100)
    value=100;
  if (value<0)
    value=0;
  value=Math.round(value/sliderTicks)*sliderTicks;
  window.location.href = sliderValueUrl+value;
  return false;
}

function stopSlider(){
  sliderInAction=false;
  sliderWasActive=false;
  ySliderStart = ySliderPos;

  var value=100-sliderValue;
  if (value>100)
    value=100;
  if (value<0)
    value=0;
  value=Math.round(value/sliderTicks)*sliderTicks;
  window.location.href = sliderValueUrl+value;
}
