// support functions for Virginia Fish and Wildlife Information Service Online
//--- July 6, 2009  abj3  mapMeasure coordinate lists re-written
//--- July 24 debugging line 896
//--- July 27, 2009  abj3  add anti-cache to ID window call
//--- August 17, 2009  abj3  HU6
//--- November 10, 2009  abj3  gap
//--- February 11, 2010  abj3  line vs polygon revisited; map measure map report "please wait"
//--- June 1, 2010  abj3  work on map zoom limits
//--- July 15, 2010  abj3  putValueTextXY  setNAD83/setNAD27

if( !document.getElementById ) { alert('Your browser does not support Java functions needed by this window.'); }

// Imbeded Function List
//
// function VaFWIS_MapFormInit( mapImageName, divMap, divMapMeasureIdA, divMapMeasureIdB, divZoomBox )
// function mouseCoords(e)
// function zbCrossLines(color) [Private]
// function testMouseDown(e)
// function testMouseUp(e)
// function XYoffset(imageObject)
// function XYscroll()
// function click_map(idName,mX,mY,fromMapMeasureTool)
// function nDecString(floatNumber,nDec)
// function sendFunc()
// function CancelFunc()
// function display_dataRecord()
// function set_bm(basemap)
// function replace_bm(basemap)
// function display_poi()
// function mapSourceComment()
// function set_rings(parm)
// function setOverlayLegend(list)
// function setMapScale(s)
// function clickZoomSelect()
// function setMapSize(tilex,tiley)
// function clickSizeSelect()
// function refbutton()
// function close_windows()
// function get_basemap()
// function openHelpWin(fileName)
// function openAuxillaryLegendWin(fileName)
// function get_overlay()
// function set_shift(s)
// function panButton( mode )
// function measureDrawPoint( graphicObject, x, y, color )
// function initMeasureTool(mode)
// function openMeasureTool()
// function mapMeasureOverScrollBar()
// function measureButton(mode)
// function measureTool(mode)
// function measureToolDrawB()
// function mapMeasureReport()
// function mapMeasureCoord( coord )
// function mapReport( textXY )
// function getValue_textXY()
// function getValue_map_coord()
// function putValueTextXY(textXY,coord,polyLineDelimiter)
// function pageWidth()
// function pageHeight()
// function posLeft()
// function posTop()
// function posRight()
// function posBottom()
// function progress_clear()
// function progress_update()
// function progress_stop()
// function progress_start()
// function locateMap()
// function styleObject(object)
// function monitorReadyState( errorText )
// function monitorReadyStateIgnore()
// function loadXMLDocAsync(url)
// function processXMLText( status, textString )
// function buildImageMap(refName,data,columnNames)
// function replaceMap()
// function mapMeasureAddList()
// function mapMeasureRemoveList()
// function measureToolListArrays2Text(polyLineDelimiter,coord)
//

var child_window;
var mapName;
var mouseX,mouseY;
var timeMouseDown, timeMouseUp;
var jg, zb, mapLeftX, mapTopY, mapRightX, MapBottomY, mapMessageMaxX;
var mouseDown, ScrollBarThickness;
var mapIdName, mapIdObject, Xoffset, Yoffset, Xscroll, Yscroll;
var xList, yList;
var lastX, lastY, mouseMode, lastMouseMode;
var fullXArray, fullYArray;
var mapMeasure, mmA, mmB;
var mapMeasure_poiLL, mapMeasure_dpLL;
var textXY;
var overScrollBar;
var mapMeasureFinish;
var poiDescription;
var ringDescription;
var doNotReplaceMap;

var map_poiLL;
var map_dpLL;
var map_itemUTM17;
var map_poiUTM17;
var map_dpUTM17;
var map_dist;
var map_s;
var map_t;
var map_pixel;
var map_pan;
var map_porUTM17,porDescription;

var divMapId, divZoomBoxId, zbLeft, zbTop, xLeft, yTop, xRight, yBottom, zoomMin, zoomMax;
var isOverMap;
var currentMouseX, currentMouseY, lastMouseX, lastMouseY;
var zoomPixel;
var mapTitle;
var cursorLL;

var mmWindow, mmWindowLoadMode;
var unDoArray;
var unDoTag = 0;
var unDoLine;
var bm_nad;

var showingMapReport = 0;
var savedIdCoordinates = '';
var divMapMeasureIdA, divMapMeasureIdB;
var adjustScrollX = 0;
var adjustScrollY = 0;
var adjustPointerX = 3;
var adjustPointerY = 3;
var mapMeasureDDList = '';
var mapMeasureDDListArray;
var permission_mmID = false;

var mmShadePolygon = false;

//-----------------------------------------------------------------------------------
/* external global variables:
	mapWidth
	mapHeight
	map_pixel
	map_min_utmx
	map_max_utmy
	map_dpz
*/
//-----------------------------------------------------------------------------------

function VaFWIS_MapFormInit( mapImageName, divMap, divMapMeasureIdAparam, divMapMeasureIdBparam, divZoomBox ) {

   divMapId = divMap;
   divZoomBoxId = divZoomBox;

   unDoArray = new Array();
   unDoTag = 0;

   setNAD27();

   map_poiLL = UTM2LL(document.mapform.poi_utm17.value,17);
   map_poiUTM17 = LL2UTM(map_poiLL,17);

   map_dpLL = UTM2LL(document.mapform.dp_utm17.value,17);
   map_dpUTM17 = LL2UTM(map_poiLL,17);

   map_dist = document.mapform.dist.value;
   map_t = document.mapform.t.value;

   map_porUTM17 = map_poiUTM17;

   poiDescription = 'Point of Interest';
   porDescription = 'Point of Interest';
   if( map_dist > 0 ) {
      poiDescription = 'Search Point';
      porDescription = 'Search Point';
   }
   map_itemUTM17 = '';
   if( re17 !== '' ) {
      map_itemUTM17 = re17 + ' ' + rn17 + ' 17';
      poiDescription = 'Item Location';
      if( map_dist < 1 ) { porDescription = 'Item Location'; }
   }

   if( divMapMeasureIdAparam != null ) { divMapMeasureIdA = divMapMeasureIdAparam; mmA  = new jsGraphics(divMapMeasureIdA); mmA.clear(); }
   if( divMapMeasureIdBparam != null ) { divMapMeasureIdB = divMapMeasureIdBparam; mmB  = new jsGraphics(divMapMeasureIdB); mmB.clear(); }
   if( divZoomBoxId != null ) {
      zb  = new jsGraphics(divZoomBoxId);
      zb.clear();
      zb.setColor("red");
      zb.setStroke(2);
   }

//-- Global variables defined elsewhere
//-------------------------------------
   map_pixel = parseInt(map_pixel,10);
   map_min_utmx = parseInt(map_min_utmx,10);
   map_max_utmy = parseInt(map_max_utmy,10);
   map_dpz = parseInt(map_dpz,10);
   document.mapform.p.value = map_pixel;
   document.mapform.dpz.value = map_dpz;
//-------------------------------------

//--- mouseMode 1 - Point  2 - Drag
   mouseMode = '1';
   lastMouseMode = '1';
   mapMeasure = '0';
   document.mapform.measure.value = mapMeasure;
   mapMeasureFinish = true;
   mouseDown = 0;
   mapMessageMaxX = 0;
   mapMeasureDDListArray = new Array();
   xList = '';
   yList = '';
   lastX = 0;
   lastY = 0;
   mapMeasureDDList = '';

   mapIdName = mapImageName;
   mapIdObject = eval('document.images.' + mapIdName);
   mapWidth = parseInt(mapIdObject.width,10);
   mapHeight = parseInt(mapIdObject.height,10);



   var tile = document.mapform.tile.value.split(',');

   doNotReplaceMap = 1;
   setMapScale();
   setMapSize(tile[0],tile[1]);
   set_bm(map_t);
   set_rings();
   setOverlayLegend();
   doNotReplaceMap = 0;
   replaceMap();

   locateMap();

   set_shift(shift);
   panButton();

//-- take over mouse

	var el = document.body;
	if (el.addEventListener){
		el.addEventListener('mousemove', mouseCoords, true); 
		el.addEventListener('mousedown', testMouseDown, true); 
		el.addEventListener('mouseup', testMouseUp, true);
	} else if (el.attachEvent){
		el.attachEvent('onmousemove', mouseCoords);
		el.attachEvent('onmousedown', testMouseDown);
		el.attachEvent('onmouseup', testMouseUp);
	} else if( document.captureEvents) {
		document.captureEvents(Event.MOUSEOVER);
		document.onmousemove = mouseCoords;
		document.onmousedown = testMouseDown;
		document.onmouseup = testMouseUp;
	}

   textXY = '';
   overScrollBar = false;
   mapMeasureFinish = true;
   ringDescription = '';
   doNotReplaceMap = 0;

   map_pan=1;

   zbLeft = 0;
   zbTop = 0;
   xLeft = 0;
   yTop = 0;
   xRight = 0;
   yBottom = 0;
   isOverMap = false;
   zoomPixel = 0;
   mapTitle = title0;
   mapMeasureDDListArray = new Array();

   mmWindow = false;
//--- initial mmWindowLoadMode -- Map Measure Mouse Mode: 1 - Point  2 - Drag
   mmWindowLoadMode = '2';

   lastMouseX = 0;
   lastMouseY = 0;

	permission_mmID = ( user_type == 'A' || user_type == 'B' );
	permission_mmID = ( permission_mmID || user_type == 'I' );

   initComplete = true;

//-- different browsers return different pointer locations. Adjustments are different;

//--- BrowserDetect.js is loaded by zMapFormJava
	if( typeof BrowserDetect != "undefined" ) {
		if( BrowserDetect.browser == "Explorer" ) {
//			alert("Explorer/"+BrowserDetect.version);
			adjustScrollX -= 2; adjustScrollY -= 2;
		} else if( BrowserDetect.browser == "Firefox" ) {
//			alert("Firefox/"+BrowserDetect.version);
		} else 	if( BrowserDetect.browser == "Opera" ) {
//			alert("Opera/"+BrowserDetect.version);
			adjustPointerX -= 1; adjustPointerY -= 1;
		} else if( BrowserDetect.browser == "Safari" ) {
//			alert("Safari/"+BrowserDetect.version);
			adjustPointerX += 1; adjustPointerY += 1;
		} else {
//			alert(BrowserDetect.browser+"/"+BrowserDetect.version);
		}
	}

}

//-----------------------------------------------------------------------------------

function locateMap() {

	XYscroll();
	XYoffset();

	mapLeftX = Xoffset;
	mapTopY = Yoffset;
	mapRightX = mapLeftX + mapWidth;
	mapBottomY = mapTopY + mapHeight;
}

//-----------------------------------------------------------------------------------

// Browser Window Size and Position
 function pageWidth() { return parseInt( window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null, 10); }
 function pageHeight() { return parseInt( window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null, 10); }
 function posLeft() { return parseInt( typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0, 10); }
 function posTop() { return parseInt( typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0, 10); }
 function posRight() { return parseInt( posLeft()+pageWidth(), 10);}
 function posBottom() { return parseInt( posTop()+pageHeight(), 10);}

//-----------------------------------------------------------------------------------

function XYoffset(imageObject) {
   if( !imageObject ) { imageObject = document.images.mapImage; }
   if( typeof imageObject.offsetLeft  == 'number' ) {
      Xoffset = parseInt(imageObject.offsetLeft,10);
      Yoffset = parseInt(imageObject.offsetTop,10);
   } else {
      Xoffset = 0;
      Yoffset = 0;
   }

   var temp = imageObject.offsetParent;

   while( temp != null ) {
      Xoffset += parseInt(temp.offsetLeft,10);
      Yoffset += parseInt(temp.offsetTop,10);
      temp = temp.offsetParent;
   }	
}

//-----------------------------------------------------------------------------------

function XYscroll() {
	Xscroll = parseInt(posLeft(),10) + adjustScrollX;
	Yscroll = parseInt(posTop(),10) + adjustScrollY;
}

//-----------------------------------------------------------------------------------

function mouseCoords(e) {
//alert("mouseCoords");
//-- set GLOBAL Variables mouseX and mouseY
	if( typeof window.event != 'undefined' && window.event.clientX ) {
		mouseX = window.event.clientX;
		mouseY = window.event.clientY;
	} else if( e && typeof( e.pageX  == 'number') ) {
		mouseX = e.pageX;
		mouseY = e.pageY;
	} else {
		mouseX = 0;
		mouseY = 0;
	}

	locateMap();

	if( window.Iterator ) {
//--- Firefox - do not add scroll
	} else {
//--- IE6+, Opera, Safari  add scroll
		mouseX += Xscroll;
		mouseY += Yscroll;
	}

	isOverMap = true;
	currentMouseX = mouseX;
	currentMouseY = mouseY;
	if( currentMouseX < mapLeftX ) { currentMouseX = mapLeftX; isOverMap = false; }
	if( currentMouseX > mapRightX ) { currentMouseX = mapRightX; isOverMap = false; }
	if( currentMouseY < mapTopY ) { currentMouseY = mapTopY; isOverMap = false; }
	if( currentMouseY > mapBottomY ) { currentMouseY = mapBottomY; isOverMap = false; }


	if( lastMouseX != currentMouseX || lastMouseY != currentMouseY ) {
		lastMouseX = currentMouseX;
		lastMouseY = currentMouseY;

// is over menu???

		if( mapMeasure == '1' ) {

			if( !mapMeasureOverScrollBar() && !mapMeasureFinish ) {

				if( mouseDown == 1 ) {
				} else {

//-- bring focus to measure tool window if outside map area
					if( overScrollBar ) { overScrollBar = false; openMeasureTool(lastMouseMode); }

				}
			} else {
				overScrollBar = true;
			}
			zbCrossLines('red');
		} else {
			if( map_pan == 1 ) {
//-- Pan button
				if( mouseDown == 1 ) {
					if( zbLeft === 0 && zbTop === 0 ) {
						zbLeft = currentMouseX;
						zbTop = currentMouseY;
					}
					zb.clear();
					xLeft = zbLeft;
					xRight = currentMouseX;
					if( xRight < xLeft ) { xLeft = currentMouseX; xRight = zbLeft; }
					yTop = zbTop;
					yBottom = currentMouseY;
					if( map_s <= zoomMin ) {
						zb.setColor("white");
						zb.fillRect( xLeft, yTop, 300, 100);
						zb.setColor("black");
						zb.setFont("arial","25px",Font.BOLD);
						zb.drawString( 'Cannot Zoom In further', xLeft+5, yTop );
						zb.drawString( 'with Base Map choice', xLeft+5, yTop+35 );
						zb.drawString( document.mapform.bm.value, xLeft+5, yTop+70 );
						zb.paint();
					}
					if( yBottom < yTop ) { yTop = currentMouseY; yBottom = zbTop; }

					if( xRight-xLeft > 3 && yBottom-yTop > 3 ) {
//-- Set Color for ZoomBox
						zb.setColor("blue");

						zb.setStroke(4);
						zb.drawRect( xLeft, yTop,  xRight-xLeft, yBottom-yTop );
						zb.paint();
						var dateMouseDown = new Date();
						timeMouseDown = dateMouseDown.getMilliseconds();
						timeMouseDown += dateMouseDown.getSeconds() * 1000.0;
						timeMouseDown += dateMouseDown.getMinutes() * 60000.0;
					}
				} else {
					if( xRight !== 0 ) {
						zbLeft = 0;
						zbTop = 0;
						xRight = 0;
						yTop = 0;
						xLeft = 0;
						yBottom = 0;
					}
					zbCrossLines();
				}

			} else {
//-- ID button
				zbCrossLines();
			}
		}
	}

	return ( !isOverMap );

//-- private functions -----------------------------------------------------------------------

	function zbCrossLines(color) {
		var message;
		if( isOverMap ) {
			var utmE = parseInt( map_min_utmx + ((currentMouseX - Xoffset - adjustPointerX )* map_pixel) + 0.5,10);
			var utmN = parseInt( map_max_utmy - ((currentMouseY - Yoffset - adjustPointerY )* map_pixel) + 0.5,10);
			message = utmE + ' ' + utmN + ' ' + map_dpz;
			setNAD27();
			cursorLL =  UTM2LL(message);

			if( mouseDown == 1 ) {
				if( mouseMode == '2' ) {
					mmA.drawLine(mouseX, mouseY, lastX, lastY);
					mmA.paint();
					xList = ',' + mouseX + xList;
					yList = ',' + mouseY + yList;
					lastX = mouseX;
					lastY = mouseY;
					mapMeasureDDList = ',' + cursorLL + mapMeasureDDList;
				}
			}

			if( map_coord == 'UTM27' ) {
				message += ' NAD27';
			} else if( map_coord == 'LL' ) {
				message = dd2dms(cursorLL);
			} else if( map_coord == 'UTM83' ) {
				setNAD83();
				message = LL2UTM(cursorLL) + ' NAD83';
				setNAD27();
			} else if( map_coord == 'DD') {
				LLArray = cursorLL.split(' ');
				message = nDecString(LLArray[0],6) + ' ' + nDecString(LLArray[1],6);
 			} else {
			}

			document.getElementById('divCursorPosition').innerHTML = '&nbsp;' + message;
			var x = posLeft();
			var y = posTop();
			if( x < 235 ) { 
				x = 0;
			} else {
				x -= 235;
				if( y < 80 ) { y += 80; }
			}

			if( y<80 ) {
				y = 0;
			} else if( y < 130 ) {
				y = 50;
			} else {
				y -= 80;
			}

			if( x || y ) { styleObject('divCursorPosition').backgroundColor = '#FFFFCC'; }   //-- #FFFFCC light yellow
			else { styleObject('divCursorPosition').backgroundColor = 'transparent'; }
			styleObject('divCursorPosition').left = x + 'px';
			styleObject('divCursorPosition').top = y + 'px';

			if( color ) {
				zb.clear();
				zb.setColor(color);
				zb.setStroke(1);
				zb.drawLine( currentMouseX, mapTopY, currentMouseX, mapBottomY );
				zb.drawLine( mapLeftX, currentMouseY, mapRightX, currentMouseY );
				zb.paint();
			}

		} else if( !isOverMap ) {
			message = '';
			zb.clear();
			document.getElementById('divCursorPosition').innerHTML = message;
			styleObject('divCursorPosition').backgroundColor = 'transparent';
		}
		return true;
	}
}

//-----------------------------------------------------------------------------------

function testMouseDown(e) {
   if( !e && document.event ) { e = document.event; }
   var x, y;
   mouseDown = 0;
   mouseCoords(e);
//---  mapMeasure is set using measure button
   mapMeasure = document.mapform.measure.value;

   if ( mapMeasureOverScrollBar() ) { return( mapMeasure!='1' ); }

   var rightclick;
   if( !e ) { e = window.event; }
   if( e.which ) { rightclick = ( e.which == 3 ); }
   else if( e.button ) { rightclick = ( e.button == 2 ); }
   if( rightclick ) { return( mapMeasure!='1' ); }

   x = mouseX;
   y = mouseY;

   if( x < mapLeftX ) { x = mapLeftX; }
   if( x > mapRightX ) { x = mapRightX; }
   if( y < mapTopY ) { y = mapTopY; }
   if( y > mapBottomY ) { y = mapBottomY; }
   if( mouseDown != 1 && x > mapLeftX && x < mapRightX && y > mapTopY && y < mapBottomY ) {

//--- preventDefault to prevent default mouse drag events so that we can drag a box for zoom in.
       if( e.preventDefault ) { e.preventDefault(); }

	isOverMap = true;

      if( mapMeasureFinish ) { measureTool('4'); }

      mouseDown = 1;

      if( mapMeasure == '1' ) {

         if( xList === '' && mapMeasureDDListArray.length === 0 ) { mmA.clear(); }
         if( mouseMode == '2' ) { 
//-- tooltip tt_disabled is defined when wz_tooltip.js is loaded.  Disable tooltip from grabbing focus
            if( typeof tt_disabled  != 'undefined' ) { tt_disabled = 1; }
         }

         mapMessageMaxX = 0;

         if( lastX != x || lastY != y ) {
            xList = ',' + x + xList;
            yList = ',' + y + yList;
		mapMeasureDDList = ',' + cursorLL + mapMeasureDDList;
            lastX = x;
            lastY = y;
            mmA.clear();
            measureDrawPoint( mmA, lastX, lastY, "lightgreen" );
            mmA.paint();
         }

//-- prepare for "Drag Your Mouse"
         if( mouseMode == '2' ) {
            mmA.setColor("blue");
            mmA.setStroke(2); 
         }

      }
   }

   var dateMouseDown = new Date();
   timeMouseDown = dateMouseDown.getMilliseconds();
   timeMouseDown += dateMouseDown.getSeconds() * 1000.0;
   timeMouseDown += dateMouseDown.getMinutes() * 60000.0;

// return false allows process in mouseCoords to continue
//   return( mapMeasure!='1' );
   return ( !isOverMap );
}

//-----------------------------------------------------------------------------------


function testMouseUp(e) {

   var i, cX, cY;
//-- tt_disabled is defined when wz_tooltip.js is loaded.  enable tooltip to get focus
   if( typeof tt_disabled  != 'undefined' ) { tt_disabled = 0; }

   if( mouseDown == 1 ) {

       mouseDown = 0;

      var dateMouseDown = new Date();
      timeMouseUp = dateMouseDown.getMilliseconds();
      timeMouseUp += dateMouseDown.getSeconds() * 1000.0;
      timeMouseUp += dateMouseDown.getMinutes() * 60000.0;

      if( mapMeasure != '1' ) {
//---  "click map" when not measuring
//--   timing left over from earlier programming; can be removed.
//--   "click" event must be less than 1000 miliseconds between mouseDown and mouseUp
//--   "box" event must be less than 4500 miliseconds between mouseDown and mouseUp
         var maxTimeDown = 1500;
         if( (xRight-xLeft) > 3  &&  (yBottom-yTop) > 3 ) {
//-- prevent mouse slip becomming zoom-in
            if( timeMouseUp-timeMouseDown < 40 ) {
//alert( "mouseTime='" + (timeMouseUp-timeMouseDown) + "'");
               zb.clear();
               xLeft = parseInt((xLeft+xRight)/2,10);
               yTop = parseInt((yTop+yBottom)/2,10);
               xRight = xLeft;
               yBottom = yTop;
               mouseX = xLeft;
               mouseY = yTop;
            } else {
                maxTimeDown = 4500;
            }
//alert( timeMouseUp-timeMouseDown );
         }
         if( timeMouseUp-timeMouseDown < maxTimeDown ) {
            lastX = mouseX;
            lastY = mouseY;
            click_map(mapIdName,mouseX,mouseY);
         }
         zb.clear();

      } else {
         if( mouseMode == '1' || mouseMode == '2' ) {
            if( ( mapMeasureDDListArray[0] != mapMeasureDDList ) ) {
               mapMeasureAddList();
            }
            measureToolDrawB();
            xList = '';
            yList = '';
            mapMeasureDDList = '';
         }
      }
   } else {
//--- mouseDown != 1

   }
   return( 0 && mapMeasure!='1' );
}

//-----------------------------------------------------------------------------------

function click_map(idName,mX,mY) {
   close_windows(); zb.clear();
   var xcoord, ycoord, idCoordinates, eX,eY,temp;
   var f, s, t, z, p, topx, topy;

   if( !idName ) { idName = 'mapImage'; }
// mouseX,mouseY global var assigned by document.onmousedown = mouseCoords()
   if( mX == null ) { mX = mouseX; }
   if( mY == null ) { mY = mouseY; }

   var press = document.mapform.pan.value;

   if( idName == 'VaLocator' ) {

//-- fixed image on left of mapform header
      p = 9240;
      topx = 181760;
      topy = 4500642;
      z = 17;
      press = 1;
      xRight=0;
      xLeft=0;
      yTop=0;
      yBottom=0;

   } else {

//-- map image
      p = map_pixel;
      topx = map_min_utmx;
      topy = map_max_utmy;
      z = map_dpz;
   }

   XYoffset(eval('document.images.' + idName));
   XYscroll();

   var xCursorError = 0;
   var yCursorError = 0;

      if( document.all  ) {
// ie 6.0.3+ by trial and error
         xCursorError = -p;
         yCursorError = p;
         xCursorError = xCursorError * 3;
         yCursorError = yCursorError * 3;
      } else {
// FireFox & other
         xCursorError = -p;
         yCursorError = 0;
      }

   var utmE,utmN,utmW,utmS;
   if( ( press > 0 ) && (xRight-xLeft) > 3  &&  (yBottom-yTop) > 3 ) {

      if( 0 && map_s <= zoomMin ) {
         zb.clear();
         zb.setColor("white");
         zb.fillRect( xLeft, yTop, 300, 100);
         zb.setColor("black");
         zb.setFont("arial","25px",Font.BOLD);
         zb.drawString( 'Cannot Zoom In further', xLeft+5, yTop );
         zb.drawString( 'with Base Map choice', xLeft+5, yTop+35 );
         zb.drawString( document.mapform.bm.value, xLeft+5, yTop+70 );
         zb.paint();
         zb.setColor("red");
         return true;
      }

	xLeft -= Xoffset;
	xRight -= Xoffset;
	yTop -= Yoffset;
	yBottom -= Yoffset;

      utmW = topx + (xLeft * p) + xCursorError;
      utmN = topy - (yTop * p) + yCursorError;

      utmE = topx + (xRight * p) + xCursorError;
      utmS = topy - (yBottom * p) + yCursorError;

	zoomPixel = (utmE-utmW)/mapWidth;
	var pixelN = (utmN-utmS)/mapHeight;
	if( pixelN < zoomPixel ) { zoomPixel = pixelN; }
	if( zoomPixel < Math.pow(2,zoomMin-10)*0.666 ) { zoomPixel = Math.pow(2,zoomMin-10)*0.666; }

      s = 10;
      if( zoomPixel > 256.0 ) { s = 20;
      } else if( zoomPixel > 128.0 ) { s = 19;
      } else if( zoomPixel > 64.0 ) { s = 18;
      } else if( zoomPixel > 32.0 ) { s = 17;
      } else if( zoomPixel > 16.0 ) { s = 16;
      } else if( zoomPixel > 8.0 ) { s = 15;
      } else if( zoomPixel > 4.0 ) { s = 14;
      } else if( zoomPixel > 2.0 ) { s = 13;
      } else if( zoomPixel > 1.0) { s = 12;
      } else if( zoomPixel > 0.5 ) { s = 11;
      }

      if( map_s <= zoomMin ) {
         zb.clear();
         zb.setColor("white");
         zb.fillRect( xLeft, yTop, 300, 100);
         zb.setColor("black");
         zb.setFont("arial","25px",Font.BOLD);
         zb.drawString( 'Cannot Zoom In further', xLeft+5, yTop );
         zb.drawString( 'with Base Map choice', xLeft+5, yTop+35 );
         zb.drawString( document.mapform.bm.value, xLeft+5, yTop+70 );
         zb.paint();
         zb.setColor("red");
         return true;
      }

	doNotReplaceMap ++;
	setMapScale(s-1);
	map_pixel = zoomPixel;
	document.mapform.p.value = map_pixel;
	doNotReplaceMap --;

//###
//###  remeber to account for scalebar and reported pixel size
//###
      zoomPixel = nDecString(zoomPixel,1+(zoomPixel < 2));
      document.images.MapScale.src = 'mapscale.asp?s=' + map_s + '&p=' + zoomPixel;
      document.getElementById('spanNotePixelSize').innerHTML = zoomPixel;

      utmE = (utmW+utmE)/2;
      utmN = (utmS+utmN)/2;

      idCoordinates = utmE  + ' ' + utmN + ' ' + z;
      map_dpLL = UTM2LL( idCoordinates );

//--- box

   } else {

//--- point

// these calculations have been replaced by cursorLL from routine testMouseDown unless VaLocator
      if( idName == 'VaLocator' ) {
         xcoord = mX - Xoffset;
         ycoord = mY - Yoffset;
         utmE = topx + (xcoord * p) + xCursorError;
         utmN = topy - (ycoord * p) + yCursorError;
         idCoordinates = utmE  + ' ' + utmN + ' ' + z;
         map_dpLL = UTM2LL( idCoordinates );
      } else {

//--- cursor location defined in routine zbCrossLines of testMouseDown
         map_dpLL = cursorLL;
      }
   }

   map_dpUTM17 = LL2UTM( map_dpLL, 17 );
   idCoordinates = map_dpUTM17;

//--- When the base map is NAD 1983, it is displayed by httpMapImage with a shift to represent NAD 1927.
//--- therefore the point clicked is always NAD 1927 even if the base map is NAD 1983.
//--- therefore do not want to convert here
//    if( bm_nad == 1983 ) {
//       utmE -= 17;
//       utmN -= 219;
//    } // nad83 to nad27 conversion

   if( ( document.mapform.t.value == '1'
      || document.mapform.t.value == '2'
      || document.mapform.t.value == 'N'
      || document.mapform.t.value == 'O' ) ) {
//--- check for change in UTM Zone when terraserver images
      idCoordinates  = LL2UTM( map_dpLL );
   }
   var xyArray = idCoordinates.split(' ');
   utmE = parseInt(xyArray.shift(),10);
   utmN = parseInt(xyArray.shift(),10);
   z = parseInt(xyArray.shift(),10);
   idCoordinates = utmE  + ' ' + utmN + ' ' + z;

   if ( press > 0 ) {

      measureDrawPoint( mmA, mX, mY, "lightgreen" );
      mmA.paint();

      if( press == 2 ) { document.mapform.r.value = 1; }

      document.mapform.dp.value = idCoordinates;
//###  changed 8/1505 abj3    map_dpUTM17 = idCoordinates;
      map_dpUTM17 = LL2UTM( map_dpLL, 17 );
      document.mapform.dp_utm17.value = map_dpUTM17;
      if( (display_only != '1' && shift == 1) ) {
          document.mapform.poi.value = idCoordinates;
          map_poiUTM17 = map_dpUTM17;
          map_porUTM17 = map_poiUTM17;
          map_poiLL = map_dpLL;
          document.mapform.poi_utm17.value = map_poiUTM17;
      }
      map_min_utmx = utmE - Math.round(mapWidth*map_pixel/2);
      map_max_utmy = utmN + Math.round(mapHeight*map_pixel/2);
      map_dpz = z;
      document.mapform.dpz.value = map_dpz;
      search_point_comment='';
      mapMeasureCoord(map_coord);
      replaceMap();

   } else {

//--- ID Function

      measureDrawPoint( mmA, mX, mY, "lightgreen" );
      mmA.paint();

	mapReport(idCoordinates);

   }
}

//-----------------------------------------------------------------------------------


function mapReport(idCoordinates) {

//--- popup VaFWIS Map Report window
	if( idCoordinates == null ) { idCoordinates = savedIdCoordinates; }

	var xyArray = idCoordinates.split(',');
	if( xyArray.length > 500 ) {
		xyArray.length = 500;
		idCoordinates = xyArray.join(',');
	}
	xyArray = null;
	savedIdCoordinates = idCoordinates;

//--- establish distance for ID function
      map_s = document.mapform.s.value;
      var click_map_dist = 10;
      if( map_s>16 ) { click_map_dist =  8; }
      if( map_s>18 ) { click_map_dist =  4; }
      click_map_dist = parseInt( click_map_dist * map_pixel,10 );

	var url = '';

if( document.getElementById("mr_tn") ) {

//-- IDWindow.html - submit a form from its parent window
//-- populate formMapReport values

	url = "IDWindow.html?name=formMapReport";
	document.getElementById("mr_tn").value = tn;
	document.getElementById("mr_opoi").value = opoi;
	document.getElementById("mr_poi").value = idCoordinates;
	document.getElementById("mr_pos").value = map_poiUTM17;
	document.getElementById("mr_dist").value = click_map_dist;
	document.getElementById("mr_overlay_list").value = overlay_list;
	document.getElementById("mr_coord").value = map_coord;
	document.getElementById("mr_gap").value = gap;
}

	var width = '350';
	var height = '550';
	if( window.document.mapform && window.document.mapform.idPageSize ) {
		var sizeArray = window.document.mapform.idPageSize.value.split(',');
		width = sizeArray[0];
		height = sizeArray[1];
	}
//-- prevent "old" cached version
	var rExp = / /g;
	url += '&version=' + parseInt(((new Date()).getTime())/1000/60/60/24,10);
	child_window = window.open(url.replace(rExp,'+'),'IDWindow',
		'top=2,left=0,width='+width+',height='+height+',scrollbars=yes,resizable=yes,toolbar=yes');
	child_window.focus();
}

//-----------------------------------------------------------------------------------

function sendFunc() {
   var poiValue = document.mapform.poi.value;
   close_windows();
   if( window.opener && window.opener.document && window.opener.document.get_poi_form ) {
      if( 0 && (map_coord == 'LL' || map_coord == 'DD') ) {
      } else { 
         poiValue = document.mapform.poi_utm17.value;
      }
      window.opener.document.get_poi_form.poi_val.value = poiValue;
      window.opener.document.get_poi_form.distance.focus();
      self.opener.mapActions(poiValue,map_coord);
   }
   close_windows();
   window.close();
}

//-----------------------------------------------------------------------------------

function CancelFunc() {
   close_windows();
   if( window.opener && window.opener.document && window.opener.document.get_poi_form ) {
      window.opener.document.get_poi_form.distance.focus();
   }
   window.close();
}

//-----------------------------------------------------------------------------------

function display_dataRecord() {
//-- set display point to coordinate in opoi_id record
   map_dpUTM17 = map_itemUTM17;
   document.mapform.dp.value = map_dpUTM17;
   var xyArray;
   if( map_t == 1 || map_t == 2 || map_t == 'N' || map_t == 'O' ) {
      xyArray = LL2UTM(UTM2LL(map_dpUTM17)).split(' ');
   } else {
      xyArray = map_dpUTM17.split(' ');
   }
   var utmE = parseInt(xyArray.shift(),10);
   var utmN = parseInt(xyArray.shift(),10);
   map_dpz = parseInt(xyArray.shift(),10);
   document.mapform.dpz.value = map_dpz;
   map_min_utmx = utmE - Math.round(mapWidth*map_pixel/2);
   map_max_utmy = utmN + Math.round(mapHeight*map_pixel/2);
   replaceMap();
}

//-----------------------------------------------------------------------------------

function set_bm(basemap) {
//-- basemap has changed

   document.mapform.bm.value='';

   if( !basemap ) { basemap = basemap=document.mapform.select_bm.value; }
   map_t = 'A';
   if(basemap == 'T') {map_t='2';}
   else if(basemap == 'S') {map_t='1';}
   else if(basemap == 'C') {map_t='3';}
   else if(basemap == 'H') {map_t='4';}
   else if(basemap == 'TI') {map_t='6';}
   else if(basemap == 'Topography') {map_t='2';}
   else if(basemap == 'BW Aerial Photography') {map_t='1';}
   else if(basemap == 'County line map') {map_t='3';}
   else if(basemap == 'NRCS Hydrography') {map_t='4';}
   else if(basemap == 'TopoIndex') {map_t='6';}
   else if(basemap == 'County - Quadrangle') {map_t='A';}
   else if(basemap == 'White') {map_t='0';}
   else if(basemap == 'County_A') {map_t='A';}
   else if(basemap == 'HydroUnit') {map_t='B';}
   else if(basemap == 'HydroDrain') {map_t='C';}
   else if(basemap == 'HU6 Hydrography') {map_t='D';}
   else if(basemap == 'Color Aerial Photography') {map_t='O';}
   else if( '0123456789ABCDO'.indexOf(basemap,0)>-1 ) {map_t=basemap;}

   document.mapform.t.value = map_t;

//-- there are six options to the select list control 0-5 with the last
//-- (5) replaced with one not available in 0-4
   var i = 5;

   if(map_t === '0')      {basemap='White';}
   else if(map_t == '1') {basemap='BW Aerial Photography';  i = 2;}
   else if(map_t == '2') {basemap='Topography';          i = 0;}
   else if(map_t == '3') {basemap='County line map';}
   else if(map_t == '4') {basemap='NRCS Hydrography';}
   else if(map_t == '6') {basemap='TopoIndex';}
   else if(map_t == 'A') {basemap='County - Quadrangle'; i = 3;}
   else if(map_t == 'B') {basemap='HydroUnit';}
   else if(map_t == 'C') {basemap='HydroDrain';}
   else if(map_t == 'D') {basemap='HU6 Hydrography';	i = 4;}
   else if(map_t == 'O') {basemap='Color Aerial Photography';  i = 1;}

   if( i == 5 ) { document.mapform.select_bm.options[i] = new Option(basemap,basemap,false,true); }

   document.mapform.select_bm.options[i].selected=true;
   document.mapform.bm.value = basemap;

   var xyArray = LL2UTM(UTM2LL(document.mapform.poi_utm17.value,17)).split(' ');
   var poiE = parseInt(xyArray.shift(),10);
   var poiN = parseInt(xyArray.shift(),10);
   var cmz = parseInt(xyArray.shift(),10);
   var cmx = parseInt( poiE/(map_pixel*200),10);
   var cmy = parseInt( poiN/(map_pixel*200),10);
   if( !cmz ) { cmz = 17; }

   if(map_t === '0')      { bm_nad=1927; }
   else if(map_t == '1') { bm_nad=1983; }
   else if(map_t == '2') { bm_nad=1983; }
   else if(map_t == '3') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '4') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '6') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '9') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'A') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'B') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'C') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'D') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'N') { bm_nad=1983; }
   else if(map_t == 'O') { bm_nad=1983; }
   else { bm_nad=1927; cmz = '17'; }
   if( cmz != map_dpz ) {
//-- switch to UTM Zone cmz
      xyArray = LL2UTM(UTM2LL(map_min_utmx + ' ' + map_max_utmy + ' ' + map_dpz),cmz).split(' ');
      map_min_utmx = parseInt(xyArray.shift(),10);
      map_max_utmy = parseInt(xyArray.shift(),10);
      map_dpz = cmz;
      document.mapform.dpz.value = map_dpz;
   }

   setMapScale();
}

//-----------------------------------------------------------------------------------

function replace_bm(basemap) {
   if( !basemap ) {
      basemap = basemap=document.mapform.select_bm.selectedIndex;
      basemap = basemap=document.mapform.select_bm[basemap].text;
   }
   basemap = basemap.split('\n')[0];
   if( basemap != document.mapform.bm.value ) {
      doNotReplaceMap += 1;
      set_bm(basemap);
      doNotReplaceMap -= 1;
      replaceMap();
   }
}

//-----------------------------------------------------------------------------------

function display_poi() {
   var xyArray;
   map_dpUTM17 = map_poiUTM17;
//?--- map_porUTM17 = map_poiUTM17;
   document.mapform.dp.value = map_poiUTM17;
   if( map_t == 1 || map_t == 2 || map_t == 'N' || map_t == 'O' ) {
      xyArray = LL2UTM(map_poiLL).split(' ');
   } else {
      xyArray = map_poiUTM17.split(' ');
   }
   var utmE = parseInt(xyArray.shift(),10);
   var utmN = parseInt(xyArray.shift(),10);
   map_dpz = parseInt(xyArray.shift(),10);
   document.mapform.dpz.value = map_dpz;
   map_min_utmx = utmE - Math.round(mapWidth*map_pixel/2);
   map_max_utmy = utmN + Math.round(mapHeight*map_pixel/2);
   replaceMap();
}

//-----------------------------------------------------------------------------------

function mapSourceComment() {
   var map_source_comment = '';
   var xyArray = LL2UTM(UTM2LL(document.mapform.poi_utm17.value,17)).split(' ');
   var poiE = parseInt(xyArray.shift(),10);
   var poiN = parseInt(xyArray.shift(),10);
   var cmz = parseInt(xyArray.shift(),10);
   var cmx = parseInt( poiE/(map_pixel*200),10);
   var cmy = parseInt( poiN/(map_pixel*200),10);
   if( !cmz ) { cmz = 17; }

   if(map_t === '0')      { bm_nad=1927; }
   else if(map_t == '1') { bm_nad=1983; }
   else if(map_t == '2') { bm_nad=1983; }
   else if(map_t == '3') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '4') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '6') { bm_nad=1927; cmz = '17'; }
   else if(map_t == '9') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'A') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'B') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'C') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'D') { bm_nad=1983; cmz = '17'; }
   else if(map_t == 'N') { bm_nad=1983; }
   else if(map_t == 'O') { bm_nad=1983; }
   else { bm_nad=1927; cmz = '17'; }
   if( map_t === '0' ) {
      map_source_comment='2003 Map data managed by Virginia Department of Game and Inland Fiosheries.';
      }
   else if( map_t == '1') {
      map_source_comment = "Black & White USGS Aerial Photography ";
      map_source_comment += "(see <a href='http://terraserver-usa.com/image.aspx?t=1&s=";
      map_source_comment += map_s + '&x=' + cmx + '&y=' + cmy + '&z=' + cmz + "&w=1'>terraserver-usa.com</a> for details)";
      }
   else if( map_t == '2' ) {
      if(map_s<13) {
         map_source_comment = "Topographic maps from TOPO! copyright 2006";
         map_source_comment += " (see <a href='http://www.national.geographic.com/topo'>";
         map_source_comment += "National Geographic</a> for details)";
         }
      else if( map_s<15 ) {
         map_source_comment="USGS 1:100,000 topographic maps ";
         map_source_comment += "(see <a href='http://terraserver-usa.com/image.aspx?t=2&s=";
         map_source_comment += map_s + '&x=' + cmx + '&y=' + cmy + '&z=' + cmz + "&w=1'>terraserver-usa.com</a> for details)";
         }
      else {
         map_source_comment="USGS 1:250,000 topographic maps ";
         map_source_comment += "(see <a href='http://terraserver-usa.com/image.aspx?t=2&s=";
         map_source_comment += map_s + '&x=' + cmx + '&y=' + cmy + '&z=' + cmz + "&w=1'>terraserver-usa.com</a> for details)";
         }
      }
   else if( map_t == '3' ) { map_source_comment='2003 Va. DGIF city/county digital lines';
      }
   else if( map_t == '4' ) { map_source_comment='2003 Va. DGIF hydrography digital lines';
      }
   else if( map_t == '6' ) { map_source_comment='1984 USGS index to Virginia 1:24,000 topographic maps';
      }
   else if( map_t == '9' ) { map_source_comment='2003 Va. DGIF Virginia Basemap ';
      }
   else if( map_t == 'A' ) { map_source_comment='2003 Va. DGIF Virginia Basemap ';
      }
   else if( map_t == 'B' ) { map_source_comment='2003 Va. DGIF Virginia Basemap ';
      }
   else if( map_t == 'C' ) { map_source_comment='2003 Va. DGIF Virginia Basemap ';
      }
   else if( map_t == 'D' ) { map_source_comment='2009 Va. DGIF National 6th Order Watersheds for Virginia ';
      }
   else if( map_t == 'O' ) { map_source_comment='Color Aerial Photography 2002 - Virginia Base Mapping Program,';
				map_source_comment+=' Virginia Geographic Information Network ';
      }

   if( map_source_comment !== '') {
      document.getElementById('spanNoteBasemap').innerHTML =
     'Base Map source: ' + map_source_comment;
   }
}

//-----------------------------------------------------------------------------------

function set_rings(parm){
   if( typeof parm  == 'undefined' ) {
      parm = 0;
      if( document.mapform.ret[0].checked === true ) { parm = 0; } else { parm = 1; }
   }
   if( parm<0 ) { parm=0; }
   if( parm>1 ) { parm=1; }
   document.mapform.ret[parm].checked = true;

//--- Ring diameters
   var radius, diam, radius4, diam4;
//---  Amy wants old system -- 1/4 mile for eagle nests
if(0) {
   if( map_coord == 'LL' || map_coord == 'DD' ) { 
      if( map_pixel < 2 ) { radius=61;            ringDescription = '50 feet and 200 feet';    //  10
      } else if (map_pixel<4) { radius=122;       ringDescription = '100 feet and 400 feet';   //  11
      } else if (map_pixel<8) { radius=244;       ringDescription = '200 feet and 800 feet';   //  11
      } else if (map_pixel<16) { radius=488;      ringDescription = '400 feet and 1600 feet';  //  13
      } else if (map_pixel<32) { radius=805;      ringDescription = '1/8 mileand 1/2 mile';    //  14
      } else if (map_pixel<64) { radius=1609;     ringDescription = '1/4 mile and 1 miles';    //  15
      } else if (map_pixel<128) { radius=3218;    ringDescription = '1/2 mile and 2 miles';    //  16
      } else if (map_pixel<256) { radius=8045;    ringDescription = '1.25 mile and 5 miles';   //  17
      } else if (map_pixel<512) { radius=16090;   ringDescription = '2.5 miles and 10 miles';  //  18
      } else if (map_pixel<1024) { radius=32180;  ringDescription = '5 miles and 20 miles';    //  19
      } else { radius=64360;                      ringDescription = '10 miles and 40 miles';   // >=20
      }

   } else {
      if( map_pixel < 2 ) { radius=50;            ringDescription = '12.5 meters and 50 meters';          //  10
      } else if (map_pixel<4) { radius=100;       ringDescription = '25 meters and 100 meters';           //  11
      } else if (map_pixel<8) { radius=200;       ringDescription = '50 meters and 200 meters';           //  12
      } else if (map_pixel<16) { radius=400;      ringDescription = '100 meters and 400 meters';          //  13
      } else if (map_pixel<32) { radius=800;      ringDescription = '200 meters and 800 meters';          //  14
      } else if (map_pixel<64) { radius=2000;     ringDescription = '1/2 Kilometer and 2 Kilometers';     //  15
      } else if (map_pixel<128) { radius=4000;    ringDescription = '1 Kilometers and 4 Kilometers';      //  16
      } else if (map_pixel<256) { radius=8000;    ringDescription = '2 Kilometers and 8 Kilometers';      //  17
      } else if (map_pixel<512) { radius=16000;   ringDescription = '4 Kilometers and 16 Kilometers';     //  18
      } else if (map_pixel<1024) { radius=32000;  ringDescription = '8 Kilometers and 32 Kilometers';     //  19
      } else { radius=50000;                      ringDescription = '12.5 Kilometers and 50 Kilometers';  // >=20
      }
   }
}


//--- POI Ring diameters
    if( map_coord == 'LL' || map_coord == 'DD' ) {
       if (map_pixel<2) { radius=201;              ringDescription = '1/8 mile and 1/32 mile';  //  10  
       } else if (map_pixel<=4) { radius=402;      ringDescription = '1/4 mile and 1/16 mile';  //  11,12
       } else if (map_pixel<=8) { radius=805;      ringDescription = '1/2 mile and 1/8 mile';   //  13
       } else if (map_pixel<=32) { radius=1609;    ringDescription = '1 mile and 1/4 mile';     //  14,15
       } else if (map_pixel<=128) { radius=6436;   ringDescription = '4 miles and 1 mile';      //  16,17
       } else if (map_pixel<=512) { radius=25744;  ringDescription = '16 miles and 4 miles';    //  18,19
       } else if (map_pixel<=4096) { radius=51488; ringDescription = '32 miles and 8 miles';    //  20
       } else { radius=102976;                     ringDescription = '64 miles and 16 miles';   // >20
       }
    } else {
       if (map_pixel<2) { radius=100;              ringDescription = '100 meters and 25 meters';          //  10
       } else if (map_pixel<=4) { radius=200;      ringDescription = '200 meters and 50 meters';          //  11,12
       } else if (map_pixel<=8) { radius=800;      ringDescription = '800 meters and 200 meters';         //  13
       } else if (map_pixel<=32) { radius=2000;    ringDescription = '2 kilometers and 1/4 kilometer';    //  14,15
       } else if (map_pixel<=128) { radius=6000;   ringDescription = '6 kilometers and 1.5 kilometer';    //  16,17
       } else if (map_pixel<=512) { radius=20000;  ringDescription = '20 kilometers and 5 kilometer';     //  18,19
       } else if (map_pixel<=4096) { radius=40000; ringDescription = '40 kilometers and 10 kilometer';    //  20
       } else { radius=100000;                     ringDescription = '100 kilometers and 25 kilometer';   //  >20
       }
    }

   document.getElementById('spanRings').innerHTML = ringDescription + ' at the <b>' + porDescription + '</b>';
   document.mapform.pointdescription.value = ringDescription + ' at the<br><b>' + porDescription + '</b>';

   overlay_list = document.mapform.overlay_list.value.replace(/ /g,'');

   if( parm === 0 ) {
      diam = radius*2;
      radius4 = Math.round(radius/4);
      diam4 = Math.round(diam/4);
      rings = radius + '%2C' + radius4;
      if( overlay_list.indexOf('Position',0) < 0 ) {
         if( overlay_list !== '' ) { overlay_list += ','; }
         overlay_list += 'Position';
      }
   } else {
      var i = overlay_list.indexOf('Position',0);
      if(i > -1 ) {
         if( i === 0 ) {
            overlay_list = overlay_list.substr(9,overlay_list.length-9);
         } else {
            overlay_list = overlay_list.substr(0,i-1) + overlay_list.substr(i+8,overlay_list.length-i-8);
         }         
      }
      rings = '';
   }

   document.mapform.overlay_list.value = overlay_list;

   setOverlayLegend();
}

//-----------------------------------------------------------------------------------

function set_search(parm){
   if( map_dist > 0 ) {
   if( typeof parm  == 'undefined' ) {
      parm = 0;
      if( document.mapform.search[0].checked === true ) { parm = 0; } else { parm = 1; }
   }
   if( parm<0 ) { parm=0; }
   if( parm>1 ) { parm=1; }
   document.mapform.search[parm].checked = true;

   if( parm === 0 ) {
      if( overlay_list.indexOf('Search',0) < 0 ) {
         if( overlay_list !== '' ) { overlay_list += ','; }
         overlay_list += 'Search';
      }
   } else {
      var i = overlay_list.indexOf('Search',0);
      if(i > -1 ) {
         if( i === 0 ) {
            overlay_list = overlay_list.substr(7,overlay_list.length-7);
         } else {
            overlay_list = overlay_list.substr(0,i-1) + overlay_list.substr(i+6,overlay_list.length-i-6);
         }         
      }
   }

   document.mapform.overlay_list.value = overlay_list;
   }
   setOverlayLegend();
}

//-----------------------------------------------------------------------------------

function setOverlayLegend(list) {
   if( !list ) { list = ''; }
   overlay_list = document.mapform.overlay_list.value;
   if( overlay_list != list || overlay_list === '' ) {
      if( list !== '' ) { overlay_list = list; }
      document.getElementById('overlaySplit').innerHTML = overlay_list.replace(/ /g,'').replace(/,/g,', ');
      document.mapform.overlay_list.value = overlay_list.replace(/ /g,'');

      var legend_dist = '';
      if( map_coord == 'LL' || map_coord == 'DD' ) {
         legend_dist = Math.round( (map_dist)/16.09 )/100  + '+mile+radius';
      } else { 
         legend_dist = map_dist + '+meter+radius';
      }

      var url = 'OverlayLegend.asp?overlay=' + overlay_list;
      url += '&legend_dist=' + legend_dist;
      url += '&width=' + bar_width;
      url += '&pixel=' + map_pixel;
      url += '&opoi=' + opoi;
      url += '&have_list=' + have_list;
      if( rings !== '' ) { url += '&rings=' + ringDescription + ' at the ' + porDescription; }
      document.images.overlayLegend.src = url.replace(/ /g,'+');
   }
}

//-----------------------------------------------------------------------------------

function setMapScale(s) {
   if( !s ) { s = document.mapform.s.value; }

   map_s = parseInt(s,10);

//--- Limit zoom by basemap type
   map_t = document.mapform.t.value;
   if(map_t === '0')      { if(s<10){map_s=10;} if(s>20){map_s=20;} zoomMin=10; zoomMax=20; }
   else if(map_t == '1') { if(s<10){map_s=10;} if(s>16){map_s=16;} zoomMin=10; zoomMax=16; }
   else if(map_t == '2') { if(s<11){map_s=11;} if(s>17){map_s=17;} zoomMin=11; zoomMax=17; }
   else if(map_t == '3') { if(s<16){map_s=16;} if(s>20){map_s=20;} zoomMin=16; zoomMax=20; }
   else if(map_t == '4') { if(s<16){map_s=16;} if(s>20){map_s=20;} zoomMin=16; zoomMax=20; }
   else if(map_t == '6') { if(s<16){map_s=16;} if(s>20){map_s=20;} zoomMin=16; zoomMax=20; }
   else if(map_t == '9') { if(s<16){map_s=16;} if(s>20){map_s=20;} zoomMin=16; zoomMax=20; }
   else if(map_t == 'A') { if(s<16){map_s=16;} if(s>20){map_s=20;} zoomMin=16; zoomMax=20; }
   else if(map_t == 'B') { if(s<15){map_s=15;} if(s>20){map_s=20;} zoomMin=15; zoomMax=20; }
   else if(map_t == 'C') { if(s<15){map_s=15;} if(s>20){map_s=20;} zoomMin=15; zoomMax=20; }
   else if(map_t == 'D') { if(s<15){map_s=15;} if(s>20){map_s=20;} zoomMin=15; zoomMax=20; }
   else if(map_t == 'O') { if(s<10){map_s=10;} if(s>20){map_s=20;} zoomMin=10; zoomMax=20; }
   else {                  if(s<10){map_s=10;} if(s>20){map_s=20;} zoomMin=10; zoomMax=20; }
   document.mapform.s.value = map_s;

   var url = 'ZoomSelect.asp?s=' + map_s;
   url += '&min=' + zoomMin + '&max=' + zoomMax;

   document.images.ZoomSelect.src = url;

   if( document.getElementById('spanZoomSelect') ) {
      if( map_s == zoomMin ) {
         document.getElementById('spanZoomSelect').innerHTML = 
            ' - Currently at closest Zoom-IN available for current map: ' +
         document.mapform.bm.value;
      }
      else if( map_s == zoomMax ) {
         document.getElementById('spanZoomSelect').innerHTML = 
            ' - Currently at greatest Zoom-OUT available for current map: ' +
            document.mapform.bm.value;

      }
      else { document.getElementById('spanZoomSelect').innerHTML = ''; }
   }

   var map_pixels = Math.pow(2,map_s-10);
   map_pixel = parseFloat(document.mapform.p.value);

   var xyArray, utmE, utmN;
   if( parseInt(document.mapform.s.value,10) != map_s || map_pixel != map_pixels ) {
      map_pixel = map_pixels;
      document.mapform.p.value = map_pixel;
      var value = map_pixel + ' meter';
      if( map_pixel>1 ) { value += 's'; }
      document.getElementById('spanNotePixelSize').innerHTML = value;
      map_dpUTM17 = document.mapform.dp_utm17.value;
      map_poiUTM17 = document.mapform.poi_utm17.value;
      xyArray = LL2UTM(UTM2LL(map_dpUTM17,17),map_dpz).split(' ');
      utmE = parseFloat(xyArray.shift());
      utmN = parseFloat(xyArray.shift());
      map_min_utmx = Math.round(utmE - (mapWidth*map_pixel/2));
      map_max_utmy = Math.round(utmN + (mapHeight*map_pixel/2));
      set_rings();
      replaceMap();
   } else {
      map_dpUTM17 = document.mapform.dp_utm17.value;
      map_poiUTM17 = document.mapform.poi_utm17.value;
      xyArray = LL2UTM(UTM2LL(map_dpUTM17,17),map_dpz).split(' ');
      utmE = parseFloat(xyArray.shift());
      utmN = parseFloat(xyArray.shift());
      map_min_utmx = Math.round(utmE - (mapWidth*map_pixel/2));
      map_max_utmy = Math.round(utmN + (mapHeight*map_pixel/2));
   }

   document.images.MapScale.src = 'mapscale.asp?s=' + map_s;

   mapSourceComment();
}

//-----------------------------------------------------------------------------------

function clickZoomSelect() {

   var s = parseInt(document.mapform.s.value,10);
   XYoffset(document.images.ZoomSelect);
   var xcoord = mouseX - Xoffset;
   var zsx = parseInt((xcoord-5)/10,10);
   if( zsx < 1 ) { s-=1; }
   else if( zsx > 11 ) { s+=1; }
   else { s = zsx+9; }
   setMapScale(s);
}

//-----------------------------------------------------------------------------------

function setMapSize(tilex,tiley) {
   var tileArray = ('' + tilex).split(',');
   tilex = parseInt(tileArray.shift(),10);
   if( tileArray[0] ) { tiley = parseInt(tileArray.shift(),10); }
   if( !tilex ) { tilex = 3; }
   if( !tiley ) { tiley = tilex; }
   tilex = parseInt( tilex,10 );
   if( tilex < 1 ) { tilex = 1; }
   tiley = parseInt( tiley,10 );
   if( tiley < 1 ) { tiley = 1; }

   var limit = 5;
   if( typeof user_type == 'undefined' ) { user_type = 'V'; }
   if( user_type == 'A' ) { limit = 23; }
   if( user_type == 'B' ) { limit = 7; }
   if( tilex > limit ) { tilex = limit; }
   if( tiley > limit ) { tiley = limit; }

//--- assign pagesize used in PageSizeSelect graphic
   var pagesize;
   if( tilex==1 && tiley==1 ) { pagesize=1; }
   else if( tilex==2 && tiley==2 ) { pagesize=2; } 
   else if( tilex==3 && tiley==3 ) { pagesize=3; }
   else if( tilex==4 && tiley==4 ) { pagesize=4; }
   else if( tilex==5 && tiley==5 ) { pagesize=5; }
   if( tilex>5 || tiley>5 ) { pagesize=6; }

   var url = 'PageSizeSelect.asp?s=' + pagesize + '"';
   document.images.PageSizeSelect.src = url;

   mapWidth = tilex * 200;
   mapHeight = tiley * 200;

   if( document.mapform.tile.value != (tilex + ',' + tiley) ) {
      document.mapform.tile.value = (tilex + ',' + tiley);
      var utm = map_dpUTM17;
      if( map_t == 1 || map_t == 2 || map_t == 'N' || map_t == 'O' ) { utm = LL2UTM( UTM2LL( utm, 17 ) ); }
      var xyArray = (utm + ' 17').split(' ');
      map_min_utmx = parseInt(xyArray.shift(),10) - Math.round(mapWidth*map_pixel/2);
      map_max_utmy = parseInt(xyArray.shift(),10) + Math.round(mapHeight*map_pixel/2);
      replaceMap();

   }
   locateMap();
}

//-----------------------------------------------------------------------------------

function clickSizeSelect() {

   var tile = parseInt(document.mapform.tile.value,10);
   XYoffset(document.images.PageSizeSelect);
   var xcoord = mouseX - Xoffset;
   var psx = parseInt((xcoord-5)/20,10);
   if( psx < 1 ) { tile-=1; }
   else if( psx > 5 ) { tile+=1; }
   else { tile = psx; }
   if( tile < 1 ) { tile = 1; }
   setMapSize(tile);
   return true;
}

//-----------------------------------------------------------------------------------

function refbutton() {
//-- referesh button (available to sysop)
   document.mapform.r.value='1';
   replaceMap();
   document.mapform.r.value='0';
   scroll(0,0);
}

//-----------------------------------------------------------------------------------

function close_windows() {
   close_child_window();
//-- tt_disabled is defined when wz_tooltip.js is loaded.  enable tooltip to get focus
   if( typeof tt_disabled  != 'undefined' ) { tt_disabled = 0; }
//-- mmUnload is defined in zMApFormJava.asp
   if( mmWindow ) { mmUnload(); }
}

//-----------------------------------------------------------------------------------

function close_child_window() {
   if( child_window && child_window.closed ) { child_window = null; }
   if( child_window && child_window.close ) { child_window.close(); }
   child_window = null;
}

//-----------------------------------------------------------------------------------

function get_basemap() {
   close_windows();
   child_window = window.open('VaFWIS_MapForm_get_basemap.htm','getWindow',
      'top=50,left=50,width=550,height=650,resizable=no,scrollbars=yes,toolbar=no');

   child_window.focus();
}

//-----------------------------------------------------------------------------------

function openHelpWin(fileName) {
   close_windows();
   child_window = window.open(fileName,'helpWindow',
       'top=50,left=50,width=700,height=550,resizable=yes,scrollbars=yes,toolbar=no');

   child_window.focus();
}

//-----------------------------------------------------------------------------------

function openAuxillaryLegendWin(fileName) {
   if( fileName !== '' ) {
      close_windows();
      child_window = window.open(fileName,'showWindow',
         'top=50,left=50,width=700,height=550,resizable=yes,scrollbars=yes,toolbar=no');

      child_window.focus();
   }
}

//-----------------------------------------------------------------------------------

function get_overlay() {
   close_windows();
   child_window = window.open('VaFWIS_MapForm_get_overlay.htm','getWindow',
      'top=50,left=50,width=550,height=650,resizable=yes,scrollbars=yes,toolbar=no');

   child_window.focus();
}

//-----------------------------------------------------------------------------------

function set_shift(s) {
//--- asign global variables shift and title0
   shift=s;
   if( display_only != '1' ) {
//--- document.mapform.shift only exists when display_only != '1'
      if( s==1 ) {
         document.mapform.shift.checked=1;
         document.mapform.shift2.checked=0;
         title0 = title1;
      }
      if( s==2 ) {
         document.mapform.shift.checked=0;
         document.mapform.shift2.checked=1;
         title0 = title2;
      }
   }
}

//-----------------------------------------------------------------------------------

function panButton( mode ) {
   if( document.mapform.measure.value === '0' ) {
      if( mode == null ) { mode = document.mapform.pan.value; }
      if ( mode == 1 ) {
         mapTitle = title0;
         document.getElementById('pan_button').src = 'images/PanButton1.png';
         document.getElementById('id_button').src  = 'images/IdButton0.png';
         document.mapform.pan.value='1';
         document.mapform.r.value='0';
       } else {
         mapTitle = title3;
         document.getElementById('pan_button').src = 'images/PanButton0.png';
         document.getElementById('id_button').src  = 'images/IdButton1.png';
         document.mapform.pan.value='0';
         document.mapform.r.value='0';
      }
   } else {
      measureButton('0');
//-- careful! recursive call
      panButton(mode);
     
   }
   map_pan = document.mapform.pan.value;
}

//-----------------------------------------------------------------------------------

function measureDrawPoint( graphicObject, x, y, color ) {
   graphicObject.setColor( color );
   graphicObject.setStroke(2);
   graphicObject.drawRect(x-6,y-6,12,12);
}

//-----------------------------------------------------------------------------------

function measureDrawLine( graphicObject, xf, yf, xl, yl ) {
	if( 	   ( xf > mapLeftX && xf < mapRightX )
		&& ( xl > mapLeftX && xl < mapRightX )
		&& ( yf > mapTopY && yl < mapBottomY )
		&& ( yl > mapTopY && yl < mapBottomY ) 
	) {
		graphicObject.drawLine(xf,yf,xl,yl);
	} else {
//--- draw any overlap

		var p1x = -1; var p1y = -1; var p2x = -1; var p2y = -1;

		var line = new Segment(new Vector(xf, yf), new Vector(xl, yl));

		var side = new Segment( new Vector( mapLeftX+1, mapTopY+1), new Vector(mapLeftX+1, mapBottomY-1) );
		var intersectionPoint = new Vector(0, 0);
		if(intersect(line, side, intersectionPoint) == INTERSECT){
			if( p1x == -1 ) { p1x = intersectionPoint.x; p1y = intersectionPoint.y; }
			else  { p2x = intersectionPoint.x; p2y = intersectionPoint.y; }
		}

		side = new Segment( new Vector( mapLeftX+1, mapBottomY-1), new Vector(mapRightX-1, mapBottomY-1) );
		var intersectionPoint = new Vector(0, 0);
		if(intersect(line, side, intersectionPoint) == INTERSECT){
			if( p1x == -1 ) { p1x = intersectionPoint.x; p1y = intersectionPoint.y; }
			else  { p2x = intersectionPoint.x; p2y = intersectionPoint.y; }
		}

		side = new Segment( new Vector(mapRightX-1, mapBottomY-1), new Vector(mapRightX-1, mapTopY+1) );
		var intersectionPoint = new Vector(0, 0);
		if(intersect(line, side, intersectionPoint) == INTERSECT){
			if( p1x == -1 ) { p1x = intersectionPoint.x; p1y = intersectionPoint.y; }
			else  { p2x = intersectionPoint.x; p2y = intersectionPoint.y; }
		}

		side = new Segment( new Vector(mapRightX-1, mapTopY+1), new Vector(mapLeftX+1, mapTopY+1) );
		var intersectionPoint = new Vector(0, 0);
		if(intersect(line, side, intersectionPoint) == INTERSECT){
			if( p1x == -1 ) { p1x = intersectionPoint.x; p1y = intersectionPoint.y; }
			else  { p2x = intersectionPoint.x; p2y = intersectionPoint.y; }
		}

		if( p1x > -1 ) {
			if( p2x == -1 ) {
				if(  	   ( xf > mapLeftX && xf < mapRightX )
					&& ( yf > mapTopY && yf < mapBottomY )
				) { graphicObject.drawLine(parseInt(p1x,10),parseInt(p1y,10),xf,yf); }
				else if(   ( xl > mapLeftX && xl < mapRightX )
					&& ( yl > mapTopY && yl < mapBottomY ) 
				) { graphicObject.drawLine(parseInt(p1x,10),parseInt(p1y,10),xl,yl); }
			} else {
				graphicObject.drawLine(parseInt(p1x,10),parseInt(p1y,10),parseInt(p2x,10),parseInt(p2y,10));
			}
		}
	}
}

//-----------------------------------------------------------------------------------

function initMeasureTool(mode) {
   if( mode == null ) { mode = '1'; }
   mouseDown = 0;
   mapMessageMaxX = 0;
   mmA.clear();
   mmB.clear();
   if( mapMeasureDDListArray.length == 0 ) {
      mapMeasureDDList = '';
      mapMeasureDDListArray = new Array();
      xList = '';
      yList = '';
      lastX = 0;
      lastY = 0;
      textXY = '';
   } else {
	measureToolDrawB();
   }
   if( mode > '2' ) { mode = '1'; }
   if( mode > '0' ) {
      mouseMode = mode;
   }
   mapMeasureFinish = false;
//---  wz_tooltip.js will take over onmousemove so as a temporary fix it is established here each time.
//   document.onmousemove = mouseCoords;
   openMeasureTool();
}

//-----------------------------------------------------------------------------------

function openMeasureTool() {

//-- mmLoad is defined in zMApFormJava.asp
   if( !mmWindow && mapMeasure == 1 && typeof mmLoad == 'function' ) { mmLoad(); }

}

//-----------------------------------------------------------------------------------

function mapMeasureOverScrollBar() {

   var x,y;
   var result = false;
   var notIE = true;
   if( document.body && typeof document.body.scrollLeft == 'number'  ) { notIE = false; }
   if( document.documentElement &&
            ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { notIE = true; }
   if( typeof window.pageYOffset == 'number' ) { notIE = true; }

// scrolbars: fucus on window if within 20 of posBottom or posRight;
// guess visiblity of bottom scrollbar
// assume right scrollbar is visible

   var viewWidth = bar_width;
   if( mapWidth > 760 ) { viewWidth += mapWidth; } else { viewWidth += 760; }
   if( mapMessageMaxX+20 > viewWidth ) { viewWidth = mapMessageMaxX+20; }


   y = posBottom() - mouseY;
   if( pageWidth() < viewWidth ) {
//-- there should be a scroll bar visible on the bottom
      if( notIE && y < ScrollBarThickness && y >= 0 ) {
         window.focus();
         result = true;
      } else {
         if( y <= 0 ) {
            window.focus();
            result = true;
         }
      }
   } 

//-- there should be a scroll bar on the right side
   x = posRight() - mouseX;
   if( notIE &&  x < ScrollBarThickness && x >= 0 ) {
      window.focus();
      result = true;
   } else {
      if( x < 0 ) {
         window.focus();
         result = true;
      }
   }
   return( result );
}

//-----------------------------------------------------------------------------------

function measureButton(mode) {
   if( mode == null ) { 
      mode = document.mapform.measure.value;
      if( mode === '0' ) { mode = '1'; } else { mode = '0'; }
   }
   close_windows();
   if( mode === '0' ) {
      mapMeasure = '0';
      document.mapform.measure.value = mapMeasure;
      mouseDown = 0;
      mouseMode = '1';
      document.getElementById('measure_button').src = 'images/MeasureButton0.png';
      panButton();
   } else {
      mapMeasure = '1';
      document.mapform.measure.value = mapMeasure;
      document.getElementById('measure_button').src = 'images/MeasureButton1.png';
      document.getElementById('pan_button').src = 'images/PanButton0.png';
	if( permission_mmID ) {
	} else {
		document.getElementById('id_button').src = 'images/IdButton0.png';
	}
      initMeasureTool('1');
   }
}

//-----------------------------------------------------------------------------------

function mapMeasureLastXY( dd, coord ) {
	if( dd && dd !== '' ) {
		if( !coord ) { coord = map_coord; }
//-- translate to image coordinates
		locateMap();
		if( coord == 'UTM83' ) { setNAD83(); } else { setNAD27(); }
		var xyz = LL2UTM( dd, map_dpz );
		setNAD27();
		var xyArray = xyz.split(' ');
		var x = parseInt(xyArray[0],10);
		var y = parseInt(xyArray[1],10);
//-- assign global variables lastX, lastY
		lastX = parseInt( Math.round( (x-map_min_utmx)/map_pixel ),10 ) + Xoffset + 3;
		lastY = parseInt( Math.round( (map_max_utmy-y)/map_pixel ),10 ) + Yoffset + 3;
	} else {
		lastX = '';
		lastY = '';
	}
}

//-----------------------------------------------------------------------------------

function measureTool(mode) {
	var i, j, t, tArray, x, y;

	if( mode == null ) { mode= mouseMode; }

	if( mode == '1' || mode == '2' ){
//-- Point Your Mouse  or  Drag Your Mouse
		mouseMode = mode;
		lastMouseMode = mouseMode;
	}

	if( mode == '3' ) {
//-- backup button

		mapMeasureRemoveList();
		mmA.clear();
		xList = '';
		yList = '';
		mapMeasureDDList = '';
		if( mapMeasureDDListArray.length > 0 ) {
			var ddArray = mapMeasureDDListArray[0].split(',');
			mapMeasureLastXY( ddArray[1] );
			if( lastX > 0 ) {
				measureDrawPoint( mmA, lastX, lastY, "lightgreen" );
			}
		} else {
			textXY='';
		}
		measureToolDrawB();

		openMeasureTool();
	}

	if( mode == '4' ) {
//-- finish button
		if( mapMeasureDDListArray.length > 0 && !mapMeasureFinish ) {
			mouseMode = '4';
			mouseDown = 1;
			mapMeasureReport();
			mapMeasureFinish = true;
		} else {
			mapMeasureDDList = '';
			mapMeasureDDListArray = new Array();
			xList = '';
			yList = '';
			lastX = 0;
			lastY = 0;
			textXY = '';
			initMeasureTool(lastMouseMode);
			close_child_window();
		}
	}

	if( mode == '5' ) {
//-- map measure window closed
		measureButton('0');
	}

	if( mode == '6' ) {
//-- import coordinates
	}

	if( mode == '7' ) {
//-- zoom to coordinates
		var minx = 1.0E44;
		var miny = 1.0E44;
		var maxx = -1.0E44;
		var maxy = -1.0E44;
		var ddArray = mapMeasureDDListArray.join(',').split(',');
		setNAD27();
		var z = 17;
 		while( ddArray.length > 0 ) {
			var dd = ddArray.shift();
			if( dd !== '' ) {
				var utmArray = LL2UTM(dd,z).split(' ');
				var n = parseInt(utmArray.shift(),10);
				if( n < minx ) { minx = n; }
				if( n > maxx ) { maxx = n; }
				n = parseInt(utmArray.shift(),10);
				if( n < miny ) { miny = n; }
				if( n > maxy ) { maxy = n; }
			}
		}
		var zoomPixel = (maxx-minx)/mapWidth;
		var pixelN = (maxy-miny)/mapHeight;
		if( pixelN > zoomPixel ) { zoomPixel = pixelN; }
		s = 10;
		if( zoomPixel > 256.0 ) { s = 20;
		} else if( zoomPixel > 128.0 ) { s = 19;
		} else if( zoomPixel > 64.0 ) { s = 18;
		} else if( zoomPixel > 32.0 ) { s = 17;
		} else if( zoomPixel > 16.0 ) { s = 16;
		} else if( zoomPixel > 8.0 ) { s = 15;
		} else if( zoomPixel > 4.0 ) { s = 14;
		} else if( zoomPixel > 2.0 ) { s = 13;
		} else if( zoomPixel > 1.0) { s = 12;
		} else if( zoomPixel > 0.5 ) { s = 11;
 		}
		if( s <= zoomMin ) { s = zoomMin; }
//--- redraw map with center dp and scale s;

		doNotReplaceMap ++;
		setMapScale(s);
		doNotReplaceMap --;
		if( zoomPixel < map_pixel*0.666 ) { zoomPixel = map_pixel*0.666; }
		map_pixel = zoomPixel;
		document.mapform.p.value = map_pixel;
		zoomPixel = nDecString(zoomPixel,1+(zoomPixel < 2));

//###
//###  remeber to account for scalebar and reported pixel size
//###
		document.images.MapScale.src = 'mapscale.asp?s=' + map_s + '&p=' + zoomPixel;
		document.getElementById('spanNotePixelSize').innerHTML = zoomPixel;

		var utmE = (maxx+minx)/2;
		var utmN = (maxy+miny)/2;

		var idCoordinates = utmE  + ' ' + utmN + ' ' + z;

		map_dpLL = UTM2LL( idCoordinates );

		map_dpUTM17 = LL2UTM( map_dpLL, 17 );
		idCoordinates = map_dpUTM17;

//--- When the base map is NAD 1983, it is displayed by httpMapImage with a shift to represent NAD 1927.
//--- therefore the point clicked is always NAD 1927 even if the base map is NAD 1983.

		if( ( document.mapform.t.value == '1'
			|| document.mapform.t.value == '2'
			|| document.mapform.t.value == 'N'
			|| document.mapform.t.value == 'O' )
		) {
//--- check for change in UTM Zone when terraserver images
			idCoordinates  = LL2UTM( map_dpLL );
		}
		var xyArray = idCoordinates.split(' ');
		utmE = parseInt(xyArray.shift(),10);
		utmN = parseInt(xyArray.shift(),10);
		z = parseInt(xyArray.shift(),10);
		idCoordinates = utmE  + ' ' + utmN + ' ' + z;

		document.mapform.dp.value = idCoordinates;
		map_dpUTM17 = LL2UTM( map_dpLL, 17 );
		document.mapform.dp_utm17.value = map_dpUTM17;
		if( (display_only != '1' && shift == 1) ) {
			document.mapform.poi.value = idCoordinates;
			map_poiUTM17 = map_dpUTM17;
			map_porUTM17 = map_poiUTM17;
			map_poiLL = map_dpLL;
			document.mapform.poi_utm17.value = map_poiUTM17;
		}
		map_min_utmx = utmE - Math.round(mapWidth*map_pixel/2);
		map_max_utmy = utmN + Math.round(mapHeight*map_pixel/2);
		map_dpz = z;
		document.mapform.dpz.value = map_dpz;
		search_point_comment='';
		replaceMap();
	}

	if( mode == '8' ) {
//-- map measure window closed
		mapMeasureFinish = true;
		mapMeasureDDList = '';
		mapMeasureDDListArray = new Array();
		xList = '';
		yList = '';
		lastX = 0;
		lastY = 0;
		textXY = '';
		mmToolMode('4');
		mmToolMode('5');
		if( showingMapReport ) {
			if( document.getElementById("mr_poi") && document.getElementById("mr_poi").value ) { document.getElementById("mr_poi").value = ''; }
			replaceMap();
		}
	}
}

//-----------------------------------------------------------------------------------

function mapMeasureAddList() {
	if( mapMeasureDDList !== '' ) {
		mapMeasureDDListArray.unshift(mapMeasureDDList);
		xList = '';
		yList = '';
		mapMeasureDDList = '';
	}
}

//-----------------------------------------------------------------------------------

function mapMeasureRemoveList() {
   if( mapMeasureDDListArray.length > 0 ) {
      mapMeasureDDListArray.shift();
   }
}

//-----------------------------------------------------------------------------------

function measureToolDrawB() {
	mmB.clear();
	var i = mapMeasureDDListArray.length - 1;

	lastX = '';
	lastY = '';
	var lx = '';
	var ly = '';
	while( i > -1 ) {
		var ddArray = mapMeasureDDListArray[i].split(',');
		i -= 1;
		if( lastX !== '' ) { measureDrawPoint( mmB, lastX, lastY, "red" ); }

		if( ddArray.length > 0 ) {
			ddArray.reverse();

			var dd = ddArray.shift();
			if( dd != '' ) {
//--- draw using NAD27 coordinate system - any NAD83 image has been shifted to NAD27 for display
				mapMeasureLastXY( dd, 'LL' );
				if( ddArray.length>0 ) { measureDrawPoint( mmB, lastX, lastY, "red" ); }

				mmB.setColor("blue");
				mmB.setStroke(2);

				if( lx !== '' ) { measureDrawLine( mmB, lx, ly, lastX, lastY); }
				lx = lastX;
				ly = lastY;

				var dd = ddArray.shift();
				while( dd ) {
					if( dd != '' ) {
//--- draw using NAD27 coordinate system - any NAD83 image has been shifted to NAD27 for display
						mapMeasureLastXY( dd, 'LL' );
						measureDrawLine( mmB, lx, ly, lastX, lastY);
						lx = lastX;
						ly = lastY;
					}
					dd = ddArray.shift();
				}
			}
		}
	}
	mmB.paint();
	mmA.clear();
	measureDrawPoint( mmA, lastX, lastY, "lightgreen" );
 	mmA.paint();
	if( typeof mmGetCoordinates == 'function' ) {  mmGetCoordinates(); }
	if( mmShadePolygon ) {
		shadeCoordinates();
	}
}

//-----------------------------------------------------------------------------------

function mapMeasureReport(){
//-- using setTimeout to create "signal" for the browser to update its display; otherwise a "please wait" may not show
	if( (mapMeasureDDListArray[0] && mapMeasureDDListArray[0].length>100) || mapMeasureDDListArray[1] ) {
		progress_start('Browser busy running map JavaScript,');
	}
	reportTimer = setTimeout('mapMeasureReportDelayed()',1);
}

function mapMeasureReportDelayed() {
	clearTimeout(reportTimer);
//-- using setTimeout to create "signal" for the browser to update its display; otherwise a "please wait" may not show
	if( mapMeasureDDListArray.length > 0 ) {

//-- call for report
		if( document.mapform.pan.value === '0' && permission_mmID ) {
			var xyString = getValue_textXY('UTM27');
			if( xyString != '' ) {
				xyString = xyString.replace(/\t/g,' ');
				xyString = xyString.replace(/\n/g,',');
				xyString = xyString.replace(/,,/g,',');
				xyString = xyString.substr(0,xyString.length-1);
//alert(xyString);
				mapReport(xyString);
			}
		}

//-- display search area on map

//-- construct xList form mapMeasureDDListArray
		var ddList = mapMeasureDDListArray.join(',');
		var ddArray = ddList.split(',');
		var dsqr = 0;

		var xArray = new Array();
		var yArray = new Array();

		while ( ddArray.length > 0 ) {
//-- the display coordinate system is always UTM27 ( July 15, 2010  abj3 )
			mapMeasureLastXY( ddArray.shift(), 'UTM27' );
			if( lastX !== '' ) {
				xArray.push(lastX);
				yArray.push(lastY);
			}
		}

		var lX = parseInt(xArray[0],10);
		var lY = parseInt(yArray[0],10);
		var firstX = lX;
		var firstY = lY;

		measureDrawPoint( mmA, lX, lY, "red" );
 		mmA.paint();

		var prod1 = 0;
		var prod2 = 0;
		var n = 0;
		var bx = lX;
		var by = lY;
		var px = 0;
		var py = 0;
		var maxX = lX;
		var maxY = lY;
		var minX = lX;
		var minY = lY;
		var Xpoints = new Array();
		var Ypoints = new Array();

		for ( i in xArray ) {
			cX = parseInt(xArray[i],10);
			cY = parseInt(yArray[i],10);
			Xpoints.push(cX);
			Ypoints.push(cY);
			if( cX > maxX ) { maxX = cX; }
			if( cY > maxY ) { maxY = cY; }
			if( cX < minX ) { minX = cX; }
			if( cY < minY ) { minY = cY; }
			dsqr += Math.sqrt( (cX-lX)*(cX-lX) + (cY-lY)*(cY-lY) );
			lX = cX;
			lY = cY;
			n += 1;
			cX -= bx;
			cY -= by;
 			prod1 += cX * py;
 			prod2 += cY * px;
			px = cX;
			py = cY;
		}

		var d1 = parseInt( dsqr + 0.5,10 );
		var area = 0.0;
		var isPolygon = false;
		if( n > 2 ) { area = parseInt(Math.abs(prod1-prod2)/2.0+0.5,10); }

		if( d1 > 2 ) {
//--- Measure
			var d0 = parseInt( Math.sqrt( (firstX-lX)*(firstX-lX) + (firstY-lY)*(firstY-lY) ) +0.5,10 );
//--- d1 is line distance
//--- d0 is close distance
//--- isPolygon calculation should match that found in mapReport.pl
			isPolygon = ( d1 > d0*8 );
			d1 = d1 * map_pixel;
			d0 = d0 * map_pixel;

			if( map_coord != 'LL' ) {
				if( d1 > 3333.0 ) { d1 = parseInt(d1/100,10)/10 + ' Kilometers'; } else { d1 = d1 + ' meters'; }
				if( d0 > 3333.0 ) { d0 = parseInt(d0/100,10)/10 + ' Kilometers'; } else { d0 = d0 + ' meters'; }
			} else {
				d1 = d1 * 5280 / 1609;
				d0 = d0 * 5280 / 1609;
				if( d1 > 6666.0 ) { d1 = parseInt(d1/528,10)/10 + ' Miles'; } else { d1 = parseInt(d1+0.5,10) + ' feet'; }
				if( d0 > 6666.0 ) { d0 = parseInt(d0/528,10)/10 + ' Miles'; } else { d0 = parseInt(d0+0.5,10) + ' feet'; }
			}
			var measure0 = 'closing length ' + d0;
			var measure1 = 'length ' + d1;

			var mapMessageLength = measure0.length*8;
			if( measure1.length > measure0.length ) { mapMessageLength = measure1.length*8; }
			maxX += 5;
			maxY += 5;
//--- bottom scroll bar may appear if message is positioned to the right
			mapMessageMaxX = maxX + mapMessageLength;

			mmA.setColor("red");
			mmA.setStroke(3);
			mmA.fillRect( maxX-2, maxY-2, mapMessageLength+4, 94) ;

			mmA.setColor("blue");
			mmA.fillRect( maxX, maxY, mapMessageLength, 60) ;
			mmA.setColor("white");
			mmA.setFont("arial","15px",Font.BOLD);
			mmA.drawString( measure1, maxX+5, maxY+5 );
//--- area in pixels
			if( area > 0 && isPolygon ) {
				area = area * map_pixel * map_pixel;
//--- area in sq. meters
				if( map_coord != 'LL' ) {
//--- area in hectares
					area = parseInt(area / 1000,10) /10;
					mmA.drawString( 'area   ' + area + ' hectares', maxX+10, maxY+40 );
				} else {
					if( area < 1609*1609*3 ) {
//--- area in acres  1609 meters in 5280 feet: (5280*5280)/(1609*1609) sq. feet per sq. meter
						area = area * (5280*5280)/(1609*1609) / 43560;
						if( area > 10.0 ) {
							mmA.drawString( 'area   ' + parseInt(area * 10,10 ) / 10 + ' acres', maxX+10, maxY+40 );
						} else {
							mmA.drawString( 'area   ' + parseInt(area * 100,10 ) / 100 + ' acres', maxX+10, maxY+40 );
						}
					} else {
						mmA.drawString( 'area   ' + parseInt(area / (1609*1609) * 10,10 ) / 10 + ' sq. miles', maxX+10, maxY+40 );
					}
				}
			}

			measureDrawPoint( mmA, lX, lY, "red" );

			mmA.setColor("#90FF90");  //-- #90FF90 LightGreen
			mmA.setStroke(6); 
			mmA.drawLine( firstX, firstY, lX, lY );
			mmA.fillRect( maxX, maxY+60, mapMessageLength, 30) ;
			mmA.setColor("black");
			mmA.setFont("arial","15px",Font.BOLD);
			mmA.drawString( measure0, maxX+5, maxY+65 );
			mmA.paint();

			opacity( divMapMeasureIdA, 70 );

//--- testing popup VaFWIS Map Report poly/line
//alert( 'minX="' + minX + '" minY="' + minY + '" maxX="' + maxX + '" maxY="' + maxY + '" mapWidth="' + mapWidth + '" mapHeight="' + mapHeight + '"');
			if( 1 && document.mapform.pan.value === '0' && permission_mmID ) {
				if( minY > mapTopY
					&& maxY < mapBottomY
					&& minX > mapLeftX
					&& maxX < mapRightX

				) {
					if( 0 ) { replaceMap(); }
					mapMeasureFinish = true;

					mmB.setColor("yellow");
					if( isPolygon ) {
						mmB.setStroke(1); 
						mmB.fillPolygon(Xpoints,Ypoints);
					} else {
						mmB.setStroke(12); 
						mmB.drawPolyLine(Xpoints,Ypoints);
					}
					mmB.setStroke(2); 
					mmB.setColor("blue");
					mmB.drawPolygon(Xpoints,Ypoints);
					mmB.paint();
					opacity( divMapMeasureIdB, 40 );

				} else {
					if( !mmShadePolygon ) {
alert( 'Map Measure:\nUnable to display site.\nSome Map Measure coordinates fall outside display bounds.' );
					}
				}
			}

		} else {
			mapMeasureFinish = true;
		}
//-- end  d1>2 
	}
// --- end if( mapMeasureDDListArray.length > 0 )
	progress_stop();
}

function shadeCoordinates(){
	if( mapMeasureDDListArray.length > 0 ) {
		var ddList = mapMeasureDDListArray.join(',');
		var ddArray = ddList.split(',');

		var Xpoints = new Array();
		var Ypoints = new Array();

		while ( ddArray.length > 0 ) {
//-- the display coordinate system is always UTM27 ( July 15, 2010  abj3 )
			mapMeasureLastXY( ddArray.shift(), 'UTM27' );
			if( lastX !== '' ) {
				Xpoints.push(parseInt(lastX,10));
				Ypoints.push(parseInt(lastY,10));
			}
		}
		mmB.setColor("yellow");
		mmB.setStroke(12);
		if( mmShadePolygon ) {
			mmB.fillPolygon(Xpoints,Ypoints);
		}
		mmB.drawPolyLine(Xpoints,Ypoints);
		mmB.setStroke(2); 
		mmB.setColor("blue");
		mmB.drawPolygon(Xpoints,Ypoints);
		mmB.paint();
		opacity( divMapMeasureIdB, 40 );
	}
}

function opacity( id, percentOpacity ) {
	if( id ) {
		if( percentOpacity == null ) { percentOpacity = 100; }
		if( percentOpacity < 0 ) { percentOpacity = 0; }
		if( percentOpacity > 99 ) { percentOpacity = 100; }
		percentOpacity = parseInt(percentOpacity,10);

		var node = document.getElementById(id);
		if( BrowserDetect.browser == 'Explorer' ) {
//--- Microsoft Internet Explorer is not compliant.  need to itterate all "div"
			var nodeArray = node.getElementsByTagName('div');
			if( nodeArray.length>0 ) {
				for (var i=0;i<nodeArray.length;i++){
					nodeArray[i].style.filter = "alpha(opacity=" + percentOpacity  + ")";
					nodeArray[i].style.zoom = "100%";
				}
			} else {
			}
		} else {
			styleObject( id ).opacity = percentOpacity/100;
		}
	}
}

//-----------------------------------------------------------------------------------

function mapMeasureCoord( coord ) {

   var display_poi, display_dp;
   if( !coord ) { coord = 'LL'; }
   map_coord = coord;
//alert("map_coord='"+map_coord+"'");

   setNAD27();
   mapMeasure_poiLL = UTM2LL(map_poiUTM17,17);
   mapMeasure_dpLL = UTM2LL(map_dpUTM17,17);
   var z = parseInt(map_dpz,10);

   if( map_coord == 'UTM27' ) {
      display_poi = LL2UTM(mapMeasure_poiLL,z);
      display_dp = LL2UTM(mapMeasure_dpLL,z);
      if( document.getElementById('spanNoteCoordinateSystem') ) {
         document.getElementById('spanNoteCoordinateSystem').innerHTML =
         'Universal Transverse Mercator in meters using North American Datum 1927.'; }
   } else if( map_coord == 'UTM83' ) {
      setNAD83();
      display_poi = LL2UTM(mapMeasure_poiLL,z);
      display_dp = LL2UTM(mapMeasure_dpLL,z);
      if( document.getElementById('spanNoteCoordinateSystem') ) {
         document.getElementById('spanNoteCoordinateSystem').innerHTML =
         'Universal Transverse Mercator in meters using North American Datum 1983.'; }
      setNAD27();
   } else if( map_coord == 'DD' ) {
      var llArray = mapMeasure_poiLL.split(' ');
      display_poi = nDecString(llArray.shift(),6);
      display_poi += ' ' + nDecString(llArray.shift(),6);
      if( llArray.length > 0 ) { display_poi += ' ' + llArray.join(' '); }
      llArray = mapMeasure_dpLL.split(' ');
      display_dp = nDecString(llArray.shift(),6);
      display_dp += ' ' + nDecString(llArray.shift(),6);
      if( llArray.length > 0 ) { display_dp += ' ' + llArray.join(' '); }
      if( document.getElementById('spanNoteCoordinateSystem') ) {
         document.getElementById('spanNoteCoordinateSystem').innerHTML =
         'decimal Degrees North and West.'; }
   } else {
      display_poi = dd2dms(mapMeasure_poiLL);
      display_dp = dd2dms(mapMeasure_dpLL);
      if( document.getElementById('spanNoteCoordinateSystem') ) {
         document.getElementById('spanNoteCoordinateSystem').innerHTML =
         'Degrees, Minutes, Seconds North and West.'; }
   }
   if( document.getElementById('poi1') ) {
	var rgb = 'rgb(250,200,255)';
	if( display_only == '1' ) { rgb = 'rgb(255,255,255)'; }
	document.getElementById('poi1').innerHTML = unescape(search_point_comment) +
		'<input id="poi1text" type="text" value="' + display_poi + '"' +
		' style="text-align: center; border: 0; font-size: 105%; background-color: ' +
		rgb +
		'; width: 11em;"' +
		' onChange="changePOI();return true;">';
   }
   if( document.getElementById('poi3') ) { document.getElementById('poi3').innerHTML = display_poi; }
   if( document.getElementById('poi4') ) { document.getElementById('poi4').innerHTML = display_poi; }
   if( document.getElementById('dp1') )  { document.getElementById('dp1').innerHTML = display_dp; }

   if( document.mapMeasure ) { mmGetCoordinates(); }

}

//-----------------------------------------------------------------------------------

function getValue_textXY(coord) {
   if( mapMeasureDDListArray.length > 0 ) {
      textXY = measureToolListArrays2Text('',coord);
   } else {
      textXY = '';
   }
   return textXY;
}

//-----------------------------------------------------------------------------------

function getValue_map_coord() {
   return map_coord;
}

//-----------------------------------------------------------------------------------

function putValueTextXY(textXY,coord,polyLineDelimiter) {
// alert('putValueTextXY');
	if( polyLineDelimiter == null ) { polyLineDelimiter = ''; }
//-- textXY is tab delimited coordinate columns with linefeed delimited rows
	mapMeasureDDList = '';
	mapMeasureFinish = false;
	mmA.clear();
	mapMeasureDDListArray = new Array();
	if( textXY && textXY !== '' ) {
//-- IE6 returns a \r
//-- textXY must be in the coordinate datum system specified by map_coord or all is lost.
//alert( 'map_coord='+map_coord );
if( map_coord == 'UTM83' ) { setNAD83(); } else { setNAD27(); }
		var lineArray = textXY.replace(/\r/g,'').split('\n');
		lineArray.reverse();

		while ( lineArray.length ) {
			var xyz = lineArray.shift();
			if( xyz == polyLineDelimiter ) {
				if( mapMeasureDDList !== '' ) { mapMeasureAddList(); }
			} else {
				xyz = xyz.replace(/\t/g,' ');

//-- best shot at interpreting coordinates.  If UTM there may be NAD 27 - 83 confusion

//-- Lat/Lon in decimal degrees
				mapMeasureDDList = ',' + dd( xyz, map_dpz ) + mapMeasureDDList;
			}
		}
	}
	if( mapMeasureDDList !== '' ) {
		mapMeasureAddList();

		measureToolDrawB();
	}
}

//-----------------------------------------------------------------------------------

function measureToolListArrays2Text(polyLineDelimiter, coord) {
	if( !polyLineDelimiter ) { polyLineDelimiter = ''; }
	if( !coord ) { coord = map_coord; }
//---------if( coord != 'UTM83' ) { coord = 'UTM27'; }
	var textXY = '';
	var i = 0;
	while( mapMeasureDDListArray.length > i ) {
		var ddArray = mapMeasureDDListArray[i].split(',');
		while ( ddArray.length ) {
			var dd = ddArray.shift();
			var coordinatePair;

			if( dd === '' ) {
			} else {
				var coordinatePair;

				if( coord == 'UTM27' ) {
//--- UTM NAD 1927
					setNAD27();
					var utm = LL2UTM(dd,map_dpz);
					var utmArray = utm.split(' ');
					coordinatePair = nDecString(utmArray.shift(),-1);
					coordinatePair += ' ' + nDecString(utmArray.shift(),-1);
					if( utmArray.length > 0 ) { coordinatePair += ' ' + utmArray.join(' '); }
				} else if( coord == 'UTM83' ) {
//--- UTM NAD 1983
					setNAD83();
					var utmArray = LL2UTM(dd,map_dpz).split(' ');
					coordinatePair = nDecString(utmArray.shift(),-1);
					coordinatePair += ' ' + nDecString(utmArray.shift(),-1);
					if( utmArray.length > 0 ) { coordinatePair += ' ' + utmArray.join(' '); }
					setNAD27();
				} else if( coord == 'LL' ) {
//--- Lat Lon DMS
					coordinatePair = dd2dms(dd,',',3);
				} else if( coord == 'DD' ) {
//--- Lat Lon decimal degrees
					var llArray = dd.split(' ');
					coordinatePair = llArray.shift().substring(0,8);
					coordinatePair += ' ' + llArray.shift().substring(0,9);
					if( llArray.length > 0 ) { coordinatePair += ' ' + llArray.join(' '); }
				} else {
//--- unsupported coordinate system
				}

				textXY += '\n' + coordinatePair;
			}
		}
		textXY += '\n';
		i++;
	}
	textXY = textXY.replace(/ /g,'\t').substr(1);
	return textXY;
}

//-------------------------------------------------------------------------------

/*
	Intersection of two lines

	retrieved June 3, 2009
	http://bloggingmath.wordpress.com/2009/05/29/line-segment-intersection/
	http://cloud.github.com/downloads/bjwbell/canvas-geolib/main.js

	seg1 is represented by p + t * r where  0 <= t <= 1
	seg2 is represented by q + u * s where  0 <= u <= 1
	
	the intersection of line 1 and line 2 is given by 
	p + t*r = q + u*s, 
	let x be the two dimensional cross product then
	(p + t*r) x s = (q + u*s) x s = q x s
	which solving for t gives
	t = (q - p) x s / (r x s).
	similarly solving for u gives
	u = (q - p) x r / (r x s).
	the segments intersect if 0 <= t <= 1 and 0 <= 1 <= u.
	If r x s is zero then the lines are parallel, in which case if 
	(q - p) x r = 0 then the lines are co-linear.
	
*/
var epsilon = 10e-6;
var DONT_INTERSECT = 0;
var PARALLEL_DONT_INTERSECT = 1;
var COLINEAR_DONT_INTERSECT = 2;
var INTERSECT = 3;
var COLINEAR_INTERSECT = 4;
function Vector(x, y){
  this.x = x;
  this.y = y;
  this.color = '#000';
  this.draw = function() {
  };
  this.scalarMult = function(scalar){
	  return new Vector(this.x * scalar, this.y * scalar);
  }
  this.dot = function(v2) {
    return this.x * v2.x + this.y * v2.y;
  };
  this.perp = function() {
    return new Vector(-1 * this.y, this.x);
  };
  this.subtract = function(v2) {
    return this.add(v2.scalarMult(-1));//new Vector(this.x - v2.x, this.y - v2.y);
  };
  this.add = function(v2) {
	  return new Vector(this.x + v2.x, this.y + v2.y);
  }
}

function Segment(p1, p2){
  //alert('s1');
  this.p1 = p1;
  this.p2 = p2;
  //alert('s2');
  this.draw = function() {
  };

}

// the cross product of vectors v1 and v2.
function cross(v1, v2) {
	return v1.x * v2.y - v2.x * v1.y;
}

function intersect(seg1, seg2, intersectionPoint) {
	p = seg1.p1;
	r = seg1.p2.subtract(seg1.p1);
	q = seg2.p1;
	s = seg2.p2.subtract(seg2.p1);
	rCrossS = cross(r, s);
	if(rCrossS <= epsilon && rCrossS >= -1 * epsilon){
		return PARALLEL_DONT_INTERSECT;
	}
	t = cross(q.subtract(p), s)/rCrossS;
	u = cross(q.subtract(p), r)/rCrossS;
	if(0 <= u && u <= 1 && 0 <= t && t <= 1){
		intPoint = p.add(r.scalarMult(t));
		intersectionPoint.x = intPoint.x;
		intersectionPoint.y = intPoint.y;
		return INTERSECT;
	}else{
		return DONT_INTERSECT;
	}
}

//-------------------------------------------------------------------------------

//-- Progress image tool
var progressEnd = 9;		// set to number of progress <span>'s.
var progressColor = '#00FF7F';	// set to progress bar color #00FF7F SpringGreen
var progressInterval = 1000;	// set to time between updates (milli-seconds)
var progressAt = progressEnd;
var progressTimer;
function progress_clear() {
	for (var i = 1; i <= progressEnd; i++) {
		document.getElementById('progress'+i).style.backgroundColor = 'transparent'; }
		
	progressAt = 0;
}
function progress_update() {
	document.getElementById('progress0').style.backgroundColor = progressColor;
	progressAt++;
	if (progressAt > progressEnd) {
		progress_clear();
	} else {
		document.getElementById('progress'+progressAt).style.backgroundColor = progressColor;
	}	
	progressTimer = setTimeout('progress_update()',progressInterval);
}
function progress_stop() {
	clearTimeout(progressTimer);
//	progress_clear();
  	document.getElementById('PleaseWait').style.visibility='hidden';
}
function progress_start(text) {
	if( !text ) { text = 'Loading map,'; }
	progress_clear();
  	progress_update();
	document.getElementById('PleaseWaitText').innerHTML = text;
	document.getElementById('PleaseWait').style.visibility='visible';
}

//----------------------------------------------------------

function styleObject(object) {
    if (document.getElementById && document.getElementById(object) != null) {
         return document.getElementById(object).style; }
    else if (document.layers && document.layers[object] != null) {
        return document.layers[object].style; }
    else if (document.all) {
        return document.all[object]; }
}

//-----------------------------------------------------------------------------------

function replaceMap() {

   var line, url;

   if( doNotReplaceMap > 0 ) { return; }
   doNotReplaceMap = 0;
   mapMeasureFinish = false;

   progress_start();
   mapMeasureCoord( map_coord );

   var tileArray = document.mapform.tile.value.split(',');
   mapWidth = parseInt(tileArray[0],10)*200;
   mapHeight = parseInt(tileArray[1],10)*200;

   var rExp = / /g;

//--- load the upper-right VaLocator image
//--  need integer coordinates
   url = '';
   url += 'aVaLocator.asp?';
   url += 's=' + document.mapform.s.value + '&width=' + mapWidth + '&height=' + mapHeight;
   url += '&dp=';
   var xyzArray = (map_dpUTM17 + ' 17').split(' ');
   url += parseInt(xyzArray.shift(),10) + '+' + parseInt(xyzArray.shift(),10) + '+' + parseInt(xyzArray.shift(),10);
   url += '&poi=';
   xyzArray = (map_poiUTM17 + ' 17').split(' ');
   url += parseInt(xyzArray.shift(),10) + '+' + parseInt(xyzArray.shift(),10) + '+' + parseInt(xyzArray.shift(),10);
   document.images.VaLocator.src = url.replace(rExp,'+');

//-- map view coordinates are set by map_min_utmx, map_max_utmy, map_dpz
//-- poi point of interest - search point
//-- por point of rings
//-- when there is a search distance then map_porUTM17 is search point
//-- when there is an observation record then POI is map_itemUTM17

//--- basemap UTM Datum and zone

   var utmE = map_min_utmx;
   var utmN = map_max_utmy;

   bm_nad=1927;
   var bmz = '17';
   if(map_t === '0')    { bm_nad=1927; bmz = ''; }
   else if(map_t == '1') { bm_nad=1983; bmz = ''; }
   else if(map_t == '2') { bm_nad=1983; bmz = ''; }
   else if(map_t == '3') { bm_nad=1927; bmz = '17'; }
   else if(map_t == '4') { bm_nad=1927; bmz = '17'; }
   else if(map_t == '6') { bm_nad=1927; bmz = '17'; }
   else if(map_t == '9') { bm_nad=1983; bmz = '17'; }
   else if(map_t == 'A') { bm_nad=1983; bmz = '17'; }
   else if(map_t == 'B') { bm_nad=1983; bmz = '17'; }
   else if(map_t == 'C') { bm_nad=1983; bmz = '17'; }
   else if(map_t == 'D') { bm_nad=1983; bmz = '17'; }
   else if(map_t == 'N') { bm_nad=1983; bmz = ''; }
   else if(map_t == 'O') { bm_nad=1983; bmz = ''; }

   if( bm_nad == 1983 ) {
//--- nad83 to nad27 display shift
//--- all overlay coordinates are UTM NAD 1927
//--- When the base map is NAD 1983 the display is shifted so that the point of interest defined in NAD 1927
//--- remains in the center of the map.  As a side effect the Javascript Click_Map routine will also return a
//--- NAD 1927 coordinate for a NAD 1983 base map.
//
//--- Virginia nad83 to nad27 display shift for terraserver iamges discovered by observation
      utmE  += 17;
      utmN += 219;
  }

   showingMapReport = 0;
   line = '';
   url = '';
   line += '<img name="mapImage" id="mapImage" usemap="#imageMap"';
   line += ' alt="map - VAFWIS - Department of Game and Inland Fisheries" style="border:1px solid darkgray"';
   line += ' title=""';
   url += 'src="' + 'httpMapImage.asp?tn=' + document.mapform.tn.value;
   url += '&min_utmx=' + utmE + '&max_utmy=' + utmN + '&utmz=' + map_dpz + '&nad=' + bm_nad;
   url += '&p=' + map_pixel + '&w=' + mapWidth + '&h=' + mapHeight + '&t=' + document.mapform.t.value;
   url += '&use_s=' + use_s;
   url += '&overlay_list=' + document.mapform.overlay_list.value;

   if( document.mapform.overlay_list.value.indexOf('Observation',0)>-1 ) { url += '&opoi=' + document.mapform.opoi.value; }

//cookie "poi" is used as default location for VaFWIS Geographic Search by Map
   cookieSet( "poi", UTM2LL(map_poiUTM17),1,"/");

   url += '&poi=' + map_poiUTM17;
   url += '&por=' + map_porUTM17;
   url += '&dist=' + document.mapform.dist.value;
   url += '&ret=' + rings;
   if( document.mapform.r.value == '1' ) { url += '&force=1';  }
   url += '&antiCache=' + (new Date()).getTime();

if( document.mapform.pan.value=='0' 
	&& document.getElementById("mr_poi")  
	&& document.getElementById("mr_poi").value
	&& document.getElementById("mr_poi").value != '' ) {
	url += '&mr_coord=' + document.getElementById("mr_coord").value;
	url += '&mr_dist=' + document.getElementById("mr_dist").value;
	url += '&mr_xy=' + document.getElementById("mr_poi").value;
//alert( url.replace(rExp,'+') );
}

   url += '"';
   line += url.replace(rExp,'+');

   line += ' style="cursor:default;"';
   line += ' height="' + mapHeight + '" width="' + mapWidth + '">\n';
   document.getElementById(divMapId).innerHTML = line;


//--- W3C does not support imageID.onload=progress_stop; but this works with FireFox, IE, Opera, Safari
	document.getElementById("mapImage").onload=progress_stop;

   document.getElementById(divMapId).style.cursor = 'default';
   document.images.mapImage.style.cursor = 'default';
   document.getElementById(divZoomBoxId).style.cursor = 'default';


//--- item of interest can be search point or observation record location

   if( document.getElementById('divCenterItemButton') ) {
      line = '<table border=0 cellpadding=0 summary="Display Data Button"><td width=60>';
      if( map_itemUTM17 !== '' ) {

         if( parseInt(ddDist(map_dpUTM17,map_itemUTM17),10) > 10*map_pixel) {
            line += '<input type="button" name="setpos" value="Display" onclick="display_dataRecord()">';
            line += '<font size=-1> &nbsp;in center</font></td><td><font size=-1><b>';
            line += poiDescription +'</b> is not at map center</font>';
         } else {
            line += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
            line += '<font size=-1> &nbsp;</font></td><td><font size=-1><b>';
            line += poiDescription + '</b> is at map center</font>';
         }
      } else if( map_dist<1 ) {
         if( parseInt(ddDist(map_dpUTM17,map_poiUTM17),10) > 10*map_pixel ) {
            line += '<input type="button" name="setpos" value="Display" onclick="display_poi()">';
            line += '<font size=-1> &nbsp;in center</font></td><td><font size=-1><b>';
            line += poiDescription + '</b> is not at map center</font>';
         } else {
            line += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
            line += '<font size=-1> &nbsp;</font></td><td><font size=-1><b>';
            line += poiDescription + '</b> is at map center</font>';
         }
      }
      line += '&nbsp;</td></table>';
      document.getElementById('divCenterItemButton').innerHTML = line;
   }

   if( document.getElementById('divSearchAreaButton') ) {
      line = '<table border=0 cellpadding=0><tr><td width=60>';
      if( map_dist>0 ) {
         if( parseInt( ddDist(map_poiUTM17,map_dpUTM17),10 ) > 10*map_pixel ) {
            line += '<input type="button" name="setpos2" value="Display" onclick="display_poi()"';
            line += '<font size=-1> &nbsp;in center</font></td>';
            line += '<td><font size=-1><b>Search Point</b> is not at map center</font>';
         } else {
            line += '&nbsp;</td><td><font size=-1><b>Search Point</b> is at map center</font>';
         }
      }
      line += '</td></table>';
      document.getElementById('divSearchAreaButton').innerHTML = line;
   }

   document.getElementById('spanNoteTopLeft').innerHTML = 'left ' + utmE + ' and top ' + utmN;

   line = 'Map is currently displayed as ' + mapWidth + ' columns by ' + mapHeight + ' rows';
   line += ' for a total of ' + (mapWidth*mapHeight) + ' pixles.';

   var tx = mapWidth*map_pixel;
   var ty = mapHeight*map_pixel;
   line += ' The map display represents ' + tx + ' meters east to west by ' + ty + ' meters north to south';
   line += ' for a total of ' + nDecString(tx*ty/1000000,2) + ' square kilometers.';

   tx = parseInt(tx*3.2814,10);
   ty = parseInt(ty*3.2814,10);
   line += ' The map display represents ' + tx + ' feet east to west by ' + ty + ' feet north to south';
   line += ' for a total of ' + nDecString(tx*ty/27878400,2) + ' square miles.';
   document.getElementById('spanNoteMapExpanse').innerHTML = line;


   if( map_t == '2' || map_t == '1' || map_t == 'N' || map_t == 'O' ) {
      var map_max_utmx = Math.round( map_min_utmx + (mapWidth * map_pixel) );
      var nwArray = UTM2LL(map_min_utmx + ' ' + map_max_utmy + ' ' + map_dpz).split(' ');
      var neArray = UTM2LL(map_max_utmx + ' ' + map_max_utmy + ' ' + map_dpz).split(' ');
      nwArray.shift();
      neArray.shift();
      if( parseInt(neArray.shift(),10) > -78 && parseInt(nwArray.shift(),10) <= -78 ) {
         line = '<br><br>A UTM Zone change occurs within the image.';
         if( map_dpz > 17 ) {
            line += 'The left-hand side of the image is a pseudo projection from UTM Zone 17 into UTM Zone 18';
            line += ' resulting in reduced spatial accuracy within the portion of the image occurring in UTM Zone 17.';
         } else {
            line += 'The right-hand side of the image is a pseudo projection from UTM Zone 18 into UTM Zone 17';
            line += ' resulting in reduced spatial accuracy within the portion of the image occurring in UTM Zone 18.';
         }
      } else { line = ''; }
      document.getElementById('spanNoteCrossZone').innerHTML = line;
      document.getElementById('divAuxillaryLegend').innerHTML = '';
   } else if( map_t == 'B' || map_t == 'C' ) {
       line = '<img border=0 width=' + bar_width;
       line += ' onmouseover="' + "this.T_STATIC=true;this.T_FONTSIZE='15px';return escape('Click to view');" + '"';
       line += ' onClick="javascript:if(initComplete) openAuxillaryLegendWin(images/auxillary_legend_' + map_t + '.jpg);"';
       line += ' alt="Auxillary Left Legend"';
       line += ' name="AuxilaryLegendImage" src="images/auxillary_left_legend_' + map_t + '.jpg">';
      document.getElementById('divAuxillaryLegend').innerHTML = line;
   } else {
      document.getElementById('divAuxillaryLegend').innerHTML = '';
   }
   document.getElementById('spanNoteProjection').innerHTML = 'UTM Zone ' + map_dpz + ' NAD ' + bm_nad;

	mmA.clear();
	measureToolDrawB();

   if( unDoTag === 0 ) {
      unDoLine = 'bm=' + document.mapform.bm.value;
      unDoLine += '&s=' + document.mapform.s.value;
      unDoLine += '&p=' + document.mapform.p.value;
      unDoLine += '&t=' + document.mapform.t.value;
      unDoLine += '&tile=' + document.mapform.tile.value;
      unDoLine += '&dp_utm17=' + document.mapform.dp_utm17.value;
      unDoLine += '&poi_utm17=' + document.mapform.poi_utm17.value;
      unDoLine += '&dpz=' + document.mapform.dpz.value;
      var newLen = unDoArray.unshift(unDoLine);
      if( unDoArray.length < 2 ) {
         hideCell('TableMapHeader',0,0);
      } else {
         showCell('TableMapHeader',0,0);
      }
   }
      
}

//-----------------------------------------------------------------------------------

function unDo() {

   unDoTag = 1;

   if( unDoArray.length > 1 ) {
      unDoArray.shift();
      unDoLine = unDoArray[0];
      var parmsArray = unDoLine.split('&');
      while( parmsArray[0] ) {
         var valueArray = parmsArray.shift().split('=');
         if( valueArray[1] ) {
            document.mapform[valueArray[0]].value = valueArray[1];
         }
      }

      var tileArray = document.mapform.tile.value.split(',');
      mapWidth = parseInt(tileArray[0],10);
      mapHeight = parseInt(tileArray[1],10);
      setMapSize(mapWidth,mapHeight);

      set_bm(document.mapform.t.value);

      panButton(document.mapform.pan.value);
      measureButton(document.mapform.measure.value);

      replaceMap();

      if( unDoArray.length < 2 ) {
         hideCell('TableMapHeader',0,0);
      }
   }
   unDoTag = 0;

}
//-----------------------------------------------------------------------------------

function hideCell(tableID, rowIndex, cellIndex) {
//--- need in page header: <STYLE> .cell { position: relative; } </STYLE>
//--- need in table: <table ID="tableID" ><td CLASS="cell" >
  if(document.all) {    
     document.all[tableID].rows[rowIndex].cells[cellIndex].style.visibility = 'hidden';
  } else if(document.getElementById) {    
     document.getElementById(tableID).rows[rowIndex].cells[cellIndex].style.visibility = 'hidden';
  }
}

//-----------------------------------------------------------------------------------

function showCell(tableID, rowIndex, cellIndex) {
//--- need in page header: <STYLE> .cell { position: relative; } </STYLE>
//--- need in table: <table ID="tableID" ><td CLASS="cell" >
   if(document.all) {
      document.all[tableID].rows[rowIndex].cells[cellIndex].style.visibility = 'visible';
   } else if(document.getElementById) {    
      document.getElementById(tableID).rows[rowIndex].cells[cellIndex].style.visibility = 'visible';
   }
}

//-----------------------------------------------------------------------------------

function ddDist( dd1, dd2 ) {
   var utmArray = LL2UTM(dd(dd1)).split(' ');
   var dd1e = utmArray.shift();
   var dd1n = utmArray.shift();
   var dd1z = utmArray.shift();

   utmArray = LL2UTM(dd(dd2),dd1z).split(' ');
   var dd2e = utmArray.shift();
   var dd2n = utmArray.shift();

   return( Math.sqrt( (dd1e-dd2e)*(dd1e-dd2e) + (dd1n-dd2n)*(dd1n-dd2n) ) );   
}

