// ----------------------------------------------------------------
//     				   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_radZoomIn;
    var m_radRecenter;
    var m_txtXCoord;
    var m_txtYCoord;
    var m_imgLoading;
    var m_imgMapCanvas;
    var m_divMapBorder;
    var m_divZoomBox;
	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_imgPan;
	var m_imgIdentify;
	var m_imgZoomIn;
	var m_imgZoomOut;
	var m_hvToolType;
	var m_x;
	var m_y;

	// 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	
				        //	identify = 3			

	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, 10);

	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 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");		' USED FOR COORDINATE REPORTING
	//m_txtYCoord = document.getElementById("txtYCoord");		' USED FOR COORDINATE REPORTING
	m_imgMapCanvas = document.getElementById("imgMapCanvas");
    m_imgLoading = document.getElementById("imgLoading");
	m_divZoomBox = document.getElementById("divZoomBox");
	m_divMapBorder = document.getElementById("divMapBorder");
  	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_imgPan = document.getElementById("imgPan");
	m_imgIdentify = document.getElementById("imgIdentify");
	m_hvToolType = document.getElementById("hvToolType");
	m_imgZoomIn = document.getElementById("imgZoomIn");
	m_imgZoomOut = document.getElementById("imgZoomOut");
	m_x = document.getElementById("x");
	m_y = document.getElementById("y");
	

	// ADJUST MAP IMAGE
/*	var width ;
	var adjust ;
	Width = document.body.offsetWidth ;
	adjust = ((Width - 800)/2)  ;
	document.getElementById('imgMapCanvas').style.left =  (adjust + 45) + 'px';
			
*/
		// 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);
   
        //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 tool mode. 
	handleToolClick(returnActiveTool());
		
	    // 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);
	}
	document.onmousedown = handleMouseDown;
	document.onmousemove = handleMouseMove;
	document.onmouseup = handleMouseUp;
	
	// Assign an event handler to the m_imgMapCanvas onload event.
	m_imgMapCanvas.onload = hideWaitImage;
	
	    //Request a map.
	submit();
}

// *******************************************************************
// *********************** EVENT HANDLERS  ***************************
// *******************************************************************

function handleMouseDown(evt) {

	// GET EVENT COORDINATES
	var eventX;
	var eventY;

	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		// ORIGINAL 
		//eventX = event.clientX;
		//eventY = event.clientY;
		// MANAGE X/Y LOCATION WHEN DOCUMENT IS BEING SCROLLED - REY
		eventX = event.clientX + document.body.scrollLeft;
		eventY = event.clientY + document.body.scrollTop ;
	}

	// CHECK TO SEE IS CLICK OVER MAP AREA
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 
	switch(m_iToolMode) {
		case 1: // zoom in mode
			if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
				m_imgMapCanvas.setCapture(); 
			}
			m_zbxZoom.show();
			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);
			//m_mapViewer.recenter(ptUserClick);
			m_x.value=ptUserClick.x;
			m_y.value=ptUserClick.y;
			//Request a new map.
			frmViewer.submit();
			break;
		case 4: // zoom out mode
			if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
				m_imgMapCanvas.setCapture(); 
			}
			m_zbxZoom.show();
			m_zbxZoom.start(eventX, eventY);
			break;			
		
	}
}

function handleMouseMove(evt) {
	var eventX;
	var eventY;

	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		// ORIGINAL 
		//eventX = event.clientX;
		//eventY = event.clientY;
		// MANAGE X/Y LOCATION WHEN DOCUMENT IS BEING SCROLLED - REY
		eventX = event.clientX + document.body.scrollLeft;
		eventY = event.clientY + document.body.scrollTop ;
	}

    // CHECK TO SEE IS CLICK OVER MAP AREA
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 		
	/*  HIDE REPORTING COORDINATES
	reportCoords(m_mapViewer.toMapPoint(eventX, eventY)); // update the textbox to reflect
	*/
																																												 // the current coordinates.
    // UPDATE ZOOMBOX
  if (m_iToolMode == 1 || m_iToolMode == 4) {
		if (m_zbxZoom.isInProgress) {
			m_zbxZoom.update(eventX, eventY);
		}
  }
}

function handleMouseUp(evt) {

	if (!(m_iToolMode == 1) && !(m_iToolMode == 4)) {
		return;
	}
	if (!(m_zbxZoom.isInProgress())) {
		return;
	}

	if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
		document.releaseCapture();
	}

	// STOP ZOOMBOX
	m_zbxZoom.stop();

	//HANDLE CLICK OR IF EVENT IS A SMALL 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);
		  m_mapViewer.recenter(ptUserClick);
		} 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
		}
		// Handle zoom in and out
		if (m_iToolMode == 1){
			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));
		}
		else if (m_iToolMode == 4){
			var zoomOutFactor;
			zoomOutFactor = 300;
			var ptStart = m_mapViewer.toMapPoint(m_zbxZoom.getStartX()+(borderWidth-zoomOutFactor), m_zbxZoom.getStartY()+(borderWidth-zoomOutFactor));
			var ptEnd   = m_mapViewer.toMapPoint(m_zbxZoom.getEndX()+(borderWidth+zoomOutFactor), m_zbxZoom.getEndY()+(borderWidth+zoomOutFactor));
			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
			m_imgMapCanvas.style.cursor = "crosshair";
			m_hvToolType.value = 1;
			m_imgZoomIn.src="images/zoomin_on.gif";
			m_imgIdentify.src="images/identify.gif";
			m_imgPan.src="images/pan.gif";
			m_imgZoomOut.src="images/zoomout.gif";
			break;
		case 2:
			// pan
			m_imgMapCanvas.style.cursor = "hand";
			m_hvToolType.value = 2;
			m_imgPan.src="images/pan_on.gif";
			m_imgIdentify.src="images/identify.gif";
			m_imgZoomIn.src="images/zoomin.gif";
			m_imgZoomOut.src="images/zoomout.gif";
			break;
		case 3:
			// identify
			m_imgMapCanvas.style.cursor = "help";
			m_hvToolType.value = 3;
			m_imgIdentify.src="images/identify_on.gif";
			m_imgPan.src="images/pan.gif";
			m_imgZoomIn.src="images/zoomin.gif";
			m_imgZoomOut.src="images/zoomout.gif";
			break;
		case 4:
			// zoom out
			m_imgMapCanvas.style.cursor = "crosshair";
			m_hvToolType.value = 4;
			m_imgZoomOut.src="images/zoomout_on.gif";
			m_imgZoomIn.src="images/zoomin.gif";
			m_imgIdentify.src="images/identify.gif";
			m_imgPan.src="images/pan.gif";
			break;
	}
	
	m_iToolMode = iToolMode;
}

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';
        break;
        case 'LARGE':
        m_imgMapCanvas.className = 'LargeMap';
        break;
        default: 
        return; // invalid sSize value
    }

        // Create a new map coordinate manager.
    m_mapViewer = new map(m_imgMapCanvas.offsetLeft,
  				    m_imgMapCanvas.offsetTop,
				    m_imgMapCanvas.width,	
				    m_imgMapCanvas.height,
					m_ExtentWidths,
				    m_mapViewer.getExtent()
				    );


        //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) {           
	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 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();
}

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 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 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();
}

/*
*******************	ORIGINAL ****************************
function returnActiveTool() {
	if (m_radZoomIn.checked) {
		return 1;
	} else if(m_radRecenter.checked) {
		return 2;
	}
}
*********************************************************
*/
function returnActiveTool() {
	// Maintain active tool
	var m_tool ;
	m_tool = m_hvToolType.value;
	//m_tool = m_hvTool.value;
	//alert(m_tool);
	if (m_tool == 1){
		return 1;			// zoom in
	}else if (m_tool == 2){
		return 2;			// recenter
	}else if (m_tool == 3){
		return 3;			// identify
	}else if (m_tool == 4){
		return 4;			// identify	
	}
	else {
		return 1;
	}
}

function showWaitImage() {
	m_imgLoading.style.visibility = 'visible';
}

function submit() {

	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();

  //updateZoomLevel(m_mapViewer.getLevel());
	showWaitImage();

	if (navigator.userAgent.indexOf('Netscape6/6') > -1) {
		m_lTimerID = setInterval("hideWaitImageForNetscape6();",100);
	}

  m_imgMapCanvas.src = sURL;

  persistExtent();	

}

function updateImgMapSize(sSize) {
    m_imgMapSize = document.getElementById("imgMapSize");
    switch(sSize) { 
        case 'SMALL':
            m_imgMapSize.name = 'SMALL';
            m_imgMapSize.src= 'images/smallmap.gif';
        break;
        case 'LARGE':
            m_imgMapSize.name = 'LARGE';
            m_imgMapSize.src= 'images/largemap.gif';
        break;
    }
}

function updateZoomLevel(inLevel) {
        var nLevels = m_ExtentWidths.length;
		for (i=1;i<nLevels+1;i++) {
			document.getElementById('imgZoomLevel' + i).src = 'images/tick.gif';
			if (i==inLevel) {
			    document.getElementById('imgZoomLevel' + i).src = 'images/tick_selected.gif';
			}
		}
}
