 
 function displayFrames(oWnd){
  if(oWnd.frames.length > 0){
    tmp = "<ul>";
    for(i=0;i<oWnd.frames.length;i++)
     {   tmp = tmp + "<li>" + oWnd.frames[i].name + "</li>\n";
        tmp = tmp + displayFrames(oWnd.frames[i]);    }
    tmp = tmp + "</ul>";
    return tmp;}
   else {
    return "";  }}
// var toDisplay = displayFrames(window.top);
/* 
** FireFox won't share variable between frames
** We need a reference to the MapFrame where MapServerParam.js is included. Ref: http://sharkysoft.com/tutorials/jsa/content/053.html 
*/
var t = window.top.frames["MapFrame"];
if(!t && top.opener)
   t = top.opener.top.frames["MapFrame"];
//variables for mouse position
var mouseX=0;
var mouseY=0;
var minClickX = 18
if(t.hspc != null)
  minClickX = t.hspc;
var minClickY = 18;
if(t.vspc != null)
  minClickY = t.vspc;
var maxClickX = 0;
var maxClickY = 0;

//variables for measure distance
ScaleBarUnits = t.ScaleBarUnits.toUpperCase(); 
MapUnits = t.MapUnits.toUpperCase();
var currentMeasure=0;

var captWin=null; 		
/************************************************************************
** This function handles the mouse click event fired by different icons
** in both Standard Toolbar and Dynamic Toolbar
 */ 
function csy_toolClick(val) {

	initVar();

	var pf = window.top.frames["PostFrame"];
  if(!pf && top.opener)
	pf = top.opener.top.frames["PostFrame"];
	var theForm = pf.document.forms[0];
	var t = top.MapFrame;
	var r = getLayer("theTop");
	
	theForm.CMD.value = "DONOTHING"; 

	redrawDynLayers();
	 
	setPrevious();
	
	switch (val) 
	{
		case 'zoomin':				
			{
			r.visibility = "hidden";
			theForm.CMD.value = 'ZOOM_IN';
			break;}
		case 'zoomout':		
			{r.visibility = "hidden";

			theForm.CMD.value = 'ZOOM_OUT';
			break;}
			
		case 'zoomfullextent':	
			showRetrieveMap();
			{theForm.CMD.value = 'RECENTER';

			var prev_minx = theForm.minx.value;
			var prev_miny = theForm.miny.value;
			var prev_maxx = theForm.maxx.value;
			var prev_maxy = theForm.maxy.value;	
	
			theForm.minx.value = theForm.MapExtMinX.value ; //pf.document.getElementById("MapExtMinX").value;
			theForm.miny.value = theForm.MapExtMinY.value ; //pf.document.getElementById("MapExtMinY").value;
			theForm.maxx.value = theForm.MapExtMaxX.value ; //pf.document.getElementById("MapExtMaxX").value;
			theForm.maxy.value = theForm.MapExtMaxY.value ; //pf.document.getElementById("MapExtMaxY").value;
			theForm.toolMode.value = val;

			//added for view previous extents
			theForm.redraw.value = "Y";
			//theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;  zoom previous already called
			theForm.toolMode.value = val;				
				
			theForm.submit();
			break;}
		case 'zoomactivelayer':	
			{
				var layerIdx = -1;
				for(i = 0;i<t.layerCount;i++)
				{
					if (ActiveLayerID == t.LayerName[i])
					{
						layerIdx = i;
						i = t.layerCount;
					}
				}		

				showRetrieveMap(); 
				var ct = -1;
				for (var i=0; i<t.layerCount; i++)
				{
					if (t.LayerID[i] == ActiveLayerID)
					{
						ct = i;		
						i = t.layerCount;
					}
				}
				if (t.LayerisRaster[ct] == 1 && projOrig!="+"+mapProjection)//SP Nov 2007	
				{
					alert("Raster layers does not support reprojection.Please chose another Active Layer!");
					hideRetrieveMap();
					break;
				}

				var strConnection1 = t.LayerConnectionName[ct];			
				var connType1 = t.getXMLValue("config/connections.xml","type", strConnection1);
				
				if (ct >=0)
				{
					
					if( t.LayerisRaster[ct]>=1 && false)
					{
					
						theForm.CMD.value = "RECENTER"; 
						var prev_minx = theForm.minx.value;
						var prev_miny = theForm.miny.value;
						var prev_maxx = theForm.maxx.value;
						var prev_maxy = theForm.maxy.value;
						var lExtent = t.LayerExtent[ct].split("*");
											
						theForm.minx.value = lExtent[0];
						theForm.miny.value = lExtent[1];
						theForm.maxx.value = lExtent[2];
						theForm.maxy.value = lExtent[3];			
						
						//alert(lExtent[0]+lExtent[1]+lExtent[2]+lExtent[3]);
						
						theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;
						
					}
					else
					{
						if(connType1.toLowerCase() == "wms")
						{
							theForm.CMD.value = 'RECENTER';

							var prev_minx = theForm.minx.value;
							var prev_miny = theForm.miny.value;
							var prev_maxx = theForm.maxx.value;
							var prev_maxy = theForm.maxy.value;	

							theForm.minx.value = pf.document.getElementById("MapExtMinX").value;
							theForm.miny.value = pf.document.getElementById("MapExtMinY").value;
							theForm.maxx.value = pf.document.getElementById("MapExtMaxX").value;
							theForm.maxy.value = pf.document.getElementById("MapExtMaxY").value;				
						}
						else
						{	theForm.CMD.value = 'RECENTER_L';
						
						}
					
					}

					theForm.redraw.value = "Y";
					//alert(val);
					theForm.toolMode.value = val;

					theForm.submit();
				}
				else
				{ 	
					hideRetrieveMap(); //added AD Oct 19, 2004
					alert("Active Layer does not exist!");
				}
				break;
			}
			
		case 'zoomlast':			

			{
			showRetrieveMap(); 
			theForm.CMD.value = 'RECENTER';			
			if (isReloaded)  
			{
				getPrevious();  // thow out current that we just set
				var prevArray = getPrevious();

				theForm.minx.value = prevArray[0];
				theForm.miny.value = prevArray[1];
				theForm.maxx.value = prevArray[2];
				theForm.maxy.value = prevArray[3];

				theForm.redraw.value = "Y";
				//theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;
				theForm.toolMode.value = val;

				theForm.submit();
			}
			else
			{ 
				hideRetrieveMap();
				alert('No previous extents')
			};
			
			break;}
			
		case 'pan':
			{
			r.visibility = "hidden";
			theForm.CMD.value = 'RECENTER';
			break;}
		case 'print':
			{//csy_displayGeneralPage("printform.htm");
			csy_PrintForm()
			break;}
			
		case 'identify':
			{
				// clicking this with a selection made will cause the results to be returned. 
				if(theForm.toolMode.value = "identify" || theForm.selectShpResults.value !="")
				{  // Keep out state, empty existing results?
					clearSelection(1);
					break;
				}
				//AD June, 2007, added no support for raster layer
				var ct = -1;
				for (var i=0; i<t.layerCount; i++)
				{
					if (t.LayerID[i] == ActiveLayerID)
					{
						ct = i;		
						i = t.layerCount;
					}
				}

				if (ct >=0)
				{
					if( t.LayerisRaster[ct]>=1)
					//original raster loaded from map, have a value of 2
					{
						alert("This operation isn't supported on Raster layers!");
					}
				}
				//the code to test WMS layers is in setactivelayer as well
				var strConnection = t.LayerConnectionName[ct];
				var connType = t.getXMLValue("config/connections.xml","type", strConnection);
				if(connType.toLowerCase() == "wms")
				{
					theForm.mapScale.value =  mapScaleOld;
					var lyrProj= GetProjLayer(ActiveLayerID);
					if( lyrProj = "+init=epsg:4326")
						MapUnits = "DEGREES";
					else
						MapUnits = "METERS"
					var mapProj="+"+mapProjection;
					if(lyrProj!==mapProj)
					{
						var input_box=confirm(" This is a WMS layer.\n To increase the accuracy of identifying features, this layer must be reprojected to it's source projection. \n Click OK to reproject the map accordingly or click Cancel to stay in the current projection.");
						
						if (input_box==true)
						{
							t.mapProjectionName="Geographic(lat long)";
							
							theForm.projectionStringOld.value = mapProjection;
							t.mapProjectionOld = mapProjection;
							mapProjection= lyrProj.substr(1,lyrProj.length-1);
							theForm.projectionString.value = mapProjection;
							theForm.mapunit.value = t.MapUnits;
							
							theForm.CMD.value = 'REPROJECT';
						//	mMapScale = getMapScale(false);	
							
						
						
							break;
						}
					
					}
				}
				r.visibility = "hidden";			
				theForm.CMD.value = 'QUERY_POINT';
				break;
			}
			
		case 'zoomToBoundary':
			// Zoom To Boundary function
			{csy_displayZoomToBoundary();
			break;}	
			
		case 'selectProjection':
			 
			{csy_selectProjection();
			break;}
						
		case 'quickFind':
			//Quick Find function			
			{csy_find();
			break;}
			
		case 'selectbox':			 			
			{			 
			r.visibility = "hidden";			
			theForm.CMD.value = 'SELECTION';
			csy_selection();
			break;}

		case 'selectpoint':
			//Select by Point function			
			{
			r.visibility = "hidden";			
			theForm.CMD.value = 'SELECTION';
			csy_selection();
			break;}
			
		case 'selectline':
			//Select by Line function			
			{
			r.visibility = "hidden";
			theForm.CMD.value = 'SELECTION';		
			csy_selection();
			break;}
			
		case 'selectshape':
			//Select by Shape function			
			{
			r.visibility = "hidden";			
			theForm.CMD.value = 'SELECTION';
			csy_selection();
			break;}

		case 'measure':
			{theForm.CMD.value = 'MEASURE'; //does not do anything			
			r.visibility = "visible";
			r.cursor = "crosshair";
			currentMeasure=0 ; //SP MAy 2007
			csy_displayGeneralPage("measure.htm");
			break;}

		case 'addText':
			{
			r.visibility = "hidden";			
			theForm.CMD.value = 'ADD_TEXT';
			csy_displayGeneralPage("annotateDisplay_start.htm");
			break;}
			
		case 'setunits':
			{//csy_displayGeneralPage("setUnits.htm");
			csy_setUnits();
			break;}
			
		case 'buffer':
			{
			csy_buffer();
			break;}
		
		case 'customQuery':
			{theForm.CMD.value = 'CUSTOMQUERY';
			csy_displayGeneralPage("Query.htm");
			break;}

		case 'stdReports':
			{
			csy_standardReports();
			break;}
			
		case 'saveimage':
			{
				/*var strURL = cuestaJspURL + "saveimage.jsp";
				parent.TextFrame.document.location = strURL;*/
			csy_SaveImage();	
			break;
			}
			
		case 'customPrint':
			{csy_displayGeneralPage("CustomPrintform.htm");
			break;}

		case 'notificationList':
			{
			t.useNotification = true;
			theForm.CMD.value = 'SELECTION';
			theForm.toolMode.value = "selectbox";//set default value to select by box
			
			if (Trim(sqryShpResults).length>0) clearSelection(1);//AD June 17, 2005 - only clear selection if selection found	

			csy_displayGeneralPage("NotificationList.htm");
			break;}
		case 'extractData':
			{			
   			csy_extractData();
			break;
			}	
		case 'extractData_Full':
			{			
   			csy_extractDataFull();
			break;
			}			
		case 'extractWizard':
			{			
   			csy_extractWizard();
			break;
			}	
		case 'captureXY':
			{r.visibility = "hidden";
			theForm.CMD.value = "MAPCOORD";
			csy_displayCaptureXY();
			break;}

		case 'zoomToBox':
			{csy_displayZoomToBox();
			break;}			

		//AD June 2007, added rest of tools
		case 'manageLayers':
			{csy_addServiceLayer();
			break;}	
		case 'reorderLayers':
			{csy_reorderLayer();
			break;}	
		case 'localLayerList':
			{csy_addDynamicLayer();
			break;}	
		case 'clearSelection':
			{clearSelection(1);
			break;}	
		case 'clearHighlighted':
			{clearHighlight();
			break;}	
		case 'loadView':
			{
			break;}	
		case 'quickSearch':
			{
			break;}	
		case 'zoomNTS':
			{
			break;}	
		case 'openProjectFile':
			{csy_loadSession();
			break;}	
		case 'saveProjectFile':
			{csy_saveSession();
			break;}	
		case 'layerMetaData':
			{openMetaPage();
			break;}		
		case 'layerList':
			{
			break;}		
		case 'manageBookmarks':
			{csy_manageBookmarks();
			break;}			
		case 'customizeLayer':
			{csy_customizeLayer();
			break;}				
		case 'showAttributes':
			{csy_showAttrib();
			break;}
		//
		default:
			//nothing
		
	} //end of switch

	//AD June 2007, added save sTheCommand
	sTheCommand = theForm.CMD.value;
	
	toolMode = val;
	csy_setMode(toolMode);
	writeModeFrame();
	
	document.onmouseup = mouseUp;
	document.onmousedown = mouseDown;
	document.onmousemove = getMouse;

}


function csy_SetWMSIdentify(projString)
{
pf = top.opener.top.frames["PostFrame"];
var theForm = pf.document.forms[0];
theForm.mapScale.value = t.mapScaleOld;
theForm.projectionString.value = projString;
theForm.CMD.value = 'QUERY_POINT';

}


/************************************************************************
** This function is called by MapFrame, on pan direction click
*/
function csy_panDirectionClick(direction) 
{
	pansize = .4;
	showRetrieveMap(); 
	
	initVar();

 var pf = window.top.frames["PostFrame"];
  if(!pf && top.opener)
   pf = top.opener.top.frames["PostFrame"];
  theForm = pf.document.forms[0];
	width = theForm.imagewidth.value;
	height = theForm.imageheight.value;

	if(direction == 'n') {
	x = (width-1)/2.0;
	y = 0 - height * pansize + height/2.0;
	} else if(direction == 'nw') {
	x = 0 - width * pansize + width/2.0;
	y = 0 - height * pansize + height/2.0;
	} else if(direction == 'ne') {
	x = (width-1) + width * pansize - width/2.0;
	y = 0 - height * pansize + height/2.0;
	} else if(direction == 's') {
	x = (width-1)/2.0;
	y = (height-1) + height * pansize - height/2.0;
	} else if(direction == 'sw') {
	x = 0 - width * pansize + width/2.0;
	y = (height-1) + height * pansize - height/2.0;
	} else if(direction == 'se') {
	x = (width-1) + width * pansize - width/2.0;
	y = (height-1) + height * pansize - height/2.0;
	} else if(direction == 'e') {
	x = (width-1) + width * pansize - width/2.0;
	y = (height-1)/2.0;
	} else if(direction == 'w') {
	x = 0 - width * pansize + width/2.0;
	y = (height-1)/2.0;
	}

	theForm.CMD.value = 'RECENTER';
	theForm.pandirection.value = x + '*' + y;

	redrawDynLayers();
	theForm.submit();

}

//********************************************
//** This function loads the map image
//*
function csy_loadMapImage(str) {

	var mp = str;
	document.getElementById("mapLocation").innerHTML= mp;
	hideRetrieveMap();
	//destroy DHTML element, layer is redrawn by mapscript
	if (isDrawPointLayer == true) destroyElement("pointLayer");
}


//********************************************
//** This function loads the map image
//*
function csy_loadOVMapImage() {
	document.OVMap.src= ovImage;
}


//********************************************
//** This function loads the map image
//*
function csy_loadScaleBar() {
	document.theScale.src = scaleImage;
}



/*******************************************
** This function refreshes the map image
*/
function csy_drawMap(str) {
	var theForm = top.PostFrame.document.forms[0];
	theForm.redraw.value="Y";
	theForm.CMD.value="RECENTER";
	theForm.submit();	
}



/***********************************************
** This function toggles the overview map image
** Created By: Monica Socol, June 15 2004
*/
function csy_toggleOVMap() {
	var theForm = top.PostFrame.document.forms[0];
	if (hasLayer("theOVMap"))
	{	
		if (isOVMapVisible)
		{
			hideOVMap();
			isOVMapVisible = false;
			theForm.isOVMapVisible.value = "N";
		}
		else
		{
			showOVMap();
			isOVMapVisible = true;
			theForm.isOVMapVisible.value = "Y";
		}
	}	
}

/*************************************************************
** This function displays a message on screen
** similar with the alert, but it is driven from the php side.
*/
function csy_alert(str) {	
	alert(str);
}

/******************************************
** This function sets the Reload flag
** that defines if the map object is initialized or re-loaded only
*/
function csy_setReloadFlag(str) {	
	if (str =="Y")
		isReloaded = true;
	else
		isReloaded = false;
}

/******************************************
** This function sets the mode
*/
function csy_setMode(toolMode) {

	//AD May 2007
	/*if (top.PostFrame.document.forms[0])
	{
		var theForm = top.PostFrame.document.forms[0];
		theForm.toolMode.value = toolMode;
	}*/
	var frame=parent.PostFrame;
	if (top.PostFrame!=null) frame = top.PostFrame;
	if (frame && frame.document.forms[0])
	{
		var theForm = frame.document.forms[0];
		var PreviousTool = theForm.toolMode.value; //SP 2008	
		if (PreviousTool == 'manageBookmarks' || PreviousTool == 'openProjectFile')
		  theForm.CMD.value = "DONOTHING"; 
		
		theForm.toolMode.value = toolMode;
	
		//AD June 2007, force php to save toolmode
		//for tool such as customQuery already do it on form submit		
		if (toolMode!='customQuery' && toolMode!='ReferencesQuery' && toolMode!='ShowingsQuery' && toolMode!='GmetaQuery' && toolMode!='DiamondsQuery'  )		
		{
			if (isNav) 
				theForm.submit;
			else
				theForm.submit();			
		}
			highlightToolIcon();
	}
	switch (toolMode) 
		{
			case 'zoomin':			
				{modeName = "Zoom In";			
				break;}
			case 'zoomout':		
				{modeName = "Zoom Out";
				break;}
			case 'zoomfullextent':	
				{modeName = "Zoom Full Extent";
				break;}
			case 'zoomactivelayer':
				{modeName = "Zoom Active Layer";			
				break;}
			case 'zoomlast':			
				{modeName = "Zoom Previous";
				break;}
			case 'pan':						
				{modeName = "Pan";
				break;}
			case 'zoomscale':			
				{modeName = "Zoom To Scale";
				break;}
			case 'identify':
				{modeName = "Identify";
				break;}
			case 'zoomToBoundary':
				{//modeName = "Zoom To Boundary";
				modeName = "Zoom To Feature";//AD June 2007
				break;}
			case 'quickFind':
				{
					
				modeName = "Quick Search";
				break;}
			case 'selectbox':
				{ 
	     			 modeName ="Select by Box";
				break;}
			case 'selectpoint':
				{      						
				modeName = "Select by Point";
				break;}
			case 'selectline':
				{       						
				modeName = "Select by Line";
				break;}
			case 'selectshape':
				{
	       				
				modeName = "Select by Shape";
				break;}
			case 'measure':
				{modeName = "Measure Distance";
				break;}
			case 'addText':
				{modeName = "Annotate Map";
				break;}
			case 'setunits':
				{modeName = "Set Units";
				break;}
			case 'buffer':
				{modeName = "Spatial Query";
				break;}
			case 'customQuery':
				{modeName = "Custom Query";
				break;}
			case 'captureXY':
				{modeName = "Find Map Coordinates";
				break;}
			case 'notificationList':
				{modeName = "Notification List"; 
				break;}
			//AD June 2007, added rest of tools
			case 'print':
				{modeName = "Print Map"; 
				break;}
			case 'selectProjection':
				{modeName = "Set Map Projection"; 
				break;}
			case 'stdReports':
				{modeName = "Standard Reports"; 
				break;}
			case 'saveimage':
				{modeName = "Save Image"; 
				break;}
			case 'customPrint':
				{modeName = "Custom Print"; 
				break;}
			case 'extractData_Full':
				{modeName = "Extract Full Layer"; 
				break;}
			case 'extractData':
				{modeName = "Save Map Data"; 
				break;}	
			case 'extractWizard':
				{modeName = "Download Wizard"; 
				break;}				
			case 'zoomToBox':
				{modeName = "Zoom To Box"; 
				break;}			
			case 'manageLayers':
				{modeName = "Manage Layers";
				break;}	
			case 'reorderLayers':
				{modeName = "Reorder Layers";
				break;}	
			case 'localLayerList':
				{modeName = "Local Layer List";
				break;}	
			case 'clearSelection':
				{modeName = "Clear Selection";
				break;}	
			case 'clearHighlighted':
				{modeName = "Clear Highlighted Features";
				break;}	
			case 'loadView':
				{modeName = "Load Saved Project";
				break;}	
			case 'quickSearch':
				{modeName = "Quick Search";
				break;}	
			case 'zoomNTS':
				{modeName = "Zoom To NTS";
				break;}	
			case 'openProjectFile':
				{modeName = "Open Project";
				break;}	
			case 'saveProjectFile':
				{modeName = "Save Project";
				break;}	
			case 'layerMetaData':
				{modeName = "Layer Meta Data";
				break;}		
			case 'layerList':
				{modeName = "Layer List";
				break;}		
			case 'manageBookmarks':
				{modeName = "Manage Bookmarks";
				break;}			
			case 'customizeLayer':
				{modeName = "Customize Layer";
				break;}				
			case 'showAttributes':
				{modeName = "Show Attributes";
				break;}
			case 'ReferencesQuery':
				{modeName = "References Query";
				break;}
			case 'ShowingsQuery':
				{modeName = "Showings Query";
				break;}
			case 'GmetaQuery':
				{modeName = "Gmeta Query";
				break;}
			case 'DiamondsQuery':
				{modeName = "Diamonds Query";
				break;}
				
			//
			default:
				//modeName = 'Zoom In';
				modeName = 'Error: Tool not specified!';//AD June 2007
		}	
			

		
}

/******************************************
** This function redraws the mode page
** Created By: Monica Socol, June 16 2004
*/
function writeModeFrame() {
	parent.ModeFrame.document.location= "ModeFrame.htm";
}

/********************************************
** getMapScale function
** Returns map scale using iScreenDPI value set in MapServerParams.js
** If formated == true then it is returned as a string in the format "1:x,xxx"
** Otherwise an integer is returned
**
*/
function getMapScale(formated)
{
	var theForm = top.PostFrame.document.forms[0];
	var tempFactor = iScreenDPI;
	var inchPerMeter = 39.4;
	var tempScale=0;
	if (theForm== undefined) return ""; //SP Jun 2007
	iWidth = theForm.imagewidth.value;
	if (MapUnits=="DEGREES") 
	{ //SP Apr 2006 "IF" added to handle Decimal Degrees as units measure
	
		var midY = parseFloat(theForm.miny.value );
		var tempL = theForm.minx.value;
		var tempR = theForm.maxx.value;
		if (tempL<-180) tempL = (-1799999 /10000);
		if (tempR>180) tempL = (1799999/10000);
	
		var Lon1 = tempL * Math.PI / 180;
		var Lon2 = tempR * Math.PI / 180;
		var Lat1 = midY* Math.PI / 180;
		var Lat2 = midY* Math.PI / 180;
		var LonDist = Math.abs(Lon2-Lon1);
		var LatDist = Math.abs(Lat2-Lat1);
		
		var A = Math.pow(Math.sin(LatDist / 2),2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(LonDist /2),2);
		var C = 2 * Math.asin(Math.min(1, Math.sqrt(A)));		
		var D = (3963 - 13 * Math.sin((Lat1 + Lat2) / 2)) * C;

		mDistance = D * 5280;
		mUnits = "FEET";
		tempScale = convertUnits(mDistance,mUnits,"METERS"); // UTM are in meters
 		tempScale=tempScale / iWidth;
		
	}
	else
	{
		
		minxVal = theForm.minx.value;
		maxxVal = theForm.maxx.value;		

		tempScale = (maxxVal - minxVal) / iWidth;
		
	}
	t.mapScaleOld = parseInt((tempScale * tempFactor * inchPerMeter) + 0.5) ;
	theForm.mapScaleOld = t.mapScaleOld ;

	if (formated)
	{
		var scaleValue = parseInt((tempScale * tempFactor * inchPerMeter) + 0.5);
		var scale = scaleValue.toString(10);

		var formatedScale = "";
		var scaleLength = scale.length;

		if (scaleLength > 3)
		{
			var rightPos = scaleLength;
			// The first three numbers on the right
			formatedScale = scale.substring(rightPos - 3, rightPos);
			// Now all the bits in the middle
			for (rightPos -= 3; rightPos > 3; rightPos -= 3)
			{
				formatedScale = scale.substring(rightPos - 3, rightPos) + "," + formatedScale;				
			}
			// Finally the header
			formatedScale = scale.substring(0, rightPos) + "," + formatedScale;				
		}
		else
		{  formatedScale = scale; }		
		return "1:" + formatedScale;
	}
	else
	{  return parseInt((tempScale * tempFactor * inchPerMeter) + 0.5); }

}

/***********************************************************************************
** rubberBand functions, to draw rectangle on image to zoom in or out
**
*/

var clickMapZone = true;
//AD July 27, 2005 - used to count number of clicks on map for moving annotation object.
var numClicks = 0;
var moveXFrom = -1;var moveYFrom = -1;
var moveXTo = -1;var moveYTo = -1;

function mouseDown(e)
{   
clickMapZone = true;

maxClickX = mapWidth + minClickX;
maxClickY = mapHeight + minClickY;

document.onmouseup = mouseUp;
document.onmousedown = mouseDown;
document.onmousemove = getMouse;

if (isNav)
{var evt = e;}

else {var evt = event; }

  if ((evt.clientX <= maxClickX) && (evt.clientX >= minClickX) && (evt.clientY <= maxClickY) && (evt.clientY >= minClickY)){ 
  	if (evt.button != 2) 
  	{
  		if (toolMode != "captureXY" && toolMode != "addText" && toolMode != "measure" && toolMode != "selectline" && toolMode != "selectshape")
  		{
  			//AD July 15, 2004 - to reset the CMD value, based on current tool mode
  			csy_resetCMDvalue(toolMode);
  		}
  		//AD July 9, 2004 - to force all dynamic layers to display on mouse click
  		redrawDynLayers();
  		switch (toolMode) 
			{
				case 'zoomin':
					{
					  if (isNav)
					   {startRubber(e);}
					  else
					   {startRubber();}
					break;
					}
				case 'zoomout':
					{
					  if (isNav)
					   {startRubber(e);}
					  else
					   {startRubber();}
					break;
					}
				case 'measure':
					{
					
					if (isMeasDistLayerOn==false) 
					{
						emptyArray(clickMapPointX);
						emptyArray(clickMapPointY);
					}
					clickAddPoint();
					break;}
				case 'addText':
					{mapTextX = mouseX;
 					mapTextY = mouseY;
 					if (annotationAction == "MOVE")
 					{//AD July 27, 2005 - created new annotationAction variable 
 						var resArr = checkAnnotationToMove();
 						if (resArr[0]) 
 						{
							numClicks++;
							if (numClicks==1){
								moveXFrom = PixToMapCoord(mapTextX, 0); 
								moveYFrom = PixToMapCoord(mapTextY, 1); 
							}
							else if (numClicks>=2){
								moveXTo = PixToMapCoord(mapTextX, 0);
								moveYTo = PixToMapCoord(mapTextY, 1);
								var dX=moveXTo-moveXFrom;
								var dY=moveYTo-moveYFrom;
								moveAnnotation(dX,dY,resArr[1],resArr[2]);
							}
 						}
 					} else
 					{
						
						initAnnotDetails(annotationType); 					
						if ( (annotationType == 0) || ((annotationType == 1) && (annoteWithText == true)) || ((annotationType == 2) && (annoteWithText == true)) )
							{startLabel();}
						else if ( (annotationType == 1) && (annoteWithText == false) )
							{addPinAnnotation_noText();}
						else if ( (annotationType == 2) && (annoteWithText == false) )
							{addPointAnnotation_noText();}
						else if (annotationType == 3)
							{addLineAnnotation();}
						else if (annotationType == 4)
							{
								if (isNav)
								{startDrawRectAnnot(e);}
								else
								{startDrawRectAnnot();}						
							}
						else if (annotationType == 5)
							{addShapeAnnotation();}	
					}
					break;}
				case 'selectpoint':
					{resetSelectFields(0);
					clickSelectionPoint();
					break;}
				case 'selectbox':
					{resetSelectFields(0);
					if (isNav)
					{startDrawSelectBox(e);}
					else
					{startDrawSelectBox();}
					
					break;}
				case 'selectshape':
					{resetSelectFields(0);
					clickSelectionShape();
					break;}
				case 'selectline':
					{resetSelectFields(0);
					clickSelectionLine();
					break;}
				case 'captureXY':
					{csy_setCaptureXY();
					break;}
				default:
					//nothing
			}
  		}
  }
  else
  clickMapZone = false;
}

function mouseUp(e)
{
  var theForm = top.PostFrame.document.forms[0];

	if (isNav) {var evt = e;}
	else {var evt = event;}
	

  if (evt.button != 2) { //if no right-click
  
  	  if (sTheCommand=="DONOTHING") {return;}//AD June, 2007, do nothign if CMD not set  	
  	  
	  if ((clickMapZone == true) && ((toolMode == 'zoomin') || (toolMode == 'zoomout'))) {
		showRetrieveMap();
		stopRubber();

		if (toolMode == 'zoomout') {theForm.CMD.value = 'ZOOM_OUT'}
		else if (toolMode == 'zoomin') {theForm.CMD.value = 'ZOOM_IN'};
		setPrevious();
  		//theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;
  		sendRectangleBox(rubberBandExtent[0],rubberBandExtent[1],rubberBandExtent[2],rubberBandExtent[3],1);
	  }
	  else if (clickMapZone == false)//AD Feb 23, 2005
	  {
	  }	  

	  else if ( (clickMapZone == true) && ((toolMode == 'measure') || (toolMode == 'selectline') || (toolMode == 'selectshape')) )
	  {
	  }	  

	  else if ( (clickMapZone == true) && ( ( (toolMode == 'captureXY') || (toolMode == 'addText' && annotationType == 3) || (toolMode == 'addText' && annotationType == 5) )  ) )
	  {}//do nothing 
	  //AD July 28, 2005, added not to refresh map on first click for move annotation 
	  else if ( (clickMapZone == true) && (toolMode == 'addText' && annotationAction == 'MOVE' && numClicks==1) )
	  {}//do nothing 
	  else
	  {//for all the other tools just submit the form	  
	  	showRetrieveMap();
	  	if (numClicks>=2) numClicks=0;//to reset annotation move after 2 clicks

	  	//added to consider mouse offset and correct bug fix on identify map click
	  	theForm.mainmap_x.value = evt.clientX - minClickX;
	  	theForm.mainmap_y.value = evt.clientY - minClickY;
	  	d = new Date()    ;
	  	submittime = d.getSeconds()+" " +d.getMilliseconds();
		theForm.submit();
	  }
  }//end if no right-click
}

var startx = "";
var starty = "";
var endx = "";
var endy = "";

function startRubber (e)
{

  var r = getLayer("rubberBand");
	
	if (isNav) 
	{//if (!e) var e = window.event;
	  startx = e.clientX; 
	  starty = e.clientY;
	}
	else 
	{
	  startx = event.clientX; 
	  starty = event.clientY;
	}

  r.width = 0;
  r.height = 0;

  endx = startx;
  endy = starty;
  

  if (isNav) {
	  r.left = startx + 'px';
	  r.top  = starty + 'px';
  }
  else
  {
	  r.pixelLeft = startx;
	  r.pixelTop  = starty;
  }
  r.visibility = 'visible';
  
  document.onmousemove = moveRubber;
  clickMapZone = true;

}



function moveRubber (e)
{

    var r = getLayer("rubberBand");

	if (isNav) {var evt = e;}
	else {var evt = event;}

    endx = evt.clientX;
    endy = evt.clientY;
	 
	 if ((endx <= maxClickX) && (endx >= minClickX) && (endy <= maxClickY) && (endy >= minClickY)){
	  // don't allow draw outside the map zone
		  
		  if (isNav) {
		  	r.left = Math.min(startx, endx) + 'px';
			r.top = Math.min(starty, endy) + 'px';
		  }
		  else
		  {
		  	r.pixelLeft = Math.min(startx, endx);
			r.pixelTop = Math.min(starty, endy);
		  }
		  r.width = Math.abs(startx - endx);
		  r.height = Math.abs(starty - endy);
	 }
	 else 
	 {
		if (endx > maxClickX) {endx = maxClickX;}
		else if (endx < minClickX) {endx = minClickX;}
		else if (endy > maxClickY) {endy = maxClickY;}
		else if (endy < minClickY) {endy = minClickY;}

		if (isNav) {
		  	r.left = Math.min(startx, endx) + 'px';
			r.top = Math.min(starty, endy) + 'px';
		}
		  else		
		{
			r.pixelLeft = Math.min(startx, endx);
			r.pixelTop = Math.min(starty, endy);
		}
		r.width = Math.abs(startx - endx);
		r.height = Math.abs(starty - endy);

		mouseUp();
	 }
}

//function stopRubber (evt)
function stopRubber ()
{
  var r = getLayer("rubberBand"); 

  //store RubberBand extents
  //subtract offsets from page left and top
  rubberBandExtent[0] = startx - minClickX;
  rubberBandExtent[1] = starty - minClickY;
  rubberBandExtent[2] = endx - minClickX;
  rubberBandExtent[3] = endy - minClickY;

  document.onmousemove = getMouse;
  
  //AD July 1st, 2004 added to hide box
  r.visibility = 'hidden';
  
}

//************************************************************************************
//** These functions get the coords at mouse position
//** and display them into the windows status as the mouse is moving over the map
//*
function getMouse(e) {
	window.status="";
	getImageXY(e);
	if (toolMode == 'measure' && isMeasDistLayerOn) //SP May 2007 
	{	document.onmousemove = getMouseDistance;  //Calculate Distance 
		
	}
	else
	{	displayXY();
	}}

function getImageXY(e) {
	if (isNav) {

		mouseX=e.clientX;
		mouseY=e.clientY;
	} else {
		mouseX=event.clientX + document.body.scrollLeft;
		mouseY=event.clientY + document.body.scrollTop;
	}
	// subtract offsets from page left and top
	mouseX = mouseX-t.hspc;
	mouseY = mouseY-t.vspc;
}	

function displayXY() {

  var pf = window.top.frames["PostFrame"];
  if(!pf && top.opener)
   pf = top.opener.top.frames["PostFrame"];

  if (pf && pf.document && pf.document.forms[0])
  {
  	var theForm = pf.document.forms[0];
  	x2=mouseX;
  	y2=mouseY;
  
  	pixelX = xDistance / mapWidth;
  
  	eLeft = theForm.minx.value*1;
  	eBottom = theForm.miny.value*1;
  
  	mapX = pixelX * mouseX + eLeft;
  	var theY = mapHeight - mouseY;
  	pixelY = yDistance / mapHeight;
  	mapY = pixelY * theY + eBottom;
  	
  	var u = Math.pow(10,2);
  	var uX = parseInt(mapX * u + (5/10)) / u
  	var uY= parseInt(mapY * u + (5/10)) / u
  	var mouseString = "Map Coordinates: " + uX + " , " + uY + " -- Image Coordinates: " +  mouseX + " , " + mouseY;
  	window.status = mouseString;
   }
}

//************************************************************************
//** This function sets the active layer
//*
function setActiveLayer(theLayer) {
	
	for(ct = 0;ct<t.layerCount;ct++)
	{	
		if (theLayer == t.LayerID[ct])
		{
			ActiveLayerID = t.LayerID[ct];
			ActiveLayerName = t.LayerName[ct];
			ActiveLayerFields = t.LayerFieldList[ct];
			ActiveLayerType = t.LayerType[ct].toLowerCase();
			if (t.LayerJSourceFieldList[ct].length >0)
				ActiveLayerJoinFields = t.LayerJSourceFieldList[ct];
			else
				ActiveLayerJoinFields = "";


			var theForm = top.PostFrame.document.forms[0];			

			theForm.activeLayer.value = theLayer;
			theForm.activeLayerFields.value = ActiveLayerFields;
			theForm.activeLayerJoinFields.value = ActiveLayerJoinFields;			
			//----------------------------- Used with new identify tool mode
						
			if(LayerIdentifyFieldsHeader[ct] != "")
			{
				identifyMode = 1;
				theForm.identifyMode.value=1; //means quick identify
				theForm.identifyFields.value = LayerIdentifyFieldsHeader[ct] + "," + LayerIdentifyFields[ct]; //LM March 27 2006
			}
			else
			{
				theForm.identifyFields.value =LayerIdentifyFields[ct];
				identifyMode = 2;
				theForm.identifyMode.value=2; //means normal identify
			}
			//identify WMS layer 2008
			if(toolMode=='identify')
			{
				var strConnection = t.LayerConnectionName[ct];
				var connType = t.getXMLValue("config/connections.xml","type", strConnection);
				if(connType.toLowerCase() == "wms")
				{
					theForm.mapScale.value =  mapScaleOld;
					var lyrProj= GetProjLayer(ActiveLayerID);
					if( lyrProj = "+init=epsg:4326")
						MapUnits = "DEGREES";
					else
						MapUnits = "METERS"
					var mapProj="+"+mapProjection;
					if(lyrProj!==mapProj)
					{
						var input_box=confirm(" This is a WMS layer.\n To increase the accuracy of identifying features, this layer must be reprojected to it's source projection. \n Click OK to reproject the map accordingly or click Cancel to stay in the current projection.");

						if (input_box==true)
						{
							t.mapProjectionName="Geographic(lat long)";

							theForm.projectionStringOld.value = mapProjection;
							t.mapProjectionOld = mapProjection;
							mapProjection= lyrProj.substr(1,lyrProj.length-1);
							theForm.projectionString.value = mapProjection;
							theForm.mapunit.value = t.MapUnits;

							theForm.CMD.value = 'REPROJECT';				

							writeModeFrame();
							theForm.submit();
							break;
						}

					}
				}
			}
			//2008
			
			
			writeModeFrame();
		}
	}
}

//************************************************************************
//** This function puts the active layer ON and makes it visible
//*
function setActiveLayerON(theLayer) {
	for(i = 0;i<t.layerCount;i++)
	{	
		if (theLayer == LayerID[i])
		{
			loadedLayers[i] = 1;
			LayerVisible[i] = 1;

			var strV ="";
			for (var i=0;i<LayerID.length; i++)
			{
				if ( LayerVisible[i] == 1 )
				{
					strV += LayerID[i] +"*"
				}
			}
			strV = strV.substring(0,strV.length-1)

			var strL = "";
			for (var i=0;i<LayerID.length; i++)
			{
				if ( loadedLayers[i] == 1 )
				{
					strL += LayerID[i] +"*";
					LayerOnLegend[i] = 1;
				}
			}
			strL = strL.substring(0,strL.length-1)

			var theForm = top.PostFrame.document.forms[0];			
			theForm.layers.value = strV;
			theForm.lyLoaded.value = strL;
		}
	}
}

/************************************************************************
** These functions trim out the whitespaces
*/

function LTrim(str){
   var whitespace = new String(" \t\n\r");		
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...		
      var j=0, i = s.length;		
      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
	 j++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

function RTrim(str){
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");		
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)..		
      var i = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
	 i--;		

      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }
   return s;
}

function Trim(str){
   return RTrim(LTrim(str));
}

/************************************************************************
** This function zooms to a selected record
** 	to handle both usual queries + buffer
*/

function showHighlight(i, caller)
{
	 //LM June 05 , save previous extent before refresh
        //t.setPrevious();
	//i is the query index 
	var strTemp = qryLayerShapeIndex[i];

	//var theForm = document.forms[0];
	var theForm = top.PostFrame.document.forms[0];
	var prev_minx = theForm.minx.value;
	var prev_miny = theForm.miny.value;
	var prev_maxx = theForm.maxx.value;
	var prev_maxy = theForm.maxy.value;

	/*  Should be using setPrevious shouldn't we?
  theForm.prevMinX.value = theForm.minx.value;
	theForm.prevMinY.value = theForm.miny.value;
	theForm.prevMaxX.value = theForm.maxx.value;
	theForm.prevMaxY.value = theForm.maxy.value;
	theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;*/
	
	if (caller == "buffer")
		theForm.qfield.value = bufferTargetLayer;		
	else if (caller == "geocode")
		theForm.qfield.value = "MARKXY(" + t.addrSearched + ")";
	else if (caller == "intersection")
		theForm.qfield.value = "MARKXY";
	else
	{	theForm.qfield.value = ActiveLayerID;
		theForm.CMD.value="HIGHLIGHT";
	}

	theForm.qvalue.value = strTemp;
	theForm.hightlightShapeResults.value = strTemp; //LM APril 22 2006
	hightlightShapeResults=strTemp
	
	theForm.highlightLayer.value = ActiveLayerID;
	highlightLayer = ActiveLayerID
	 theForm.redraw.value = "Y";
	theForm.submit();
}
//************************************************************************
//************************************************************************
//LM April 18 2006
function showHighlightMulitple(i,caller)
{

	//split out query indexes
	var qryIdx = i.split("~");
	var ind = "";

	var strTemp = qryLayerShapeIndex[i];
	for(var i=0; i<qryIdx.length; i++)
	{
		if(ind != "") ind += "^";
		ind += qryLayerShapeIndex[qryIdx[i]];
	}
 	var theForm = top.PostFrame.document.forms[0];

	/* should be using setPrevious
 	var prev_minx = theForm.minx.value;
	var prev_miny = theForm.miny.value;
	var prev_maxx = theForm.maxx.value;
	var prev_maxy = theForm.maxy.value;

	theForm.prevMinX.value = theForm.minx.value;
	theForm.prevMinY.value = theForm.miny.value;
	theForm.prevMaxX.value = theForm.maxx.value;
	theForm.prevMaxY.value = theForm.maxy.value;
	
	theForm.zoomlast.value = prev_minx+'*'+prev_miny+'*'+prev_maxx+'*'+prev_maxy;*/

	if (caller == "buffer")
		theForm.qfield.value = bufferTargetLayer;		
	else if (caller == "geocode")
		theForm.qfield.value = "MARKXY(" + t.addrSearched + ")";
	else if (caller == "intersection")
		theForm.qfield.value = "MARKXY";
	else
	{	theForm.qfield.value = ActiveLayerID;
		theForm.CMD.value="HIGHLIGHT";
	}

	theForm.hightlightShapeResults.value = ind; //LM APril 22 2006
	hightlightShapeResults =ind;
	theForm.highlightLayer.value = ActiveLayerID;
	highlightLayer = ActiveLayerID
	theForm.redraw.value = "Y";
	theForm.submit();
}

//************************************************************************
//LM April 18 2006
function getStandardReportFeatures(i)
{
	var qryIdx = i.split("~");
	var ind = "";
	var ind1 = "";

	var strTemp = qryLayerShapeIndex[i];
	for(var i=0; i<qryIdx.length; i++)
	{
		if(ind1 != "") ind1 += "^";
		ind1 += qryLayerShapeIndex[qryIdx[i]];
	}

	for(var i=0; i<qryIdx.length; i++)
		{
			if(ind != "") ind += "^";
			ind += qryIdx[i];
	}
	var theForm = top.PostFrame.document.forms[0];
	//theForm.qfield.value = ActiveLayerID;
	theForm.hightlightShapeResults.value = ind1; //LM APril 22 2006
	hightlightShapeResults =ind1;
	theForm.CMD.value="STDREPORT";
	theForm.StandardReportFeatures.value = ind;
	theForm.submit();
}




/* ***********************************************************************
** This function converts a pixel coordinate into a map coordinate
  */
function PixToMapCoord(pixCoord, coordType) {
//coordType=0 for X, coordType=1 for Y
	var theForm = top.PostFrame.document.forms[0];
	var mapCoord=0; //SP Apr 2006
	switch (coordType) 
	{
		case 0:			
			if (top.PostFrame.document.forms[0]) {
				eLeft = theForm.minx.value*1;}
			pixelX = xDistance / mapWidth;
			Coord = pixelX * pixCoord + eLeft;			
			break			
		case 1:		
			if (top.PostFrame.document.forms[0]) {
				eBottom = theForm.miny.value*1;}
			var theY = mapHeight - pixCoord;
			pixelY = yDistance / mapHeight;
			Coord = pixelY * theY + eBottom;
			break			
		default:
			//nothing
	}
        if(MapUnits!='DEGREES')
	{	var u = Math.pow(10,2);
		mapCoord = parseInt(Coord * u + (5/10)) / u;}
	else
	{       mapCoord =  Coord;}
	       
	return mapCoord;

}

/************************************************************************
** This function converts a map coordinate into a pixel coordinate
*/
function MapToPixCoord(mapCoord, coordType) {
//coordType=0 for X, coordType=1 for Y
	var theForm = top.PostFrame.document.forms[0];

   if (top.PostFrame.document.forms[0])
   {
	switch (coordType) 
	{
		case 0:			
			if (top.PostFrame.document.forms[0]) {
				eLeft = theForm.minx.value*1;
				pixelX = (theForm.maxx.value - theForm.minx.value) / mapWidth;}
			Coord = Math.abs((mapCoord - eLeft)/pixelX);			
			break			
		case 1:
			if (top.PostFrame.document.forms[0]) {
				eBottom = theForm.maxy.value*1;
				pixelY = (theForm.maxy.value - theForm.miny.value) / mapHeight;}
			Coord = Math.abs((mapCoord - eBottom)/pixelY);
			
			break			
		default:
			//nothing
	}
		
	var u = Math.pow(10,2);
	var mapCoord = parseInt(Coord * u + (5/10)) / u;
	return mapCoord;
   }	
}

//************************************************************************
//** calculate distance in current scalebarunits	
 
function calcDistance(mX,mY) {
	// Note: decimal are not hard coded to allow use with locales using commas instead of points.
	//mX,mY are in pixel coordinates
	if (clickCount>0) {
		
		var mUnits = MapUnits;
		var mDistance = 0;
		var p = clickCount-1;
		
		//convert pixel into map coordinates
		var a = clickMapPointX[p];
		var b = clickMapPointY[p];
		
		var Lon1 = a * Math.PI / 180;
		var Lon2 = mX * Math.PI / 180;
		var Lat1 = b * Math.PI / 180;
		var Lat2 = mY * Math.PI / 180;
		var LonDist = Lon1-Lon2;
		var LatDist = Lat1-Lat2;
		if (MapUnits=="DEGREES") {
			var A = Math.pow(Math.sin(LatDist / 2),2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(LonDist /2),2);
			//var A = Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(LonDist /2),2);
			var C = 2 * Math.asin(Math.min(1, Math.sqrt(A)));
			var D = (3963 - 13 * Math.sin((Lat1 + Lat2) / 2)) * C
			mDistance = D * 5280;
			mUnits = "FEET";
		} else {
			var xD = Math.abs(mX - a);
			var yD = Math.abs(mY - b);
			mDistance = Math.sqrt(Math.pow(xD,2) + Math.pow(yD,2));
		}
				
		var theDist = convertUnits(mDistance,mUnits,ScaleBarUnits);
		var u = Math.pow(10,numDecimals);
		currentMeasure = parseInt(theDist*u+(5/10))/u;
		
		updateMeasureBox();
		
	}
}
//************************************************************************
//** convert the amounts to new units	
 
function convertUnits(theDist1,mUnits,sUnits) {
	// Note: decimal are not hard coded to allow use with locales using commas instead of points.	
	var theDist = parseFloat(theDist1);
	var mDistance = theDist;

	if (mUnits == "FEET") {
		if (sUnits=="MILES") {
			mDistance = theDist / 5280;
		} else if (sUnits == "METERS") {
			mDistance = theDist * (3048/10000);
		} else if (sUnits == "KILOMETRES") {
			mDistance = theDist * (3048/10000000);
		}
	} else {
		if (sUnits=="MILES") {
			mDistance = theDist * (6213711922/10000000000000);
		} else if (sUnits == "FEET") {
			mDistance = theDist * (3280839895/1000000000);
		} else if (sUnits == "KILOMETRES") {
			mDistance = theDist / 1000;
		}
	}
	var u = Math.pow(10,numDecimals);
	if (!isNav) mDistance = parseInt(mDistance * u + (5/10)) / u

	return mDistance;
}

//************************************************************************
//** update measure.htm form	
 
function updateMeasureBox() {
var str = parent.TextFrame.location.pathname;

if (str.indexOf("measure.htm") > 0) {
	
	//var theForm = top.TextFrame;
	var theForm = top.TextFrame.document;
	
	var j = 1;
	for (var i=0;i<sUnitList.length;i++) {
		if (ScaleBarUnits==sUnitList[i]) j=i;
		}
		var u = Math.pow(10,numDecimals);
		var tMeas = 0;
		if (totalMeasure!=0) tMeas = parseInt(totalMeasure*u+0.5)/u;	

	theForm.getElementById("theMeasTotal").value = tMeas + " " + unitList[j];
	theForm.getElementById("theMeasSegment").value = currentMeasure + " " + unitList[j];
	
	if (clickCount > 2) {
	     getPolygonArea();	     
        	}		

	theForm.getElementById("theMeasArea").value = currentArea + " Sq." + " " + unitList[j];
	
	}

}
//*************************************************************************
//** Function to return number of mapunits per scalebar unit for measure distance
 
 function getPolygonArea()
 {
   // assumes" Map Units="Meters"
   //Scale Units = "Kilometres"
   var poly_area = 0;
 
   var u_i = new Array();
   var v_i = new Array();   
  
    for (var i=0;i<(clickMapPointX.length - 1);i++)
    {
       u_i[i] = clickMapPointX[i + 1] - clickMapPointX[i];
       v_i[i] = clickMapPointY[i + 1] - clickMapPointY[i];
    } 
 
    u_i[clickMapPointX.length - 1] = clickMapPointX[0] - clickMapPointX[clickMapPointX.length - 1];
    v_i[clickMapPointY.length - 1] = clickMapPointY[0] - clickMapPointY[clickMapPointY.length - 1]; 
        
    for (var i=0;i<u_i.length;i++)   
    {
       poly_area = poly_area + (clickMapPointX[i] * v_i[i] - clickMapPointY[i] * u_i[i]);
    }   
  
   poly_area = Math.abs(poly_area) * 0.5 

   var theConversion = 1;
   if (MapUnits=="METERS")
   {
   	switch (ScaleBarUnits)
   	{	case "KILOMETRES":
          	    theConversion = 1000000;
          	    break;
         	case "ACRES":
         	   theConversion = 4047;
		   break;
	        case "FEET":
          	   //theConversion = 10.76387;
          	   theConversion = 0.09290;
                   break;      
                case "MILES":
          	   theConversion = 2590000;
                   break;               
         	default: //(METERS) 
         	   theConversion = 1;      
          	   break;
   	} 
   } 
   poly_area = poly_area/theConversion;
   
   var u = Math.pow(10,2);
   if (!isNav) poly_area = parseInt(poly_area * u + (5/10)) / u
   currentArea = poly_area;
 } 
 
//*************************************************************************
//** Function recalculate distance automatically when mouse move for measure distance
 
function getMouseDistance(e) {
	getImageXY(e);
	var thePtX = PixToMapCoord(mouseX,0);
	var thePtY = PixToMapCoord(mouseY,1);
	calcDistance(thePtX,thePtY);
}

//*************************************************************************
//** Point click functions, used by Measure
 
function clickAddPoint() {
	var theForm = top.PostFrame.document.forms[0];
	var a = mouseX;
	var b = mouseY;
	
	isMeasDistLayerOn = true;
	
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);
	
	clickMapPointX[clickCount] = a;
	clickMapPointY[clickCount] = b;
	clickCount++
	
	totalMeasure = totalMeasure + currentMeasure;
	//document.onmousemove = getMouseDistance;  //SP May 2007, remove from here and move to getmouse

	theForm.addpoints_mx.value = clickMapPointX;
	theForm.addpoints_my.value = clickMapPointY;	
	theForm.redraw.value = "Y";
	
	csy_drawPointLayer(clickCount,a,b,clickMapPointX[clickCount-2],clickMapPointY[clickCount-2]);

}


//*************************************************************************
//** Redraw all dynamic layers such as measure distance, etc...	 
//**Important note: when calling this function, insert, before form submit
function redrawDynLayers()
{
  var theForm = top.PostFrame.document.forms[0];
	theForm.redraw.value = "Y";
	
	//for measure distance layer
	if (isMeasDistLayerOn==true) {
		theForm.addpoints_mx.value = clickMapPointX;
		theForm.addpoints_my.value = clickMapPointY;			
	}

	//for add map text layers
	if (isAddTextLayerOn==true) {
		theForm.addtext.value = annotationStr;
		theForm.addpin.value = annotationPinStr;
		theForm.addpoint.value = annotationPointStr;
		theForm.addline.value = annotationLineStr;
		theForm.addrect.value = annotationRectStr;
		theForm.addshape.value = annotationShapeStr;
	}

	//for selection layers
	if (isSelectionLayerOn==true) {
		theForm.selectpoint.value = selectionPointStr;
		theForm.selectline.value = selectionLineStr;
		theForm.selectshape.value = selectionShapeStr;
		theForm.selectShpResults.value = sqryShpResults;
	}
}


//*************************************************************************
//** function that displays a window for the user to enter the text of the label in Add Text tool	

function startLabel()
{  
   isAddTextLayerOn = true;

   var iwidth=(screen.width*.35);
   var ileft= (screen.width - iwidth)/2;
   var iheight = (screen.height*.54);

   var parm = "top=50,left="+ileft+",scrollbars=yes,resizable=yes,menubar=no,width="+iwidth+",height="+iheight;
   customizeLayerWin = parent.TextFrame.open(appDir+"addAnnotation.htm","customizeLayerWin", parm);
    
	var newTimeoutFunc = function () {  customizeLayerWin.focus(); };
	setTimeout(newTimeoutFunc, 750);
	
   var theForm = top.PostFrame.document.forms[0];
   redrawDynLayers();
   theForm.submit();

}

//*************************************************************************
//** Convert hexidecimal rgb number to delimited decimal rgb	

function convertHexToDec(hexColor) {
	var pos = hexColor.indexOf(",");
	var decString = hexColor;
	if (pos==-1) {
		pos = hexColor.indexOf("#");
		if (pos!=-1) {
			hexColor = hexColor.substring((pos + 1),(pos + 7));
		}
		var redHex = hexColor.substring(0,2);
		var greenHex = hexColor.substring(2,4);
		var blueHex = hexColor.substring(4,6);
		decString = parseInt(redHex,16) + "," + parseInt(greenHex,16) + "," + parseInt(blueHex,16);
	}
	return decString;
}


//*************************************************************************
//** Convert hexidecimal rgb number to delimited decimal rgb	

function convertHexToDec2(hexColor) {
var pos = hexColor.indexOf(",");
	var decString = hexColor;
		if (pos==-1) {
			pos = hexColor.indexOf("#");
			if (pos!=-1) {
				hexColor = hexColor.substring((pos + 1),(pos + 7));
			}
			var redHex = hexColor.substring(0,2);
			var greenHex = hexColor.substring(2,4);
			var blueHex = hexColor.substring(4,6);
			decString = parseInt(redHex,16) + "~" + parseInt(greenHex,16) + "~" + parseInt(blueHex,16);
		}
		return decString;
}


//*************************************************************************
//** Reset the value of CMD in jsForm, on mouse click	
 
function csy_resetCMDvalue(toolmode) {
var theForm = top.frames["PostFrame"].document.forms[0];
theForm.CMD.value = 'DONOTHING';//AD June 2007, do nothing by default	
	
	if (toolmode=='zoomin')
	{theForm.CMD.value = 'ZOOM_IN'}	
	else if (toolmode=='zoomout')
	{theForm.CMD.value = 'ZOOM_OUT'}	
	else if (toolmode=='measure')
	{theForm.CMD.value = 'MEASURE'}
	else if (toolmode=='addText')
	{theForm.CMD.value = 'ADD_TEXT'}
	if ( (toolmode=='zoomfullextent') || (toolmode=='zoomactivelayer') || (toolmode=='zoomlast') || (toolmode=='pan') )
	{theForm.CMD.value = 'RECENTER'}
	else if (toolmode=='identify')
	{theForm.CMD.value = 'QUERY_POINT'}	
	else if ( (toolmode=='selectbox') || (toolmode=='selectpoint') || (toolmode=='selectline') || (toolmode=='selectshape') )
	{theForm.CMD.value = 'SELECTION'}
	//AD June 2007, do nothing by default
	//else
	//{theForm.CMD.value = 'ZOOM_IN'}
	//

// added to solve issue were hold on mouse down during zooming, cause full extent first before zooming to new extents
theForm.redraw.value= "Y";

if (isNav) 
{theForm.submit;}
else
{theForm.submit();}
}

//*************************************************************************
//** Point click functions, used add map annotation / shape symbols
var numpts = 0;
function addShapeAnnotation() {
	var theForm = top.PostFrame.document.forms[0];
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
	var doc = window.parent.TextFrame.document;	

	var a = mouseX;
	var b = mouseY;

	isAddTextLayerOn = true;
	
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);

	prevClickMapXY[prevClickMapXY.length] = a + "|" + b;
	var tmp_bi = [-1,-1];
	if (prevClickMapXY.length >= 2)
		var tmp_bi = prevClickMapXY[prevClickMapXY.length-2].split("|");
	csy_drawPointLayer(prevClickMapXY.length,a,b,tmp_bi[0],tmp_bi[1]);
	
	if (isNewShape==true) {
		shapeStrCount++;
		var fillStyle = t.setForm.fillStyle.value;
		var fillColor = convertHexToDec2(doc.getElementById("fillColor").value);
			if (fillColor.indexOf("NaN") >= 0) {fillColor = "-1~-1~-1"};
		var outlineStyle = t.setForm.outlineStyle.value;
		var outlineSize = t.setForm.outlineSize.value;
		var outlineColor = convertHexToDec2(doc.getElementById("outlineColor").value);
			if (outlineColor.indexOf("NaN") >= 0) {outlineColor = "-1~-1~-1"};
		var transp = t.setForm.transparency.value;

		var str = fillStyle + "|" + fillColor + "|" + outlineStyle + "|" + outlineSize + "|" + outlineColor + "|" + transp;
		annotationShapeStr[shapeStrCount] = str;
		annotationShapeStr[shapeStrCount] += "|" + a + "|" + b;
		numpts = 1;
		isNewShape = false;
	}
	else
	{
		annotationShapeStr[shapeStrCount] += "|" + a + "|" + b;
		numpts++;
	}

	//enabled the complete shape button, only if more than 2 points
	if (numpts>2) {t.setForm.completeShp.disabled = false;shapeDetails[5] = false;} 
	else {t.setForm.completeShp.disabled = true;shapeDetails[5] = true;} 
	
	window.parent.TextFrame.document.location.reload();
				
	theForm.addshape.value = annotationShapeStr;
	theForm.redraw.value = "Y";	

}

//*************************************************************************
//** Point click functions, used add map annotation / line symbols
 
var numpts1 = 0;
function addLineAnnotation() {
	var theForm = top.PostFrame.document.forms[0];
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
	var doc = window.parent.TextFrame.document;

	var a = mouseX;
	var b = mouseY;
	
	isAddTextLayerOn = true;
	
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);
	
 	prevClickMapXY[prevClickMapXY.length] = a + "|" + b;
	var tmp_bi = [-1,-1];
	if (prevClickMapXY.length >= 2)
		var tmp_bi = prevClickMapXY[prevClickMapXY.length-2].split("|");
	csy_drawPointLayer(prevClickMapXY.length,a,b,tmp_bi[0],tmp_bi[1]);
		
	if (isNewLine==true) {
		lineStrCount++;
		var fillStyle = t.setForm.fillStyle.value;
		var fillColor = convertHexToDec2(doc.getElementById("fillColor").value);
			if (fillColor.indexOf("NaN") >= 0) {fillColor = "-1~-1~-1"};
		var lineSize = t.setForm.lineSize.value;

		var str = fillStyle + "|" + fillColor + "|" + lineSize;
		annotationLineStr[lineStrCount] = str;
		annotationLineStr[lineStrCount] += "|" + a + "|" + b;
		numpts1 = 1;
		isNewLine = false;
	}
	else
	{
		annotationLineStr[lineStrCount] += "|" + a + "|" + b;
		numpts1++;
	}

	//enabled the complete line button, only if at least 2 points
	if (numpts1>=2) {t.setForm.completeLine.disabled = false;lineDetails[3] = false;} 
	else {t.setForm.completeLine.disabled = true;lineDetails[3] = true;} 

	window.parent.TextFrame.document.location.reload();
			
	//do not submit yet, only set annotation variables
	theForm.addline.value = annotationLineStr;
	theForm.redraw.value = "Y";

}


//*****************************************************************************
//** Set class list in selectExisting drop down list of annotateDisplay_start.htm page
 
function setClassList(i,txt,type,color)
{
		classList[i] = txt;//label text
		classType[i] = type;//annotation type
		classColor[i] = color; //background color in annotation list
		
 		if (annotListStr.length > 0) 
			annotListStr += "|";
		annotListStr  += txt + "^" + type + "^" + color;
  		window.parent.TextFrame.document.location.reload();

}

//*****************************************************************************
//** Use to draw pin annotations on map, with no option of adding label
 
function addPinAnnotation_noText()
{
	var theForm = top.PostFrame.document.forms[0];
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
			
	var x = mapTextX;
	var y = mapTextY;
	var offset = 10; //to place pin end on mouse click
	x = PixToMapCoord(x + offset,0);
	y = PixToMapCoord(y - offset,1);

	var pushpin = "";var pinstr="";
	// set the pin color
	if (t.setForm.pushpin[0].checked)
	{ pushpin = "pushpin_red";pinSelected[0]=1;pinstr="(red pin)";}
	if (t.setForm.pushpin[1].checked)
	{ pushpin = "pushpin_green";pinSelected[1]=1;pinstr="(green pin)";}
	if (t.setForm.pushpin[2].checked)
	{ pushpin = "pushpin_orange";pinSelected[2]=1;pinstr="(orange pin)";}
	if (t.setForm.pushpin[3].checked)
	{ pushpin = "pushpin_blue";pinSelected[3]=1;pinstr="(blue pin)";}
	if (t.setForm.pushpin[4].checked)
	{ pushpin = "pushpin_purple";pinSelected[4]=1;pinstr="(purple pin)";}
			
	var color = "#000000";
	setClassList(classList.length,pinstr,t.setForm.selectAnnotationType.value,color);

	annotationPinStr[annotationPinStr.length] = x + "|" + y + "|nolabel|" + pushpin;

	theForm.addpin.value = annotationPinStr;
	theForm.redraw.value="Y";
	theForm.submit();

}
//*****************************************************************************
//** Use to draw point annotations on map, with no option of adding label
 function addPointAnnotation_noText()
{
	var theForm = top.PostFrame.document.forms[0];
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
	var doc = window.parent.TextFrame.document;

	var x = mapTextX;
	var y = mapTextY;
	x = PixToMapCoord(x,0);
	y = PixToMapCoord(y,1);
			
	var color = "#000000";
	setClassList(classList.length,"(point)",t.setForm.selectAnnotationType.value,color);

	var fillColor = convertHexToDec2(doc.getElementById("fillColor").value);
		if (fillColor.indexOf("NaN") >= 0) {fillColor = "-1~-1~-1"};
	var fillStyle = t.setForm.fillStyle.value;
	var pointSize = t.setForm.pointSize.value;
		
	annotationPointStr[annotationPointStr.length] = x + "|" + y + "|nolabel|" + fillColor + "|" + fillStyle + "|" + pointSize;

	theForm.addpoint.value = annotationPointStr;
	theForm.redraw.value="Y";
	theForm.submit();

}

//************************************************************************
//** populate TextFrame dynamic
 function csy_populateTextFrame(val) {
	//*****   POSSIBLE PARAMETER LIST	
	//***** this list can be further customized
	//layer list 		0
	//quick find		1	
	//zoom to boundary	2
	//annotation 		3
	//selection		4
	//notification list	5
	//measure		6
	//extract		7
	//quick print		8
	//custom print		9
	//save image		10
	//custom query		11
	//set units		12
	//*****   END
	switch(val)
	{
		case 0:
			csy_displayLayerList();
			break;
		case 1:
			csy_toolClick('quickFind');
			break;			
		case 2:
			csy_toolClick('zoomToBoundary');
			break;
		case 3:
			csy_toolClick('addText');	
			break;
		case 4:		
 			if (toolMode=='selectbox'||toolMode=='selectline'||toolMode=='selectpoint'||toolMode=='selectshape')
				csy_toolClick(toolMode);
			else
 				csy_toolClick('selectbox');
			break;
 		case 5:
			csy_toolClick('notificationList');
			break;			
		case 6:
			csy_toolClick('measure');	
			break;
		case 7:			
			csy_toolClick('extractData');
			break;
		case 8:
			csy_toolClick('print');
			break;
		case 9:
			csy_toolClick('customPrint');
			break;			
		//case 10.: Was moved to popup window
		//	csy_toolClick('saveimage');
		//	break;
		case 11:
			csy_toolClick('customQuery');	
			break;
		//case 12:	Was moved to popup window		
		//	csy_displayGeneralPage("setUnits.htm");
		//	break;
		case 14:			
			csy_toolClick("extractData_Full");
			break;

		//end AD July 14, 2005
		default:
			csy_displayLayerList();
			break;
	}	
}

 

//*************************************************************************
//** Function to start drawing rectangle layer: drawRectAnnot for Rectangle annotation
function startDrawRectAnnot (e)
{
  var r = getLayer("drawRectAnnot");
   
	if (isNav) 
	{
	  startrectx = e.clientX; 
	  startrecty = e.clientY;
	}	else 
	{  startrectx = event.clientX; 
	  startrecty = event.clientY;	}	
  endrectx = startrectx;
  endrecty = startrecty; 
  
  if (isNav) {
	  r.left = startrectx + 'px';
	  r.top  = startrecty + 'px';
  }
  else {
	  r.pixelLeft = startrectx;
	  r.pixelTop  = startrecty;
  }  
	
  r.visibility = 'visible'; 
  
  document.onmousemove = moveDrawRectAnnot;
  document.onmouseup = stopDrawRectAnnot;
}

//*************************************************************************
//** Function to draw rectangle layer: drawRectAnnot for Rectangle annotation,on mouse move.
 
function moveDrawRectAnnot (e)
{
    var r = getLayer("drawRectAnnot");
          
	 
	if (isNav) {var evt = e;}
	else {var evt = event;}

    //used to adjust to map zone bounds if user draw zoom rectangle outside map zone
    //endrectx = event.x;
    //endrecty = event.y;
    endrectx = evt.clientX;
    endrecty = evt.clientY;
	 if ((endrectx <= maxClickX) && (endrectx >= minClickX) && (endrecty <= maxClickY) && (endrecty >= minClickY)){
	  // don't allow draw outside the map zone

		//AD Oct 12, 2004, added for browser check
		if (isNav) {
			r.left = Math.min(startrectx, endrectx) + 'px';
			r.top  = Math.min(startrecty, endrecty) + 'px';
		}
		else
		{
			r.pixelLeft = Math.min(startrectx, endrectx);
			r.pixelTop = Math.min(startrecty, endrecty);
		}
		r.width = Math.abs(startrectx - endrectx);
		r.height = Math.abs(startrecty - endrecty);
	 }
	 else 
	 {
		if (endrectx > maxClickX) {endrectx = maxClickX;}
		else if (endrectx < minClickX) {endrectx = minClickX;}
		else if (endrecty > maxClickY) {endrecty = maxClickY;}
		else if (endrecty < minClickY) {endrecty = minClickY;}
		
		//AD Oct 12, 2004, added for browser check
		if (isNav) {
			r.left = Math.min(startrectx, endrectx) + 'px';
			r.top  = Math.min(startrecty, endrecty) + 'px';
		}
		else
		{
			r.pixelLeft = Math.min(startrectx, endrectx);
			r.pixelTop = Math.min(startrecty, endrecty);
		}
		
		r.width = Math.abs(startrectx - endrectx);
		r.height = Math.abs(startrecty - endrecty);
		stopDrawRectAnnot();
	}
}

//*************************************************************************
//** Function to stop drawing rectangle layer: drawRectAnnot for Rectangle annotation,

function stopDrawRectAnnot()
{
  var r = getLayer("drawRectAnnot"); 

  document.onmousemove = getMouse;
  r.visibility = 'hidden';
  addRectAnnotation(startrectx,startrecty,endrectx,endrecty);
  
}

//*************************************************************************
//** Use to draw rectangle annotations on map
function addRectAnnotation(x1,y1,x2,y2) {
	var theForm = top.PostFrame.document.forms[0];
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
	var doc = window.parent.TextFrame.document;

	rectStrCount++;
	
	isAddTextLayerOn = true;
	
	a1 = PixToMapCoord(x1-minClickX,0);a2 = PixToMapCoord(x2-minClickX,0);
	b1 = PixToMapCoord(y1-minClickY,1);b2 = PixToMapCoord(y2-minClickY,1);
	
	//var fillStyle = t.fillStyle.value;
	var fillStyle = t.setForm.fillStyle.value;
	var fillColor = convertHexToDec2(doc.getElementById("fillColor").value);
		if (fillColor.indexOf("NaN") >= 0) {fillColor = "-1~-1~-1"};
	//var outlineStyle = t.outlineStyle.value;
	var outlineStyle = t.setForm.outlineStyle.value;
	//var outlineSize = t.outlineSize.value;
	var outlineSize = t.setForm.outlineSize.value;
	var outlineColor = convertHexToDec2(doc.getElementById("outlineColor").value);
		if (outlineColor.indexOf("NaN") >= 0) {outlineColor = "-1~-1~-1";}
	//var transp = t.transparency.value;
	var transp = t.setForm.transparency.value;
	
	annotationRectStr[rectStrCount] = fillStyle + "|" + fillColor + "|" + outlineStyle + "|" + outlineSize + "|" + outlineColor + "|" + transp + "|" + a1 + "|" + b1  + "|" + a2 + "|" + b1 + "|" + a2 + "|" + b2  + "|" + a1 + "|" + b2 + "|end";

	//open add text pop up window, if addText box selected
	if (annoteWithText == true) {
			var iwidth=(screen.width*.35);
			var ileft= (screen.width - iwidth)/2;
			var iheight = (screen.height*.54);

			var parm = "top=50,left="+ileft+",scrollbars=yes,resizable=yes,menubar=no,width="+iwidth+",height="+iheight;
			//AD Nov 4, 2004, corrected for Netscape
			//customizeLayerWin = window.open(appDir+"addAnnotation.htm","customizeLayerWin", parm);
			customizeLayerWin = parent.TextFrame.open(appDir+"addAnnotation.htm","customizeLayerWin", parm);
			var newTimeoutFunc = function () {  customizeLayerWin.focus(); };
			setTimeout(newTimeoutFunc, 750);
		}
		else
		{
			//var color = t.outlineColor.value;
			var color = t.setForm.outlineColor.value;
			if (color.length<7 || color == "" || t.setForm.outlineStyle.value == "none") color = "#000000";
			setClassList(classList.length,"(rect)",t.setForm.selectAnnotationType.value,color);		
		}

	showRetrieveMap();

	theForm.addrect.value = annotationRectStr;
	theForm.redraw.value="Y";
	theForm.submit();
}

//*************************************************************************
//** Point click functions, used by Selection by Point
 
function clickSelectionPoint() {
	var theForm = top.PostFrame.document.forms[0];
	
	var a = mouseX;
	var b = mouseY;
	
	isSelectionLayerOn = true;
	
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);
	
	selectionPointStr[selpointCount] = a + "|" + b;
	showRetrieveMap();
	if (isAddSelection == true) {
		theForm.CMD.value = "ADDSELECTION";
		theForm.selectShpResults.value = sqryShpResults;		
		}
	else if (isDelSelection == true) {
		theForm.CMD.value = "DELSELECTION";
		theForm.selectShpResults.value = sqryShpResults;
		}
	if (useNotification == true && ActiveLayerName == PropertyLayerName) {
		theForm.bufferAttributes.value = "NOTIFICATION";
		theForm.qfield.value = PropertyPKName;
	}	
	theForm.selectLayer.value = ActiveLayerID;//AD June 16, 2005 - set selection Layer
	theForm.selectpoint.value = selectionPointStr;
	theForm.redraw.value = "Y";
	theForm.submit();
}


//*****************************************************************************
//** This common function clears all selection query on map
 
function clearSelection(submit)
{
	var theForm = top.PostFrame.document.forms[0];
	setPrevious();
	isSelectionLayerOn = false;
	isAddSelection = false;
	isDelSelection = false;

	emptyArray(selectionPointStr);
	emptyArray(selectionShapeStr);
	emptyArray(selectionLineStr);
	theForm.CMD.value = "CLRSELECTION";
	theForm.inputType.value = "Y"; //set to simulate a map click
	resetSelectFields(0);
	csy_setqryShpResults("0");	
	 
	//clear the buffer as well
	isBuffer = false;
	csy_setbufferShapeIndexes("");
	bufferTargetLayer="";
	bufferDistance="";
	theForm.bufferTargetLayer.value = "";
	theForm.bufferDistance.value = "";
	theForm.bufferShapeIndexes.value = "";	
	 
	strExportLayers = "";
	theForm.strExportLayers.value = "";	 
	theForm.hightlightShapeResults.value = "";
	theForm.highlightLayer.value = "";
	hightlightShapeResults=""; //  fix bug with persisted hightlightShapeResults on zooming
	
	 
	//clear buffer results for Notification as well
	emptyArray(PropertySelectedFeatures);
	PropertySelectedFeatures.length = 0;	
	emptyArray(qryNotificationResults);
	qryNotificationResults.length = 0;	
	//sqryShpResults = "";
	if (submit==1){	
		showRetrieveMap();

		theForm.redraw.value = "Y";
		theForm.submit();
	}
}

//*************************************************************************
//** Point click functions, for Selection by line
 
function resetSelectFields(submit)
{
 	var theForm = top.PostFrame.document.forms[0];
 	theForm.selectLayer.value=""; 
 	theForm.selectpoint.value="";
 	theForm.selectline.value="";
 	theForm.selectshape.value="";
	if (submit==1){
		theForm.redraw.value = "Y";
		theForm.submit();
	}
} 

//*************************************************************************
//** Common function to empty an array variable
 
function emptyArray(arr)
{
	while (arr.length != 0) {
		arr.splice(arr.length-1,1);
	}

	if (arr==clickMapPointX || arr==clickMapPointY) {clickCount = 0}
	if (arr==selectionPointStr) {selpointCount = 0}
	if (arr==selectionShapeStr) {selshapeCount = 0}
	if (arr==selectionLineStr) {sellineCount = 0}
}

//*************************************************************************
//** Function to start drawing rectangle layer: drawSelectBox for Selection Box
 
function startDrawSelectBox (e)
{
  var r = getLayer("drawSelectBox");

	if (isNav) 
	{//if (!e) var e = window.event;
	  startboxx = e.clientX; 
	  startboxy = e.clientY;
	}
	else 
	{
	  startboxx = event.clientX; 
	  startboxy = event.clientY;
	}
	
  r.width = 0;
  r.height = 0;   

  endboxx = startboxx;
  endboxy = startboxy; 

	
	if (isNav) {
		r.left = startboxx + 'px';
		r.top  = startboxy + 'px';
	}
	else
	{
		r.pixelLeft = startboxx;
		r.pixelTop  = startboxy;
	}
  
  r.visibility = 'visible';  
  
  document.onmousemove = moveDrawSelectBox;
  document.onmouseup = stopDrawSelectBox;

}

//*************************************************************************
//** Function to draw rectangle layer: drawSelectBox for Selection Box,
//** on mouse move.
 
function moveDrawSelectBox (e)
{
    var r = getLayer("drawSelectBox");

	
	if (isNav) {var evt = e;}
	else {var evt = event;}

    //used to adjust to map zone bounds if user draw zoom rectangle outside map zone
    endboxx = evt.clientX;
    endboxy = evt.clientY;
	 if ((endboxx <= maxClickX) && (endboxx >= minClickX) && (endboxy <= maxClickY) && (endboxy >= minClickY)){
	  // don't allow draw outside the map zone
		
 		if (isNav) {
			r.left = Math.min(startboxx, endboxx) + 'px';
			r.top  = Math.min(startboxy, endboxy) + 'px';
		}
		else
		{
			r.pixelLeft = Math.min(startboxx, endboxx);
			r.pixelTop = Math.min(startboxy, endboxy);
		}
		r.width = Math.abs(startboxx - endboxx);
		r.height = Math.abs(startboxy - endboxy);
	}
	else 
	{
		if (endboxx > maxClickX) {endboxx = maxClickX;}
		else if (endboxx < minClickX) {endboxx = minClickX;}
		else if (endboxy > maxClickY) {endboxy = maxClickY;}
		else if (endboxy < minClickY) {endboxy = minClickY;}
		
 		if (isNav) {
			r.left = Math.min(startboxx, endboxx) + 'px';
			r.top  = Math.min(startboxy, endboxy) + 'px';
		}
		else		
		{
			r.pixelLeft = Math.min(startboxx, endboxx);
			r.pixelTop = Math.min(startboxy, endboxy);
		}
		r.width = Math.abs(startboxx - endboxx);
		r.height = Math.abs(startboxy - endboxy);
		stopDrawSelectBox();
	}
}

//*************************************************************************
//** Function to stop drawing rectangle layer: drawSelectBox for Selection Box,
function stopDrawSelectBox()
{
  var r = getLayer("drawSelectBox"); 
  var theForm = top.PostFrame.document.forms[0];

  document.onmousemove = getMouse;
  r.visibility = 'hidden';
  showRetrieveMap();
	if (isAddSelection == true) {
		theForm.CMD.value = "ADDSELECTION";
		theForm.selectShpResults.value = sqryShpResults;}
	else if (isDelSelection == true) {
		theForm.CMD.value = "DELSELECTION";
		theForm.selectShpResults.value = sqryShpResults;
		}
	
 	if (useNotification == true && ActiveLayerName == PropertyLayerName) {
		theForm.bufferAttributes.value = "NOTIFICATION";
		theForm.qfield.value = PropertyPKName;
	}
	
  theForm.selectLayer.value = ActiveLayerID;//AD June 16, 2005 - set selection Layer	
  sendRectangleBox(startboxx-minClickX,startboxy-minClickY,endboxx-minClickX,endboxy-minClickY,1);
  isSelectionLayerOn = true;
  
}

//*************************************************************************
//** Send auto-rectangle information, on mouse rectangle draw
 function sendRectangleBox(x1,y1,x2,y2,submit) {
	var theForm = top.PostFrame.document.forms[0];
	
  	//subtract offsets from page left and top
  	x3 = Math.min(x1,x2); // minx LL of rectobject
  	y3 = Math.min(y1,y2); // miny LL of rectobject
  	x4 = Math.max(x1,x2); // maxx UR of rectobject
  	y4 = Math.max(y1,y2); // maxy UR of rectobject
  
	theForm.inputType.value = 'auto_rect';
	theForm.inputCoord.value = x3 + "," + y3 + ";" + x4 + "," + y4;
	
	if (submit == 1) {
		theForm.redraw.value = "Y";
		theForm.submit();
	}
}


//*************************************************************************
//** Point click functions, for Selection by shape
 function clickSelectionShape() {

	var theForm = top.PostFrame.document.forms[0];
	var a = mouseX;
	var b = mouseY;
	
	isSelectionLayerOn = true;
	
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);
	
	selectionShapeStr[selshapeCount] = a + "|" + b;
	selshapeCount++;
	//showRetrieveMap();
	theForm.CMD.value = "SELECTION";
	if (isAddSelection == true) {
		theForm.CMD.value = "ADDSELECTION";
		theForm.selectShpResults.value = sqryShpResults;}
	else if (isDelSelection == true) {
		theForm.CMD.value = "DELSELECTION";
		theForm.selectShpResults.value = sqryShpResults;
		}
 	if (useNotification == true && ActiveLayerName == PropertyLayerName) {
		theForm.bufferAttributes.value = "NOTIFICATION";
		theForm.qfield.value = PropertyPKName;
	}

	var tmp_bi = [-1,-1];
	if (selshapeCount >= 2)
		var tmp_bi = selectionShapeStr[selshapeCount-2].split("|");
	csy_drawPointLayer(selshapeCount,a,b,tmp_bi[0],tmp_bi[1]);

	theForm.selectLayer.value = ActiveLayerID;//AD June 16, 2005 - set selection Layer	
	theForm.selectshape.value = selectionShapeStr;
	theForm.redraw.value = "Y";
}


//*************************************************************************
//** Point click functions, for Selection by line
 function clickSelectionLine() {

	var theForm = top.PostFrame.document.forms[0];
	var a = mouseX;
	var b = mouseY;
	
	isSelectionLayerOn = true;
			
	a = PixToMapCoord(a,0);
	b = PixToMapCoord(b,1);
	
	selectionLineStr[sellineCount] = a + "|" + b;
	sellineCount++;
	theForm.CMD.value = "SELECTION";
	if (isAddSelection == true) {
		theForm.CMD.value = "ADDSELECTION";
		theForm.selectShpResults.value = sqryShpResults;}
	else if (isDelSelection == true) {
		theForm.CMD.value = "DELSELECTION";
		theForm.selectShpResults.value = sqryShpResults;
		}

	
	if (useNotification == true && ActiveLayerName == PropertyLayerName) {
		theForm.bufferAttributes.value = "NOTIFICATION";
		theForm.qfield.value = PropertyPKName;
	}
	

	var tmp_bi = [-1,-1];
	if (sellineCount >= 2)
		var tmp_bi = selectionLineStr[sellineCount-2].split("|");
	csy_drawPointLayer(sellineCount,a,b,tmp_bi[0],tmp_bi[1]);
	
	theForm.selectLayer.value = ActiveLayerID;//AD June 16, 2005 - set selection Layer
	theForm.selectline.value = selectionLineStr;
	theForm.redraw.value = "Y";
}

//***********************************************************************
//* 	addCustomRenderToMap function
//* 	used to customize the active layer
//* 	write interactive ValueRenderer strings in Map XML request
 //***********************************************************************
function addCustomRenderToMap(i) {
	var renderString = "";
	var j=-1;

	for (var k=0;k<CustomLayer.length;k++) {
		if (LayerName[CustomLayer[k]]==LayerName[i]) j=k;
	}
	if (j!=-1) {
		if (CustomLayerString[j]!="") {
			// add custom rendering for this request
			renderString += 'type="' + LayerType[i] + '"'
			renderString += '>\n'
			renderString +=	CustomLayerString[j] + '\n</LAYERDEF>\n';
		} else {
			renderString += '/>\n';
		}
	} else {
		renderString += '/>\n';
	}
	return renderString;
}
 //************************************************************************
// reset order to numeric
function numberorder(a,b) 
{ return a - b; }

//************************************************************************
//** Point click functions, for Selection by line
 var extractWin = null;
function csy_showExtractURL(theFile) 
{
	var flagDownload=false;  
	var Win1 = parent.TextFrame;
	var theURL = "http://" + hostName + "/tmp/Extract/"; 
 	theURL += theFile; 

	// IM TODO: need to check the file size against the maximum file size set in the AdminTool for the extract
	// the export file size comes in bytes, however strAllowedFileSize comes in Mega bytes, so we need to do appropriate
	// conversion
	var strRealFileSize = t.strExportFileSize / 1000000;    // Note: 1 megabyte is 1048576 bytes
	if(strRealFileSize > t.strAllowedFileSize)
	{
		if (confirm("You have selected to download a large amount of data. Total size of archive to download is " + strRealFileSize + "MB. Do you wish to continue? (Click 'OK' to download the file, click 'Cancel' to cancel."))
		{
			//SP Nov 2006 Win1.location.href= theURL;
			flagDownload=true ;  
		}
	}
	else
	{ 	
		//SP Nov 2006 Win1.location.href= theURL;
		flagDownload=true ;  
	}

		 
	if (flagDownload && Trim(theFile) != "")
	{    
		
		var iwidth=450;
		var iheight=600;
		var ileft= (screen.width - iwidth)/2;  

		var parm = " scrollbars=yes,menubar=no,top=20,left="+ileft+",width="+iwidth+",height="+iheight
		//Not FROM COOKIE var parm = configureOpenWindowFromCookie("Download Warning",ileft,20,iwidth,iheight, false, true) + ",toobars=no,scrollbars=yes,menubar=no,resizable=no";
		extractWin = window.open("saveIntermediate.php?file="+theURL,"download",parm);
		csy_setWindowFocus(extractWin);
      
	 } else if(extractWin!=null) 
	 {
	 if(!extractWin.closed)
 	   extractWin.close();
	 }
	
}

//************************************************************************
//** Point click functions, for Capture Coordinates
 //* changed window size.
function csy_setCaptureXY()
{        
  	var u = Math.pow(10,2);
  	var uX = parseInt(mapX * u + (5/10)) / u
  	var uY= parseInt(mapY * u + (5/10)) / u

  	mapCaptureX = uX;
  	mapCaptureY = uY;
  	
  	var theForm = top.PostFrame.document.forms[0];
  	theForm.captureXY.value = mapCaptureX + '*' + mapCaptureY;
  	theForm.zoomToPointNeedsProjection.value = 'Y';
  	theForm.tempProjectionString.value=t.mapTempProjection;	//'init=epsg:4326';
  	//theForm.reload.value == 'N';
  	theForm.submit();
  	
}
//************************************************************************
function csy_resetCaptureXY(projX, projY)
{
		parent.MapFrame.mapCaptureX = projX;
		parent.MapFrame.mapCaptureY = projY;
		
		//AD May 2007
		/*var theUrl="";
		if (navigator.appName.indexOf("Netscape")>=0)
		{
	 		theUrl = cuestaURL + "captureXY.htm";
	 	}
	 	else
	 	{
			theUrl = "captureXY.htm";
		}
	 
		//reopen capture form, on mouse click in case it was previously closed.
		if (captWin==null || captWin.closed == true)//AD July 20, 2005,check on null captWin
		{
			var parm = "top=200,left="+150+",scrollbars=no,resizable=no,menubar=no,width="+2*(screen.width/5)+",height="+4*(screen.height/11);
    	captWin = window.open(appDir+"captureXY.htm","captureXYWindow",parm);
		}
  	captWin.document.location.href= theUrl; //refresh captureXYWindow
  	captWin.focus();*/
  		csy_displayGeneralPage("captureXY.htm");
  		//
  	
}

//************************************************************************
//** Draw a point on click, and draw line with previous point for DHTML layer, based on map extents
//** Created By: Aida Dodo, October, 2004
 function csy_drawPointLayer(numpts, currX, currY, prevX, prevY)
{
	isDrawPointLayer = true;
	var x1 = MapToPixCoord(currX,0);
	var y1 = MapToPixCoord(currY,1);
	drawPoint(x1,y1,"4px","pointLayer");
	if (numpts >= 2) {
		var x0 = MapToPixCoord(prevX,0);
		var y0 = MapToPixCoord(prevY,1);
		drawDotLine(x0,y0,x1,y1,"2px","pointLayer");	
		}
}

//************************************************************************
//** Redraw pointLayer DHTML for shape and line annotations, based on new map extents,
//** used to recreate DHTML layer after it has been destroyed, like for delete or restart selection
//** selectionType is the Selection Type: in this case "Select by Shape" or "Select by Line"
 function csy_redrawPointLayer(selectionType){
	destroyElement("pointLayer");
//alert("selshapeCount"+selshapeCount+"\n"+"sellineCount"+sellineCount)
	if (selectionType == "Select by Shape" && selshapeCount>=1) {
		var numpts = selshapeCount;
		for(var i=0;i<numpts-1;i++) {
			var tmp_bi1 = selectionShapeStr[i].split("|");		
			var x1 = MapToPixCoord(tmp_bi1[0],0);
			var y1 = MapToPixCoord(tmp_bi1[1],1);
			var tmp_bi2 = selectionShapeStr[i+1].split("|");
			var x2 = MapToPixCoord(tmp_bi2[0],0);
			var y2 = MapToPixCoord(tmp_bi2[1],1);
			drawDotLine(x1,y1,x2,y2,"2px","pointLayer");
			drawPoint(x1,y1,"4px","pointLayer");		
		}
		var tmp_bi = selectionShapeStr[numpts-1].split("|");
		var x = MapToPixCoord(tmp_bi[0],0);
		var y = MapToPixCoord(tmp_bi[1],1);	
		drawPoint(x,y,"4px","pointLayer");
	}
	else if (selectionType == "Select by Line" && sellineCount>=1) {
		var numpts = sellineCount;
		for(var i=0;i<numpts-1;i++) {
			var tmp_bi1 = selectionLineStr[i].split("|");		
			var x1 = MapToPixCoord(tmp_bi1[0],0);
			var y1 = MapToPixCoord(tmp_bi1[1],1);
			var tmp_bi2 = selectionLineStr[i+1].split("|");
			var x2 = MapToPixCoord(tmp_bi2[0],0);
			var y2 = MapToPixCoord(tmp_bi2[1],1);
			drawDotLine(x1,y1,x2,y2,"2px","pointLayer");
			drawPoint(x1,y1,"4px","pointLayer");		
		}
		var tmp_bi = selectionLineStr[numpts-1].split("|");
		var x = MapToPixCoord(tmp_bi[0],0);
		var y = MapToPixCoord(tmp_bi[1],1);	
		drawPoint(x,y,"4px","pointLayer");	
	}

}

//************************************************************************
//** Function to initialize annotation details, based on annotation type
  function initAnnotDetails(type)
{
	//var t = top.TextFrame.document[0];
	var t = top.TextFrame.document;
	switch (type)
	{
		case '1': //pin
			pinSelected[0] = t.setForm.pushpin[0].checked;
			pinSelected[1] = t.setForm.pushpin[1].checked;
			pinSelected[2] = t.setForm.pushpin[2].checked;
			pinSelected[3] = t.setForm.pushpin[3].checked;
			pinSelected[4] = t.setForm.pushpin[4].checked;
			break;
		case '2': //point
			pointDetails[0] = t.setForm.fillColor.value;
			pointDetails[1] = t.setForm.fillStyle.value;
			pointDetails[2] = t.setForm.pointSize.value;
			break;
		case '3': //line
			lineDetails[0] = t.setForm.fillColor.value;
			lineDetails[1] = t.setForm.fillStyle.value;
			lineDetails[2] = t.setForm.lineSize.value;
			lineDetails[3] = t.setForm.completeLine.disabled;
			break;
		case '4': //rect
			rectDetails[0] = t.setForm.fillStyle.value;
			rectDetails[1] = t.setForm.fillColor.value;
			rectDetails[2] = t.setForm.outlineStyle.value;
			rectDetails[3] = t.setForm.outlineSize.value;
			rectDetails[4] = t.setForm.outlineColor.value;
			rectDetails[5] = t.setForm.transparency.value;			
			break;
		case '5': //shape
			shapeDetails[0] = t.setForm.fillStyle.value;
			shapeDetails[1] = t.setForm.fillColor.value;
			shapeDetails[2] = t.setForm.outlineStyle.value;
			shapeDetails[3] = t.setForm.outlineSize.value;
			shapeDetails[4] = t.setForm.outlineColor.value;
			shapeDetails[5] = t.setForm.completeShp.disabled;
			shapeDetails[6] = t.setForm.transparency.value;
			break;
		default:
			break;
	}
}

//************************************************************************
//** Function to clear the current settings
//** in preparation for loading a different project file
 function clearCurrentSettings()
{
	clearLayerList();
	
	var theForm = top.PostFrame.document.forms[0];
	//dynamic data
	useDynamicLayers = false;
	dynamicDataString = "";					
	theForm.dynamicDataString.value = "";	
	//reorder
	useLayerReorder = false;
	//customization
	useLayerCustomization = false;
	tempCustomString = "";
	theForm.cstmzString.value = "";
	CustomLayer.length = 0;
	CustomType.length = 0;
	CustomLayerString.length = 0;
	for (var k=0; k<LayerID.length; k++)
	{
		KTCustomLabelString[k] = KTDefaultLabelString[k];
		KTCustomLayerString[k] = KTDefaultLayerString[k];
		KTCustomType[k] = KTDefaultType[k];
		KTType[k] = KTTypeDef[k];
		KTCustomized[k] = 0;
	}	
}
	
//************************************************************************
//** Function to clear the javascript layers arrays
//** in preparation for loading a different project file
 function clearLayerList()
{
	LayerID.length = mapLayersNumber;
	LayerName.length = mapLayersNumber;
	LayerDataPath.length = mapLayersNumber;
	LayerDataSet.length = mapLayersNumber;
	LayerType.length = mapLayersNumber;
	LayerVisible.length = mapLayersNumber;
	LayerIsFeature.length = mapLayersNumber;
	loadedLayers.length = mapLayersNumber;
	arrVisibleLayers.length = mapLayersNumber;
	LayerLegendArray.length = mapLayersNumber;
	LayerLegendNameArray.length = mapLayersNumber;
	LayerMaxScale.length = mapLayersNumber;
	LayerMinScale.length = mapLayersNumber;
	LayerClassMaxScale.length = mapLayersNumber;
	LayerClassMinScale.length = mapLayersNumber;
	LayerClassStatus.length = mapLayersNumber;
	LayerExtent.length = mapLayersNumber;
	LayerisDynamic.length = mapLayersNumber;
	LayerFieldList.length = mapLayersNumber;
	LayerFieldAliasList.length = mapLayersNumber;

	LayerisPersist.length = mapLayersNumber; //SP Mar 2006
	LayerFieldWidthList.length = mapLayersNumber; //SP Mar 2006
	LayerFieldVisibleList.length = mapLayersNumber; //AD May 2007
	LayerOnLegend.length = mapLayersNumber; //AD May 2007
	
	//MS Oct 19, 2004
	LayerJNameList.length = mapLayersNumber;
	LayerJTabList.length = mapLayersNumber; //AD Nov 19, 2004
	LayerJConnectionList.length = mapLayersNumber;
	LayerJSourceFieldList.length = mapLayersNumber;
	LayerJFieldList.length = mapLayersNumber;
	LayerJFieldAliasList.length = mapLayersNumber;
	LayerJClauseList.length = mapLayersNumber;
	LayerJTargetFieldTypeList.length = mapLayersNumber;
	LayerJFieldVisibleList.length = mapLayersNumber; //AD June 2007

	KTType.length = mapLayersNumber;
	KTTypeDef.length = mapLayersNumber;
	KTCustomType.length = mapLayersNumber;
	KTDefaultType.length = mapLayersNumber;
	KTDefaultLayerString.length = mapLayersNumber;
	KTCustomLayerString.length = mapLayersNumber;
	KTDefaultLabelString.length = mapLayersNumber;
	KTCustomLabelString.length = mapLayersNumber;
	LayerOrderInitialPHP.length = mapLayersNumber;
}

 //************************************************************************
//** This function sets the selection layer in sqryLayerName MapFrame variable
  
function setSelectLayer(theLayer) {
	sqryLayerName = theLayer;//AD June 16, 2005, force to set selection layer, in case form is not submitted yet.
	var theForm = top.PostFrame.document.forms[0];			
	theForm.selectLayer.value = theLayer;
}
//************************************************************************
function csy_loadProjectFile(xmlDoc)
{ 
	if (xmlDoc.documentElement.nodeName == "cuesta")
	{
		var theForm = top.PostFrame.document.forms[0];
		 
		//clear the current settings first
		clearCurrentSettings();
		//   client wants to clear any selection/buffer before drawing project
		clearSelection(1);
		nodes = xmlDoc.documentElement.childNodes;
		 
		minx=0;
		miny=0;
		maxx=0;
		maxy=0;
		flag=1;
		 
		if (nodes.length > 0)
		{
			showRetrieveMap();
			theForm.cstmzString.value = "";
			for (i=0; i<nodes.length; i++)
			{
				if (nodes.item(i).nodeName == "projString")
				{ 
					var theProj = nodes.item(i).firstChild.nodeValue;
					theForm.projectionString.value = theProj;
					t.mapProjection = theProj;
				}
				if (nodes.item(i).nodeName == "projName")
				{ 
					if (nodes.item(i).firstChild != null)
					{
							var projName = nodes.item(i).firstChild.nodeValue;
							theForm.projectionName.value = projName;
							t.mapProjectionName = projName;
					}
				}
				if (nodes.item(i).nodeName == "mapunit")
				{
					var tmpMU=nodes.item(i).firstChild.nodeValue;
				 	theForm.mapunit.value = tmpMU;
				 	t.MapUnits=tmpMU.toUpperCase();
				 }

				if (nodes.item(i).nodeName == "layers")
				{	theForm.layers.value = nodes.item(i).firstChild.nodeValue;						
				}

				if (nodes.item(i).nodeName == "lyLoaded")
				{	theForm.lyLoaded.value = nodes.item(i).firstChild.nodeValue; 					
				}
				
				if (nodes.item(i).nodeName == "dynamicDataString")
				{
					useDynamicLayers = true;
					dynamicDataString = nodes.item(i).firstChild.nodeValue;
					dynamicDataString = dynamicDataString.replace(/\$/g,'&');
					theForm.dynamicDataString.value = dynamicDataString;
					csy_populateDynamicArrays(dynamicDataString);
				}
				if (nodes.item(i).nodeName == "lyOrder")
				{
					useLayerReorder = true;
					theForm.lyOrder.value = nodes.item(i).firstChild.nodeValue;
				}
				if (nodes.item(i).nodeName == "lyCustomize")
				{
					useLayerCustomization = true;
					var cststr = nodes.item(i).firstChild.nodeValue;

					var tmpArr = cststr.split("*");
					var arrL = tmpArr[0].split("^");
					var arrT = tmpArr[1].split(",");

					tempCustomString = tmpArr[0];
					theForm.cstmzString.value = tmpArr[0];
					CustomLayer.length = 0;
					CustomType.length = 0;
					CustomLayerString.length = 0;
					for (var z=0; z<arrL.length; z++)
					{
						var arrC = arrL[z].split(",");
						CustomLayer[z] = arrC[0];
						CustomType[z] = arrC[1];
						var strCustom = "";
						for (var j=2; j<arrC.length-1; j++)
							strCustom += arrC[j] + ",";
						if (strCustom.length>0)
							strCustom = strCustom.substr(0,strCustom.length-1);
						
						//CustomLayerString[z] = strCustom + arrC[arrC.length-1];
						CustomLayerString[z] = strCustom + "," + arrC[arrC.length-1];
						
						for (var k=0; k<LayerID.length; k++)
							if (arrC[0] == LayerID[k])
							{
								KTType[k] = arrT[z];
								KTCustomType[k]=arrC[1];
								KTCustomLayerString[k] = strCustom;
								KTCustomLabelString[k] = arrC[arrC.length-1];
								k = LayerID.length;
							}

					}
				}
				//load the active layer if set so
				if (loadActiveLayer)
				{ 
					if (nodes.item(i).nodeName == "activeLayer")
					{ setActiveLayer(nodes.item(i).firstChild.nodeValue);}
				}
				
				if (nodes.item(i).nodeName == "minx")
				{  
					  theForm.minx.value = nodes.item(i).firstChild.nodeValue; 
					minx = theForm.minx.value; //SP Nov 2006 
				}
				
				if (nodes.item(i).nodeName == "miny")
				{   theForm.miny.value = nodes.item(i).firstChild.nodeValue;
				miny = theForm.miny.value;
				}
				if (nodes.item(i).nodeName == "maxx")
				{	theForm.maxx.value = nodes.item(i).firstChild.nodeValue; 
				maxx = theForm.maxx.value;
				}
				if (nodes.item(i).nodeName == "maxy")
				{	theForm.maxy.value = nodes.item(i).firstChild.nodeValue; 
				maxy = theForm.maxy.value;
				}
				
				
				if (nodes.item(i).nodeName == "addtext")
				{
					annotationStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addtext.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationStr[z] = tmp_arr[z];
							}
						}
					}
				}
				if (nodes.item(i).nodeName == "addpin")
				{
					annotationPinStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addpin.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationPinStr[z] = tmp_arr[z];
							}
						}
					}
				}
				if (nodes.item(i).nodeName == "addshape")
				{
					annotationShapeStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addshape.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationShapeStr[z] = tmp_arr[z];
							}
							shapeStrCount = tmp_arr.length-1;
						}
						
					}	
				}
				if (nodes.item(i).nodeName == "addpoint")
				{
					annotationPointStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addpoint.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationPointStr[z] = tmp_arr[z];
							}
						}
					}
				}
				if (nodes.item(i).nodeName == "addline")
				{
					annotationLineStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addline.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationLineStr[z] = tmp_arr[z];
							}
							lineStrCount = tmp_arr.length-1;
						}
					}
				}
				if (nodes.item(i).nodeName == "addrect")
				{
					annotationRectStr.length = 0;
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.addrect.value = tmp;
						var tmp_arr = tmp.split(",");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0; z<tmp_arr.length; z++)
							{
								annotationRectStr[z] = tmp_arr[z];
							}
							rectStrCount = tmp_arr.length-1;
						}
					}
				}
				 
				if (nodes.item(i).nodeName == "annotList")
				{
					 
					//initialize annotation list variables
					classList.length = 0;
					classType.length = 0;
					classColor.length = 0;
					
					 
					if (nodes.item(i).childNodes.length >= 1) {
						var tmp = nodes.item(i).firstChild.nodeValue;
						theForm.annotList.value = tmp;
						var tmp_arr = tmp.split("|");
						if (Trim(tmp_arr).length > 0) {
							for (var z=0;z<tmp_arr.length;z++)
							{
								var tmp_tri = tmp_arr[z].split("^");
								classList[z] = tmp_tri[0];
								classType[z] = tmp_tri[1];
								classColor[z] = tmp_tri[2];
							}
						}
					}
				}

			}
			theForm.redraw.value="Y";
		 	theForm.CMD.value="BMK";
			 
			if(flag==1 && minx>0 && miny>0 && maxx>0 && maxy>0)
			{
				flag=0;
				var pixCenterX = -1;
				var pixCenterY = -1;
				pixCenterX = 1*minx + Math.abs((maxx-minx)/2);
				pixCenterY = 1 * miny + Math.abs((maxy-miny)/2);

				pixCenterX = t.MapToPixCoord(pixCenterX,0);
				pixCenterY = t.MapToPixCoord(pixCenterY,1);
				theForm.pandirection.value = pixCenterX + '*' + pixCenterY;

			}
			 
			// need next two lines for projection to persist and for proj name to appear:
			parent.ModeFrame.document.location= "ModeFrame.htm";
			theForm.mapScale.value = t.mapScaleOld;
			theForm.submit();
			
		}  //nodes>0
	} else {
	   alert("The selected file is not well formatted.\n      Please select another file!");
	}
}
//************************************************************************
//** This function sets the jsp CONNECTION parameter for find.jsp
 
function getJSPConnString(mode,param) 
{//mode="FIND" or "STOREDQUERY" or "SHOWNOTIFYLIST"
	var str="";
	var connArr=getLayerConnInfo(mode,param);
	if (connArr[2]!="")
		//str+="&CONNECTION="+connArr[2];
		str="&CONNECTION="+connArr[2];//AD June 10, 2005
	return str;
}
 
//************************************************************************
//** This function get the layer connection info for find.jsp, storedQuery.jsp and
//** ShowNotifyList.jsp
 
function getLayerConnInfo(mode,param)
{//mode="FIND" or "STOREDQUERY" or "SHOWNOTIFYLIST"
	var resArray = new Array();
	var lyrName = "";
	var lyrConnection = "";
	var lyrConnectionStr = "";
	
	switch (mode) {
	case "FIND":
		//take the id of the called 
		var callerID = -1;
		for (var i = 0; i<qfcallerArray.length; i++)
		{ if (qfcallerArray[i] == param)
		       {
				callerID = i;	
				i = qfcallerArray.length;
		       }		
		}

		if (callerID!=-1) {
			lyrName = qflayerArray[callerID];
		}
	break;
	default://nothing
		lyrName = param;
	break;
	}
	
	if (lyrName.length>0) {
		var idx=-1;
		for (var i = 0; i<LayerID.length; i++)
		{ if (LayerID[i] == lyrName)
		       {
				idx = i;	
				i = LayerID.length;
		       }		
		}
		if (idx!=-1) {
			lyrConnection = LayerConnectionName[idx];
			
			var connType = getXMLValue("config/connections.xml","type", lyrConnection);
			var connUser = getXMLValue("config/connections.xml","user", lyrConnection);
			var connPassword = getXMLValue("config/connections.xml","password", lyrConnection);
			var connDriver = getXMLValue("config/connections.xml","driver", lyrConnection);
			lyrConnectionStr = connType + "~" + connUser + "~" + connPassword + "~" + connDriver;	
		}
	}
	
	resArray[0] = lyrName;//layer name
	resArray[1] = lyrConnection;//connection name
	resArray[2] = lyrConnectionStr;//connection string
	return resArray;
}

//************************************************************************
//** This function get the layer connection table name from the LayerConnectionTable array
  
function getLayerTableName(lName)
{
	var idx=-1;
	var res="";
	for(i = 0;i<t.layerCount;i++)
	{
		if (t.LayerID[i]==lName)
		{
			idx=i;
			res=t.LayerConnectionTable[idx];
			i=t.layerCount;
		}
	}
	return res;
}


//************************************************************************
//** This function checks for annotation selection before making a move action
 function checkAnnotationToMove()
{
	var theForm = top.TextFrame.document;

	var aIndex=-1;var aType="";

	var sel="";
	var str="";
	var annottype="";
	var resArray = new Array();
	resArray[0]=false;
	resArray[1]="";
	resArray[2]="";
	var hasSelect = false;var numSelected=0;
	var txtIndex = 0; var pinIndex = 0; var ptIndex = 0; var lnIndex = 0; var rectIndex = 0; var shpIndex = 0;

	if (t.classList.length > 0)
	{
		for (var i=0;i<t.classList.length;i++)
		{
			sel = theForm.setForm.selectExisting.options[i].selected;
			str = theForm.setForm.selectExisting.options[i].value;
			pos1=str.indexOf("(");
			pos2=str.indexOf(")");
			annottype = str.substr(pos1+1,pos2-1);

			if (sel==true)	{
				hasSelect = true;numSelected++;
				if (numSelected==1) 
				{//only consider first selection
					aType=annottype;
					if (aType == 'text') {aIndex=txtIndex;}
					if (aType == 'pin') {aIndex=pinIndex;}
					if (aType == 'point') {aIndex=ptIndex;}
					if (aType == 'line') {aIndex=lnIndex;}
					if (aType == 'rect') {aIndex=rectIndex;}
					if (aType == 'shape') {aIndex=shpIndex;}
				}
			}
			else
			{
				if (annottype == 'text') {txtIndex++;}
				if (annottype == 'pin') {pinIndex++;}
				if (annottype == 'point') {ptIndex++;}
				if (annottype == 'line') {lnIndex++;}
				if (annottype == 'rect') {rectIndex++;}
				if (annottype == 'shape') {shpIndex++;}
			}
		}//end for

		if (!hasSelect || numSelected==0) {
			alert("Please select the annotation you want to move from the annotation list first!");
			return resArray;
		} else if (numSelected>1) {
			alert("Only one annotation can be selected to be moved at a time!");
			return resArray;
		} else {
			t.annotationAction = "MOVE";
			resArray[0]=true;
			resArray[1]=aType;
			resArray[2]=aIndex;
			return resArray;
		}
	}
	else
	{
		alert("There is no existing annotation to move.");return resArray;
	}
}
//************************************************************************
//** This function moves an annotation object from the origin and last point clicked on map
 
function moveAnnotation(diffX,diffY,annotType,annotIndex) 
{
	var theForm = top.PostFrame.document.forms[0];

	var selAnnotStrOrig = "";
	var selAnnotStrFinal = "";
	var tmpArr = new Array();
	var xValue=-1;
	var yValue=-1;

	if (annotType=="text" || annotType=="pin" || annotType=="point" )
	{
		if (annotType=="text")
			selAnnotStrOrig = annotationStr[annotIndex];
		else if (annotType=="pin")
			selAnnotStrOrig = annotationPinStr[annotIndex];
		else if (annotType=="point")
			selAnnotStrOrig = annotationPointStr[annotIndex];
			
		tmpArr = selAnnotStrOrig.split("|");
		xValue=parseFloat(tmpArr[0])+diffX;
		yValue=parseFloat(tmpArr[1])+diffY;
		selAnnotStrFinal = xValue+"|"+yValue+"|";
		for (var k=2;k<tmpArr.length;k++)
		{
			selAnnotStrFinal+=tmpArr[k]+"|";
		}
		selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);

		if (annotType=="text")
			annotationStr[annotIndex] = selAnnotStrFinal;
		else if (annotType=="pin")
			annotationPinStr[annotIndex] = selAnnotStrFinal;
		else if (annotType=="point")
			annotationPointStr[annotIndex] = selAnnotStrFinal;
	}
	else if (annotType=="line")
	{
		selAnnotStrOrig =  annotationLineStr[annotIndex];
		tmpArr = selAnnotStrOrig.split("|");
		var endPos=-1;
		for (var k=0;k<3;k++)
		{//line style
			selAnnotStrFinal+=tmpArr[k]+"|";
		}
		for (var k=3;k<tmpArr.length;k=k+2)
		{//for each point
			if (tmpArr[k]=="end") 
			{
				endPos=k;
				k=tmpArr.length;
			}
			else
			{
				xValue=parseFloat(tmpArr[k])+diffX;
				yValue=parseFloat(tmpArr[k+1])+diffY;
				selAnnotStrFinal += xValue+"|"+yValue+"|";
			}
		}
		if (endPos!=-1)
			for (var k=endPos;k<tmpArr.length;k++)
			{//reset of label style
				selAnnotStrFinal+=tmpArr[k]+"|";
			}
		
		selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
		annotationLineStr[annotIndex] = selAnnotStrFinal;
	}
	else if (annotType=="rect" || annotType=="shape")
	{
		if (annotType=="rect")
			selAnnotStrOrig = annotationRectStr[annotIndex];
		else if (annotType=="shape")
			selAnnotStrOrig = annotationShapeStr[annotIndex];

		tmpArr = selAnnotStrOrig.split("|");
		var endPos=-1;
		for (var k=0;k<6;k++)
		{//poly style
			selAnnotStrFinal+=tmpArr[k]+"|";
		}
		for (var k=6;k<tmpArr.length;k=k+2)
		{//for each point
			if (tmpArr[k]=="end") 
			{
				endPos=k;
				k=tmpArr.length;
			}
			else
			{
				xValue=parseFloat(tmpArr[k])+diffX;
				yValue=parseFloat(tmpArr[k+1])+diffY;
				selAnnotStrFinal += xValue+"|"+yValue+"|";
			}
		}
		if (endPos!=-1)
			for (var k=endPos;k<tmpArr.length;k++)
			{//reset of label style
				selAnnotStrFinal+=tmpArr[k]+"|";
			}
		
		selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
		if (annotType=="rect")
			annotationRectStr[annotIndex] = selAnnotStrFinal;
		else if (annotType=="shape")
			annotationShapeStr[annotIndex] = selAnnotStrFinal;
	}

	theForm.addtext.value=annotationStr;
	theForm.addpin.value=annotationPinStr;
	theForm.addpoint.value=annotationPointStr;
	theForm.addline.value=annotationLineStr;
	theForm.addrect.value=annotationRectStr;
	theForm.addshape.value=annotationShapeStr;

	//force display dynamic layers
	redrawDynLayers();

	theForm.redraw.value="Y";
	theForm.submit();
}

 
 //******************************************************************
  //quick find tool with spatial constaint
  //******************************************************************
  function bufferQuickFind(Units, theField, theClause, Distance) {
  	
  	
 	//get center of screen
 	var theForm = top.PostFrame.document.forms[0];
 	var theTop = theForm.maxy.value * 1;
 	var theBottom = theForm.miny.value * 1;
 	var buffY = (theTop + theBottom)/2;
 
 	var theRight = theForm.maxx.value * 1;
 	var theLeft = theForm.minx.value * 1;
 	var buffX = (theLeft + theRight)/2;
 	
 	var envMaxY="";
 	var envMaxX="";
 	var envMinY="";
     	var envMinX="";
 	
 	selectionPointStr[selpointCount] = buffX + "|" + buffY;
 	showRetrieveMap();
 	theForm.CMD.value = 'QUERY_QUICKFINDSPATIAL';
 	theForm.qvalue.value = qfQueryFilter;
 	theForm.setunit.value = Units;
 	//theForm.selectLayer.value = ActiveLayerID;
 	theForm.selectpoint.value = selectionPointStr;
 	theForm.bufferDistance.value = Distance;
 	theForm.redraw.value = "Y";
 	theForm.submit();
 	
 	
 }
 //************************************************************************
 //** This function change the values of an annotation coordinates from one projection string to another
 
 function ReprojectAnnotation(projXStr,projYStr,annotType) 
 {
 
 	var theForm = top.PostFrame.document.forms[0];
 	projXStr=""+projXStr;
 	projYStr=""+projYStr;
 	
 	var selAnnotStrOrig = "";
 	var selAnnotStrFinal = "";
 	var tmpArr = new Array();
 	var xValue=-1;
 	var yValue=-1;
 
 	var projX = new Array();
 	var projY = new Array();
 	var projX1 = new Array();
 	var projY1 = new Array();
 
 	if(projXStr.indexOf("~")==-1 && projXStr.indexOf("~")==-1)
 	{
 		(projXStr.indexOf("|")!=-1) ? projX= projXStr.split("|") : projX[0]=projXStr;
 		(projYStr.indexOf("|")!=-1) ? projY = projYStr.split("|") : projY[0]=projYStr;
 	}
 	if (annotType=="text")
 	{		
 		for(var i=0 ; i<annotationStr.length;i++)	
 		{
 			selAnnotStrOrig = annotationStr[i];
 			tmpArr = selAnnotStrOrig.split("|");
 			xValue=projX[i];
 			yValue=projY[i];
 			selAnnotStrFinal = xValue+"|"+yValue+"|";
 			for (var k=2;k<tmpArr.length;k++)
 			{
 				selAnnotStrFinal+=tmpArr[k]+"|";
 			}
 			selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
 			annotationStr[i] = selAnnotStrFinal;
 		
 		}
 
 	}
 	else if( annotType=="pin")
 	{
 		for(var i=0 ; i<annotationPinStr.length;i++)	
 		{
 			selAnnotStrOrig = annotationPinStr[i];			
 			tmpArr = selAnnotStrOrig.split("|");
 			xValue=projX[i];
 			yValue=projY[i];
 			selAnnotStrFinal = xValue+"|"+yValue+"|";
 			for (var k=2;k<tmpArr.length;k++)
 			{
 				selAnnotStrFinal+=tmpArr[k]+"|";
 			}
 			selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);		
 			annotationPinStr[i] = selAnnotStrFinal;
 		}
 	
 	}
 	else if( annotType=="point")
 	{ //projX,projY and annotationPointStr should have the same length
 	     
 		
 		for(var i=0 ; i<annotationPointStr.length;i++)	
 		{
 			selAnnotStrOrig = annotationPointStr[i];			
 			tmpArr = selAnnotStrOrig.split("|");
 			xValue=projX[i];
 			yValue=projY[i];
 			selAnnotStrFinal = xValue+"|"+yValue+"|";
 			for (var k=2;k<tmpArr.length;k++)
 			{
 				selAnnotStrFinal+=tmpArr[k]+"|";
 			}
 			selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);		
 			annotationPointStr[i] = selAnnotStrFinal;
 		}
 
 	}
 	else if (annotType=="line")
 	{
 	     for(var i=0 ; i<annotationLineStr.length;i++)	
 		{
 			selAnnotStrOrig =  annotationLineStr[i];
 			tmpArr = selAnnotStrOrig.split("|");
 			var endPos=-1;
 			for (var k=0;k<3;k++)
 			{//line style
 				selAnnotStrFinal+=tmpArr[k]+"|";
 			}
 			var idx=0;
 			for (var k=3;k<tmpArr.length;k=k+2)
 			{//for each point
 				if (tmpArr[k]=="end") 
 				{
 					endPos=k;
 					k=tmpArr.length;
 				}
 				else
 				{
 					xValue=projX[idx];
 					yValue=projY[idx];
 					selAnnotStrFinal += xValue+"|"+yValue+"|";
 				}
 				idx++; 
 			}
 
 			if (endPos!=-1)
 				for (var k=endPos;k<tmpArr.length;k++)
 				{//reset of label style
 					selAnnotStrFinal+=tmpArr[k]+"|";
 				}
 
 			selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
 			annotationLineStr[i] = selAnnotStrFinal;
 		}
 	}
 	else if (annotType=="rect")
 	{
 		if(projXStr.indexOf("~")==-1 && projYStr.indexOf("~")==-1)
 		{
 			(projXStr.indexOf("|")!=-1) ? projX= projXStr.split("|") : projX[0]=projXStr;
 			(projYStr.indexOf("|")!=-1) ? projY = projYStr.split("|") : projY[0]=projYStr;
 		}
 		else
 		{
 			(projXStr.indexOf("~")!=-1) ? projX1= projXStr.split("~") : projX1[0]=projXStr;
 			(projYStr.indexOf("~")!=-1) ? projY1= projYStr.split("~") : projY1[0]=projYStr;
 
 		}
 	     for(var i=0 ; i<annotationRectStr.length;i++)	
 	    {
 		if(projXStr.indexOf("~")!=-1 || projYStr.indexOf("~")!=-1)
 		{
 		(projX1[i].indexOf("|")!=-1) ? projX= projX1[i].split("|") : projX[0]=projX1[i];
 		(projY1[i].indexOf("|")!=-1) ? projY= projY1[i].split("|") : projY[0]=projY1[i];
 		}
 		selAnnotStrOrig = annotationRectStr[i];
 		selAnnotStrFinal ="";	
 		tmpArr = selAnnotStrOrig.split("|");
 		var endPos=-1;
 		for (var k=0;k<6;k++)
 		{//poly style
 			selAnnotStrFinal+=tmpArr[k]+"|";
 		}
 		var idx=0;
 		for (var k=6;k<tmpArr.length;k=k+2)
 		{//for each point
 			if (tmpArr[k]=="end") 
 			{
 				endPos=k;
 				k=tmpArr.length;
 			}
 			else
 			{
 				xValue=projX[idx];
 				yValue=projY[idx];
 				selAnnotStrFinal += xValue+"|"+yValue+"|";
 			}
 			idx++; 
 		}
 		
 		if (endPos!=-1)
 		for (var k=endPos;k<tmpArr.length;k++)
 		{//reset of label style
 			selAnnotStrFinal+=tmpArr[k]+"|";
 		}
 		
 		selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
 		
 		annotationRectStr[i] = selAnnotStrFinal;
 		}
 		
 	}
 	else if (annotType=="shape")
 	{
 	
 		if(projXStr.indexOf("~")==-1 && projYStr.indexOf("~")==-1)
 		{
 			(projXStr.indexOf("|")!=-1) ? projX= projXStr.split("|") : projX[0]=projXStr;
 			(projYStr.indexOf("|")!=-1) ? projY = projYStr.split("|") : projY[0]=projYStr;
 		}
 		else
 		{
 			(projXStr.indexOf("~")!=-1) ? projX1= projXStr.split("~") : projX1[0]=projXStr;
 			(projYStr.indexOf("~")!=-1) ? projY1= projYStr.split("~") : projY1[0]=projYStr;
 
 		}
 	
 		for(var i=0 ; i<annotationShapeStr.length;i++)	
 		{	
 			if(projXStr.indexOf("~")!=-1 || projYStr.indexOf("~")!=-1)
 			{
 			(projX1[i].indexOf("|")!=-1) ? projX= projX1[i].split("|") : projX[0]=projX1[i];
 			(projY1[i].indexOf("|")!=-1) ? projY= projY1[i].split("|") : projY[0]=projY1[i];
 			}
 			selAnnotStrOrig = annotationShapeStr[i];
 			selAnnotStrFinal ="";	
 			tmpArr = selAnnotStrOrig.split("|");
 			
 			var endPos=-1;
 			for (var k=0;k<6;k++)
 			{//poly style
 				selAnnotStrFinal+=tmpArr[k]+"|";
 			}
 			var idx=0;
 			for (var k=6;k<tmpArr.length;k=k+2)
 			{//for each point
 				if (tmpArr[k]=="end") 
 				{
 					endPos=k;
 					k=tmpArr.length;
 				}
 				else
 				{
 					xValue=projX[idx];
 					yValue=projY[idx];
 					selAnnotStrFinal += xValue+"|"+yValue+"|";
 				}
 				idx++;
 			}
 			
 			if (endPos!=-1)
 			{ 
 				
 				for (var k=endPos;k<tmpArr.length;k++)
 				{//reset of label style
 					selAnnotStrFinal+=tmpArr[k]+"|";
 				}
 			}
 			selAnnotStrFinal = selAnnotStrFinal.substring(0,selAnnotStrFinal.length-1);
 			annotationShapeStr[i] = selAnnotStrFinal;
 			
 		}
 	}
 
 
 
}
/****************************************************************************
** This function returns the field type,based on width type
** used in Custom Query. Returns 'N' for number, 'F' for float or 'C' for string.
*/
function csy_isFloat(layerIndex, fieldName) {
var returnVal = false;

var tempVal = LayerFieldWidthList[layerIndex].split("~");
	if (tempVal.length > 0) {
		for (var i=0;i<tempVal.length;i++) 	{			
			var tempPair = tempVal[i].split(":");			
			if (Trim(tempPair[0].toUpperCase()) == fieldName.toUpperCase()) {
				if(tempPair[1].indexOf(",")!=-1)returnVal=true;
				break;
			}
		}
	}//end if
	return returnVal;
}


//****************************************************************************
//This function is used to extract the id for the features in a selection layer.
//Values are sent to add to cart. 
 
function addToCartReferences(strValues,fieldName)
{
	
	var layerFields="";
	var fields="";
	var index=0;
	//SP Dec 2006
	var type_index=0;
	var ids_type="";
	//SP Dec 2006
	var ids = "";
			
	if ( strValues.substring(0,3) == "-1|")
	{ 	alert("No fields defined for this layer!"); return;}
	if (strValues.length > 1)
	{
		var arrFlds = fieldName.split("|");
		 
		var type_Field=arrFlds[3];
		var typeFld ="";
		 

		var sourceLayer=arrFlds[0];
		var curLayer=arrFlds[1];
		var searchFld = arrFlds[2];
		var curFld ="";
		
		//get real field name in persistent layer
		var srcIndex=-1;
		var curIndex=-1;
		
		for(ct = 0;ct<layerCount;ct++)
		{	
			if ( sourceLayer == LayerID[ct])
			{
				srcIndex =ct;
			}
			else
			{
				if ( curLayer == LayerID[ct])
				curIndex = ct;
			}
		}
			
		var srcFields = LayerFieldList[srcIndex].split(",");
		var curFields = LayerFieldList[curIndex].split(",");
		
		for (var j=0; j<=srcFields.length; j++)
		{
			if (srcFields[j] == searchFld)
			{
				curFld = curFields[j];			
			}
		}
		

		var arrTemp = strValues.split("|");
		if (arrTemp[0].length>0)
			layerFields = arrTemp[0].split("^");	
		
		for (var i=0; i<=layerFields.length; i++)
		{
			if (layerFields[i] == curFld)
				index = i;
		}
 
		for (var j=0; j<=srcFields.length; j++)
		{
			if (srcFields[j] == type_Field)
			{
				typeFld = curFields[j];			
			}
		}
		for (var i=0; i<=layerFields.length; i++)
		{
			if (layerFields[i] == typeFld)
			{	type_index = i;
				break;
			}
		}
 
		
	}
	

	if(arrTemp[1].length>0)
	{
		var arrValues = arrTemp[1].split("*");
		for (var k=0;k<arrValues.length;k++)
		{
			var arrIds = arrValues[k].split("^");
			if (ids.length >0) ids+=",";
			ids+=arrIds[index];
			//SP DEc 2006
			if (ids_type.length >0) ids_type+=",";
			ids_type+=arrIds[type_index];
			//SP Dec 2006
		}
	}
	
	var chkFeatures = "";
	
	//check if each row is checked
	var refNBR= ids.split(",")
	var refType= ids_type.split(",");
	for (var i=0; i<refNBR.length; i++)
	{	
		if(chkFeatures != "") chkFeatures += " OR ";
		chkFeatures += "("+searchFld+"='"+refNBR[i]+"' and "+type_Field+"='"+refType[i]+"')"; 
	}
	 ids = "";
	if(chkFeatures.length>0)
	{	
		ids = GetIDSForList(chkFeatures) ;
	}
	
	//SP Dec 2006

	callGatewayAddtoCart(ids);
}
//****************************************************************************

 //URL format for gateway should be somethig like /gateway/gateway.php?action=cart_add_normin&c1=XXX?c2=XXX&c3=SSSS&c4=WERWER?....
function callGatewayAddtoCart(referenceIds)
{
	var strURL =gatewayURL +"/gateway.php?action=cart_add_normin&";
	var arrValues = referenceIds.split(",");
	for (var k=0;k<arrValues.length;k++)
	{
		if (k==0) strURL+="C"+k+"="+arrValues[k];
		else
		   strURL+="&"+"C"+k+"="+arrValues[k];
	}
	
	var parm = "toobars=no,width=800,height=680,scrollbars=yes,resizable=yes,";
	cartWin = window.open(Trim(strURL),"addToCartWin", parm);
	
}
//****************************************************************************

 function GetIDSForList(strWhereSQL)
	{
		var strReturn="";
    var oXMLHTTP = null;
    if(window.ActiveXObject) oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
    if(window.XMLHttpRequest) oXMLHTTP = new XMLHttpRequest();
		var sURL =  t.cuestaJspURL+"getGatewayIds.jsp" ;

		oXMLHTTP.open( "POST", sURL, false );
		oXMLHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		oXMLHTTP.send("sqlWhereScript="+strWhereSQL);
		strReturn = oXMLHTTP.responseText;
		strReturn=t.Trim(strReturn)
 		
		oXMLHTTP = null;
		arrReturn= new Array();
		if( strReturn.substring(0,5).toUpperCase()=="ERROR") strReturn="";	
		return strReturn
	}
//****************************************************************************

 function addRasterImage(path)
{
	var theForm = top.PostFrame.document.forms[0];
	theForm.CMD.value="ADDRASTER";
	theForm.rasterLayerPath.value = path;
	var pathToSend = cuestaReplace("\\", "\\\\",theForm.rasterLayerPath.value);

	theForm.submit();
}

//****************************************************************************

function cuestaReplace(original, from, to)
{

	var cc = -1;
	cc = original.indexOf(from);
	if (cc == -1)
		return original;
	var inStr = "";
	if (cc >= 0)
	{
		inStr = original.substring(0,cc) + to + original.substring(cc+from.length,original.length);
		inStr = cuestaReplace(inStr, from, to);
	}

	return inStr;
}

//****************************************************************************

//get real field name in persistent layer
function getRealFieldName(sourceLayer, curLayer, searchFld)
{
   var curFld="";
   

	var srcIndex=-1;
	var curIndex=-1;

	for(ct = 0;ct<LayerID.length;ct++) //use LayerID.length instead layerCount
	{	
		if ( sourceLayer == LayerID[ct])
		{
			srcIndex =ct;
		}
		else
		{
			var xx="'"+Trim(LayerID[ct])+"'";
			var zz="'"+Trim(curLayer)+"'"; 
			if (zz==xx) //in one scenario it did not work with direct comparison
			{			
			curIndex = ct;			
			}				
		}
	}

	var srcFields = LayerFieldList[srcIndex].split(",");
	var curFields = LayerFieldList[curIndex].split(",");

	for (var j=0; j<=srcFields.length; j++)
	{
		if (srcFields[j] == searchFld)
		{
			curFld = curFields[j];			
		}
	}
    return curFld;		
}
//****************************************************************************
// to solve refreshing problem. Over write previous extents only when extent changes, not after selection etc.
function setPrevious()
{
	var theForm = top.PostFrame.document.forms[0];

	var aPrevMinX = theForm.prevMinX.value.split(",");
	var aPrevMinY = theForm.prevMinY.value.split(",");
	var aPrevMaxX = theForm.prevMaxX.value.split(",");
	var aPrevMaxY = theForm.prevMaxY.value.split(",");
  
	if(theForm.minx.value != aPrevMinX[aPrevMinX.length-1] && theForm.miny.value != aPrevMinY[aPrevMinY.length-1]
     && theForm.maxx.value != aPrevMaxX[aPrevMaxX.length-1] && theForm.maxy.value != aPrevMaxY[aPrevMaxY.length-1]){
	aPrevMinX.push(theForm.minx.value);
	aPrevMinY.push(theForm.miny.value);
	aPrevMaxX.push(theForm.maxx.value);
	aPrevMaxY.push(theForm.maxy.value);

	theForm.prevMinX.value = aPrevMinX.join(",");
	theForm.prevMinY.value = aPrevMinY.join(",");
	theForm.prevMaxX.value = aPrevMaxX.join(",");
	theForm.prevMaxY.value = aPrevMaxY.join(",");
	}
}
//****************************************************************************
// returns array[prevMinX, prevMinY, prevMaxX, prevMaxY]
function getPrevious(){
  var theForm = top.PostFrame.document.forms[0];
  var retArray = new Array(4);
  
  var aPrevMinX = theForm.prevMinX.value.split(",");
  var aPrevMinY = theForm.prevMinY.value.split(",");
  var aPrevMaxX = theForm.prevMaxX.value.split(",");
  var aPrevMaxY = theForm.prevMaxY.value.split(",");
  
  retArray[0] = aPrevMinX.pop();
  retArray[1] = aPrevMinY.pop();
  retArray[2] = aPrevMaxX.pop();
  retArray[3] = aPrevMaxY.pop();

  if(aPrevMinX.length > 0){  // Keep initial extent to avoid being empty
    theForm.prevMinX.value = aPrevMinX.join(",");
    theForm.prevMinY.value = aPrevMinY.join(",");
    theForm.prevMaxX.value = aPrevMaxX.join(",");
    theForm.prevMaxY.value = aPrevMaxY.join(",");
  }
  
  return retArray;
}
//****************************************************************************
// for button Show_Attribute of selected feature on active layer
function csy_showAttrib()
{
	
	if (hasQueryResults == "1")
	{
		alert("No fields defined for this layer!");
		return;
	}
	if (sqryLayerName == "" || Trim(sqryShpResults).length == 0)
	{
		alert("Please select the features from '" + ActiveLayerID + "' layer first!");
		return;
	}

	if (sqryLayerName != ActiveLayerID)
	{
		alert("The selected features do not belong to the active layer. Please make a selection from the active layer.");
		return;
	}
	if(t.identifyMode ==1 )
	{
		var pf = t.parent.PostFrame;
		var theForm = pf.document.forms[0];
		t.sqryLayerName=t.ActiveLayerID;

		theForm.selectLayer.value = t.ActiveLayerID;
		theForm.CMD.value = 'QUERY_POINT';
		theForm.identifyMode.value = 2;	
		t.identifyMode = 2;
		theForm.submit();
	}
	else
	{
		csy_displayIdentifyResults(qryResults,ActiveLayerID);
	}
	
}
//****************************************************************************
// clears all selection query on map

function clearHighlight()
{
	var theForm = top.PostFrame.document.forms[0];
		
	//theForm.inputType.value = "Y"; //set to simulate a map click
	
	theForm.hightlightShapeResults.value = "";
	theForm.highlightLayer.value = "";
	hightlightShapeResults=""; 
		
	setPrevious();
	showRetrieveMap();
	csy_drawMap();
	theForm.redraw.value = "Y";
	theForm.submit();
	
}

//****************************************************************************
// get index of source layer for saved layers

function getOriginalSourceLayerIndex(idx)
{
	var prvIdx=0;
	var origSourceIDX=-1;
	prvIdx = idx;
	if(t.LayerisPersist[prvIdx] == 1)
	{
		for (var i=0; i<t.layerCount; i++)
		{
		  if(t.LayerName[i].toUpperCase() == t.PersistLayerSource[prvIdx].toUpperCase())
		  {
		    if(t.LayerisPersist[i] == 1)
		    {
				prvIdx= i;
		    }
		    else
		    {
		  		origSourceIDX = i;
		  		break;
		  	}
		  }

		}

	}
return origSourceIDX;
}
//****************************************************************************
function removeFromRefIdList(lyrName)
{
	if(refIdList!="")
	{
		  arrRefIdList = split(";",$refIdList );
		  $tmpLyrName="";
		  for(k=0;k<arrRefIdList.length; k++)
		  {
			  if(arrRefIdList[k].indexOf("*")!=-1)
			  {
			 	$tmpLyrName = substr($arrRefIdList[k],0,arrRefIdList[k].indexOf("*")-1);
				if (tmpLyrName.toUpperCase() == lyrName.toUpperCase())
				{	refIdList= refIdList.splice(k,1);
					return;
				}	
			   }
		 }
	 }
}
//*****************************************************************************

//AD June 2007, to highlight toolmode icon
function highlightToolIcon()
{
	var url = "";
	if (selectedToolType=="DYNAMIC_TOOL")
	{//dyn tool clicked, reset standard tools
		url="standard_group.htm";
		var stb = top.frames["StandardToolbarFrame"];	
		stb.document.location= url;
			}
	else if (selectedToolType=="STANDARD_TOOL")
	{//stn tool clicked, reset dynamic group tools
		if(toolDynGroupName){
			url="dyn_group.jsp?GROUP="+toolDynGroupName;
			var dtb = top.frames["DynamicToolbarFrame"];
			dtb.document.location= url;	
		}
	}
}

//****************************************************************************
//AD June 2007, to set selected tool type, called from standard_group.htm and dyn_group.jsp
function setSelectedToolType(type)
{
	selectedToolType = type.toUpperCase();
}

function spacer()
{//do nothing
	;	
}


function GetProjLayer(LyrName)
{
	var strReturn="";
	var oXMLHTTP = null;
	if(window.ActiveXObject) oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
	if(window.XMLHttpRequest) oXMLHTTP = new XMLHttpRequest();
	//need a function to MakeStringUrlSafe
	var sURL = t.cuestaJspURL+"GetProjLayer.php" ;

	oXMLHTTP.open( "POST", sURL, false );
	oXMLHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	oXMLHTTP.send("LYRNAME="+LyrName);
	strReturn = oXMLHTTP.responseText;
	strReturn= ""+Trim(strReturn);
	oXMLHTTP = null;

	return strReturn
}

function resetExit(val)
{
if(val!="")
{
	selectedToolType="STANDARD_TOOL";
	var stb = t.top.frames["StandardToolbarFrame"];
	
	{var zTool = stb.document.getElementById(val);
		if(zTool)
		{
			zTool.onclick();
		}
	}
	//toolmode = val;
	refreshToolMode(val)
	
}
}
//2008 extension

function SplitTo1000(strField,strList)
{
	var tmpStr="";

	return tmpStr
}

function isInArray(valSearch, strIds)
{
	returnVal = false;
	arrA = strIds.split("~");
	for (i = 0 ; i < arrA.length; i++  )
	{
		if (valSearch== arrA[i])
		{
			returnVal = true;
			break;
		}
	}
	return returnVal;
}