// aimsClick.js
aimsClickPresent=true;
var onOVArea = false;

// Global vars to save mouse position
var mouseX=0;
var mouseY=0;
var x1=0;
var y1=0;
var x2=0;
var y2=0;
var zleft=0;
var zright=0;
var ztop=0;
var zbottom=0;

var totalMeasure=0;
var currentMeasure=0;
var lastTotMeasure=0;

// variables for interactive clicks
var clickCount = 0;
var	clickPointX = new Array();
var clickPointY = new Array();
var clickMeasure = new Array();
	// type - 1=Measure; 2=SelectLine ; 3=SelectPolygon
var clickType = 1;

var shapeSelectBuffer = false;

var panning=false;
var zooming=false;
var selectBox=false;
var blankImage = "images/map.png";

var leftButton =1;
var rightButton = 2;
if (isNav) {
	leftButton = 1;
	rightButton = 3;
}

var t = parent.MapFrame;
var topDoc = parent.TopFrame.document;

// put a point at click and add to clickCount
function clickAddPoint() {
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount += 1;
	selectCount=0;
	totalMeasure = totalMeasure + currentMeasure;
		//var u = Math.pow(10,numDecimals);
		//if (totalMeasure!=0) totalMeasure = parseInt(totalMeasure*u+0.5)/u;

	clickMeasure[clickCount]=totalMeasure;
	legendTemp=legendVisible;
	legendVisible=false;
	var theString = writeXML();
	sendToServer(imsURL,theString,203);
}


function clickOnePoint() {
	clickCount = 0;
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount = 1;

	var theString = writeXML();
	sendToServer(imsURL,theString,203);
}

function clickBufferPoint() {
	clickCount = 0;
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount = 1;

	var theString = writeXML();
	sendToServer(imsURL,theString,203);
}

//Koulutoimi moduulia varten tehty piirtotyökalu by Jani 24.7.2003
function clickAddMultiPoint() {
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	clickPointX[clickCount]=mapX;
	clickPointY[clickCount]=mapY;
	clickCount += 1;
	selectCount=0;
	totalMeasure = totalMeasure + currentMeasure;
		//var u = Math.pow(10,numDecimals);
		//if (totalMeasure!=0) totalMeasure = parseInt(totalMeasure*u+0.5)/u;

	clickMeasure[clickCount]=totalMeasure;
	legendTemp=legendVisible;
	legendVisible=false;
	var theString = writeXML();
	var theNum = 204;
	sendToServer(imsURL,theString,theNum);

}

// zero out all clicks in clickCount
function resetClick() {
	var c1 = clickCount;
	clickCount=0;
	clickPointX.length=1;
	clickPointY.length=1;
	currentMeasure=0;
	totalMeasure=0;
	lastTotMeasure=0;
	clickMeasure.length=1;
	selectCount=0;

	legendTemp=legendVisible;
	legendVisible=false;
	var theString = writeXML();
	sendToServer(imsURL,theString,203);
	if(toolMode==20) updateMeasureBox();
}

// remove last click from clickCount
function deleteClick() {
	var c1 = clickCount;
	clickCount=clickCount-1;
	selectCount=0;
	if (clickCount<0) clickCount=0;
	if (clickCount>0) {
		totalMeasure = clickMeasure[clickCount]
		clickPointX.length=clickCount;
		clickPointY.length=clickCount;
		clickMeasure.length=clickCount;

	} else {
		totalMeasure=0;
		clickMeasure[0]=0;
	}
	currentMeasure=0;
	if (c1>0) {
		legendTemp=legendVisible;
		legendVisible=false;
		var theString = writeXML();
		sendToServer(imsURL,theString,203);
	}

}

//keep track of currently selected tool, and display it to user
// set the imsMap cursor tool
function clickFunction (toolName) {
	//if(hasLayer("measureBox"))
	//	hideLayer("measureBox");

	switch(toolName) {
	// Zooming functions
	case "zoomin":
		// zoom in mode
		toolMode = 1;
		panning=false;
		selectBox=false;

		document.getElementById("theMap").style.cursor = "crosshair";
            theCursor = document.getElementById("theMap").style.cursor;

		modeBlurb = modeList[0];
		break
	case "zoomout":
		// zoom out mode
		toolMode = 2;
		panning=false;
		selectBox=false;

		document.getElementById("theMap").style.cursor = "crosshair";
            theCursor = document.getElementById("theMap").style.cursor;

		modeBlurb = modeList[1];
		break
	case "zoomlast":
		zoomBack();
		panning=false;
		zooming=false;
		selectBox=false;
		break
	case "zoomactive":
		//alert(LayerExtent[ActiveLayerIndex]);
		var q = LayerExtent[ActiveLayerIndex].split("|");
		panning=false;
		zooming=false;
		selectBox=false;
		//zoomToEnvelope(parseFloat(q[0]),parseFloat(q[1]),parseFloat(q[2]),parseFloat(q[3]));

		var l = parseFloat(setDecimalString(q[0]));
		var b = parseFloat(setDecimalString(q[1]));
		var r = parseFloat(setDecimalString(q[2]));
		var t = parseFloat(setDecimalString(q[3]));
		var w = r-l;
		var h = t-b;
		// add a bit of a margin around the layer
		var wm = w * (5/100);
		var hm = h * (5/100);
		l = l - wm;
		r = r + wm;
		b = b - hm;
		t = t + hm;
		
		//zoomToEnvelope(l,b,r,t);
		left = l;
		right = r;
		bottom = b;
		top = t;
		
		//estetään liian lähelle zoomaus
		if( ((r-l)<5000) || ((t-b)<5000) ){
		//if(ActiveLayerType == "point")
			zoomToChoiceMeasure2(7950, 6000);		
		}
		zoomToEnvelope(left,bottom,right,top);
		break
	case "fullextent":
		fullExtent();
		break

	// Pan functions
	case "pan":
		// pan mode
		toolMode = 3;

		zooming=false;
		selectBox=false;
		if (isIE)	{
			document.getElementById("theMap").style.cursor = "move";
                        theCursor = document.getElementById("theMap").style.cursor;
		}
		modeBlurb = modeList[2];
		break

	// Identify-Hyperlink functions
	case "identify":
		// identify mode - layer attributes - requires aimsIdentify.js
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		whatPopup = 1;
		if(canQuery) {
			toolMode = 4;

			document.getElementById("theMap").style.cursor = "crosshair";
            	theCursor = document.getElementById("theMap").style.cursor;

			modeBlurb = modeList[3];
		} else {
			alert(msgList[46]);
		}
		showGeocode=false;
		hideLayer("measureBox");

		break

	case "identifyall":
		// identify drill mode
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		toolMode = 5;
		if (canQuery) {

		document.getElementById("theMap").style.cursor = "crosshair";
            theCursor = document.getElementById("theMap").style.cursor;

				//modeBlurb = modeList[19]; // identify all
			modeBlurb = modeList[20]; // identify visible features
			//modeBlurb = modeList[3]; // identify
		} else {
			alert(msgList[46]);
		}
		//alert("Function Not Implemented");
		showGeocode=false;
		drawSelectBoundary=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		break
	case "hyperlink":
		// hyperlink mode - requires aimsIdentify.js
		var isOk = false;
		var j=-1;
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		toolMode = 15;
		modeBlurb = modeList[9];
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
		var isOk = checkHyperLinkLayer(ActiveLayerIndex)
		if (isOk) {
			if (canQuery) {


				//if (isIE)	{
					document.getElementById("theMap").style.cursor = "crosshair";
                                        theCursor = document.getElementById("theMap").style.cursor;
			//	}

			} else {
				alert(msgList[46]);
			}
			//alert("Function Not Implemented");
		} else {
			currentHyperLinkLayer="";
			currentHyperLinkField="";
			alert(msgList[47]);

		}
		break

	case "hyperlinkany":
		// hyperlink mode - requires aimsIdentify.js
		var j=-1;
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		toolMode = 30;
		modeBlurb = modeList[9];
		showGeocode=false;
		if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
		hideLayer("measureBox");
			if (canQuery) {


				//if (isIE)	{
					document.getElementById("theMap").style.cursor = "crosshair";
                                        theCursor = document.getElementById("theMap").style.cursor;
				//}

			} else {
				alert(msgList[46]);
			}
			//alert("Function Not Implemented");
		break

	// Measure-Unit function
	case "measure":
		aimsClickPresent=true;
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		if (clickCount>0) {
			if (totalMeasure==0) resetClick();
		}
		toolMode = 20;

		document.getElementById("theMap").style.cursor = "crosshair";
            theCursor = document.getElementById("theMap").style.cursor;

		modeBlurb = modeList[12];
		useTextFrame = true;
		if (clickType==1) {
                  if (useTextFrame)
                    parent.TextFrame.location= appDir + "mensuration.html";
                }
		showGeocode=false;
		break

	// Graphic Selection functions
	case "shape":
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		toolMode = 21;
		//if (isIE)	{
			document.getElementById("theMap").style.cursor = "crosshair";
                        theCursor = document.getElementById("theMap").style.cursor;
		//}

		modeBlurb = modeList[13];

		showGeocode=false;

		hideLayer("measureBox");
		break

	case "selectbox":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if(canQuery) {
			toolMode=10;
			queryTool=0;
			clickCount=0;
			showBuffer=false;

			document.getElementById("theMap").style.cursor = "crosshair";
                  theCursor = document.getElementById("theMap").style.cursor;

			modeBlurb = modeList[4];
		} else {
			alert(msgList[46]);
		}
		//alert("Function Not Implemented");
		showGeocode=false;
		if(useTextFrame) parent.TextFrame.document.location = appDir + "areaSearch.html";
		hideLayer("measureBox");
		break

	case "selectpoint":
		panning=false;
		zooming=false;
		shapeSelectBuffer = false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 11;
			queryTool=0;
			clickCount=0;
			 resetClick();

			document.getElementById("theMap").style.cursor = "hand";
                  theCursor = document.getElementById("theMap").style.cursor;

			modeBlurb = modeList[5];
		} else {
			alert(msgList[46]);
		}
		//alert("Function Not Implemented");
		showGeocode=false;
		showBuffer=false;
		hideLayer("measureBox");
		break

        case "education":
                //alert("jepulis");
		panning=false;
		zooming=false;
		shapeSelectBuffer = false;
		// select mode - requires aimsSelect.js

                if (canQuery) {
			toolMode = 16;
			queryTool=0;
			if (isIE)	{
				document.all.theTop.style.cursor = "crosshair";
				theCursor = document.all.theTop.style.cursor;
			}
			hideLayer("measureBox");
                        modeBlurb = modeList[8];
		} else {
			alert(msgList[46]);
		}
		//alert("Function Not Implemented");
		showGeocode=false;
		showBuffer=false;
		break


	case "buffershape":
		panning=false;
		zooming=false;
		aimsClickPresent = true;

		// interactive shape buffer - not implemented
		if (canQuery) {
			toolMode = 17;
			queryTool=0;
			shapeSelectBuffer = true;

			document.getElementById("theMap").style.cursor = "crosshair";
                  theCursor = document.getElementById("theMap").style.cursor;

			hideLayer("measureBox");
                }
                else {
			alert(msgList[46]);
		}
		//alert("Function Implemented");
		showGeocode=false;
		showBuffer=false;
		break


	// Geocode Function
	case "geocode":
		panning=false;
		zooming=false;
		selectBox=false;
		shapeSelectBuffer = false;
		// geocode mode - requires aimsGeocode.js
		hideLayer("measureBox");
		modeBlurb = modeList[14];
		setupGeocode();
		//parent.TextFrame.document.location= appDir + "addmatch.htm";
		break

	case "clearsel":
		 clearSelection();
		 break

	// Buffer function
	case "buffer":
		//buffer - requires aimsBuffer.js
		if (useBuffer) {
			if (checkSelected()) {
				toolMode = 25;
				shapeSelectBuffer = false;
				modeBlurb = modeList[18];
				writeBufferForm();
			} else {
				showBuffer=false;
				alert(msgList[48]);
			}
		} else {
			alert(msgList[49]);
		}
		break

	case "options":
		writeOptionForm();
		break

	// Print function
	case "print":
		 printIt();
		 break

	// Approach Map's print function
	case "printMap":
		getApproachMap(1, 107);
		break

	case "legend":
		if (aimsLegendPresent) {
			if (imsURL!="") {
				if (hasTOC) {
					if (legendVisible) {
						legendVisible=false;
					        //writeLayerList();
						//parent.TextFrame.document.location=appDir+"toc.htm";
					} else {
						legendVisible=true;
						getLegend();
					}
				} else {
					legendVisible=true;
					getLegend();
				}
			} else {
				alert(msgList[45]);
			}
		} else {
			alert(msgList[50]);
		}
		break

	case "layerlist":
		// put LayerList in separate window
		writeLayerListForm();
		break

        //omaa tuotantoa 18.2.2002 jani
        case "selectarea":
		panning=false;
		zooming=false;
		// select mode - requires aimsSelect.js
		if (canQuery) {
			toolMode = 41;
			queryTool=0;
			clickCount=0;
			showBuffer=false;

			document.getElementById("theMap").style.cursor = "crosshair";
                  theCursor = document.getElementById("theMap").style.cursor;

			modeBlurb = modeList[4];
		} else {
			alert(msgList[46]);
		}

		showGeocode=false;
		hideLayer("measureBox");
		break

	case "positionLink":
		aimsClickPresent=true;
		zooming=false;
		toolMode = 22;

		document.getElementById("theMap").style.cursor = "crosshair";
                theCursor = document.getElementById("theMap").style.cursor;
                //if(clickType==1) {
                  parent.TextFrame.location = appDir + "positionLink.html";
                //}
		break

	case "areasearch":
		parent.TextFrame.document.location = appDir + "areaSearch.html";
		var hakulistaTmp = new Array();
		parent.MapFrame.hakulista = hakulistaTmp;

		break

	default:
		alert(msgList[51]);
	}
	modeName=modeBlurb;
	if (useModeFrame) {
		writeModeFrame(modeBlurb);
	} else if ((drawFloatingMode) && (modeLayerOn)) {
		writeModeLayers(modeBlurb);
	} else if ((modeRefreshMap) && (drawModeOnMap)) {
		//var theString = writeXML();
		sendMapXML();
	}
}

// check for mouseup
function chkMouseUp(e) {
	if ((toolMode == 1) && (zooming)) {
		stopZoomBox(e);

	}
	if ((toolMode == 2) && (zooming)) {
		stopZoomOutBox(e);
	}
	if ((toolMode == 3) && (panning)) {
		stopPan(e);

	}
	if ((toolMode == 10) && (selectBox)) {
		stopSelectBox(e);
	}

	return false;

}

// perform appropriate action with mapTool
function mapTool (e) {
	var theButton= 0;
	// get the button pushed... if right, ignore... let browser do the popup... it will anyway
	if (isNav) {
		theButton = e.which;
	} else {
		theButton =window.event.button;
	}
	if (theButton==leftButton) {
		if(!isNav5up) document.getElementById("theMap").disabled = true;
		getImageXY(e);
		if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
			if ((hasOVMap) && (ovIsVisible) && (mouseX<i2Width+ovBoxSize) && (mouseY<i2Height) && (ovMapIsLayer)) {
                          ovMapClick(mouseX,mouseY);
                          window.status = "On OV Map Area";
			}
                        else {
                          switch(toolMode) {
				case 1:
						startZoomBox(e);
						return false;
						break

				case 2:
						startZoomOutBox(e);
						return false;
						break
				case 3:
						startPan(e);
						return false;
						break

				case 4:
					if(!isNav5up) {
						document.getElementById("theMap").disabled = false;
					} else {
						identify(e);
					}
					break

				case 5:
					// identify all
					identifyAll(e);
					break

				// custom modes

				case 10:
					//select(e);
						startSelectBox(e);
						return false;
						break
				case 11:
					//select point
					if (checkIfActiveLayerAvailable()) {
						select(e);
					}
					break
				case 12:
					//select line
					if (checkIfActiveLayerAvailable()) {
						clickType=2;
						clickAddPoint();
						if (useTextFrame) {
							if (parent.TextFrame.document.title!==modeList[60]) {
								parent.TextFrame.document.location= appDir + "selectline.htm";
							}
						}
					}
					break
				case 13:
					//select polygon
					if (checkIfActiveLayerAvailable()) {
						clickType=3;
						clickAddPoint();
						if (useTextFrame) {
							if (parent.TextFrame.document.title!==modeList[7]) {
								parent.TextFrame.document.location= appDir + "selectpoly.htm";
							}
						}
					}
					break
				case 15:
					// hyperlink
					hyperLink(e);
					break
				case 16:
					//select shape

                                        //if (checkIfActiveLayerAvailable()) {
						clickType=2;
						clickAddMultiPoint();

					break

				case 17:
					//buffer shape

                                        if (checkIfActiveLayerAvailable()) {
                                        	clickType=2;
						//clickAddPoint();
                                                clickBufferPoint();
					}
					break
				case 20:
					// measure
					clickType=1;
					clickAddPoint();
					break
				case 21:
					// shape
					clickType=4;
					clickAddPoint();
					break
				case 22:
					// Position link
					clickType=1;
                                        if(parent.TextFrame.document.forms[0].linkName.value=="")
                                          alert("Anna ensin paikkalinkille nimi!");
					else {
                                          clickOnePoint();
					  UpdatePositionLinkBox();
                                        }
					break
				case 23:
					// Vaikutuskanava
					//sendToServlet();
					//t.showLayer("AppletLayer");
					//document.KPApplet.selectMode("freehand");

					break
				case 30:
					// hyperlink
					hyperLinkAny(e);
					break
				case 40:
					// db identify - requires custom db query - not in default
					if (aimsDBPresent) {
						matchDBLinkLayer(dbLinkLayer);
						dbIdentify(e);
					}
					break
                                 case 41:
                                        select(e);
                                        alue_valittu2 = true;
                        		    parent.TextFrame.document.location = appDir + "areaSearch.html";
                                        return false;
                                        break
				default:
					if (toolMode>=1000) {
						customMapTool(e);
					}
				}
			}
		}
	}
}

// update measureBox layer
function updateMeasureBox() {
	var j = 1;
	for (var i=0;i<sUnitList.length;i++) {
		if (ScaleBarUnits==sUnitList[i]) j=i;
	}
	var u = Math.pow(10,numDecimals);
	var tMeas = 0;
	if (totalMeasure!=0)
		tMeas = parseInt(totalMeasure*u+0.5)/u;

	if(parent.TextFrame.document.forms[0].theMeasTotal.value != "")
	{
		parent.TextFrame.document.forms[0].theMeasTotal.value = tMeas + " " + unitList[j];
		parent.TextFrame.document.forms[0].theMeasSegment.value = currentMeasure + " " + unitList[j];
	}
}

function UpdatePositionLinkBox() {
	var mkRatio = (8.87 - ((screen.width - 640) * 0.0068359));
	var mkValue = parseInt(xDistance * mkRatio);

	if(parent.TextFrame.document.forms[0].linkName.value != "") {
		t.positionLinkValue = parent.TextFrame.document.forms[0].linkName.value;
		t.positionLinkUrl = "http://" + location.host + appDir + "aloitus_coordinate.jsp?x=" + mapX + "&y=" + mapY + "&mk=" + mkValue + "&piirrapiste=true&teksti=" + t.positionLinkValue;
            t.positionLinkUrl = ConvertSpecialCharacters(t.positionLinkUrl);
            parent.TextFrame.document.location = appDir + "positionLink.html";
	}
}

function loadTopFrame() {
	if(t.maplayersBetween || t.addressAreaBetween || t.serviceDirBetween || t.servicesBetween || t.commentsBetween || t.positionLinkBetween || t.populationBetween || t.apartmentSearchBetween || t.educationSystemBetween || t.eServiceDirBetween || t.mSkiBetween || t.mSkiTrackSituation || t.instructionBetween) {
		t.visibleBetweenFirst="visible";
		t.visibleBetweenLast="visible";

		if(t.mSkiBetween) t.visibleBetween1 = "visible";
		if(t.maplayersBetween) t.visibleBetween2 = "visible";
		if(t.addressAreaBetween) t.visibleBetween3 = "visible";
		if(t.serviceDirBetween) t.visibleBetween4 = "visible";
		if(t.servicesBetween) t.visibleBetween5 = "visible";
		if(t.commentsBetween) t.visibleBetween6 = "visible";
		if(t.positionLinkBetween) t.visibleBetween7 = "visible";
		if(t.populationBetween) t.visibleBetween8 = "visible";
		if(t.apartmentSearchBetween) t.visibleBetween9 = "visible";
		if(t.educationSystemBetween) t.visibleBetween10 = "visible";
		if(t.eServiceDirBetween) t.visibleBetween11 = "visible";
		if(t.mSkiTrackSituation) t.visibleBetween12 = "visible";
		if(t.instructionBetween) t.visibleBetweenInstruction = "visible";
	}
	t.loadBetweens = 1;
	topDoc.location = appDir + "topframe.jsp";
}
function waitOneMoment(text1, text2) {
	var top = parent.TextFrame.document;

	top.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
	top.writeln('<HTML>');
	top.writeln('<HEAD>');
	top.writeln('<TITLE>MapLocus</TITLE>');
	top.writeln('<link href="styles/textframe.css" rel="stylesheet" type="text/css">');
	top.writeln('</HEAD>');

	top.writeln('<BODY BACKGROUND="images/bg_left.png" LEFTMARGIN=0 TOPMARGIN=0 MARGINWIDTH=0 MARGINHEIGHT=0>');

	top.writeln('<TABLE WIDTH="85%" ALIGN="center" border="0">');
 	top.writeln('<TR ALIGN="left"><TD CLASS="label"><BR><B>' + text1 + '</B></TD></TR>');
 	top.writeln('<TR ALIGN="left"><TD><IMG SRC="images/bu_closewnd.png" WIDTH="200" HEIGHT="28" ALT="Sulje ikkuna" BORDER="0">');
 	top.writeln('<BR></TD></TR>');
 	top.writeln('<TR><TD>');
 	top.writeln('<BR><FONT SIZE="2">' + text2 + ' ladataan... Odota hetki!</FONT>');
	top.writeln('</TD></TR>');
	top.writeln('</TABLE>');

	top.writeln('</BODY>');
	top.writeln('</HTML>');
}
