


var grid = false;
var coordinates_layer = false;
var measure = false;
var lat = 0;
var lon = 0;

var polygon = false;
var id = 0;

var mouseX = 0;
var mouseY = 0;

var lat = 0;
var lon = 0;

var arRecord = new Array();

// DPN: added 11.12.2003...
var toolMode = 0;

function Change_Theme(strUrl){
		document.map.mapOption.value = '';
		document.map.submit();
	}
	function CheckScale(fieldvar,textvar) {
				
			document.map[fieldvar.name].checked = false
			alert(textvar)
					
		}		
		
	function reloadBrowser(){	
	if(innerWidth!=origWidth||innerHeight!=origHeight)location.reload()	
	}	
	if (is_nav4){		
		origWidth=innerWidth;origHeight=innerHeight;onresize=reloadBrowser();
	}

//**************************************************


function toggle_coordinates(val, val2, val3) {
        
    if (val) {
		
		// DPN: adding the same setLayerZIndex function call that's in toggle_measure().
		//      showLayer() expects a string parameter, not an object; changing all showLayer function calls.
		
		setLayerZIndex(getLayerObj('MEASUREGLASS2'),10);
		showLayer("COORDINATES");
		coordinates_layer = true;
                if (val2)
                 {
                  document.cookie="onSP";
                 }
                if (val3)
                 {
                  document.cookie="onLL";
                 }
	}
	else {
               // changed by Valentin Negrea, when unchecking the coordinate check box, don't set Measureglass = 0
		hideLayer("COORDINATES");
		coordinates_layer = false;
		setLayerZIndex(getLayerObj('MEASUREGLASS2'),0);
                document.getElementById('theMap').style.cursor = 'crosshair';
                document.cookie="off";
	}
}




function toggle_measure(val1)
{
	//alert(id);
	
	if (id > 1){	
             // added by Valentin Negrea
             // as the measure check box is unchecked the page gets refreshed and cursor of mouse reset
	        document.execCommand('Refresh');
                document.getElementById('mylayerDiv').style.cursor = 'crosshair';
	}
	
	if (val1)
	{		
		setLayerZIndex(getLayerObj('MEASUREGLASS'),10)		
		setLayerZIndex(getLayerObj('mylayerDiv'),0)
		setLayerZIndex(getLayerObj('MEASUREGLASS2'),0);
		
		return true;
	}
	else
	{
		setLayerZIndex(getLayerObj('MEASUREGLASS'),0)		
		setLayerZIndex(getLayerObj('mylayerDiv'),10)
                document.getElementById('mylayerDiv').style.cursor = 'crosshair';
		return true;
	}
}


	function findLeft(objectID) {
		var domStyle = findDOM(objectID,1);
		var dom = findDOM(objectID,0);
		if (domStyle.left)
			return domStyle.left;
		if (domStyle.pixelLeft)
			return domStyle.pixelLeft;
		if (dom.offsetLeft)
			return dom.offsetLeft;
		return (null);
	}

	function findTop(objectID) {
		var domStyle = findDOM(objectID,1);
		var dom = findDOM(objectID,0);
		if (domStyle.top)
			return domStyle.top;
		if (domStyle.pixelTop)
			return domStyle.pixelTop;
		if (dom.offsetTop)
			return dom.offsetTop;
		return (null);
	}

	function handleSubmit()	{
		myArray = new Array("click.x","click.y","x1","x2","y1","y2","tool")		
		for (i=0;i<myArray.length;i++) {	
		document.map[myArray[i]].value = '';
		}
		return true;
	}

	function getMouseEvent(EVENT, myEventArray) {
		if (dyn) {
		    if (ie) {
				cursorWinX = event.clientX - leftPos - 2; 
		        cursorWinY = event.clientY - topPos - 2;
		        cursorPageX = cursorWinX + document.body.scrollLeft;
		        cursorPageY = cursorWinY + document.body.scrollTop;	             
		    }
		    else {
				cursorPageX = EVENT.pageX - leftPos;
				cursorPageY = EVENT.pageY - topPos;
				cursorWinX = cursorPageX - window.pageXOffset;
				cursorWinY = cursorPageY - window.pageYOffset;
	        }	        	         
		}  
		
		myEventArray[0] = cursorPageX;
		myEventArray[1] = cursorPageY;
	}



	function beginZoomBox(e) {                

		var clickArray = new Array();        
	    getMouseEvent(e, clickArray);        


	    if (document.all && (mapsubmitted == 'false' )) {            			
			
			xStore = clickArray[0];
			yStore = clickArray[1];						      
			document.all.mylayerDiv.style.cursor =  "crosshair";
			document.onmousemove = stretchZoomBox;
			
			setLayerSize(getLayerObj("rubberBand"),0,0);
					        
	    }
	    else if (document.getElementById && (mapsubmitted == 'false' )) {			
			xStore = clickArray[0];			
			yStore = clickArray[1];			
	            		
			var w = document.getElementById("mylayerDiv");
			w.onmousemove = stretchZoomBox;
			w.onmouseup = endZoomBox;
	    }
	    else if (document.layers) {                
					      
			var x = (is.ns)? e.layerX:event.offsetX
			var y = (is.ns)? e.layerY:event.offsetY
				       
			xStore = x;
			yStore = y;
	        			
			mylayer = new DynLayer("mylayerDiv")			
			mylayer.elm.onmousemove = stretchZoomBox;
				
			return false;			
		}      
	}
	

	function stretchZoomBox(evt) {
            
        var mouseArray = new Array();        
        getMouseEvent(evt, mouseArray)
 
        if ( ( mapsubmitted == 'false' ) && ( ie || ns6 ) )	{	//IE OR NS6
        		
			//showLayer(getLayerObj("rubberBand"))
			showLayer("rubberBand");
			
			// HANDLE ZOOM BOX OUT OF BOUNDS		
			if ( mouseArray[0] >= ( MapWidthXpx - 2 ) || mouseArray[0] <= 2 ) {
				hideLayer(getLayerObj("rubberBand"))
				endZoomBox();
			}			
			if ( mouseArray[1] >= ( MapHeightYpx - 2 ) || mouseArray[1] <= 2 ) {
				hideLayer(getLayerObj("rubberBand"))
				endZoomBox();
			}
			setLayerSize(getLayerObj("rubberBand"),Math.abs(xStore - mouseArray[0]),Math.abs(yStore - mouseArray[1]))
			if (xStore < mouseArray[0])	{
				divLeft = xStore;
			}	
			else {
				divLeft = mouseArray[0];
			}
			if (yStore < mouseArray[1]) {
				divTop = yStore;
			}	
			else {
				divTop = mouseArray[1];
			}			
			moveLayerTo(getLayerObj("rubberBand"),divLeft,divTop)			
			 
        }       
        else if (document.layers && (mapsubmitted == 'false' )) {                     
                 
                var r = document.mylayerDiv.document.zoomboxTop                
				r.visibility = "show"
                r.resize(Math.abs(xStore-evt.x),3)
                
                if (evt.x > xStore) {                
					r.left = xStore
					r.top = yTrimTop + yStore                
                }
                else {
					r.left = evt.x;
					r.top =  yTrimTop + yStore                 
                }
                  
                var u = document.mylayerDiv.document.zoomboxBottom                
				u.visibility = "show"
				u.resize(Math.abs(xStore-evt.x),3)
				
				if (evt.x > xStore)	{
					u.left = xStore
					u.top =  yTrimBottom + evt.y                
                }
                else {
					u.left = evt.x;
					u.top =  yTrimBottom + evt.y
				}
				               
                var s = document.mylayerDiv.document.zoomboxLeft 
                s.visibility = "show"               
               
				if (evt.y > yStore)	{			// dragging south
                	s.top = yTrimLeft + yStore				
					if(evt.x > xStore)	{		// dragging southeast 
						s.left = xStore
					}
					else {						// dragging southwest
						s.left = evt.x
					}				                              
                }
                else {							// dragging north
                	s.top =   yTrimLeft + evt.y;
                	if(evt.x > xStore) {		// dragging northeast
					s.left = xStore
					}
					else {						// dragging northwest
					s.left = evt.x
					}				       
                }		
					s.resize(3,Math.abs(yStore-evt.y)); 				
												
				var t = document.mylayerDiv.document.zoomboxRight                
                t.visibility = "show"       
				
				if (evt.y > yStore)	{
                t.top =   yTrimRight + yStore;
                
					if(evt.x > xStore) {
					t.left = evt.x
					}
					else {
					t.left = xStore
					}
               
                }
                else {
                t.top = yTrimRight + evt.y;
                 
					if(evt.x > xStore) {
					t.left = evt.x
					}
					else {
					t.left = xStore
					}                               
                }	
								
				t.resize(3,Math.abs(yStore-evt.y)+3); 		
				      
        }
    }
	
	
	function endZoomBox(e) {
	    var mouseArray = new Array();        
		getMouseEvent(e, mouseArray)
	            
	    var x = (is.ns)? e.layerX:event.offsetX
	    var y = (is.ns)? e.layerY:event.offsetY
		var xMin;
	    var yMin;
	    var xMax;
	    var yMax;
	        
	        
	    if (document.layers) {	           
			mylayer.elm.releaseEvents(Event.MOUSEMOVE);
	    }
	            
	    if (ie) {    
	        document.all.mylayerDiv.style.cursor = "wait"
	    }
	    	              
		if ( ie || ns6 || ns )	{								// MSIE OR NS6
	               
	        hideLayer(getLayerObj("rubberBand"))
	        	        
	        if (xStore < mouseArray[0]) {
	            xMin = xStore;
	            xMax = mouseArray[0];
	            	                        
	        }
	        else {
	            xMin = mouseArray[0];
	            xMax = xStore;	            
	            
	        }            
	        if (yStore < mouseArray[1]) {
	            yMin = yStore;
	            yMax = mouseArray[1];	            
	            
	        }
	        else {
	            yMin = mouseArray[1];
	            yMax = yStore;            
	            
	        }
		}
            
	        mapsubmitted = 'true';
	        
	        document.map.x1.value = xMin;
	        document.map.x2.value = xMax;
	        document.map.y1.value = yMin;
	        document.map.y2.value = yMax;
	        
	        document.map['click.x'].value = xMin + ((xMax-xMin)/2);
	        document.map['click.y'].value = yMin + ((yMax-yMin)/2)
        
	        
	        if (( xMax - xMin ) >= 3 && (yMax - yMin) >=3)
	        {        
	           document.map.tool.value = "zoombox"; 
  	           window.document.map.submit();  
	        }
	        else
	        {        
	          document.map.tool.value = "pointclick"; 
	          window.document.map.submit();
	        }
	        return false
	}






function queryString(key){
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}

function PageQuery(q) {
	if(q.length > 1) 
		this.q = q.substring(1, q.length);
	else 
		this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	
this.getKeyValuePairs = function() { return this.keyValuePairs; }
this.getValue = function(s) {
	for(var j=0; j < this.keyValuePairs.length; j++) {
	if(this.keyValuePairs[j].split("=")[0] == s)
	return this.keyValuePairs[j].split("=")[1];
}
return false;
}
this.getParameters = function() {
	var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
	return a;
}
this.getLength = function() { return this.keyValuePairs.length; } 
}




function showPosition(e)
{
	
	//alert(map.coordinateTool.value)
	
	
		if (document.all)
		{
			mouseX = event.x - leftPos + document.body.scrollLeft;
			mouseY = event.y - topPos + document.body.scrollTop;		
		}
		else if (document.layers)
		{
			mouseX = e.x;
			mouseY = e.y;
		}
		else if (document.getElementById)
		{
			mouseX = e.pageX - leftPos;
			mouseY =  e.pageY - topPos;
					
		}
			
				
		content = "<img src='images/pixel.gif' border='0' width='1' height='1' >"
		
		

           if (!(queryString("mo") > 1))
                 {
		  if(document.map.position[0].checked)
				{			
                                	// state plane values
					
					Xsp = Math.round(MapMinXsp + ( mouseX * MapWidthRatio ))	
					Ysp = Math.round(MapMaxYsp - ( mouseY * MapHeightRatio ))
			
					content = content + "Coordinates (State Plane) X:" + Xsp + "&nbsp;&nbsp;&nbsp;Y:" + Ysp + " ";
			
				}
		   if(document.map.position[1].checked) 
                                {
					// lat long values
					
					Xsp = MapMinXsp + ( mouseX * MapWidthRatio )	
					Ysp = MapMaxYsp - ( mouseY * MapHeightRatio )
	
					convertSP(Xsp,Ysp);
					
					
					//lat = format_number(lat,7)	
					//lon = format_number(lon,8)	
					
					
					
					strLon = "";
					strLat = "";
					
					
					strLat = strLat + lat;					
					i = strLat.indexOf('.');					
					strLatA = strLat.substring(0,i+1);					
					strLatB = strLat.substring(3,10);					
					lat = strLatA + strLatB
					
					
					strLon = strLon + lon;
					j = strLon.indexOf('.');					
					strLonA = strLon.substring(0,j+1);					
					strLonB = strLon.substring(4,10);					
					lon = strLonA + strLonB
					
					content = content + "Coordinates (Lat - Long) Lat:" + lat + "&nbsp;&nbsp;&nbsp;Long:" + lon + " ";
					
 			   }
		    }



           if ((queryString("mo") > 1))
                 {
                  if ((document.cookie).indexOf("onSP") != -1 )
				{			
					// state plane values
					
					Xsp = Math.round(MapMinXsp + ( mouseX * MapWidthRatio ))	
					Ysp = Math.round(MapMaxYsp - ( mouseY * MapHeightRatio ))
			
					content = content + "Coordinates (State Plane) X:" + Xsp + "&nbsp;&nbsp;&nbsp;Y:" + Ysp + " ";
			
				}

                  if ((document.cookie).indexOf("onLL") != -1 )
                                {
					// lat long values
					
					Xsp = MapMinXsp + ( mouseX * MapWidthRatio )	
					Ysp = MapMaxYsp - ( mouseY * MapHeightRatio )
	
					convertSP(Xsp,Ysp);
					
					
					//lat = format_number(lat,7)	
					//lon = format_number(lon,8)	
					
					
					
					strLon = "";
					strLat = "";
					
					
					strLat = strLat + lat;					
					i = strLat.indexOf('.');					
					strLatA = strLat.substring(0,i+1);					
					strLatB = strLat.substring(3,10);					
					lat = strLatA + strLatB
					
					
					strLon = strLon + lon;
					j = strLon.indexOf('.');					
					strLonA = strLon.substring(0,j+1);					
					strLonB = strLon.substring(4,10);					
					lon = strLonA + strLonB
					
					content = content + "Coordinates (Lat - Long) Lat:" + lat + "&nbsp;&nbsp;&nbsp;Long:" + lon + " ";
					
 			      }
                 }


			
		if (document.all)
		{	
			//if((document.map.mapOption.value == "advanced-tools" && document.map.coordinateTool.checked)|| (document.map.coordinateTool && (document.map.mapOption.value != "advanced-tools" && document.map.coordinateTool.value == "on")) )
                   // if (((document.cookie).substring(0,2))=="on")
			// if (!(queryString("mo") > 1))
                        // if (document.map.coordinateTool.checked)
			 // {			
			//	if (coordinates_layer)
				COORDINATES.innerHTML = content;
				//*window.status = map.coordinateTool.checked
			//  }
		}
		else if (document.layers)
		{
			document.COORDINATES.document.write(content)
			document.COORDINATES.document.close()
		}
		else if (document.getElementById)
		{
			document.getElementById("COORDINATES").innerHTML = content;		
		}
}



// Code to convert from map units to decimal degrees.
// Code based on asp code from Gerry Daumiller, Montana State Library 8-23-02 email.
// Translated to javascript by Jeff Miller, Jefferson County, WA.
// Updated Additionally by NCTCOG Research and Information Services February 2003

// The formulae this program is based on are from "Map Projections,
// A Working Manual" by John P. Snyder, U.S. GeoLogical Survey
// Professional Paper 1395, 1987, pages 295-298

// Updated Based on Above USGS Document and by NCTCOG for State Plane Zone 4204

function convertSP(uX,uY) {

// Convert StatePlane to Meters

uX = uX * .304800609
uY = uY * .304800609

a = 6378137;   					//major radius of ellipsoid, map units (NAD 83)
ec = 0.08181922146;  			//eccentricity of ellipsoid (NAD 83)
angRad = 0.01745329252;  		//number of radians in a degree
pi4 = 3.141592653582 / 4;  		//Pi / 4
p0 = 31.666666666 * angRad; 	//latitude of origin
p1 = 32.133333333 * angRad;  	//latitude of first standard parallel
p2 = 33.966666666 * angRad;  	//latitude of second standard parallel
m0 = -98.5 * angRad;  			//central meridian
x0 = 600000; 					//False easting of central meridian, map units
y0 = 2000000;					// False northing

// Calculate the coordinate system constants.
with (Math) {
m1 = cos(p1) / sqrt(1 - (pow(ec,2)) * pow(sin(p1),2));  
m2 = cos(p2) / sqrt(1 - (pow(ec,2)) * pow(sin(p2),2));
t0 = tan(pi4 - (p0 / 2));
t1 = tan(pi4 - (p1 / 2));
t2 = tan(pi4 - (p2 / 2));
t0 = t0 / pow(((1 - (ec * (sin(p0)))) / (1 + (ec * (sin(p0))))),ec/2);  
t1 = t1 / pow(((1 - (ec * (sin(p1)))) / (1 + (ec * (sin(p1))))),ec/2);
t2 = t2 / pow(((1 - (ec * (sin(p2)))) / (1 + (ec * (sin(p2))))),ec/2);
n = log(m1 / m2) / log(t1 / t2);
f = m1 / (n * pow(t1,n)); 
rho0 = a * f * pow(t0,n);

// Convert the coordinate to Latitude/Longitude.

// Calculate the Longitude.
uX = uX - x0;		//Apply Easting Factor
uY = uY - y0;		//Apply Northing Factor


pi2 = pi4 * 2;

rho = sqrt(pow(uX,2) + pow((rho0 - uY),2));  
theta = atan(uX / (rho0 - uY));
txy = pow((rho / (a * f)),(1 / n));
lon = (theta / n) + m0;
uX = uX + x0;

// Estimate the Latitude
lat0 = pi2 - (2 * atan(txy));

// Substitute the estimate into the iterative calculation that
// converges on the correct Latitude value.
part1 = (1 - (ec * sin(lat0))) / (1 + (ec * sin(lat0)));
lat1 = pi2 - (2 * atan(txy * pow(part1,(ec/2))));

while ((abs(lat1 - lat0)) > 0.000000002) {
  lat0 = lat1;
  part1 = (1 - (ec * sin(lat0))) / (1 + (ec * sin(lat0)));
  lat1 = pi2 - (2 * atan(txy * pow(part1,(ec/2))));
  }

// Convert from radians to degrees.
lat = lat1 / angRad;
lon = lon / angRad;





//alert(lat);
//alert(lon);

//Round the latitude and longitude
//lat = (CLng(lat * 100000)) / 100000;
//lon = (CLng(lon * 100000)) / 100000;

//lat = lat.toPrecision(7);
//lon = lon.toPrecision(8);

}
}
//End of Code for converting map units to decimal degrees.







function format_number(pnumber,decimals){

 
if (isNaN(pnumber)) { return 0}; 
if (pnumber=='') { return 0}; 

var snum = new String(pnumber); 
var sec = snum.split('.'); 
var whole = parseFloat(sec[0]); 
var result = ''; 

if(sec.length > 1){ 
var dec = new String(sec[1]); 
dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals))); 
dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals)); 
var dot = dec.indexOf('.'); 
if(dot == -1){ 
dec += '.'; 
dot = dec.indexOf('.'); 
} 
while(dec.length <= dot + decimals) { dec += '0'; } 
result = dec; 
} else{ 
var dot; 
var dec = new String(whole); 
dec += '.'; 
dot = dec.indexOf('.'); 
while(dec.length <= dot + decimals) { dec += '0'; } 
result = dec; 
} 
return result; 
} 



function mouseposition(e)
{	
	if (e != '') 
	{
		if (document.all)					//IE
		{ 
			mouseX = event.x + document.body.scrollLeft - 3;
		    mouseY = event.y + document.body.scrollTop - 3;
		} 
		else if (document.layers)			//NS4 
		{ 
		    mouseX = e.pageX - 3;
		    mouseY = e.pageY - 3;
		}
		else if (document.getElementById)	//NS6
		{ 
		    var evt=arguments.callee.caller.arguments[0];
		    mouseX = evt.pageX - 3;
		    mouseY = evt.pageY - 3;
		}
	}
}




function collect_vertices(e){

	mouseposition(e);
	
	var d = 0;
	var slope = 0;
	strpolygon = "";

	i = arRecord.length;
	
	/*
	 * TEST TO SEE IF A POLYGON HAS ALREADY BEEN CREATED
	 */	
	if (!polygon){	
	
		/*
		 * TEST TO SEE IF THERE ARE AT LEAST THREE POINTS
		 */
		if (arRecord.length >= 3)
		{	
			dx = Math.abs(arRecord[0][0] - mouseX);
			dy = Math.abs(arRecord[0][1] - mouseY);
			d = Math.sqrt( Math.pow(dx,2) + Math.pow(dy,2) );
					
			/*
			 * THERE ARE AT LEAST THREE POINTS
			 * TEST TO SEE IF THE LAST POINT IS CLOSE TO THE FIRST POINT
			 */		
			if (d < 7) {
			
			arRecord[i] = new Array();
			arRecord[i][0] = arRecord[0][0];      
			arRecord[i][1] = arRecord[0][1];
			
			strImage = "<img src='images/polygon_close.gif' vspace=0 hspace=0>";
			drawLine(arRecord[arRecord.length-2][0],arRecord[arRecord.length-2][1],arRecord[arRecord.length-1][0],arRecord[arRecord.length-1][1]);
			createLayerADV(arRecord[0][0]-3,arRecord[0][1]-3,10,10,strImage,'transparent');
			
			polygon = true;
					
			} else {
			
			arRecord[i] = new Array();
			arRecord[i][0] = mouseX;       
			arRecord[i][1] = mouseY;		
			
			}		
			
		} else {
			arRecord[i] = new Array();
			arRecord[i][0] = mouseX;       
			arRecord[i][1] = mouseY;	
		}	     
	
		/*
		for (j=0;j<arRecord.length;j++)	{
			strpolygon = strpolygon + arRecord[j][0] + "," + arRecord[j][1] + "|"
		}	
		*/
			
		//PUT AN IMAGE ON THE STARTING POINT 
		/**/
				
		if (arRecord.length == 1) {
			
			strImage = "<img src='images/polygon_open.gif' vspace=0 hspace=0>";
			createLayerADV(arRecord[0][0]-3,arRecord[0][1]-3,8,8,strImage,'transparent');
			setLayerOnTop(getLayerObj('MEASUREGLASS'));
			
		}	
		else if (arRecord.length >= 2 && !polygon) {
			drawLine(arRecord[arRecord.length-2][0],arRecord[arRecord.length-2][1],arRecord[arRecord.length-1][0],arRecord[arRecord.length-1][1])
		}	
	
		area = 0;	
		if(polygon) {			
			area = find_area(arRecord);
		}

		results_panel(arRecord,area);
		
	}
 
	document.execCommand('Stop')
}

function drawLine(ax,ay,bx,by)
{
	
	var slope = 0;
	
	run = bx - ax;
	rise = by - ay;
	slope = rise / run;	
		
		
		if (Math.abs(run) > Math.abs(rise))
		{					
		
		/*
		 *  HORIZONTAL SEPERATION IS GREATER THAN VERTICAL SEPERATION
		 *  ITERATE OVER THE X-AXIS	
		 */			
						
			if (ax < bx){
			
			/*
			 *  ITERATE FROM LEFT TO RIGHT (X INCREASING )	
			 */			
				for(j=ax;j<bx;j++)
				{				
					createLayerADV(j,ay + Math.round((j-ax) * slope ),2,2,'','#FF3333')
				}			
			} else {							
			
			/*
			 *  ITERATE FROM RIGHT TO LEFT (X DECREASING )	
			 */
				for(j=ax;j>bx;j--)
				{								
					createLayerADV(j,ay + Math.round((j-ax) * slope ),2,2,'','#FF3333')
				}			
			}				
		}
		else 
		{		
		
		/*
		 *  VERTICAL SEPERATION IS GREATER THAN HORIZONTAL SEPERATION
		 *  ITERATE OVER THE Y-AXIS	
		 */ 
									
			if (ay < by){			
			/*
			 *  ITERATE FROM TOP TO BOTTOM (Y INCREASING )	
			 */ 
			
				for(j=ay;j<by;j++)
				{				
					createLayerADV(ax + Math.round((j-ay) * 1/slope ),j,2,2,'','#FF3333')
				}
			
			} else {
			/*
			 *  ITERATE FROM BOTTOM TO TOP (Y DECREASING )	
			 */
						
				for(j=ay;j>by;j--)
				{				
					createLayerADV(ax + Math.round((j-ay) * 1/slope ),j,2,2,'','#FF3333')
				}			
			}				
		}
		
		setLayerOnTop(getLayerObj('MEASUREGLASS'))  

}




function find_area(areaArray)
{
	
	areaArray[i+1] = new Array()
	areaArray[i+1][0] = areaArray[1][0]      
	areaArray[i+1][1] = areaArray[1][1]
	
	var n = areaArray.length - 2

	var area = 0;
	
	for (i=1, j=2, k=0; i<=n; i++, j++, k++) 
	{
	area += areaArray[i][0] * (areaArray[j][1] - areaArray[k][1]);
	}

	area = Math.abs(area/2);
	
	//convert to square ft
	area = area * Math.pow(MapWidthRatio,2)
	
	return area;
}

function results_panel(myarray,area)
{
		
	if (area > 0)	//polygon 
	{	
		max = myarray.length - 1;
	}
	else			//line
	{
		max = myarray.length;
	}
	
	var content = "";
	var sum = 0;
	var s = 0;
	
	
	
	content += "<TABLE WIDTH='170' BORDER='0' CELLSPACING='1' CELLPADDING='0' BGCOLOR='#FFFFFF'>"	
	content += "<TR>"
	content += "<TD BGCOLOR='#FFFFFF' ALIGN='LEFT' COLSPAN='2'>"
	
	// PROBLEM : THIS IMAGE NEEDS TO BE INCLUDED OR ELESE 
	// THE REST OF THE TABLE CONTENTS ARE NOT SHOWN IN NS4 DONT KNOW WHY ?
	content += "<img src='images/pixel.gif' border='0' width='1' height='1' >"
	
	content += "<FONT FACE='VERDANA' SIZE='1' COLOR='#CE6500'><B><U>Measure Tool</U></B></FONT></TD>"	
	content += "</TR>"
	content += "</TABLE>"
	
	
	
	content += "<TABLE WIDTH=170 BORDER='0' CELLSPACING='1' CELLPADDING='2' BGCOLOR='#FFFFFF' >"
	
	content += "<TR>"
	content += "<TD BGCOLOR=#FFFFFF COLSPAN=2 HEIGHT=5PX></TD>"	
	content += "</TR>"
		
	content += "<TR>"
	content += "<TD BGCOLOR=#EFEBEF>&nbsp;</TD>"
	content += "<TD BGCOLOR=#EFEBEF ALIGN=CENTER><FONT FACE='VERDANA' SIZE='1'>DISTANCE</FONT></TD>"	
	content += "</TR>"

	if (myarray.length >= 2)
	{	
		for (i=1;i<max;i++)
		{			
			dx = Math.abs(myarray[i][0] - myarray[i-1][0]);
			dy = Math.abs(myarray[i][1] - myarray[i-1][1]);
			
			s = ( Math.sqrt( Math.pow(dx,2) + Math.pow(dy,2) ) * MapWidthRatio );
						
			sum = sum + s;	
			
						
			if(s > 5280){
			
				s = s/5280
				s = format_number(s,1)
				s = s + "&nbsp;mi"
				
			}
			else {
			
				
				s = format_number(s,1);
				//s = Math.round(s);
				s = s + "&nbsp;ft"
			
			}
			
	
			content += "<TR>"
			content += "<TD BGCOLOR=#EFEBEF><FONT FACE='VERDANA' SIZE='1'>LINE&nbsp;"+i+"</FONT></TD>"
			content += "<TD BGCOLOR=#EFEBEF ALIGN=RIGHT><FONT FACE='VERDANA' SIZE='1'>"+s+"</FONT></TD>"	
			content += "</TR>"	
		} 
	} 
	
	
	
			if(sum > 5280){
			
				sum = sum/5280
				sum = format_number(sum,1)
				sum = sum + "&nbsp;mi"
				
			}
			else {
			
				
				sum = format_number(sum,1)
				//sum = Math.round(sum);
				sum = sum + "&nbsp;ft"
			
			}
			
	content += "<TR>"
	content += "<TD BGCOLOR=#EFEBEF><FONT FACE='VERDANA' SIZE='1' COLOR='#003399'><B>Total Distance</B></FONT></TD>"
	content += "<TD BGCOLOR=#EFEBEF ALIGN=RIGHT><FONT FACE='VERDANA' SIZE='1'>" + sum + "</FONT></TD>"	
	content += "</TR>"
	
	if (area > 0)
	{		
		
		if ( area > .5 * ( Math.pow(5280,2) ) )	{
			area = area/( Math.pow(5280,2) )			
			area = format_number(area,1) + "&nbsp; sq mi"
		}else{
		
			area = format_number(area,1) + "&nbsp; sq ft"
			
		
		}
				
		content += "<TR>"
		content += "<TD BGCOLOR=#EFEBEF><FONT FACE='VERDANA' SIZE='1' COLOR='#003399'><B>Total Area</B></FONT>"
		content += "<TD BGCOLOR=#EFEBEF ALIGN=RIGHT><FONT FACE='VERDANA' SIZE='1'>" + area + "</TD>"	
		content += "</TR>"	
	}
	
	content += "</TABLE>"

	content += "<TABLE WIDTH=170 BORDER=0 CELLSPACING=1 CELLPADDING=2 >"
	
	content += "<TR>"
	content += "<TD align='center' BGCOLOR=#EFEBEF>"
	content += "<a href='javascript:window.location.reload()' border='0'>"
	content += "<img alt='Click to clear all selected items on the map'" 
	content += "src='images/clear_measurements.gif' border='0' name='ClearMap'"
	content += " width='120' height='20' >"
	content += "</a>"
	content += "</TD>"
	content += "</TR>"
	
	content += "<TR>"
	content += "<TD align='center'>"
	content += "<font color='gray' face='verdana' size='1' >"
	content += "All measurements are approximations"
	content += "</font>"
	content += "</TD>"
	content += "</TR>"	
	content += "</TABLE>"
	
	

		
	if (document.all)
	{	
		RESULTSPANEL.innerHTML = content;
		
    }
    else if (document.layers)
	{
		document.RESULTSPANEL.document.write(content)
		document.RESULTSPANEL.document.close()
	}
    else if (document.getElementById)
	{
		document.getElementById("RESULTSPANEL").innerHTML = content;		
	}	
		
	//showLayer(getLayerObj('RESULTSPANEL'));
	showLayer("RESULTSPANEL");
	setLayerOnTop(getLayerObj('RESULTSPANEL'));
	
}

// DPN 11.10.2003: removing createLayer from advancedTools; see createLayerADV's notes, below...
/*
function createLayer(left,top,width,height,content,bgColor,visibility,zIndex)
{		
	divID = "div" + (id += 1);

	redLayerObj = addLayer(divID);

	setLayerZIndex(redLayerObj,10)
	
	moveLayerTo(redLayerObj,left,top);	
	showLayer(redLayerObj);		
	
	if(bgColor != 'transparent'){ 
		setLayerBgColor(redLayerObj,bgColor);	
	}	
	
	setLayerSize(redLayerObj,width,height);
	setLayerClip(redLayerObj,0,width,height,0);
	
	setLayerHTML(redLayerObj,content);
}	
*/

// function createLayerADV():
// --------------------------
// Removing advancedTools' createLayer function because of its ambiguous name: js_zoombox also has a
// createLayer() function, and you can't overload in JavaScript.
function createLayerADV(left,top,width,height,content,bgColor,visibility,zIndex)
{		
	divID = "div" + (id += 1);

	redLayerObj = addLayer(divID);

	setLayerZIndex(redLayerObj,10)
	
	moveLayerTo(redLayerObj,left,top);	
	//showLayer(redLayerObj);		
	showLayer(divID);
	
	if(bgColor != 'transparent'){ 
		setLayerBgColor(redLayerObj,bgColor);	
	}	
	
	setLayerSize(redLayerObj,width,height);
	setLayerClip(redLayerObj,0,width,height,0);
	
	setLayerHTML(redLayerObj,content);
}	


function format_number(pnumber,decimals){ 
	if (isNaN(pnumber)) { return 0}; 
	if (pnumber=='') { return 0}; 

	var snum = new String(pnumber); 
	var sec = snum.split('.'); 
	var whole = parseFloat(sec[0]); 
	var result = ''; 

	if(sec.length > 1){ 
		var dec = new String(sec[1]); 
		dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals))); 
		dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals)); 
		var dot = dec.indexOf('.'); 
		if(dot == -1){ 
			dec += '.'; 
			dot = dec.indexOf('.'); 
		} 
		while(dec.length <= dot + decimals) { dec += '0'; } 
		result = dec; 
	} else { 
		var dot; 
		var dec = new String(whole); 
		dec += '.'; 
		dot = dec.indexOf('.'); 
		while(dec.length <= dot + decimals) { dec += '0'; } 
		result = dec; 
	} 
	return result; 
}   


function showPos(objectID) {
	leftPos = findLeft(objectID);
	topPos = findTop(objectID);
	//alert('Left: ' + leftPos + 'px; Top: ' + topPos + 'px' );
			
}

		
function init(e) {

	if (document.layers)
	{
        
				
	showPos("mylayerDiv")
        
	mylayer = new DynLayer("mylayerDiv")
	mylayer.elm.onmousedown = beginZoomBox

	mylayer2 = new DynLayer("box3")
	mylayer2.elm.onmousedown = beginZoomBox		        
        
	mylayer.elm.onmousemove =  showPosition
	mylayer.elm.onmouseup = endZoomBox
                
	if (is.ns) mylayer.elm.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP | Event.MOUSEMOVE)
	if (is.ns) mylayer2.elm.captureEvents(Event.MOUSEDOWN)
				

	mgLayer = new DynLayer("MEASUREGLASS")
	mgLayer.elm.onmouseup = collect_vertices        
	if (is.ns) mgLayer.elm.captureEvents( Event.MOUSEUP )
				
	}
		
	if (document.getElementById)
	{
		var demoObj;

		demoObj = document.getElementById("mylayerDiv");
		demoObj.addEventListener("mousedown", beginZoomBox, false);
		demoObj.addEventListener("mousedown", showPosition, false);
				
		demoObj.addEventListener("click", showPosition, false);				
		showPos("mylayerDiv")
											
		el = document.getElementById("mylayerDiv");
 		el.addEventListener("mousemove", showPosition, true);
 		
 		//ADD MOUSEMOVE EVENT LISTENER TO THE MEASUREGLASS LAYER IN NS6
 		//TO GET THE MOUSE COORDINATES
 		coordObj = document.getElementById("MEASUREGLASS");
 		coordObj.addEventListener("mousemove", showPosition, true);
				
	}
}
