// aimsClick.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*       dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js,
*       aimsLayers.js, aimsDHTML.js
*       aimsNavigation.js
*/

var aimsClickPresent=true;

// 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 panning=false;
var zooming=false;
var selectBox=false;
var blankImage = "images/map.gif";

var leftButton =1;
var rightButton = 2;
if (isNav) {
    leftButton = 1;
    rightButton = 3;
}


/*  *****************************************************
*   Point click functions
*   used by Measure and Select by Line/Polygon
*   *****************************************************
*/

// 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;
    if (noOverlay) {
        legendTemp=legendVisible;
        legendVisible=false;
            var theString = writeXML();
            var theNum = 99;        
    } else {
            var theString = writeOverlayXML();    
            var theNum = 901;
    }
    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;
    
    if (noOverlay) {
        legendTemp=legendVisible;
        legendVisible=false;
        var theString = writeXML();
        var theNum = 99;
            //showRetrieveMap();
        sendToServer(imsURL,theString,theNum);
        
    } else {
        document.theClickImage.src = blankImage;
    }
    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) {
        if (noOverlay) {
            legendTemp=legendVisible;
            legendVisible=false;
                var theString = writeXML();
                var theNum = 99;
        } else {
                var theString = writeOverlayXML();
                var theNum = 901;     
        }
        sendToServer(imsURL,theString,theNum);
    } 
}

//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;
        if (isIE)   {
            document.all.theTop.style.cursor = "crosshair";
            theCursor = document.all.theTop.style.cursor;
        }
        modeBlurb = "Zoom In - Click and drag an area or click a single point on the map to zoom to.";
        //if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
        break
    case "zoomout":
        // zoom out mode
        aimsSelectPresent=false;        
        toolMode = 2;
        panning=false;
        selectBox=false;
        if (isIE)   {
            document.all.theTop.style.cursor = "crosshair";
            theCursor = document.all.theTop.style.cursor;
        }
        modeBlurb = "Zoom Out - Click and drag an area or click a single point on the map to zoom from.";
        //if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
        break
    case "zoomlast":
        zoomBack();
        panning=false;
        zooming=false;
        selectBox=false;
        break
    case "pan":
        // pan mode
        toolMode = 3;
        
        zooming=false;
        selectBox=false;
        if (isIE)   {
            document.all.theTop.style.cursor = "move";
            theCursor = document.all.theTop.style.cursor;
        }
        modeBlurb = "Pan - Click a single point and hold your mouse button down whilst dragging the map";
        //if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
        break

    // Identify-Hyperlink functions
    case "identify":
        // identify mode - layer attributes - requires aimsIdentify.js
        panning=false;
        zooming=false;
        selectBox=false;
        fromTOCnotIdent = false;    // t103
        if (canQuery) {
            toolMode = 4;            
            if (isIE)   {
                document.all.theTop.style.cursor = "crosshair";
                theCursor = document.all.theTop.style.cursor;
            }
            modeBlurb = "Identify - Set the active theme and then select an element on the map.";
        } else {
            alert("Cannot query Service\nIdentify, Select, and Query functions are disabled.");
        }
        showGeocode=false;
        //if (useTextFrame) parent.TextFrame.document.location= appDir + "text.htm";
        hideLayer("measureBox");
        parent.TOCFrame.turnOffMenuse();
        break

    // Measure-Unit function
    case "measure":
        panning=false;
        zooming=false;
        selectBox=false;
        if (clickCount>0) {
            if (totalMeasure==0) resetClick();
        }
        toolMode = 20;
        if (isIE)   {
            document.all.theTop.style.cursor = "crosshair";
            theCursor = document.all.theTop.style.cursor;
        }
        modeBlurb = "Measure -  select two points. To stop measuring select another tool e.g. pan.";
        if (clickType==1) {
            //if (useTextFrame) parent.TextFrame.location= appDir + "measure.htm";
                showLayer("measureBox");
                updateMeasureBox();
        }
        showGeocode=false;
        break
              
    default:
        alert("Function not enabled.");
    }
}

// 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) {
    getImageXY(e);
    if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
      if ((hasOVMap) && (ovIsVisible) && (mouseX<i2Width+ovBoxSize) && (mouseY<i2Height) && (ovMapIsLayer)) {
        //ovMapClick(mouseX,mouseY);
      } 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:
          identPass1=true;
          identify(e,1);  // hardcoded
          //identify(e,42);                      
          break
        case 10:
          //select(e);
          startSelectBox(e);
          return false;
          break
        case 11:
          //select point
          select(e);
          break
        case 12:
          //select line
          clickType=2;
          clickAddPoint();
          if (useTextFrame) {
            if (parent.TextFrame.document.title!="Select Line") {
              parent.TextFrame.document.location= appDir + "selectline.htm";
            }
          }
          break
        case 13:
          //select polygon
          clickType=3;
          clickAddPoint();
          if (useTextFrame) {
            if (parent.TextFrame.document.title!="Select Polygon") {
              parent.TextFrame.document.location= appDir + "selectpoly.htm";
            }
          }
          break
        case 20:
          // measure
          clickType=1;
          clickAddPoint();
          break
        default:
          if (toolMode>=1000) {
            customMapTool(e);
          }
        }
      }
    }
  }
}

function twoDigit(n) {
  var str=(n-1+1.005).toString();
  return str.substring(0,str.indexOf('.')+3);
}

// update measureBox layer
function updateMeasureBox() {
  if (isNav4) {
    var theForm = document.layers["measureBox"].document.forms[0];
  } else {
    //var theForm = document.measureBox.forms[0];
    var theForm = document.forms[0];
  }
  theForm.theMeasTotal.value = twoDigit(totalMeasure / 1000) + " " + " km";
  theForm.theMeasSegment.value = twoDigit(currentMeasure / 1000) + " " + " km";
  showLayer("measureBox");
}

function writeOverlayXML() {
    var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_IMAGE>\n<PROPERTIES>\n<EXTENT minx="' + left + '" miny="' + bottom + '" maxx="' + right + '" maxy="' + top + '" />';
    theString += '<IMAGESIZE height="' + iHeight + '" width="' + iWidth + '" />\n';
    // tell the server that the layers are to be invisible
    theString += '<LAYERLIST >\n';
    for (var i=0;i<layerCount;i++) {
        theString += '<LAYERDEF name="' + LayerName[i] + '" visible="false" />\n';
    }
    theString += '</LAYERLIST>\n';
    // map background color
    theString += '<BACKGROUND color="255,255,254" transcolor="255,255,254" />\n';
    var theImage = theServiceName + "_" + hostName.toUpperCase() + (Math.round(Math.random()*100000000)).toString() + "." + theImageType;
    var thePath = theImagePath + theImage;
    var theURL = theImageURLPath + theImage;
    theString += '<OUTPUT name="' + thePath + '" url="' + theURL + '" ';
    theString += 'type="' + theImageType + '" />\n';
    theString += '</PROPERTIES>\n';
    if (clickCount>0) {
        theString += '<LAYER type="ACETATE" name="allTheClicks">\n';
        if (clickCount>1) {
            theString += '<OBJECT units="DATABASE">\n<LINE coords="' + clickPointX[0] + " " + clickPointY[0];
            for (var i=1;i<clickCount;i++) {
                theString += ","  + clickPointX[i] + " " + clickPointY[i]; 
            }
            theString += '" >\n';
            theString += '<SIMPLELINESYMBOL type="SOLID" color="' + clickMarkerColor;
            theString += '" width="3" />\n</LINE>\n</OBJECT>\n'; 
            theString += '<OBJECT units="DATABASE">\n<LINE coords="' + clickPointX[0] + " " + clickPointY[0];
            for (var i=1;i<clickCount;i++) {
                theString += ","  + clickPointX[i] + " " + clickPointY[i]; 
            }
            theString += '" >\n';
            theString += '<SIMPLELINESYMBOL type="SOLID" color="255,255,255" width="1" />\n</LINE>\n</OBJECT>\n'; 
        }
        for (var i=0;i<clickCount;i++) {
            theString += '<OBJECT units="DATABASE">\n<POINT coords="' + clickPointX[i] + ' ' + clickPointY[i] + '">\n';
            theString += '<SIMPLEMARKERSYMBOL  type="' + clickMarkerType + '"';
            theString += ' color="' + clickMarkerColor + '" size="' + clickMarkerSize + '" />\n</POINT>\n</OBJECT>\n';
            }
        theString += '</LAYER>\n';
    }
    theString += '</GET_IMAGE>\n</REQUEST>\n</ARCXML>';
    return theString;
}