//==============================
// GLOBAL Variables
//==============================
var IE = document.all?true:false;   // Browser test script
var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false; // Test for IE7
var myTimeOut;						// used for pausing the resize event so it only fires once for a drag/resize
var mydebug = "";
var debugText = "";					// string used to fill the debug Textarea
var iObj = new Object();            // will be used if the user resizes the identify box.
var gpsLatList = "";                // list of gps lat pts to download
var gpsLonList = "";                // list of gps lon pts to download
var accord;							// Rico accordion variable

// These variables are set to their actual values in the initializeVars function
var mapContainer = null;			// pointer to the main MapContainer DIV
var glassSheetLayer = null;			// pointer to the glassSheetLayer DIV control
var zoomInBox = null;				// pointer to the zoomInBox DIV control
var actualMapImage = null;			// pointer to the actualMapImage IMG control
var tempPanMapImage = null;			// pointer to the image used to reduce image jump and flicker
var statusBar = null;				// pointer to the status bar below the map image
var drawingSpaceTop = 0;			// offset of the DIV to allow zero-based pan and zoom calculations
var drawingSpaceLeft = 0;			// offset of the DIV to allow zero-based pan and zoom calculations
var drawingSpaceHeight = 0;			// for calculations when resizing the image and AXL envelope
var drawingSpaceWidth = 0;			// for calculations when resizing the image and AXL envelope

var headerHeight = 0;
var toolBarHeight = 0;
var footerHeight = 0;
var accordionWidth = 0;
var selectedHeader = "legendHeader";

var mouseX = 0;						// coords of current mouse location when it's being tracked
var mouseY = 0;						// coords of current mouse location when it's being tracked
var mouseDownX = 0;					// original place of click hold
var mouseDownY = 0;					// original place of click hold

var leftOffset;
var rightOffset;
var topOffset;
var bottomOffset;

var cursor = "default";
var cursorBody = "";
var cursorMapContainer = "";
var cursorGlassSheet = "";
var mouseCursor = "";				// used to switch to a Wait cursor while getting new map and then return to current cursor
var mouseWaitCursor = "wait";

var mdFunction = null;				// mousedown function
var mmFunction = null;				// mousemove function
var muFunction = null;				// mouseup function

var mouseButtonDown = false;		// used when zooming in

var envMinX = 0;					// current AXL envelope
var envMaxX = 0;					// current AXL envelope
var envMinY = 0;					// current AXL envelope
var envMaxY = 0;					// current AXL envelope
var envWidth = 0;					// current AXL envelope
var envHeight = 0;					// current AXL envelope

var selectedTool = null;			// which tool is being used: zoom, pan, add...
var prevSelectedTool = null;		// used to hold the previous selectedTool when we are using a 'single use' tool like ZoomFullExtent.  After we finish with singleUse, revert back to the previous Tool

var imgDotClear = new Image();  imgDotClear.src = "images/dot_Clear.gif";

var background = null;				// Used in defaultPage.js to manage the background radio buttons

var airShed = "";
var naCO = "";
var naLead = "";
var naPM10 = "";
var naSO2 = "";

var prevQuery = "";

var nonGameType = "";
var nonGameCategory = "";
var nonGameLayerId = "";
var elCode = "";
var commonName = "";
var currentNonGame = "";
var prevNonGame = "";

var fishDistType = "";
var currentFishDistType = "";
var prevFishDistType = "";

var aTab = "base";					// Used in defaultPage.js to set the initial active tab in Custimize Map accordion window
var selectedQuality = "?80";		// Used in defaultPags.js to set the quality of the image to return.

var checkBoxes = "hillshade|topo|doqq|naip|landcover|dem|" + 
    "cadastral|cadastrallabels|plss|plsslabels|township|townshiplabels|town|" + 
    "roads|roadslabels|stream|streamlabels|lakes|lakeslabels|" + 
    "reservoir|reservoirlabels|dam|damlabels|diversion|diversionlabels|placeofuse|placeofuselabels|" + 
    "ssurgosoil|aquarodstations|bankerosionpoint|" + 
    "channelintersection|bhdiversion|headgates|naturalobstructions|otherfeature|photos|pools|" + 
    "riffles|staffgages|bankerosionline|bankprotection|berms|ccaamanagementareas|" + 
    "beaverdamsfwp|bigholegrazingdiversions|bridgesfwp|crossingsfwp|culvertsfwp|debrisfwp|" + 
    "diversionsfwp|headgatesfwp|livestockstructuresfwp|streambankconditionfwp|" + 
    "christianseneastbenchdiversions|circle3ranchdiversions|clemansdiversions|cornellranchesdiversions|" +
    "diamondonediversions|dickhirschycattleinc|doolinglivestockdiversion|erblivestock|" +
    "finchranchesdiversions|fishtrapcreekranch|fostercompanydiversions|fredandlynnhirschy|" +
    "harringtoncodiversions|hlazyjranch|huntleyranchdiversions|hustedranchesdiversions|" +
    "jackhirschydiversions|jacksonranchesdiversions|jcranchesdiversions|johnnelsondiversions|" +  
    "johnsonbrothersdiversions|lamarchecreekranchdiversions|laphamranchco|petersonbroscattleco|" + 
    "quartercircle3tranchdiversions|ralstonranchinc|rasmussendiversions|reinhardtranchco|" + 
    "robertneilldiversions|rockymountainranchesinc|sitzangusfarmsdiversions|steelcreekranch|" + 
    "strodtmantrustdiversions|weaverranch|wisdomriverdiversions|wuestefamilylimitedpartnership";

var chkBoxes = checkBoxes.split("|");

var layers = "hillshade|topo250k,topo100k,topo24k|doqq|naip|landcover|dem|" + 
    "cadastral|cadastrallabels|plss|plsslabels|township|townshiplabels|town|" + 
    "highways,tgrroad|highwayslabels,tgrroadlabels|stream|streamlabels|lakes|lakeslabels|" + 
    "reservoir|reservoirlabels|dam|damlabels|diversion|diversionlabels|placeofuse|placeofuselabels|" + 
    "ssurgosoil|aquarodstations|bankerosionpoint|" + 
    "channelintersection|bhdiversion|headgates|naturalobstructions|otherfeature|photos|pools|" + 
    "riffles|staffgages|bankerosionline|bankprotection|berms|ccaamanagementareas|" + 
    "beaverdamsfwp|bigholegrazingdiversions|bridgesfwp|crossingsfwp|culvertsfwp|debrisfwp|" + 
    "diversionsfwp|headgatesfwp|livestockstructuresfwp|streambankconditionfwp|" + 
    "christianseneastbenchdiversions|circle3ranchdiversions|clemansdiversions|cornellranchesdiversions|" + 
    "diamondonediversions|dickhirschycattleinc|doolinglivestockdiversion|erblivestock|" + 
    "finchranchesdiversions|fishtrapcreekranch|fostercompanydiversions|fredandlynnhirschy|" +
    "harringtoncodiversions|hlazyjranch|huntleyranchdiversions|hustedranchesdiversions|" +
    "jackhirschydiversions|jacksonranchesdiversions|jcranchesdiversions|johnnelsondiversions|" +
    "johnsonbrothersdiversions|lamarchecreekranchdiversions|laphamranchco|petersonbroscattleco|" +
    "quartercircle3tranchdiversions|ralstonranchinc|rasmussendiversions|reinhardtranchco|" + 
    "robertneilldiversions|rockymountainranchesinc|sitzangusfarmsdiversions|steelcreekranch|" + 
    "strodtmantrustdiversions|weaverranch|wisdomriverdiversions|wuestefamilylimitedpartnership";

var chkLayers = layers.split("|");


//--END Global Variables---------------------------------------------------

function initializeVars()
{
    var browserName = navigator.appName;
    var browserVer = parseInt(navigator.appVersion);
    
	// Initialize some of the global variables that require the full page to be loaded first
	mapContainer = document.getElementById("MapContainer");
	glassSheetLayer = document.getElementById("glassSheetLayer");
	zoomInBox = document.getElementById("zoomInBox");
	actualMapImage = document.getElementById("actualMapImage");
	tempPanMapImage = document.getElementById("tempPanMapImage");
	
	headerHeight = document.getElementById("header").offsetHeight;
	toolBarHeight = document.getElementById("toolBar").offsetHeight;
	footerHeight = document.getElementById("footer").offsetHeight;
		
	// I am just hardcoding the width for now because of the way the accordion works. Can't get
	// the width.
	accordionWidth = "210";
	//alert(headerHeight + "," + footerHeight + "," + accordionWidth);
	//alert(document.getElementById("textArea").offsetWidth);
	
	// Set the offsets for drawing the zoombox in mapFunctions.js
    if (IE)
    {
        leftOffset = -2;
        topOffset = -2;
        rightOffset = -3;
        bottomOffset = -1;
    }
    else // Netscape
    {
        leftOffset = -1;
        topOffset = -1;
        rightOffset = -1;
        bottomOffset = -1;	
    }
    
    // Set check boxes for visible layers
    setLayerCheckBoxes();
    
    // Set the initial image quality to low
	setImageQuality(selectedQuality);
}


/*  Called from initializeVars to set check boxes for visible layers
*/
function setLayerCheckBoxes()
{
    BigHole.Map.SetLayerChkBoxes(setLayerChkBoxes_callback);
}


/*	When the page loads, progressBar.js creates the html for the progress bar. This function loads
	the html into the waitDiv.
*/
function progressBarLoad(){
	document.getElementById("waitDiv").innerHTML = txt;
}


/*	Called anytime the page loads. Sets the Accordion control and performs other functions.
*/
function windowLoaded() {
	
	// Position and size the help box
	formatBoxes();
	
	// Populate the identify drop down list with active vector layers
	filterIdentifyList();
	
	// Set up the accordion and override properties as necessary
	accord = new Rico.Accordion( $('accordionDiv'), 
	    {
	        panelHeight:drawingSpaceHeight - 90,
	        expandedBgImg:'./images/accordionexpanded.gif',
	        expandedHoverTextColor:'#ffffff',
	        collapsedBgImg:'./images/accordioncollapsed.gif',
	        collapsedTextColor:'#5F837E',
	        collapsedFontWeight:'bold',
	        collapsedHoverTextColor:'#5F837E'
	    } );
}


/*	I used this timeout routine to keep from calling the resize function too quickly/often.
	Say that the user is slowly dragging the size of their browser window, 
	I don't want to generate 20 arcims requests for new maps.
	Rather with this timeout, I will keep resetting the clock as they drag the screen, 
	and ### miliseconds after they finish resizing, it will send the map request.
*/
function waitForResize()
{
	clearTimeout(myTimeOut);
	myTimeOut = setTimeout('executeResize();resizeControls();', 500);
}


/*	Called primarily from waitForResize to resize the window anytime the user resizes the window.
	Also called from the onload event from the page body. This essentially determines the size of the 
	window, sets the drawing space to that size, and determines what size image to ask for.
*/
function executeResize()
{
    // Get the height and width of the window.
	if (IE)
	{
	    if (ie7)
	    {
	        //  When the window width is resized smaller in ie7, the bottom scrollbar(17px) is included in the 
	        //  clientHeight. In this case, we can use drawingSpaceHeight.style.height
	        if ((document.documentElement.clientHeight < 
	            parseInt(document.getElementById("drawingSpace").style.height.replace("px",""))) && 
	            document.getElementById("drawingSpace").style.height != 0)
	        {
	            drawingSpaceHeight = parseInt(document.documentElement.clientHeight) + 17 - headerHeight - toolBarHeight - footerHeight;
	        }
	        else
	        {    
	            drawingSpaceHeight = document.documentElement.clientHeight - headerHeight - toolBarHeight - footerHeight;	        
	        }
	    }
	    else // Other version of IE
	    {
	        //drawingSpaceHeight = document.body.offsetHeight - headerHeight - toolBarHeight - footerHeight;
	        // In IE6 you have to figure for the width of the scrollbar when you resize the window narrower. The 
	        // scrollbar width is 17px so add it on and the window is perfect height.
	        if ((document.body.offsetWidth - accordionWidth) < drawingSpaceWidth)
	        {
	            drawingSpaceHeight = document.documentElement.clientHeight - headerHeight - toolBarHeight - footerHeight + 17;
	        }
	        else
	        {
	            drawingSpaceHeight = document.documentElement.clientHeight - headerHeight - toolBarHeight - footerHeight;
	        }
	    }
	    drawingSpaceWidth = document.body.offsetWidth - accordionWidth;
	}
	else // Firefox
	{
		//drawingSpaceHeight = window.innerHeight-2 - headerHeight - toolBarHeight - footerHeight;
		drawingSpaceHeight = window.innerHeight - headerHeight - toolBarHeight - footerHeight;
		drawingSpaceWidth = window.innerWidth - accordionWidth;
	}
	
	// We need to size the left panel now so that the accordion will have enough room
	document.getElementById("leftPanel").style.height = drawingSpaceHeight;	
	
	// Display and position the footer and set height of accordion.
	document.getElementById("footer").style.top = drawingSpaceHeight + headerHeight + toolBarHeight + "px";
	// Now that we have the new window size, we can start the progressbar
	setWaitCursor();
	// Get the location of the drawing space
	drawingSpaceTop = document.getElementById("MapContainer").offsetTop;
	// Set the height of the drawingSpace div
	document.getElementById("drawingSpace").style.height = drawingSpaceHeight + "px";
	// Set the width of the drawingSpace div
	document.getElementById("drawingSpace").style.width = drawingSpaceWidth + "px";
	// update the global vars for the new drawingSpace div
	var ds = document.getElementById("MapContainer");
	drawingSpaceTop = ds.offsetTop;
	drawingSpaceLeft = ds.offsetLeft;
	
//	mydebug += "resizing\n";
//	mydebug += "W/H=" + drawingSpaceWidth + ":" + drawingSpaceHeight + "\n";
//	document.getElementById('textArea').value = mydebug;
	// Call the Ajax function to get a new map image
	// (use the panzoom function with the zoom box equal to the canvas size)
	// BigHole.Map.PanZoomMap(drawingSpaceWidth, drawingSpaceHeight, 0, 0, drawingSpaceWidth, drawingSpaceHeight, quickChangeMapImage_callback);
	//alert(drawingSpaceWidth + "," + drawingSpaceHeight);
	BigHole.Map.PanZoomMap(drawingSpaceWidth, drawingSpaceHeight, 0, 0, drawingSpaceWidth, drawingSpaceHeight, changeMapImage_callback);
    //setNormalCursor();
}


/*	Called explicitly from the waitForResize function to resize the accordion anytime the 
	user resizes the map window.
*/
function resizeControls(){
	// Resize help box
	formatBoxes();
	
	// Resize the accordion control to the height of the drawingspace
	accord.options.panelHeight = drawingSpaceHeight - 90;
	accord.lastExpandedTab.content.style.height = (accord.options.panelHeight) + 'px';
	
	
}


/*	Called anytime the user selects a tool in the user interface. Sets up eventlisteners and turns
	tools on and off.
*/
function selectTool(tool){

	// If a(ny) tool was used previously, we need to remove the event listeners that were assigned to it
	// This will only happen if a tool is selected
	detachEventListener("glassSheetLayer", "onmousedown", mdFunction);		
	detachEventListener("glassSheetLayer", "onmousemove", mmFunction);
	detachEventListener("glassSheetLayer", "onmouseup", muFunction);
	
	// In NS this prevents cascading events, allowing user to drag the mouse during pan/zoom 
	// without hilighting text on other parts of the page.
	document.onmousedown = falsefunc;
	document.onmouseup = falsefunc;
	
	switch(tool){
	
		case 'zoomin':
			document.getElementById('zoomin').src = "images/zoominactive.gif";
			selectedTool = "zoomin";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "zoomin";
			cursor = "crosshair";
			
			mdFunction = zoomInMouseDown; 
			mmFunction = zoomInMouseMove; 
			muFunction = zoomInMouseUp;
			
			attachEventListener("glassSheetLayer", "onmousedown", mdFunction);
			attachEventListener("glassSheetLayer", "onmousemove", mmFunction);
			attachEventListener("glassSheetLayer", "onmouseup", muFunction);
			
			break;
		case 'zoomout':
			document.getElementById('zoomout').src = "images/zoomoutactive.gif";
			selectedTool = "zoomout";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "zoomout";
			cursor = "default";
			
			mdFunction = zoomOutMouseDown;
			muFunction = zoomOutMouseUp;
			
			attachEventListener("glassSheetLayer", "onmousedown", mdFunction);
			attachEventListener("glassSheetLayer", "onmouseup", muFunction);
			
			break;
		case 'pan':
			document.getElementById('pan').src = "images/panactive.gif";
			selectedTool = "pan";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "pan";
			cursor = "move";
			
			mdFunction = panMouseDown;
			mmFunction = panMouseMove;
			muFunction = panMouseUp;
			
			attachEventListener("glassSheetLayer", "onmousedown", mdFunction);
			attachEventListener("glassSheetLayer", "onmousemove", mmFunction);
			attachEventListener("glassSheetLayer", "onmouseup", muFunction);
			
			break;
		case 'fullextent':
			setWaitCursor();
			document.getElementById('fullextent').src = "images/fullextentactive.gif";
			selectedTool = "fullextent";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "fullextent";
			cursor = "default";
			GoToFullExtent();
			document.getElementById('fullextent').src = "images/fullextent.gif";
			break;
	    case 'layerreset':
			setWaitCursor();
			document.getElementById('layerreset').src = "images/layerresetactive.gif";
			selectedTool = "layerreset";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "layerreset";
			cursor = "default";
			ResetLayers();
			document.getElementById('layerreset').src = "images/layerreset.gif";
			break;
		case 'identify':
		    var sid = document.getElementById('selectIdentify');
		    if (sid.options.length == 0)
		    {
	            document.getElementById("selectIdentify").options.add(new Option("No Layers Available"), 0);
		    }
		    document.getElementById('identify').src = "images/identifyactive.gif";
	        selectedTool = "identify";
	        deSelectTool(prevSelectedTool);
	        prevSelectedTool = "identify";
	        cursor = "help";
			
	        mdFunction = identifyMouseDown;
	        muFunction = identifyMouseUp;
			
	        attachEventListener("glassSheetLayer", "onmousedown", mdFunction);
	        attachEventListener("glassSheetLayer", "onmouseup", muFunction);
		    
	        document.getElementById("identifyList").style.display = "block";
			break;
		case 'gps':
			document.getElementById('gps').src = "images/gpsactive.gif";
			selectedTool = "gps";
			deSelectTool(prevSelectedTool);
			prevSelectedTool = "gps";
			cursor = "default";
			
			muFunction = gpsMouseUp;
			
			attachEventListener("glassSheetLayer", "onmouseup", muFunction);
			
			// Each time the user clicks on the GPS button, reset all params
			gpsLonList = "";
            gpsLatList = "";
    		gslObj = document.getElementById("glassSheetLayer");
            gslObj.innerHTML = "";
			
			document.getElementById("gpsUpload").style.display = "block";
			break;
		default:
		    selectedTool = null;
		    deSelectTool(prevSelectedTool);
			break;
	}
	
	// Set the cursor based on the browser type
	glassSheetLayer.style.cursor = cursor;

	// Set focus to the glassSheetLayer
	glassSheetLayer.focus;
	glassSheetLayer.style.zIndex = 1000;
}


/*	Called from selectTool function to set the image of the now inactive tool.
    If you pass null to this function, any previously selected tool will be deselected.
*/
function deSelectTool(tool){
	if (prevSelectedTool != selectedTool){
		switch(tool){
			case 'zoomin':
				document.getElementById('zoomin').src = "images/zoomin.gif";
				break;
			case 'zoomout':
				document.getElementById('zoomout').src = "images/zoomout.gif";
				break;
			case 'pan':
				document.getElementById('pan').src = "images/pan.gif";
				break;
			case 'fullextent':
			    document.getElementById('fullextent').src = "images/fullextent.gif";
				break;
			case 'identify':
				document.getElementById('identify').src = "images/identify.gif";
				document.getElementById("identifyList").style.display = "none";
				break;
			case 'gps':
				document.getElementById('gps').src = "images/gps.gif";
				document.getElementById("gpsUpload").style.display = "none";
				break;
		}
	}
}

/*	Called from selectTool function to attach (add) an event listener to an object
	Accepts target object id as string, event as string, function as function
	Sample syntax: attachEventListener("canvas","onmouseover", fooFunc);
*/
function attachEventListener(sTargetObj, sEvent, fFunction)
{
	// Get the targetObj from the id string
	var targetObj = document.getElementById(sTargetObj);

	// Check browser before attaching
	if (IE)
	{
		// Attach the event listener
		targetObj.attachEvent(sEvent, fFunction);
	}
	else
	{
		// If not IE, we need to translate the event names
		sEvent = sEvent.replace("on", "");

		// Attach the event listener
		targetObj.addEventListener(sEvent, fFunction, false);
	}
}


/*	Called from selectTool function to detach (remove) an event listener from an object
	Accepts target object id as string, event as string, function as function
	Sample syntax: detachEventListener("canvas","onmouseover", fooFunc);
*/
function detachEventListener(sTargetObj, sEvent, fFunction)
{
	// Get the targetObj from the id string
	var targetObj = document.getElementById(sTargetObj);

	// Check browser before removing
	if (IE)
	{
		// Remove the event listener
		targetObj.detachEvent(sEvent, fFunction);
	}
	else
	{
		// If not IE, we need to remove "on" from the event names
		sEvent = sEvent.replace("on", "");

		// Remove the event listener
		targetObj.removeEventListener(sEvent, fFunction, false);
	}
}


/*	When the user clicks one of the three major background buttons, turn that layer on and turn the 
	others off. We only display one of these at a time.
*/
function ChangeBackground(button)
{
	switch (button)
	{
		case "topo":
			if (document.getElementById('topo').checked == true && background == "topo")
			{
				document.getElementById('topo').checked = false;
				background = "";
			}
			else
			{
				document.getElementById('topo').checked = true;
				background = "topo";
			}
			document.getElementById('doqq').checked = false;
			document.getElementById('naip').checked = false;
			document.getElementById('dem').checked = false;
			document.getElementById('landcover').checked = false;
			break;
		case "doqq":
			document.getElementById('topo').checked = false;
			if (document.getElementById('doqq').checked == true && background == "doqq")
			{
				document.getElementById('doqq').checked = false;
				background = "";
			}
			else
			{
				document.getElementById('doqq').checked = true
				background = "doqq";
			}
			document.getElementById('naip').checked = false;
			document.getElementById('dem').checked = false;
			document.getElementById('landcover').checked = false;
			break;
	    case "naip":
			document.getElementById('topo').checked = false;
			document.getElementById('doqq').checked = false;
			if (document.getElementById('naip').checked == true && background == "naip")
			{
				document.getElementById('naip').checked = false;
				background = "";
			}
			else
			{
				document.getElementById('naip').checked = true
				background = "naip";
			}
			document.getElementById('dem').checked = false;
			document.getElementById('landcover').checked = false;
			break;
		case "dem":
			document.getElementById('topo').checked = false;
			document.getElementById('doqq').checked = false;
			document.getElementById('naip').checked = false;
			if (document.getElementById('dem').checked == true && background == "dem")
			{
				document.getElementById('dem').checked = false;
				background = "";
			}
			else
			{
				document.getElementById('dem').checked = true;
				background = "dem";
			}
			document.getElementById('landcover').checked = false;
			break;	
		case "landcover":
			document.getElementById('topo').checked = false;
			document.getElementById('doqq').checked = false;
			document.getElementById('naip').checked = false;
			document.getElementById('dem').checked = false;
			if (document.getElementById('landcover').checked == true && background == "landcover")
			{
				document.getElementById('landcover').checked = false;
				background = "";
			}
			else
			{
				document.getElementById('landcover').checked = true;
				background = "landcover";
			}
			break;
	}
}


/*	changeMapLayer is called when a user selects a layer from the Customize Map accordion tab. It determines
	which layers the user wants to display and then calls the server side ajax method ToggleLayers to get a 
	new map with the correct layers drawn. Three variables are passed in: 1)chkId - the id of 
	the checkbox control. 2)label - does the layer have labels that can be toggled on and off. 
	3)labelOn - if you can toggle the labels, are they on by default.
*/
function changeMapLayer(chkId, label, labelOn)
{
    setWaitCursor();
    
    // String variable to hold layers
	var layerList = "";
	
    for (i=0;i<chkBoxes.length;i++)
    {
        if (label && (chkBoxes[i] == chkId))
        {
            if (document.getElementById(chkBoxes[i]).checked == true)
            {
                layerList += getLayerList(i,"true",false);
                
                if (labelOn)
                {
                    document.getElementById(chkBoxes[i] + "labels").disabled = "";
                    document.getElementById(chkBoxes[i] + "labels").checked = true;
                    layerList += getLayerList(i,"true",true);
                }
                else
                {
                    layerList += getLayerList(i,"false",true);
                    document.getElementById(chkBoxes[i] + "labels").disabled = "";
                }
            }
            else
            {
                layerList += getLayerList(i,"false",false);
                
                document.getElementById(chkBoxes[i] + "labels").disabled = "disabled";
                document.getElementById(chkBoxes[i] + "labels").checked = false;
                layerList += getLayerList(i,"false",true);
            }
        }
        else
        {
            if (document.getElementById(chkBoxes[i]).checked == true)
            {
                layerList += getLayerList(i,"true",false);
            }
            else
            {
                layerList += getLayerList(i,"false",false);
            }
        }
    }

	BigHole.Map.ToggleLayers(layerList, changeMapImage_callback);
	
	// Populate the identify drop down list with active vector layers
	filterIdentifyList();
}


function getLayerList(index, visible, label)
{
    // String variable to hold layers
	var layers = "";
	
    var aLayer = chkLayers[index].split(",");
    
    if (label)
    {
        for (t=0;t<aLayer.length;t++)
        {
            layers += aLayer[t] + "labels," + visible + "|";
        }
    }
    else
    {
        for (t=0;t<aLayer.length;t++)
        {
            layers += aLayer[t] + "," + visible + "|";
        }
    }
    
    return layers;
}


/*  called when user clicks a checkbox for a acetate layer.
*/
function toggleAcetateLayer(chkbox)
{
    setWaitCursor();

    var display;
    
    if(document.getElementById(chkbox).checked == true){
		display = "true";
	}
	else{
		display = "false";
	}
	
	BigHole.Map.ToggleAcetateLayers(chkbox, display, changeMapImage_callback);
}


/*  called when a user wants to turn off or on the labels for a gps theme.
*/
function showGPSThemeLabels(chkbox, themeid)
{
    setWaitCursor();
	
	// var species = document.getElementById("ddlSpecies").value;
	
	var display;
	
	if(chkbox.checked == true){
		display = "true";		
	}
	else{
		display = "false";
	}
	
	// BigHole.Map.ToggleAcetateLayers("gpstheme" + themeid + "," + display, quickChangeMapImage_callback);
	BigHole.Map.ToggleAcetateLayers("labels" + themeid, display, changeMapImage_callback);
}


/*	Called anytime we go for a new map. Sets the cursor style and positions and starts the progress bar.
*/
function setWaitCursor()
{
	// The next three lines control the waitDiv which shows a looping progress bar.
	document.getElementById('waitDiv').style.left = (drawingSpaceWidth/2 - 50) + "px";
	document.getElementById('waitDiv').style.top = (drawingSpaceHeight/2 - 12) + "px";
	StartBar();
	
	// Set the cursor style
	document.body.style.cursor = "wait";
	mapContainer.style.cursor = "wait";
	glassSheetLayer.style.cursor = "wait";
}


/*	When the new map is done redrawing, set the cursor style back to the original and stop the progress bar.
*/
function setNormalCursor()
{
	// Back to normal cursor
	document.body.style.cursor = cursor;
	mapContainer.style.cursor = cursor;
	glassSheetLayer.style.cursor = cursor;

	// Stop the progress bar.
	StopBar();
}


/*	This mammoth function sets the scale bar on the page. I modeled this after the really sweet
	Google scale bar. Works fine but needs some refinement. Consists of a set of divs on the page
	which all contain a image called scale.png which I got from google. I take the envelope width,
	divide it by the drawingspacewidth to get pixels/meter. I then perform a series of if...else if
	statements to determine how to size it. It is this part that needs refinement because at some
	scales it is a little wide.
*/
function SetScale(scale)
{
	var parentScale = document.getElementById('parentScale');
	var child1Scale = document.getElementById('child1Scale');
	var child2Scale = document.getElementById('child2Scale');
	var englishScale = document.getElementById('englishScale');
	var metricScale = document.getElementById('metricScale');
	var englishText = document.getElementById('englishText');
	var metricText = document.getElementById('metricText');
	
	// pixels/meter
	var pixelSize = envWidth/drawingSpaceWidth;
	
	//var eLeft = englishScale.style.left.substring(0,englishScale.style.left.length - 2);
	//var mLeft = metricScale.style.left.substring(0,metricScale.style.left.length - 2);
	
	var e = ((100*pixelSize*100)/2.54)/12/3;
	var m = 100*pixelSize;
	
	if (m <= 250000 && m >= 150000){
		var eW = 160934.4/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "100 miles";
		
		var mW = 200000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "200 km";
	}
	else if(m < 150000 && m >= 75000){
		var eW = 80467.2/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "50 miles";
		
		var mW = 100000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "100 km";
	}
	else if(m < 75000 && m >= 35000){
		var eW = 32186.88/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "20 miles";
		
		var mW = 50000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "50 km";
	}
	else if(m < 35000 && m >= 15000){
		var eW = 16093.44/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "10 miles";
		
		var mW = 20000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "20 km";
	}
	else if(m < 15000 && m >= 7500){
		var eW = 8046.72/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "5 miles";
		
		var mW = 10000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "10 km";
	}
	else if(m < 7500 && m >= 3500){
		var eW = 3218.688/pixelSize;
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "2 miles";
		
		var mW = 5000/pixelSize;
		parentScale.style.width = mW + 4 + "px";
		child1Scale.style.width = mW + 1 + "px";
		child2Scale.style.left = mW + 3 + "px";
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "5 km";
	}
	else if(m < 3500 && m >= 1500){
		var eW = 3218.688/pixelSize;
		parentScale.style.width = eW + 4 + "px";
		child1Scale.style.width = eW + 1 + "px";
		child2Scale.style.left = eW + 3 + "px";
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "2 miles";
		
		var mW = 2000/pixelSize;
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "2 km";
	}
	else if(m < 1500 && m >= 750){
		if (pixelSize < 6)
		{
			var eW = 1609.344/pixelSize;
			parentScale.style.width = eW + 4 + "px";
			child1Scale.style.width = eW + 1 + "px";
			child2Scale.style.left = eW + 3 + "px";
			englishScale.style.left = eW + "px";
			englishText.innerHTML = "1 mile";
			
			var mW = 1000/pixelSize;
			metricScale.style.left = mW + "px";
			metricText.innerHTML = "1 km";
		}
		else{
			var eW = 609.599/pixelSize;
			parentScale.style.width = eW + 4 + "px";
			child1Scale.style.width = eW + 1 + "px";
			child2Scale.style.left = eW + 3 + "px";
			englishScale.style.left = eW + "px";
			englishText.innerHTML = "2000 ft";
			
			var mW = 500/pixelSize;
			metricScale.style.left = mW + "px";
			metricText.innerHTML = "500 m";
		}
	}
	else if(m < 750 && m >= 350){
		var eW = 609.599/pixelSize;
		parentScale.style.width = eW + 4 + "px";
		child1Scale.style.width = eW + 1 + "px";
		child2Scale.style.left = eW + 3 + "px";
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "2000 ft";
		
		var mW = 500/pixelSize;
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "500 m";
	}
	else if(m < 350 && m >= 150){
		var eW = 304.799/pixelSize;
		parentScale.style.width = eW + 4 + "px";
		child1Scale.style.width = eW + 1 + "px";
		child2Scale.style.left = eW + 3 + "px";
		englishScale.style.left = eW + "px";
		englishText.innerHTML = "1000 ft";
		
		var mW = 200/pixelSize;
		metricScale.style.left = mW + "px";
		metricText.innerHTML = "200 m";
	}
	else if(m < 150 && m >= 0){
		if (pixelSize > 1){
			var eW = 60.96/pixelSize;
			englishScale.style.left = eW + "px";
			englishText.innerHTML = "200 ft";
			
			var mW = 100/pixelSize;
			parentScale.style.width = mW + 4 + "px";
			child1Scale.style.width = mW + 1 + "px";
			child2Scale.style.left = mW + 3 + "px";
			metricScale.style.left = mW + "px";
			metricText.innerHTML = "100 m";
		}
		else{
			var eW = 60.96/pixelSize;
			parentScale.style.width = eW + 4 + "px";
			child1Scale.style.width = eW + 1 + "px";
			child2Scale.style.left = eW + 3 + "px";
			englishScale.style.left = eW + "px";
			englishText.innerHTML = "200 ft";
			
			var mW = 50/pixelSize;
			metricScale.style.left = mW + "px";
			metricText.innerHTML = "50 m";
		}
	}		
	
	// Don't display the scale until all parameters set
	document.getElementById('parentScale').style.display = "block";
	
	if(scale != "" && scale != null)
	{
	    document.getElementById('mapScale').innerHTML = "Map Scale: " + scale;
	}
	document.getElementById('mapScale').style.display = "block";
	
	//document.getElementById('textArea').value = "m: " + m + "  pixelSize: " + pixelSize;
}


/*	This function called when a user clicks on a tab in the Customize Map accordion window. It sets the 
	class of the active tab and sets the display property of the content div for that tab.
*/
function swapContent(divID){
	var li = document.getElementById(divID);
	var content = document.getElementById(divID + "Content");
	
	content.style.display = "block";
	li.className = "tabActive";
	
	if (aTab != "" && aTab != divID)
	{
		deactivateTab(aTab);
	}
	
	aTab = divID;
}
/*	Called from the swapContent function above to set the style on the now previously active tab back 
	to the default style and also sets the display property of the content div for that tab.
*/
function deactivateTab(tab){
	var li = document.getElementById(tab);
	li.className = "tabInactive";
	
	var content = document.getElementById(tab + "Content");
	content.style.display = "none";
}


/*	Called when the user clicks on one of the image quality tools.
*/
function setImageQuality(q){
	var Hres = document.getElementById("reshigh2");
	var Mres = document.getElementById("resmed2");
	var Lres = document.getElementById("reslow2");
	switch(q)
	{
		case "?80":
			selectedQuality = "?80";
			break;
		case "?60":
			selectedQuality = "?60";
			break;	
		case "?40":
			selectedQuality = "?40";
			break;
	}
}


/*  Called when the user clicks on the help button on the toolbar
*/
function showBox(box)
{
    switch (box)
    {
        case "help":
            document.getElementById('helpDiv').style.display = "block";
            document.getElementById('helpDivBody').style.display = "block";
            document.getElementById('helpDivBody').style.height = drawingSpaceHeight - 34 + "px";
            document.getElementById('helpDiv').style.height = drawingSpaceHeight - 10 + "px";
            
            var img = document.getElementById('expandHelp');
                img.style.display = "none";
                if (IE)
                    img.style.marginLeft = "0px";
                else
                    img.style.paddingLeft = "0px";
            var img = document.getElementById('collapseHelp');
                img.style.display = "inline";
                if (IE)
                    img.style.marginLeft = "220px";
                else
                    img.style.paddingLeft = "223px";
            break;
        case "query":
            document.getElementById('queryDiv').style.display = "block";
            document.getElementById('queryDivBody').style.display = "block";
            document.getElementById('queryDivBody').style.height = drawingSpaceHeight - 34 + "px";
            document.getElementById('queryDiv').style.height = drawingSpaceHeight - 10 + "px";
            
            var img = document.getElementById('expandQuery');
                img.style.display = "none";
                if (IE)
                    img.style.marginLeft = "0px";
                else
                    img.style.paddingLeft = "0px";
            var img = document.getElementById('collapseQuery');
                img.style.display = "inline";
                if (IE)
                    img.style.marginLeft = "255px";
                else
                    img.style.paddingLeft = "258px";
            break;
        case "identify":
            document.getElementById('identifyDiv').style.display = "block";
            document.getElementById('identifyDiv').style.top = drawingSpaceHeight - 150 + "px";
            document.getElementById('identifyDiv').style.height = 150 + "px";
            document.getElementById('identifyDivBody').style.height = 120 + "px";
            break;
        default:
            document.getElementById(box).style.display = "block";
            break;
    }
}

function hideBox(id) {
    document.getElementById(id).style.display = "none";
}

function hidePasswordReset() {
    hideBox('passwordReset');
    hideBox('passwordResetFailed');
    hideBox('passwordResetSuccess');
}

/*  Called when the user clicks on the X on the help screen 
*/
function closeWindow(divToClose)
{
    document.getElementById(divToClose).style.display = "none";
}


/*  Called when the user clicks on the up or down arrow on the help screen
    to display or hide the help info.
*/
function toggleWindow(image)
{
    switch (image.id)
    {
        case "collapseHelp":
            var img1 = document.getElementById('collapseHelp');
            img1.style.display = "none";
            var img2 = document.getElementById('expandHelp');
            img2.style.display = "inline";
            if (IE)
                img2.style.marginLeft = "220px";
            else
                img2.style.paddingLeft = "223px";
            document.getElementById('helpDivBody').style.display = "none";
            document.getElementById('helpDiv').style.height = "20px";
            break;
        case "expandHelp":
            var img1 = document.getElementById('collapseHelp');
            img1.style.display = "inline";
            if (IE)
                img1.style.marginLeft = "220px";
            else
                img1.style.paddingLeft = "223px";
            var img2 = document.getElementById('expandHelp');
            img2.style.display = "none";        
            document.getElementById('helpDivBody').style.display = "block";
            document.getElementById('helpDivBody').style.height = drawingSpaceHeight - 34 + "px";
            document.getElementById('helpDiv').style.height = drawingSpaceHeight - 10 + "px";
            break;
        
        case "collapseQuery":
            var img1 = document.getElementById('collapseQuery');
            img1.style.display = "none";
            var img2 = document.getElementById('expandQuery');
            img2.style.display = "inline";
            if (IE)
                img2.style.marginLeft = "220px";
            else
                img2.style.paddingLeft = "223px";
            document.getElementById('queryDivBody').style.display = "none";
            document.getElementById('queryDiv').style.height = "20px";
            break;
        case "expandQuery":
            var img1 = document.getElementById('collapseQuery');
            img1.style.display = "inline";
            if (IE)
                img1.style.marginLeft = "220px";
            else
                img1.style.paddingLeft = "223px";
            var img2 = document.getElementById('expandQuery');
            img2.style.display = "none";        
            document.getElementById('queryDivBody').style.display = "block";
            document.getElementById('queryDivBody').style.height = drawingSpaceHeight - 34 + "px";
            document.getElementById('queryDiv').style.height = drawingSpaceHeight - 10 + "px";
            break;        
    }
}


/*  Called when the user selects a query type from the drop down list
    in the Search tab.
*/
function swapQuery(type){

    switch (type)
    {
        case "city":
            setWaitCursor();
            document.getElementById("town").checked = true;
            BigHole.Map.GetCityList(getCityList_callback);
            break;
        /*case "parcelowner":
            setWaitCursor();
            BigHole.Map.GetCountyList(getCountyList_callback);
            break;*/
        default:
            break;
    }
    if (type != "")
        document.getElementById(type).style.display = "block";
    else if (prevQuery != "")
        document.getElementById(prevQuery).style.display = "none";
            
    if (prevQuery != ""){
        document.getElementById(prevQuery).style.display = "none";
    }
    prevQuery = type;
}


function selectSection(obj)
{
	if (obj.colorChanged == true)
	{
		obj.style.background = '#D6D6E0';
		obj.colorChanged = false;
	}
	else
	{
		obj.style.background = '#ffcc00';
		obj.colorChanged = true;
	}

	//alert(	obj.colorChanged)
}


function getSelectedSections()
{
	var sec;
	var strSections = '';

	for (i=1; i<37; i++)
	{
		sec = eval('sec' + i);

		if (sec.colorChanged == true)
		{
			strSections = strSections + sec.innerText + ',';
		}
	}

	if (strSections.length > 0)
	{
		trsForm.fSections.value = strSections.substr(0, strSections.length-1)
	}
	else
	{
		trsForm.fSections.value = '';
	}

}


/* Prevent postback when user hits the enter key.
*/
function noEnter() {
    return !(window.event && window.event.keyCode == 13);
}


/* Filters the identify list for active vector layers.
*/
function filterIdentifyList()
{
    BigHole.Map.FilterIdentifyList(filterIdentifyList_callback);
}


/*  Open a new window without restrictions.
*/
function newWindow(url, name, w, h) {
	var arg = "";
	var x = (window.screen.width - w) / 3;
	var y = (window.screen.height - h) / 3;

	arg += 'left='+x+',top='+y+',width='+w+',height='+h+',scrollbars=yes,resizable=yes,location=yes,directories=no,status=yes,toolbar=yes';
	window.open(url, name, arg);
}


/*  Open a new window with restricted interactivity.
*/
function newSimpleWindow(url, name, w, h) {
	var arg = "";
	var x = (window.screen.width - w) / 3;
	var y = (window.screen.height - h) / 3;

	arg += 'left='+x+',top='+y+',width='+w+',height='+h+',scrollbars=yes,resizable=yes,location=no,directories=no,status=no,toolbar=no';
	window.open(url, name, arg);
}


/*  Called on page load and page resize to set the size of the help box
*/
function formatBoxes()
{
    /****** BEGIN: Format the identify box *******/
	var box = document.getElementById('identifyDiv');
	var dbox = document.getElementById('identifyDrag');
	var hbox = document.getElementById('identifyDivHeader');
	var bbox = document.getElementById('identifyDivBody');
	
	// Set Width
	box.style.width = drawingSpaceWidth + "px";
	dbox.style.width = drawingSpaceWidth + "px";
	hbox.style.width = drawingSpaceWidth + "px";
	bbox.style.width = drawingSpaceWidth + "px";
	
	// If iObj is not null, then the user has resized the identify box. Base position off of that
	// if it exists.
	if (iObj.elNode)
	{
	    var h = iObj.elNode.style.height;
	    h = h.substring(0, h.length - 2);
	    
	    box.style.top = drawingSpaceHeight - (parseInt(h)) + "px";
	}
	else
	{
	    box.style.top = (drawingSpaceHeight - 150) + "px";
	}
	/****** END: Format the identify box *******/
	
}



/*  Handles the onmousedown event for the drag bar on the identify box.
*/
function identifyDragMDFunction(event, id)
{
    var el;
    var x, y;
    
    if (id)
    {
        iObj.elNode = document.getElementById(id);
    }
    else
    {
        if(IE)
        {
            iObj.elNode = window.event.srcElement;
        }
        else
        {
            iObj.elNode = event.target;
        }
            
    }
    
    // Get cursor position with respect to the page.
    if (IE) {
        x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }
    else {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Save starting positions of cursor and element.
    iObj.cursorStartX = x;
    iObj.cursorStartY = y;
    iObj.elStartLeft  = parseInt(iObj.elNode.style.left, 10);
    iObj.elStartTop   = parseInt(iObj.elNode.style.top,  10);

    if (isNaN(iObj.elStartLeft)) iObj.elStartLeft = 0;
    if (isNaN(iObj.elStartTop))  iObj.elStartTop  = 0;

    // Update element's z-index.
    iObj.elNode.style.zIndex = ++iObj.zIndex;

	attachEventListener("identifyDrag", "onmousemove", identifyDragMMFunction);
	attachEventListener("identifyDrag", "onmouseup", identifyDragMUFunction);
}


/*  Handles the onmousemove event for the drag bar of the identify box
*/
function identifyDragMMFunction(event)
{
    var x, y;

    // Get cursor position with respect to the page.

    if (IE) {
        x = window.event.clientX + document.documentElement.scrollLeft
            + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
            + document.body.scrollTop;
    }
    else {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }

    // Move drag element by the same amount the cursor has moved.
    //iObj.elNode.style.left = (iObj.elStartLeft + x - iObj.cursorStartX) + "px";
    iObj.elNode.style.top  = (iObj.elStartTop  + y - iObj.cursorStartY) + "px";
    iObj.elNode.style.height = (drawingSpaceHeight - (iObj.elStartTop  + y - iObj.cursorStartY)) + "px";
    document.getElementById('identifyDivBody').style.height = (drawingSpaceHeight - (iObj.elStartTop  + y - iObj.cursorStartY)) - 30 + "px";

    if (IE) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }
    else
        event.preventDefault();
}


/*  Handles the onmouseup event for drag bar of identify box
*/
function identifyDragMUFunction(eventObj)
{
    // Stop capturing mousemove and mouseup events.
    detachEventListener("identifyDrag", "onmousedown", identifyDragMDFunction);		
	detachEventListener("identifyDrag", "onmousemove", identifyDragMMFunction);
	detachEventListener("identifyDrag", "onmouseup", identifyDragMUFunction);
}

/*	Called when the user clicks on the expand or collapse icon in the Customize Map accordion tab
*/
function toggleLegend(legendId, image){
	if (document.getElementById){
		var style2 = document.getElementById(legendId).style;
		style2.display = style2.display?"":"block";		
	}
	else if (document.all){
		var style2 = document.all[legendId].style;
		style2.display = style2.display?"":"block";
	}
	else if (document.layers){
		var style2 = document.all[legendId].style;
		style2.display = style2.display?"":"block";
	}
	
	if(image)
	{
	    // Swap the images
	    var temp = document.getElementById(legendId + "Image").src;
	    var i = temp.lastIndexOf("/");
	    var src = temp.substring(i + 1);
	    var expand = "expandlegend.gif";
	    var collapse = "collapselegend.gif";
	    if (src == expand)
	    {
		    document.getElementById(legendId + "Image").src = "images/" + collapse;
	    }
	    else if (src == collapse)
	    {
		    document.getElementById(legendId + "Image").src = "images/" + expand;
	    }
	}
}

/* The user is using the affiliates div to login to the application
*/
function LogIn()
{
    var userId = document.getElementById("email").value;
    var password = document.getElementById("password").value;    
    
    BigHole.Map.LogIn(userId, password, LogIn_callback);
}

function SendPasswordResetRequest() {
    var email = document.getElementById("passwordResetEmail").value,
        username = document.getElementById("passwordResetUsername").value;

    BigHole.Map.ResetPassword(username, email, passwordReset_callback);
}

/***********************************************
* Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
                
function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			var i;
			for (i = 0; i < field.form.elements.length; i++)
				if (field == field.form.elements[i])
					break;
			i = (i + 1) % field.form.elements.length;
			field.form.elements[i].focus();
			return false;
		} 
		else
		return true;
	}
