// ----------------------------------------------------------------
//     				   ArcWeb Services Site Starter Client
// ----------------------------------------------------------------
// Purpose:  Manages "active" navigation functionality.  
//           + Manages map coordinate logic.
//           + Uses DHTML to produce rubber-banding effect 
//             when user zooms in or out.  This is handled
//             by the zoomBox class.
// ----------------------------------------------------------------
// Notes:		
// -------------------------------------------------------------------

// The following variables are global to the page.
	// These vars reference HTML tags in the page whose
	// values may be read or set dynamically.
    
    var m_LayerNames = new Array()
    var m_LayerVisible = new Array()
    var m_radZoomIn;
    var m_radRecenter;
	var m_imgLoading;
    var m_imgMapCanvas;    
    var m_divZoomBox;
    
    /*var m_txtXCoord;
    var m_txtYCoord;
    
    var m_divMapBorder;
    
	var m_divMapTools;
	var m_divNorth;
	var m_divSouth;
	var m_divEast;
	var m_divWest;*/
	
	
    var	m_hvMinX;
    var	m_hvMinY;
    var	m_hvMaxX;
    var	m_hvMaxY;
	var m_hvMapPage;
	var m_hvOverviewPage;
	
	var m_iOVWidth = 130;
	var m_iOVHeight = 130;
	var m_LinePtsCount = 0;
	var m_PolyPtsCount = 0;
	var m_PolyPts = 4;
	var m_Pts;
	var m_LinePts;
	var pt1X,pt1Y;
	var pt1;

	// These vars represent javascript classes that will
	// handle logic.
    var m_mapViewer;  // Object of type map.  Handles map coordinate management.

    var m_zbxZoom;      // Object of type zoombox.  Handles drawing the zoombox.  
				        // Operates entirely within page coordinates and has no 
				        // awareness of the map space or even the image that 
				        // represents the map on the page.

    var m_iToolMode;    // Indicates the currently selected tool, where
				        //				+ zoom in  = 1
				        //				+ recenter = 2	

	var m_sClientBrowserType;	// Possible values: "IE", "Netscape"
	var m_sClientPlatform;		// Possible values: "Windows","Mac"
    
    		           // The array that stores the level extent widths				  
	//var m_ExtentWidths = new Array(0.005, 0.015, 0.035, 0.1, 0.3, 0.75, 2, 6, 10, 30, 110);
	//var m_ExtentWidths = new Array(50, 100, 200, 500, 700, 1000, 2000, 5000, 7000, 10000, 50000);
	var m_MapScales = new Array(2000,5000,10000,25000,50000,100000,150000,400000);
	var m_ExtentWidths = new Array(2000,793.15, 1586.29, 5341.880, 500, 700, 1000, 2000);

	var m_lTimerID = 1; // used only for hiding the "Wait" image for Netscape 6.x

	// Determine browser type and platform.

	if (navigator.appName.indexOf("Netscape")>=0) {
		m_sClientBrowserType = 'Netscape';
	} else if (navigator.appName.indexOf('Microsoft') >=0) {
		m_sClientBrowserType = 'IE';
	} else {
		window.location = "unsupported.htm";
	}

	if (navigator.userAgent.indexOf("Win") >= 0) {
		m_sClientPlatform = 'Windows';
	} else if (navigator.platform.indexOf("Mac") >= 0) {
		m_sClientPlatform = 'Mac';
	} else {
		window.location = "unsupported.htm";
	}
    

// *******************************************************************
// *********************** STARTUP FUNCTION **************************
// *******************************************************************
function getMapWidth(scale)
{
	var tempFactor;
	var inchPerMeter;
	var wid;

	tempFactor = 96;
	inchPerMeter = 39.4;
	wid = m_imgMapCanvas.width;
	return (scale * wid / (tempFactor * inchPerMeter));
}

function updateExtentWidths()
{
	//alert(m_imgMapCanvas.width);
	var i;
	for(i=0;i<m_MapScales.length;i++)
	{
		m_ExtentWidths[i] = getMapWidth(m_MapScales[i]);
		//alert("width " + i + " = " + m_ExtentWidths[i]);
		
	}
	
}

function changeExtent(minx,miny,maxx,maxy,arcs)
{
//alert("sunil");
	m_mapViewer = new map(m_imgMapCanvas.offsetLeft,
  						  m_imgMapCanvas.offsetTop,
						  m_imgMapCanvas.width,	
						  m_imgMapCanvas.height,
						  m_ExtentWidths,
						  new rect(minx, miny, maxx, maxy)
						  );
	var arr;
	var rstr;
	rstr = document.frmViewer.hvFlds.value;
	arr = rstr.split(";");
	rstr = arr[0];
	for(i=1;i<8;i++)
		rstr = rstr + ";" + arr[i];
	document.frmViewer.hvFlds.value = rstr + ";" + arcs;
	submit();
}


function startUp() {

// Purpose: Fires when the page first loads.  

		// Find the HTML tags that will be used throughout the
		// page.
	
	//m_radZoomIn = document.getElementById("radZoomIn");
	//m_radRecenter = document.getElementById("radRecenter");
	
	
	/*m_txtXCoord = document.getElementById("txtXCoord");
	m_txtYCoord = document.getElementById("txtYCoord");*/
	
	m_imgMapCanvas = document.getElementById("imgMapCanvas");
    m_imgLoading = document.getElementById("imgLoading");
	m_divZoomBox = document.getElementById("divZoomBox");
	
	/*m_divMapBorder = document.getElementById("divMapBorder");
  	m_divNorth = document.getElementById("divNorth");
  	m_divSouth = document.getElementById("divSouth");
  	m_divEast = document.getElementById("divEast");
  	m_divWest = document.getElementById("divWest");
  	m_divMapTools = document.getElementById("divMapTools");*/
  	
	m_hvMinX = document.getElementById("hvMinX");
	m_hvMinY = document.getElementById("hvMinY");
	m_hvMaxX = document.getElementById("hvMaxX");
	m_hvMaxY = document.getElementById("hvMaxY");
	m_hvMapPage = document.getElementById("hvMapPage");
	m_hvOverviewPage = document.getElementById("hvOverviewPage");
	
	//updateExtentWidths();
		// Create a map coordinate manager.
	m_mapViewer = new map(m_imgMapCanvas.offsetLeft,
  						  m_imgMapCanvas.offsetTop,
						  m_imgMapCanvas.width,	
						  m_imgMapCanvas.height,
						  m_ExtentWidths,
						  new rect(m_hvMinX.value, m_hvMinY.value, m_hvMaxX.value, m_hvMaxY.value)
						  );
		// Create a zoom box.
		
    m_zbxZoom = new zoomBox(m_divZoomBox);
	
	//m_mapViewer.updateWidths();
        //Orient other page elements - Map Border, Map Tools, Loading Image, Border Navigation.
    posLoadingImage();

    //posBorder();
    //posBorderNavigation(); //must be called BEFORE posTools()
    //posTools();  //must be called AFTER posBorderNavigation()  


		
	    // Initialize the X,Y coordinate display.
	//m_txtXCoord.value = "X:"
	//m_txtYCoord.value = "Y:"

		// Assign custom event handlers to mousedown, mousemove, 
		// and mouseup.
	if (m_sClientBrowserType == 'Netscape') {
		document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}

	
	// Assign an event handler to the m_imgMapCanvas onload event.
	m_imgMapCanvas.onload = hideWaitImage;

	//alert(sliderTD.innerHTML);
	//if (sliderTD.innerHTML == "")
	{
	// Initialize the tool mode. 
	//handleToolClick(returnActiveTool());
	handleToolClick(2);
		
	document.onmousedown = handleMouseDown;
	document.onmousemove = handleMouseMove;
	document.onmouseup = handleMouseUp;
	
			/*var A_TPL4h = {
			'b_vertical' : false,
			'b_watch': true,
			'n_controlWidth': 100,
			'n_controlHeight': 16,
			'n_sliderWidth': 17,
			'n_sliderHeight': 16,
			'n_pathLeft' : 0,
			'n_pathTop' : 0,
			'n_pathLength' : 83,
			's_imgControl': '/MarGIS/images/sldr3h_bg.gif',
			's_imgSlider': '/MarGIS/images/sldr3h_sl.gif',
			'n_zIndex': 1
		}
		var A_INIT4h = {
			's_form' : 0,
			's_name': 'sliderValue',
			'n_minValue' : 0,
			'n_maxValue' : 100,
			'n_value' : 85,
			'n_step' : 1
		}*/

		//coomented by sunil new slider(A_INIT4h, A_TPL4h);
	}
	    //Request a map.
	    
	submit();
}

// *******************************************************************
// *********************** EVENT HANDLERS  ***************************
// *******************************************************************

function handleMouseDown(evt) {
// Purpose:  Any time a mouse button is depressed, this function
//           is given the opportunity to respond to the event.
//
//           For the purposes of the map, we are only interested
//           in the click if it happened within the map area, so 
//           an initial check kicks us out of the function if the
//           click has not occurred in the map area.
//
//           If the click is over the map, then -- depending on
//           the tool mode -- either the zoombox must be started
//           or a recenter must be performed.


	// Get event coordinates by browser-specific means.
	var eventX;
	var eventY;


	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		eventX = event.clientX + Body.scrollLeft;
		eventY = event.clientY + Body.scrollTop;
	}

	// Check to see if click is over map
	
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {
		//A_SLIDERS[0].f_sliderMouseDown();
		return;
	} 
	switch(m_iToolMode) {
		case 1: // zoom in mode
			if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
	  		// For IE, a call to "setCapture" is made to ensure that
				// new IE dragging events do not interfere with capturing 
				// the mousemove events -- effectively, this turns off 
				// drag and drop events temporarily.
				m_imgMapCanvas.setCapture(); 
			}
			m_zbxZoom.show();
			//alert("scrollLeft = " + Body.scrollLeft + " scrollTop = " + Body.scrollTop);
			m_zbxZoom.start(eventX, eventY);
			break;
		case 2: // recenter mode
  			var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
			m_mapViewer.recenter(ptUserClick);
			//Request a new map.
			submit();
			break;
		case 3: // identify mode
  			var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
			//alert("x is " + ptUserClick.x);
			//alert("y is " + ptUserClick.y);
			var Width = 400;
			var Height = 250;
			var lyrs;
			lyrs = getVisibleLayersList();
			//window.open("identify.aspx?tool=Identify&lyr=" + frmViewer.layerToIdentify.options[frmViewer.layerToIdentify.selectedIndex].value + "&lyrs=" + lyrs + "&x=" + ptUserClick.x + "&y=" + ptUserClick.y,"new_page","Height="+Height+",width="+Width+",left="+((screen.width/2)-(Width/2))+",top="+((screen.height/2)-(Height/2))+",resizable=yes,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,copyhistory=no,location=no");			
			window.open("identify.aspx?tool=Identify&lyrs=" + lyrs + "&x=" + ptUserClick.x + "&y=" + ptUserClick.y,"new_page","Height="+Height+",width="+Width+",left="+((screen.width/2)-(Width/2))+",top="+((screen.height/2)-(Height/2))+",resizable=yes,scrollbars=yes,toolbar=no,status=no,directories=no,menubar=no,copyhistory=no,location=no");
			//Request a new map.
			break;
		case 4:
			m_LinePtsCount++;
			m_LinePtsCount = m_LinePtsCount % 2;

			var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);			
			//alert(ptUserClick.x + " " + ptUserClick.y)
			if (m_LinePtsCount == 1)
			{
				m_LinePts = ptUserClick.x + " " + ptUserClick.y;
				document.frmViewer.hvHighlightBy.value = "xy";
				document.frmViewer.hvFlds.value = m_LinePts;
				submit();
			}	
			else
			{
				m_LinePts = m_LinePts + ";" + ptUserClick.x + " " + ptUserClick.y;
				document.frmViewer.hvHighlightBy.value = "drawLine";
				document.frmViewer.hvFlds.value = m_LinePts;
				submit();
				alert("Distance = " + round(calcDist(m_LinePts),2) + " Km");
			}
			break;
		case 5:
			m_PolyPtsCount++;

			var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);			
			//alert(ptUserClick.x + " " + ptUserClick.y)
			if (m_PolyPtsCount == 1)
			{
				pt1 =  ptUserClick.x + " " +  ptUserClick.y;
				m_Pts = pt1;
				document.frmViewer.hvHighlightBy.value = "xy";
				document.frmViewer.hvFlds.value = m_Pts;
				submit();
			}	
			else
			{
				m_Pts = m_Pts + ";" + ptUserClick.x + " " + ptUserClick.y;
				if (m_PolyPtsCount > m_PolyPts-1)
				{
					var ptsArr = new Array();
					var pt = new Array(2);
					var temp;
					var areaTotal = 0;
					document.frmViewer.hvHighlightBy.value = "drawPolygon";
					document.frmViewer.hvFlds.value = m_Pts;
					m_Pts = m_Pts + ";" + pt1;					
					var firstPt = new Array(2);
					var secondPt = new Array(2);
					ptsArr = m_Pts.split(";");
					for(var j=0;j<ptsArr.length-1;j++)
					{
						temp = ptsArr[j];
						pt = temp.split(" ");
						firstPt = ToUTM(pt[1],pt[0]);
						temp = ptsArr[j+1];
						pt = temp.split(" ");
						secondPt = ToUTM(pt[1],pt[0]);		
						areaTotal = areaTotal + ((firstPt[0] * secondPt[1]) - (secondPt[0] * firstPt[1]))
					}
					areaTotal = round(Math.abs(areaTotal / 2000000),2);
					alert("Total Area = " + areaTotal + " sq Kms");
					m_PolyPtsCount = 0;
					submit();						
				}
				else
				{
					document.frmViewer.hvHighlightBy.value = "drawPolygonLine";
					document.frmViewer.hvFlds.value = m_Pts;
					submit();				
				}
			}
	}
}


function round(number,X) {
// rounds number to X decimal places, defaults to 2
    X = (!X ? 2 : X);
    return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
function calcDist(pts)
{
	var lat1,lon1,lat2,lon2;
	var ptsArr = new Array();
	var pt = new Array(2);
	var temp;
	
	ptsArr = pts.split(";");
	
	temp = ptsArr[0];
	pt = temp.split(" ");
	lat1 = toRadian(pt[1]);
	lon1 = toRadian(pt[0]);
	
	temp = ptsArr[1];
	pt = temp.split(" ");
	lat2 = toRadian(pt[1]);
	lon2 = toRadian(pt[0]);
	
	var earthRadius;
	earthRadius = 6378;	
	//3963.1 statute miles
	//3443.9 nautical miles
	//6378 km
	var dist = Math.acos(Math.cos(lat1)*Math.cos(lon1)*Math.cos(lat2)*Math.cos(lon2) + Math.cos(lat1)*Math.sin(lon1)*Math.cos(lat2)*Math.sin(lon2) + Math.sin(lat1)*Math.sin(lat2)) * earthRadius;
	return dist;
}

function toRadian(degrees)
{
	var pi = Math.atan2(1,1) * 4;
	
	// make sure the sign of the angle is correct for the direction
	// West an South are negative angles
	var radians = degrees*(pi/180);
	return radians;
}

function getVisibleLayersList()
{
	var lyrsVis;
	var lyrsVisArr;
	var lyrsIds;
	var lyrsIdsArr;				
	var str;
	var i,j;
	lyrsVis = document.frmViewer.hvLayerVisible.value;
	lyrsVisArr = lyrsVis.split(",");
	lyrsIds = document.frmViewer.hvLayerIDs.value;
	lyrsIdsArr = lyrsIds.split(",");		
	str = "";
	for (i=0;i<lyrsVisArr.length;i++)
		if (lyrsVisArr[i] == "true")
			str = str + "," + lyrsIdsArr[i] + ";" + i;
	if (str != "")
	{
		str = str.substring(1,str.length);
	}
	return str;
}

function getLayerName(i)
{
  var layerNames = new Array();
  layerNames[0] = "Coast Line"
  layerNames[1] = "International border"
  layerNames[2] = "Off-shore Reefs (Fashts)"      
  //layerNames[3] = "Artificial islands"  
  //layerNames[4] = "Dredged channels"  
  layerNames[3] = "Coastal land-cover" 
  layerNames[4] = "Industrial Plants" 
  layerNames[5] = "Water Desalination"   
  layerNames[6] = "Waste-water Treatment" 
  layerNames[7] = "Drainage Outfalls" 
  layerNames[8] = "Ports" 
  layerNames[9] = "Fishing Harbors" 
  layerNames[10] = "Recreational Beaches"  
  layerNames[11] = "Marinas"
  //layerNames[14] = "Planned Reclamation"
  layerNames[12] = "Fishing Traps (Hadrah)" 
  layerNames[13] = "Pearl Oyster Banks" 
  layerNames[14] = "Sea-bed type" 
  layerNames[15] = "Off-shore Springs"
  layerNames[16] = "Major Industrial Effluents"
  layerNames[17] = "Inspected Dead Turtles 2007"
  layerNames[18] = "Inspected Dead Turtles 2008"
  layerNames[19] = "Algae"      
  layerNames[20] = "Coral"
  layerNames[21] = "Seagrass" 
  layerNames[22] = "Sand" 
  layerNames[23] = "Mud" 
  layerNames[24] = "Rock" 
  layerNames[25] = "Salt Marsh"  
  layerNames[26] = "Mangrove"  
  layerNames[27] = "Sabkha"  
  layerNames[28] = "Coral, rock and sand" 
  layerNames[29] = "Deep water mixed" 
  layerNames[30] = "Deep water mud" 
  layerNames[31] = "Mixed habitat" 
  layerNames[32] = "Mud and sand" 
  layerNames[33] = "Rock and sand" 
  layerNames[34] = "Algae, rock and sand" 
  layerNames[35] = "Bathymetry"
  layerNames[36] = "Inter-tidal Zone" 
  layerNames[37] = "Water Salinity"
  //layerNames[39] = "Water Quality"
  layerNames[38] = "Field Survey Data"
  layerNames[39] = "Trace Metal Concentration"
  layerNames[40] = "Badeh-Gillnet"
  layerNames[41] = "Channad-Hook"
  layerNames[42] = "Channad-Longline"
  layerNames[43] = "Channad-Gillnet + Troll"       
  layerNames[44] = "Gubgub-Gargor" 
  layerNames[45] = "Hagool-Flashlight" 
  layerNames[46] = "Hagool-Gillnet"    
  layerNames[47] = "Hamour-Gargoor"
  layerNames[48] = "Hagool-hook + troll + longline"
  layerNames[49] = "Janam-Gargoor"
  layerNames[50] = "Jellyfish-Jellyfish"
  layerNames[51] = "Jenees-Gargoor + Hook"
  layerNames[52] = "Lobester-Trawl"
  layerNames[53] = "Maid- Gillnet"
  layerNames[54] = "Miscellaneous-Longline"
  layerNames[55] = "Rabeeb-Gargoor" 
  layerNames[56] = "Safee-Gargoor"
  layerNames[57] = "Safee-Gillnet"
  layerNames[58] = "Sharee-Hook" 
  layerNames[59] = "Shrimp-Hadhra"
  layerNames[60] = "Shrimp-Trawll"
  layerNames[61] = "Sils-Gillnet" 
  layerNames[62] = "Subiaty-hook + longline + troll"
  layerNames[63] = "Dugongs"
  layerNames[64] = "Sea Turtles"
  layerNames[65] = "Sea Birds" 
  layerNames[66] = "Sooty Falcon"
  layerNames[67] = "Map Scenario 1"
  layerNames[68] = "Map Scenario 2"
  layerNames[69] = "Map Scenario 3"
  layerNames[70] = "Satellite Medium Resolution" 
  layerNames[71] = "Satellite High Resolution" 
  layerNames[72] = "Videos"        
  layerNames[73] = "Images"
 
  return layerNames[i];
}

function handleMouseMove(evt) {
// Purpose:  Any time the mouse moves anywhere on the document, 
//           this function is given the opportunity to respond to 
//           the event.

	// Get event coordinates by browser-specific means.

	var eventX;
	var eventY;

	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		eventX = event.clientX + Body.scrollLeft;
		eventY = event.clientY + Body.scrollTop;
	}

    // If the mouse isn't currently over the map, we
    // have nothing to do.
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {
		//A_SLIDERS[0].f_sliderMouseMove(evt);	
		return;
	} 		
	//reportCoords(m_mapViewer.toMapPoint(eventX, eventY)); // update the textbox to reflect
																																												 // the current coordinates.
    // If the current tool is zoom in and a zoombox is in progress, update
    // the zoom box.
  var ptMouseMove = m_mapViewer.toMapPoint(eventX, eventY);
  var myPrecision = 2;
  var myFactor =  Math.pow(10, myPrecision);
  window.status = "Lat: " + Math.round(ptMouseMove.y * myFactor)/myFactor + " Lon: " + Math.round(ptMouseMove.x * myFactor)/myFactor;
  if (m_iToolMode == 1) {
		if (m_zbxZoom.isInProgress) {
			m_zbxZoom.update(eventX, eventY);
		}
  }
}

function handleMouseUp(evt) {
	// Purpose:  Any time a mouse button is released, this function is 
	//					 given the opportunity to respond to the event.

		// If a ZoomBox is not in progress, we've got nothing
		// to do.

	if (!(m_iToolMode == 1)) {
		//A_SLIDERS[0].f_sliderMouseUp();
		return;
	}
	if (!(m_zbxZoom.isInProgress())) {
		return;
	}
		// Release the capture that was set in the mousedown
		// handler (again, this is something that we have to do because
		// of drag events in IE).
	if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
		document.releaseCapture();
	}

		// Stop the current effect.
	m_zbxZoom.stop();

		// If the width of the zoom box is less than five pixels,
		// treat is as a single click and zoom in one map level.
		// Otherwise, set the extent to the zoom box.
	if ((Math.abs(m_zbxZoom.getStartX() - m_zbxZoom.getEndX()) < 5) && (Math.abs(m_zbxZoom.getStartY() - m_zbxZoom.getEndY()) < 5))  {	
		var ptUserClick = m_mapViewer.toMapPoint(m_zbxZoom.getStartX(), m_zbxZoom.getStartY());
		if (m_mapViewer.getLevel() == 1) {   //if we reach the minimum zoom level, zoom a fixed amount.
		  m_mapViewer.zoom(0.5);
		} else {
			m_mapViewer.setLevel(m_mapViewer.getLevel() - 1);
     }
		m_mapViewer.recenter(ptUserClick);
  } else {
  		borderWidth = 0;
  		if (m_sClientBrowserType == 'Netscape') {
			borderWidth = 4; // 2 times border width
		}
		var ptStart = m_mapViewer.toMapPoint(m_zbxZoom.getStartX()+borderWidth, m_zbxZoom.getStartY()+borderWidth);
		var ptEnd   = m_mapViewer.toMapPoint(m_zbxZoom.getEndX()+borderWidth, m_zbxZoom.getEndY()+borderWidth);
		m_mapViewer.setExtent(new rect(ptStart.x,ptStart.y,ptEnd.x,ptEnd.y));
	}
	//Request a new map.
	submit();

}

function handleToolClick(iToolMode) {
	switch(iToolMode) {
		case 1:
			// zoom in mode
			m_imgMapCanvas.style.cursor = "crosshair";
			selectTool("zoomin");
			break;
		case 2:
			// pan mode
			m_imgMapCanvas.style.cursor = "hand";
			selectTool("recentermp");
			break;
		case 3:
			// identify mode
			m_imgMapCanvas.style.cursor = "crosshair";
			selectTool("idfy");
			//alert("Please select a layer from the list on the right before clicking features to identify on map.");
			break;
		case 4:
			// measure distance mode
			m_imgMapCanvas.style.cursor = "crosshair";
			//m_LinePtsCount = 0;
			selectTool("distance");
			break;
		case 5:
			// measure polygon area mode
			m_imgMapCanvas.style.cursor = "crosshair";
			//m_PolyPtsCount = 0;
			selectTool("area");
			window.showModalDialog("EnterPts.htm",window,"dialogWidth:350px;dialogHeight:70px;status:no;scroll:no") 
			break;					
	}
	m_iToolMode = iToolMode;
}

function convert2Radian(ddff)
{
	return (ddff*Math.PI/180);
}

function convert2UTM(lat,lon)
{
	lat = convert2Radian(lat);
	lon= convert2Radian(lon);
	var a = 6378137;
	var b = 6356752.3142;
	var long0 = 51;
	var k0 = 0.9996;
	var e = 0.08;
	var e12 = 0.007;
	var n = (a-b)/(a+b) ;
	
	var nu = a/Math.pow(1-Math.pow(e,2) * Math.pow(Math.sin(lat),2),0.5);
	var p = (lon-long0);
	var sin1 = 4.8481368 * Math.pow(10,-6);
	
	var A = a * (1 - n + (5/4) * (Math.pow(n,2) - Math.pow(n,3)) + (81/64) * (Math.pow(n,4) - Math.pow(n,5)));
	var B = (3*a*n/2) * (1 - n + (7/8) * (Math.pow(n,2) - Math.pow(n,3)) + (55/64) * (Math.pow(n,4) - Math.pow(n,5)));	
	var C = (15*a*Math.pow(n,2)/16) * (1 - n + (3/4) * (Math.pow(n,2) - Math.pow(n,3)));
	var D = (35*a*Math.pow(n,3)/48) * (1 - n + (11/16) * (Math.pow(n,2) - Math.pow(n,3)));	
	var E = (315*a*Math.pow(n,4)/51) * (1 - n);
	
	var S = A *lat - B*Math.sin(2*lat) + C*Math.sin(4*lat) - D*Math.sin(6*lat) + E*Math.sin(8*lat);

	//y = northing = K1 + K2p2 + K3p4 , where

	var K1 = S*k0;
	var K2 = k0*Math.pow(sin1,2) * nu * Math.sin(lat) * Math.cos(lat)/2;
	var K3 = (k0*Math.pow(sin1,4) * nu * Math.sin(lat) * Math.pow(Math.cos(lat),3)/24) * (5 - Math.pow(Math.tan(lat),2) + 9 * e12 * Math.pow(Math.cos(lat),2) + 4 * Math.pow(e12,2) * Math.pow(Math.cos(lat),4));
	UTMy = K1 + K2*Math.pow(p,2) + K3*Math.pow(p,4)
	/*alert("S = " + S);
	alert("B = " + B);
	alert("C = " + C);
	alert("D = " + D);
	alert("E = " + E);
	alert(K3);*/

	//x = easting = K4p + K5p3, where
	K4 = k0 * sin1 * nu * Math.cos(lat); 
	K5 = (k0 * Math.pow(sin1,3) * nu * Math.pow(Math.cos(lat),3)/6)* (1 - Math.pow(Math.tan(lat),2) + e12 * Math.pow(Math.cos(lat),2));

	UTMx = K4 * p + K5 * Math.pow(p,3) + 500000;
	//alert(p);
	//alert("x = " + UTMx);
	//alert("y = " + UTMy);
	
	//example
	//x = 56088526.12(50.38)  y = 2947095(26.47)
}

function ResizeMap(sSize) {

    if (((sSize == 'SMALL') && (m_imgMapCanvas.className == 'SmallMap')) || 
        ((sSize == 'LARGE') && (m_imgMapCanvas.className == 'LargeMap'))) {
        return;
    }
    
    /*switch(sSize) { 
        case 'SMALL':
        m_imgMapCanvas.className = 'SmallMap';
        Container1.style.height = 570;
        Container1.style.width = 800;
        break;
        case 'LARGE':
        m_imgMapCanvas.className = 'LargeMap';
        Container1.style.height = 620;
        Container1.style.width = 800;
        break;
        default: 
        return; // invalid sSize value
    }
	
        // Create a new map coordinate manager.
    //updateExtentWidths();
    //alert("getleft = " + m_mapViewer.getExtent().getLeft());


	var dblWidth = m_ExtentWidths[m_mapViewer.getLevel() - 1];
	var rctExtent = m_mapViewer.getExtent();
	var rect1 =  new rect(
									rctExtent.getCenter().x - (dblWidth / 2),
									rctExtent.getCenter().y, 
									rctExtent.getCenter().x + (dblWidth / 2), 
									rctExtent.getCenter().y
									);
	rect1 = m_mapViewer.getAdjustedRect(rect1,m_imgMapCanvas.width,m_imgMapCanvas.height);
	
    m_mapViewer = new map(m_imgMapCanvas.offsetLeft,
  				    m_imgMapCanvas.offsetTop,
				    m_imgMapCanvas.width,	
				    m_imgMapCanvas.height,
					m_ExtentWidths,
				    rect1
				    );
	        //Orient other page elements - MapSizeImage, Map Border, Map Tools, Loading Image.
    /*switch(sSize) { 
        case 'SMALL':
        updateImgMapSize('LARGE');
        break;
        case 'LARGE':
        updateImgMapSize('SMALL');
        break;
    }*/
    
    //posLoadingImage();
    //posBorder();
    //posBorderNavigation(); //must be called BEFORE posTools()
    //posTools();  //must be called AFTER posBorderNavigation()
    	
   // submit();
}

function ZoomToLevel(iLevel) { 
//alert(iLevel);
	if (iLevel == 0)
		iLevel = 0.005;
	m_mapViewer.setLevel(iLevel);
    //Request a new map.
    submit();
}


// *******************************************************************
// ********************** HELPER FUNCTIONS  **************************
// *******************************************************************

function hideWaitImage() {
    m_zbxZoom.hide();
    m_imgLoading.style.visibility = 'hidden';
}

function hideWaitImageForNetscape6() {
	if (m_imgMapCanvas.complete) {
		clearInterval(m_lTimerID);
		m_divZoomBox.style.visibility = 'hidden';
		m_imgLoading.style.visibility = 'hidden';
	}
}

function moveEast() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveEast();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveEast();
			submit();
    
}

function moveNorth() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveNorth();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveNorth();
			submit();
}

function moveSouth() {
/*alert(m_hvMaxX-m_hvMinX);
alert(m_mapViewer.getLevel());
	if (m_mapViewer.getLevel() < 8)
	{
		m_mapViewer.moveSouth();
		submit();
   }else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
			m_mapViewer.moveSouth();
		submit();
}

function moveWest() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveWest();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveWest();
			submit();
}

function moveNorthEast() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveNorthEast();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		
		m_mapViewer.moveNorthEast();
			submit();
}

function moveSouthEast() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveSouthEast();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveSouthEast();
			submit();
}

function moveNorthWest() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveNorthWest();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveNorthWest();
			submit();
}

function moveSouthWest() {
	/*if (m_mapViewer.getLevel() < 8)
		{
			m_mapViewer.moveSouthWest();
			submit();
		}else{
			alert("Map is at full extent, first zoom and then try to pan");
		}*/
		m_mapViewer.moveSouthWest();
			submit();
}
function isfullextent(){
if (m_mapViewer.getExtent().getLeft()<= 413526.4589320373 && m_mapViewer.getExtent().getRight()>= 496444.6932705585){
 return false;
}
/*
m_hvMaxX-m_hvMinX
m_mapViewer.setExtent(new rect(413526.4589320373, 827662.9767839672, 496444.6932705585,909486.5809662043));
	submit();*/
}

function persistExtent() {
	m_hvMinX.value = m_mapViewer.getExtent().getLeft();
	m_hvMinY.value = m_mapViewer.getExtent().getBottom();
	m_hvMaxX.value = m_mapViewer.getExtent().getRight();
	m_hvMaxY.value = m_mapViewer.getExtent().getTop();
	/*alert("m_hvMinX.value = " + m_hvMinX.value);
	alert("m_hvMinY.value = " + m_hvMinY.value);
	alert("m_hvMaxX.value = " + m_hvMaxX.value);
	alert("m_hvMaxY.value = " + m_hvMaxY.value);*/
	
}

function posBorder() {
    if (m_sClientBrowserType == 'Netscape') { 
		m_divMapBorder.style.left = m_imgMapCanvas.offsetLeft - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
		m_divMapBorder.style.top = m_imgMapCanvas.offsetTop - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
	} else { // browser must be IE
		m_divMapBorder.style.left = m_imgMapCanvas.offsetLeft;
		m_divMapBorder.style.top = m_imgMapCanvas.offsetTop;
	}
		
    m_divMapBorder.style.width = m_imgMapCanvas.width;
    m_divMapBorder.style.height = m_imgMapCanvas.height;
    m_divMapBorder.style.visibility = "visible";

}

function posBorderNavigation() {

    var borderOffset = 0;    
    if (m_sClientBrowserType == 'Netscape') {
		borderOffset = parseInt(m_divMapBorder.style.borderWidth.replace('px','')) 
	}
   
          //align the NORTH DIV       
    m_divNorth.style.top = m_imgMapCanvas.offsetTop - (parseInt(m_divNorth.style.height.replace('px',''))) - borderOffset;
    m_divNorth.style.left = m_imgMapCanvas.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divNorth.style.width.replace('px','')) / 2);    

         //align the SOUTH DIV
    m_divSouth.style.top = m_imgMapCanvas.offsetTop + m_imgMapCanvas.height + borderOffset;
    m_divSouth.style.left = m_imgMapCanvas.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divSouth.style.width.replace('px','')) / 2);   
  
         //align the EAST DIV       
    m_divEast.style.top = m_imgMapCanvas.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divEast.style.height.replace('px','')) / 2));
    m_divEast.style.left = m_imgMapCanvas.offsetLeft + m_imgMapCanvas.width + borderOffset;    

         //align the WEST DIV       
    m_divWest.style.top = m_imgMapCanvas.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divWest.style.height.replace('px','')) / 2));
    m_divWest.style.left = m_imgMapCanvas.offsetLeft - (parseInt(m_divWest.style.width.replace('px',''))) - borderOffset;   
}

function posLoadingImage() {
    m_imgLoading.style.top = (parseInt(m_imgMapCanvas.style.top.replace('px','')) + (m_imgMapCanvas.height / 2) - (m_imgLoading.height / 2) );
    m_imgLoading.style.left = (parseInt(m_imgMapCanvas.style.left.replace('px','')) + (m_imgMapCanvas.width / 2) - (m_imgLoading.width / 2) );
}

function posTools() {
    m_divMapTools.style.top = parseInt(m_divSouth.style.top.replace('px','')) + parseInt(m_divSouth.style.height.replace('px',''));
    m_divMapTools.style.width = m_imgMapCanvas.width;
}

/*function reportCoords(ptReport) {
	// Note: Use round() instead of toFixed(), since the latter isn't supported
  //       in IE Mac.
	m_txtXCoord.value = "X: "+(Math.round(ptReport.x*10000.0)/10000.0).toString();
	m_txtYCoord.value = "Y: "+(Math.round(ptReport.y*10000.0)/10000.0).toString();
}*/

function returnActiveTool() {
	/*if (m_radZoomIn.checked) {
		return 1;
	} else if(m_radRecenter.checked) {
		return 2;
	}*/
	return 1;
}

function showWaitImage() {
	m_imgLoading.style.visibility = 'visible';
}

function zoomToLmk(xcoord,ycoord)
{
	m_mapViewer.recenter(new point(xcoord,ycoord));
	submit();
}
function ZoomToFullMap(){
/*
 <add key="DEFAULT_EXTENT_XMIN" value="385533.594190568" />
		<add key="DEFAULT_EXTENT_YMIN" value="2812137.75785003" />
		<add key="DEFAULT_EXTENT_XMAX" value="561421.783397002" />
		<add key="DEFAULT_EXTENT_YMAX" value="2944053.89975486" />
		*/
	//m_mapViewer.setExtent(new rect(385533.594190568, 2812137.75785003, 561421.783397002,2944053.89975486));
	m_mapViewer.setExtent(new rect(mapXMin, mapYMin, mapXMax,mapYMax));
	submit();
}
function submit() {

	// if we want to truly reflect the highlighted zoom level on map
	// otherwise, we can remove that line
	//m_mapViewer.setLevel(m_mapViewer.getLevel());
	//alert("level = " + m_mapViewer.getLevel());
	//debugger;
	//debugger;
	var sURL = m_hvMapPage.value+
		         "?XMIN="+m_mapViewer.getExtent().getLeft()+
				     "&YMIN="+m_mapViewer.getExtent().getBottom()+
						 "&XMAX="+m_mapViewer.getExtent().getRight()+
						 "&YMAX="+m_mapViewer.getExtent().getTop()+
						 "&WIDTH="+m_mapViewer.getTagWidth()+
						 "&HEIGHT="+m_mapViewer.getTagHeight()+
						 "&themes="+document.frmViewer.hvThemes.value;
	
	var sOURL = m_hvOverviewPage.value+
		         "?XMIN="+m_mapViewer.getExtent().getLeft()+
				     "&YMIN="+m_mapViewer.getExtent().getBottom()+
						 "&XMAX="+m_mapViewer.getExtent().getRight()+
						 "&YMAX="+m_mapViewer.getExtent().getTop()+
						 "&WIDTH=130"+
						 "&HEIGHT=130";
						 		 
	if (document.frmViewer.hvHighlightBy.value != "")
	{
		sURL = sURL + "&highlightby=" + document.frmViewer.hvHighlightBy.value + "&flds=" + document.frmViewer.hvFlds.value + "&label=" + document.frmViewer.hvLabel.value;
	}
	
	if (document.frmViewer.hvFindNearest.value != "")
	{
		sURL = sURL + "&findnearest=" + document.frmViewer.hvFindNearest.value;
	}
	if (document.frmViewer.hvRouteFiles.value != "")
	{
		sURL = sURL + "&routefiles=" + document.frmViewer.hvRouteFiles.value;
	}
	if (document.frmViewer.hvLayerIDs.value != "")
	{
		sURL = sURL + "&LayerIDs=" + document.frmViewer.hvLayerIDs.value;
	}
	if (document.frmViewer.hvLayerVisible.value != "")
	{
		sURL = sURL + "&LayerVisible=" + document.frmViewer.hvLayerVisible.value;
	}
	//alert("here");
	//updateZoomLevel(m_mapViewer.getLevel());
    
	showWaitImage();

	if (navigator.userAgent.indexOf('Netscape6/6') > -1) {
		m_lTimerID = setInterval("hideWaitImageForNetscape6();",100);
	}
	//alert(sURL);
	m_imgMapCanvas.src = sURL;
	//document.images["imgOverview"].src = sOURL;
	document.all["imgOverview"].src = sOURL;
	mapChanged = true;
	//if (legendTD.innerHTML != "")
	
	//if(legendPane.style.display == "block")
	//	refreshLegend();
		
   	//Persist extent in Hidden variables
   	//alert(Math.round(m_mapViewer.getLevelRect()));
   	var sliderL;
   	sliderL = Math.round(m_mapViewer.getLevelRect());
   	// commented by sunil A_SLIDERS[0].f_setValue(sliderL);
   	//alert("sliderL = " + sliderL);
   	HighlightZoomLevel(sliderL);
	//ZoomLevel(m_mapViewer.getLevel());
	persistExtent();
	refreshLayerList();
}

/*function updateImgMapSize(sSize) {
    m_imgMapSize = document.getElementById("imgMapSize");
    switch(sSize) { 
        case 'SMALL':
            m_imgMapSize.name = 'SMALL';
            m_imgMapSize.src= 'images/map/smallmap.gif';
        break;
        case 'LARGE':
            m_imgMapSize.name = 'LARGE';
            m_imgMapSize.src= 'images/map/largemap.gif';
        break;
    }
}

function updateZoomLevel(inLevel) {
        var nLevels = m_ExtentWidths.length;
		for (i=1;i<nLevels+1;i++) {
			document.getElementById('imgZoomLevel' + i).src = 'images/map/tick.gif';
			if (i==inLevel) {
			    document.getElementById('imgZoomLevel' + i).src = 'images/map/tick_selected.gif';
			}
		}
}*/
