/**************************************
* Global Variables for OPIS
* mikedixon@concordengineering.com
**************************************/

//LatLon Acetate Layer
var showLatLon =false;
var llactive =false;
var theLat ="";
var theLon ="";
	
//latlon reporter
var uselatlon=true;
var useZoomScale=true;

//LATLON LIMITS
var minLON = -77.8410705229608;
var minLAT = 35.2639600021473;
var maxLON = -76.9431473023885;
var maxLAT = 35.892506256548;
  
// lat lon reporter
// mikedixon@concordengineering.com
function latlon() {
    if (llactive==true) {
	var theX = mouseX;
	var theY = mouseY;
	getMapXY(theX,theY);
	var llxmin = mapX-10;
	var llxmax = mapX+10;
	var llymin = mapY-10;
	var llymax = mapY+10;
	var theString = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES>';
	var theString = theString+'<ENVELOPE minx="'+llxmin+'" miny="'+llymin+'" maxx="'+llxmax+'" maxy="'+llymax+'" />';
	var theString = theString+'<FILTERCOORDSYS id="102719" /><FEATURECOORDSYS id="4326" /></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
	sendToServer(imsURL,theString,1002);
	}
}


// lat lon plotter
// mikedixon@concordengineering.com
function plotLatLon() {
theLat=document.llform.Latitude.value;
theLon=document.llform.Longitude.value;
if (document.llform.Longitude.value > 0){
   theLon =(document.llform.Longitude.value)*-1;
   }
else { theLon=document.llform.Longitude.value;
   }
if(theLon > maxLON || theLon < minLON || theLat > maxLAT || theLat < minLAT){
alert("Coordinate value is outside of map extent");
}
else{
document.llform.Longitude.value = theLon;
showLatLon=true;
var llxmin = theLon;
var llxmax = theLon+1;
var llymin = theLat;
var llymax = theLat+1;
var theString = '<ARCXML version="1.1"><REQUEST><GET_IMAGE><PROPERTIES>';
var theString = theString+'<ENVELOPE minx="'+llxmin+'" miny="'+llymin+'" maxx="'+llxmax+'" maxy="'+llymax+'" />';
var theString = theString+'<FILTERCOORDSYS id="4326" /><FEATURECOORDSYS id="102719" /></PROPERTIES></GET_IMAGE></REQUEST></ARCXML>';
sendToServer(imsURL,theString,1003);
}
}




function closelatlon() {
llactive=false;
showLatLon =false;
hideLayer("LLBox")
sendMapXML();
document.llform.Latitude.value="";
document.llform.Longitude.value="";
document.llform.pltlatlon.src="images/plt_ll.jpg";
		if (isIE)	{
			document.all.theTop.style.cursor = "crosshair";
			theCursor = document.all.theTop.style.cursor;
		}
}

//not currently implemented in OPIS
//mikedixon@concordengineering.com
function doZoomScale(zval) { 
	saveLastExtent();
	var msize;
	if ( iHeight < iWidth) {
			msize = iHeight
	} else {
			msize = iWidth
	} 
	var midX = eRight - (xDistance / 2);
	var midY = eTop - (yDistance / 2);
	//mapscale is half the distance for the ratio scale 
	//take the input ratio factor (zval)
	//take the size of the longest side of the map/97.6925 to get the size in inches (97.. pix per inch)
	//then divide the size of the map from above by 12 to get feet since that's what our mapunits are in
	//multiply the ratio by the size of the map (length or witdh) in feet
	// then multiply that by .5 to get half the distance the extent needs to be
	//add or subtract that half map extent to the center point cooridnates to build an extent
	var mscale= (zval * ((msize/97.6925)/12)) * .5;
	eLeft = ((midX) - (mscale));
	eRight =  ((midX) + (mscale));
	eBottom = ( (midY) - (mscale));
	eTop =  ((midY) + (mscale));
	sendMapXML(); 
} 


//NEW FOR OPIS ADDRESS SEARCH ON STRUCTURES
function AddressQueryCESI(theAddress,SearchType) {
//fist the URLString (IMS server and service)
var MYURLString = "http://" + parent.document.location.host + "/servlet/com.esri.esrimap.Esrimap?ServiceName=structures"
//alert(MYURLString);
//next the address string from the search form
var MYAddrString = theAddress.toUpperCase();

//next the query request
var addrQueryString = "";
addrQueryString += '<ARCXML version="1.1">';
addrQueryString += '<REQUEST>';
addrQueryString += '<GET_FEATURES beginrecord="0" outputmode="xml" geometry="false" envelope="true" >';
addrQueryString += '<LAYER id="0" />';
if (SearchType == "NumberSearch")
{
addrQueryString += '<SPATIALQUERY subfields="#ALL#" where="ADDRESS LIKE \'' + MYAddrString + '%\'" >';
}
else if (SearchType == "NameSearch")
{
addrQueryString += '<SPATIALQUERY subfields="#ALL#" where="ADDR_SN LIKE \'' + MYAddrString + '%\'" >';
}
else if (SearchType == "FullAddrSearch")
{
addrQueryString += '<SPATIALQUERY subfields="#ALL#" where="ADDRESS LIKE \'' + MYAddrString + ' %\'" >';
}
addrQueryString += '</SPATIALQUERY>';
addrQueryString += '</GET_FEATURES>';
addrQueryString += '</REQUEST>';
addrQueryString += '</ARCXML>';

//finally send it. response is handled by aimsCustom.js
CESISendToServer(MYURLString,addrQueryString,1005);
}


function CESISendToServer(URLString,XMLRequest,theType) {
	// uses default Servlet Connector - requestMethod="Servlet";
	parent.MapFrame.XMLMode = 1005;
	var cVersion = "&ClientVersion=9.1";
	var thePostForm = parent.PostFrame.document.forms[0];
	URLString = URLString + cVersion;
	URLString = URLString + '&CustomService=Query&Form=True&Encode=False';
	var requestURL = URLString;
	thePostForm.action = requestURL + "&Form=True&Encode=False";
	var xmlHeader = '<?xml version="1.0" ' + localeEncoding + '?>';
	thePostForm.ArcXMLRequest.value = xmlHeader + XMLRequest;
	thePostForm.submit();
}



function dbIdentifyAddress(addrx,addry) {
	highlightedOne="";
	var theX = addrx;
	var theY = addry;
	searchTolerance = 1;
	//alert(xDistance + "/" + iWidth + "/" + pixelTolerance + "/" + searchTolerance);
	var tempWest = theX - searchTolerance;
	var tempNorth = theY + searchTolerance;
	var tempEast = theX + searchTolerance;
	var tempSouth = theY - searchTolerance;
	var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
	showRetrieveData();
	sendToServer(imsQueryURL,theString,70);
}
//END NEW OPIS ADDRESS SEARCH

//opis search
//sort table functions
function setDataType(cValue)
  {
    // THIS FUNCTION CONVERTS DATES AND NUMBERS FOR PROPER ARRAY
    // SORTING WHEN IN THE SORT FUNCTION
    var isDate = new Date(cValue);
    if (isDate == "NaN")
      {
        if (isNaN(cValue))
          {
            // THE VALUE IS A STRING, MAKE ALL CHARACTERS IN
            // STRING UPPER CASE TO ASSURE PROPER A-Z SORT
            cValue = cValue.toUpperCase();
            return cValue;
          }
        else
          {
            // VALUE IS A NUMBER, TO PREVENT STRING SORTING OF A NUMBER
            // ADD AN ADDITIONAL DIGIT THAT IS THE + TO THE LENGTH OF
            // THE NUMBER WHEN IT IS A STRING
            var myNum;
            myNum = String.fromCharCode(48 + cValue.length) + cValue;
            return myNum;
          }
        }
  else
      {
        // VALUE TO SORT IS A DATE, REMOVE ALL OF THE PUNCTUATION AND
        // AND RETURN THE STRING NUMBER
        //BUG - STRING AND NOT NUMERICAL SORT .....
        // ( 1 - 10 - 11 - 2 - 3 - 4 - 41 - 5  etc.)
        var myDate = new String();
        myDate = isDate.getFullYear() + " " ;
        myDate = myDate + isDate.getMonth() + " ";
        myDate = myDate + isDate.getDate(); + " ";
        myDate = myDate + isDate.getHours(); + " ";
        myDate = myDate + isDate.getMinutes(); + " ";
        myDate = myDate + isDate.getSeconds();
        //myDate = String.fromCharCode(48 + myDate.length) + myDate;
        return myDate ;
      }
  }
function sortTable(col, tableToSort)
  {
    var iCurCell = 2;
    var totalRows = parent.TextFrame.rstable.rows.length;
    var bSort = 0;
    var colArray = new Array();
    var oldIndex = new Array();
    var indexArray = new Array();
    var bArray = new Array();
    var newRow;
    var newCell;
    var i;
    var c;
    var j;
    // ** POPULATE THE ARRAY colArray WITH CONTENTS OF THE COLUMN SELECTED
    for (i=1; i < tableToSort.rows.length; i++)
      {
        colArray[i - 1] = setDataType(tableToSort.cells(iCurCell).innerText);
        iCurCell = iCurCell + tableToSort.cols;
      }
    // ** COPY ARRAY FOR COMPARISON AFTER SORT
    for (i=0; i < colArray.length; i++)
      {
        bArray[i] = colArray[i];
      }
    // ** SORT THE COLUMN ITEMS
    //alert ( colArray );
    colArray.sort();
    //alert ( colArray );
    for (i=0; i < colArray.length; i++)
      { // LOOP THROUGH THE NEW SORTED ARRAY
        indexArray[i] = (i+1);
        for(j=0; j < bArray.length; j++)
          { // LOOP THROUGH THE OLD ARRAY
            if (colArray[i] == bArray[j])
              {  // WHEN THE ITEM IN THE OLD AND NEW MATCH, PLACE THE
                // CURRENT ROW NUMBER IN THE PROPER POSITION IN THE
                // NEW ORDER ARRAY SO ROWS CAN BE MOVED ....
                // MAKE SURE CURRENT ROW NUMBER IS NOT ALREADY IN THE
                // NEW ORDER ARRAY
                for (c=0; c<i; c++)
                  {
                    if ( oldIndex[c] == (j+1) )
                    {
                      bSort = 1;
                    }
                      }
                      if (bSort == 0)
                        {
                          oldIndex[i] = (j+1);
                        }
                          bSort = 0;
                        }
          }
    }
  // ** SORTING COMPLETE, ADD NEW ROWS TO BASE OF TABLE ....
  for (i=0; i<oldIndex.length; i++)
    {
      newRow = tableToSort.insertRow();
      for (c=0; c<tableToSort.cols; c++)
        {
          newCell = newRow.insertCell();
          newCell.innerHTML = tableToSort.rows(oldIndex[i]).cells(c).innerHTML;
        }
      }
  //MOVE NEW ROWS TO TOP OF TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.moveRow((tableToSort.rows.length -1),1);
    }
  //DELETE THE OLD ROWS FROM THE BOTTOM OF THE TABLE ....
  for (i=1; i<totalRows; i++)
    {
      tableToSort.deleteRow();
    }
  }





// measure tool functions
// clear current selection
var MeasureVisible = false;

function DoMeasure() {
        MeasureVisible = true;
	var theCount = selectCount;
	var theHL = highlightedOne;
	selectCount=0;
	showBuffer=false;
	highlightedOne="";
	selectPoints.length=0;
	selectLeft.length=0;
	selectRight.length=0;
	selectTop.length=0;
	selectBottom.length=0;
	drawSelectBoundary=false;
	showGeocode=false;
	clickCount=0;
	totalMeasure=0;
	currentMeasure=0;
        updateMeasureBox();
        currentArea=0;
        workACRES=0;
        sendMapXML();
	}