//==============================
// GLOBAL Variables
//==============================
var IE = document.all?true:false;
var myTimeOut;						// used for pausing the resize event so it only fires once for a drag/resize
var myTimeOut2;						// used for pausing the Bird DDL change event so it only fires once if the user is quickly cursoring up or down through list.
var mydebug = "";					// string used to fill the debug Textarea

var pv;								// used to hold all the values returned from the Ajax call

// These variables are set to their actual values in the initializeVars function
var mapContainer = null;			// pointer to the main MapContainer DIV
var accRight = null;				// pointer to the Rico Accordion Right Side object
var accAllSightings = null;			// pointer to the Rico Accordion Right Side object
var ddlBird = null;					// pointer to the Bird dropdownlist
var activeTaskNum = -1;				// Which Report / Task is being used?  I use this for Ajax calls to load objects and to know which tab to put these objects into

// Internal Task ID's
// 0 - Generalized Observations
// 1 - My Observations
// 2 - Point Observations
// 3 - Species Of Concern Occurrences
// 4 - Single Species Overview
// 5 - Structured Surveys
// 6 - Single Species Overview (public)
// 7 - Communities
// 8 - Species Lists by Area

// This is used to translate between the Accordion Index and the ActiveTask Index
var lookupAccordionTasks = new Array(9);
lookupAccordionTasks[0] = 3;	// SpOcc
lookupAccordionTasks[1] = 2;	// Point Observations
lookupAccordionTasks[2] = 1;	// My Observations
lookupAccordionTasks[3] = 0;	// Gen Obs
lookupAccordionTasks[4] = 4;	// SS Overview
lookupAccordionTasks[5] = 5;	// Structured Surveys
lookupAccordionTasks[6] = 6;	// Communities
lookupAccordionTasks[7] = 8;	// Species Lists by Area


var toolBarIcons = null;			// pointer to the toolBarIcons DIV control
var drawingSpace = null;			// pointer to the DrawingSpace DIV control
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 ReportSlider = null;			// pointer to the ReportSlider drag bar
var SliderHandle = null;			// pointer to the SliderHandle (dots)
var TabularReport = null;			// pointer to the Tabular Report
var divDebug = null;				// pointer to the Debug DIV
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 winH = 0;
var winW = 0;
var zoomBoxLeft = 0;
var zoomBoxTop = 0;
var zoomBoxWidth = 0;
var zoomBoxHeight = 0;
var layers = "";
var currentenvelope = "";			// used to determine if the base map layers are current for this envelope, pan/zoom will change envelope and require new layers be loaded
var firstTimeOpenedBottomPanel = false;	// I use this to check if the bottom panel has been opened automatically from a query search

var leftOffset;
var rightOffset;
var topOffset;
var bottomOffset;


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 zoomOutFactor = 100;			// used with the "timer" zoom functions when a user holds the mouse button, based on 100% of the original image width
var zoomInFactor = 100;				// used with the "timer" zoom functions when a user holds the mouse button, based on 100% of the original image width
var zoomFactor = 100;				// used with the "timer" zoomToBox function when a user clicks a single point

// These are used to save the current datestamp to allow us to ignore "multiple" ajax requests
// For instance, if I pan the map twice quickly before either ajax call is returned, I only want to show the final pan results
// and ignore the first pan.  By setting these date stamps, I can compare the last timestamp with what is returned by ajax.
// If they match, process the callback.  If not, just ignore the results.
var AjaxTimeStampMap = "1";
var AjaxTimeStampIdentify = "1";

var waitCount = 0;					// used to increment/decrement the number of wait requests that are bunched together.  ie, call the wait function twice and the returnToNormal function will wait until it is called two times to reset the cursors
var identifyCount = 0;				// used to increment/decrement the number of identify features that are waiting to return.
var identifyWidth = 400;
var identifywin;

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 mapCursor = "default";			// used to hold the glasslayer cursor (restored after wait cursor)

var amIZoomedInFarEnough = false;	// they have to be zoomed in at least the minimum amount before they can click to add items to the map

var winVisibleSightings = null;		// this will be a pointer to the popup window (if it is open)

var imgDotClear = new Image();  imgDotClear.src = "images/dot_Clear.gif";

// The location object is used for all the Lat/Lon, Decimal, State Plane conversions.  
// This has properties for each location type.  
// When you call a conversion routine with some sort of xy coordinate, 
// that routine will convert to all other types and place the values in this object.  
// This keeps us from having single variables like lat and lon that may 
// be mistakenly changed somewhere else in the program
var mapLocation = new Object;
mapLocation.spx = 0;
mapLocation.spy = 0;
mapLocation.lat = 0;
mapLocation.lon = 0;


//--END Global Variables---------------------------------------------------


//==============================
// Toolbar Buttons
//==============================
var numTools = 10;

var toolArray = new Array(numTools);	// Name of tool (also used when calling onclick function)
toolArray[0] = "toolZoomIn";
toolArray[1] = "toolZoomOut";
toolArray[2] = "toolPrevZoom";
toolArray[3] = "toolFullExtent";
toolArray[4] = "toolPan";
toolArray[5] = "";
//toolArray[5] = "toolPanZoomCombo";
toolArray[6] = "toolMeasure";
toolArray[7] = "toolIdentify";
toolArray[8] = "spacer";
toolArray[9] = "toolAddObs";

var toolArray_Alt = new Array(numTools);	// Help text shown on mouseover
toolArray_Alt[0] = " Zoom In ";
toolArray_Alt[1] = " Zoom Out ";
toolArray_Alt[2] = " Previous Zoom";
toolArray_Alt[3] = " Statewide View ";
toolArray_Alt[4] = " Pan Map ";
toolArray_Alt[5] = "";
//toolArray_Alt[4] = "Pan/Zoom COMBO  |  Left+Drag&nbsp;to&nbsp;PAN,  |  Right+Drag&nbsp;to&nbsp;Zoom ";
//toolArray_Alt[5] = " LEFT-CLICK-HOLD to Zoom In   |   RIGHT-CLICK-HOLD to Zoom Out ";
toolArray_Alt[6] = " Measure  -  Doubleclick to start over";
toolArray_Alt[7] = "Click on map to Identify layers";
toolArray_Alt[8] = "";
toolArray_Alt[9] = "Add a new Observation";

var toolArray_ImgOff = new Array(numTools);	// Image shown when mouseout
toolArray_ImgOff[0] = "images/toolZoomIn_Off.gif";
toolArray_ImgOff[1] = "images/toolZoomOut_Off.gif";
toolArray_ImgOff[2] = "images/toolPrevZoom_Off.gif";
toolArray_ImgOff[3] = "images/toolFullExtent_Off.gif";
toolArray_ImgOff[4] = "images/toolPan_Off.gif";
toolArray_ImgOff[5] = "";
//toolArray_ImgOff[5] = "images/toolPanZoomCombo_Off.gif";
toolArray_ImgOff[6] = "images/toolMeasure_Off.gif";
toolArray_ImgOff[7] = "images/toolIdentify_Off.gif";
toolArray_ImgOff[8] = "images/toolSpacer.gif";
toolArray_ImgOff[9] = "images/AddObs.gif";

var toolArray_ImgOn = new Array(numTools);	// Image shown when mouseover or selected.  Leave blank to use ImgOff (ie, no mouseover effects)
toolArray_ImgOn[0] = "images/toolZoomIn_On.gif";
toolArray_ImgOn[1] = "images/toolZoomOut_On.gif";
toolArray_ImgOn[2] = "images/toolPrevZoom_On.gif";
toolArray_ImgOn[3] = "images/toolFullExtent_On.gif";
toolArray_ImgOn[4] = "images/toolPan_On.gif";
toolArray_ImgOn[5] = "";
//toolArray_ImgOn[5] = "images/toolPanZoomCombo_On.gif";
toolArray_ImgOn[6] = "images/toolMeasure_On.gif";
toolArray_ImgOn[7] = "images/toolIdentify_On.gif";
toolArray_ImgOn[8] = "";
toolArray_ImgOn[9] = "";

var toolArray_ImgDisabled = new Array(numTools);	// Image shown if disabled.  Leave blank if item is never disabled.
toolArray_ImgDisabled[0] = "";
toolArray_ImgDisabled[1] = "";
toolArray_ImgDisabled[2] = "";
toolArray_ImgDisabled[3] = "";
toolArray_ImgDisabled[4] = "";
toolArray_ImgDisabled[5] = "";
toolArray_ImgDisabled[6] = "";
toolArray_ImgDisabled[7] = "";
toolArray_ImgDisabled[8] = "";
toolArray_ImgDisabled[9] = "";

// Preload the images
if (document.images) {
	// Load image if specified or set to dotclear (or Off image for Disabled items)
	var toolArray_Off = new Array(numTools);
	var toolArray_On = new Array(numTools);
	var toolArray_Disabled = new Array(numTools);

	for (i=0;i<numTools;i++)
	{
		if (toolArray_ImgOff[i] != "")
		{
			toolArray_Off[i] = new Image();
			toolArray_Off[i].src = toolArray_ImgOff[i];
		}
		if (toolArray_ImgOn[i] != "")
		{
			toolArray_On[i] = new Image();
			toolArray_On[i].src = toolArray_ImgOn[i];
		}
		if (toolArray_ImgDisabled[i] != "")
		{
			toolArray_Disabled[i] = new Image();
			toolArray_Disabled[i].src = toolArray_ImgDisabled[i];
		}
	}
}

//--END Toolbar Buttons----------------------------------------------------


//-----------------------
function initializeVars()
//-----------------------
{
	// Initialize some of the global variables that required the full page to be loaded first
	mapContainer = document.getElementById("MapContainer");
	ddlAmphis = document.getElementById("ddlAmphis");
	ddlBird = document.getElementById("ddlBird");
	toolBarIcons = document.getElementById("ToolBarIcons");
	glassSheetLayer = document.getElementById("glassSheetLayer");
	drawingSpace = document.getElementById("DrawingSpace");
	zoomInBox = document.getElementById("zoomInBox");
	actualMapImage = document.getElementById("actualMapImage");
	tempPanMapImage = document.getElementById("tempPanMapImage");
	statusBar = document.getElementById("StatusBar");
	ReportSlider = document.getElementById("ReportSlider");
	SliderHandle = document.getElementById("SliderHandle");
	TabularReport = document.getElementById("TabularReport");
	divDebug = document.getElementById("divDebug");
	identifyWidth = document.getElementById('divIdentify').offsetWidth - 42;

	if (drawingSpace.offsetTop)
	{
		// typically would be IE
		drawingSpaceTop = drawingSpace.offsetTop;
		drawingSpaceLeft = drawingSpace.offsetLeft;
		drawingSpaceHeight = drawingSpace.offsetHeight;
		drawingSpaceWidth = drawingSpace.offsetWidth;
		
		leftOffset = -2;
		topOffset = -2;
		rightOffset = -3;
		bottomOffset = -1;
	}
	else
	{
		// typically would be NS compat
		drawingSpaceTop = drawingSpace.pageY;
		drawingSpaceLeft = drawingSpace.pageX;
		drawingSpaceHeight = drawingSpace.innerHeight;
		drawingSpaceWidth = drawingSpace.innerWidth;
		
		leftOffset = -1;
		topOffset = -1;
		rightOffset = -1;
		bottomOffset = -1;	
	}
	zoomBoxWidth = drawingSpaceWidth;
	zoomBoxHeight = drawingSpaceHeight;
	
	
	// Fill the toolbar with the buttons defined above
	loadToolBar();	// (function located in menuMouseovers.js)

	// Set up the mousewheel for the glasslayer
	if (window.addEventListener)
	{
		/** DOMMouseScroll is for mozilla. */
		glassSheetLayer.addEventListener('DOMMouseScroll', wheel, false);
	}
	/** IE/Opera. */
	glassSheetLayer.onmousewheel = glassSheetLayer.onmousewheel = wheel;



	// Setup for rightclicks
//	if (IE)
//	{
//		//document.captureEvents(Event.MOUSEDOWN)
//	}
//	document.oncontextmenu = falsefunc;
//	document.onselectstart = falsefunc;
//	document.onmousedown = falsefunc;
//	document.onmouseup = falsefunc;
//	drawingSpace.oncontextmenu = falsefunc;
//	glassSheetLayer.oncontextmenu = falsefunc;

}


//ACM Wheel Mouse function
//Code modified from http://adomas.org/javascript-mouse-wheel/
function handle(delta) 
{
	// Clear any current measure tool
	resetDrawingTool();
	hideIdentify();
	
	if (delta < 0)
	{
		getMouseXY();
		// Now adjust the coords for the offset of our drawing space.
		mouseX -= drawingSpaceLeft;
		mouseY -= drawingSpaceTop;
		window.status = delta + '-' + actualMapImage.style.width + '-' + actualMapImage.offsetWidth + ' - ' + actualMapImage.style.width.substring(0,actualMapImage.style.width.length - 1);
		// Get current map diminsions and increase size taking mouse xy into consideration
		var zoomInFactor = actualMapImage.style.width.substring(0,actualMapImage.style.width.length - 1);
		
		zoomInFactor *= .86;
//		if (zoomInFactor > 3100) { zoomInFactor = 3100; }
		// Now figure a way to zoom/shrink the image by percent, while keeping it centered on the original spot
		var newLeft = mouseX-((zoomInFactor/100)*mouseX);
		var newTop = mouseY-((zoomInFactor/100)*mouseY);
		actualMapImage.style.width = zoomInFactor.toString(10) + "%";
		actualMapImage.style.height = zoomInFactor.toString(10) + "%";
		actualMapImage.style.left = newLeft.toString(10) + "px";
		actualMapImage.style.top = newTop.toString(10) + "px";

		// get the actual pixel size of the percentage resized image.  This will give us essentially a zoom in/out box for our redraw
		var newWidth = actualMapImage.offsetWidth;
		var newHeight = actualMapImage.offsetHeight;
		// Find how far the image was moved from the original location
		var panLeft = actualMapImage.style.left.replace("px", "");
		var panTop = actualMapImage.style.top.replace("px", "");
		// now compare the resized image to the actual viewport and create a 'fake' zoombox to show what the viewport looks like compared to the resized image
		var zoomRatio = newWidth / drawingSpaceWidth;
		// see if the zoomRatio is very close to 1, if so it means they clicked and released quickly...so do a simple zoom out on the point
		if (zoomRatio>.999 && zoomRatio<1.001) { zoomRatio = .5; }
		zoomBoxWidth = Math.round(drawingSpaceWidth / zoomRatio);
		zoomBoxHeight = Math.round(drawingSpaceHeight / zoomRatio);
		zoomBoxLeft = Math.round(panLeft / zoomRatio * -1);
		zoomBoxTop = Math.round(panTop / zoomRatio * -1);

		// Update the NewScale popup
		updateNewScale();
		// wait to see if they are still scrolling
		clearTimeout(myTimeOut);
		myTimeOut = setTimeout('getNewImage();',1000);
	}
	else
	{
		getMouseXY();
		// Now adjust the coords for the offset of our drawing space.
		mouseX -= drawingSpaceLeft;
		mouseY -= drawingSpaceTop;
		window.status = delta + '-' + actualMapImage.style.width + '-' + actualMapImage.offsetWidth + ' - ' + actualMapImage.style.width.substring(0,actualMapImage.style.width.length - 1);
		// Get current map diminsions and increase size taking mouse xy into consideration
		var zoomInFactor = actualMapImage.style.width.substring(0,actualMapImage.style.width.length - 1);
		
		zoomInFactor *= 1.26;
//		if (zoomInFactor > 3100) { zoomInFactor = 3100; }
		// Now figure a way to zoom/shrink the image by percent, while keeping it centered on the original spot
		var newLeft = mouseX-((zoomInFactor/100)*mouseX);
		var newTop = mouseY-((zoomInFactor/100)*mouseY);
		actualMapImage.style.width = zoomInFactor.toString(10) + "%";
		actualMapImage.style.height = zoomInFactor.toString(10) + "%";
		actualMapImage.style.left = newLeft.toString(10) + "px";
		actualMapImage.style.top = newTop.toString(10) + "px";

		// get the actual pixel size of the percentage resized image.  This will give us essentially a zoom in/out box for our redraw
		var newWidth = actualMapImage.offsetWidth;
		var newHeight = actualMapImage.offsetHeight;
		// Find how far the image was moved from the original location
		var panLeft = actualMapImage.style.left.replace("px", "");
		var panTop = actualMapImage.style.top.replace("px", "");
		// now compare the resized image to the actual viewport and create a 'fake' zoombox to show what the viewport looks like compared to the resized image
		var zoomRatio = newWidth / drawingSpaceWidth;
		// see if the zoomRatio is very close to 1, if so it means they clicked and released quickly...so do a simple zoom out on the point
		if (zoomRatio>.999 && zoomRatio<1.001) { zoomRatio = .5; }
		zoomBoxWidth = Math.round(drawingSpaceWidth / zoomRatio);
		zoomBoxHeight = Math.round(drawingSpaceHeight / zoomRatio);
		zoomBoxLeft = Math.round(panLeft / zoomRatio * -1);
		zoomBoxTop = Math.round(panTop / zoomRatio * -1);

		// Update the NewScale popup
		updateNewScale();
		// wait to see if they are still scrolling
		clearTimeout(myTimeOut);
		myTimeOut = setTimeout('getNewImage();',1000);
	}
}

/** Event handler for mouse wheel event. */
function wheel(event){
        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;
                /** In Opera 9, delta differs in sign as compared to IE.
                 */
                if (window.opera)
                        delta = -delta;
        } else if (event.detail) { /** Mozilla case. */
                /** In Mozilla, sign of delta is different than in IE.
                 * Also, delta is multiple of 3.
                 */
                delta = -event.detail/3;
        }
        /** If delta is nonzero, handle it.
         * Basically, delta is now positive if wheel was scrolled up,
         * and negative, if wheel was scrolled down.
         */
        if (delta)
                handle(delta);
        /** Prevent default actions caused by mouse wheel.
         * That might be ugly, but we handle scrolls somehow
         * anyway, so don't bother here..
         */
        if (event.preventDefault)
                event.preventDefault();
	event.returnValue = false;
}



//end ACM



// Replaces all instances of the given substring.
String.prototype.replaceAll = function(strTarget, strSubString )
{
	// strTarget = The substring you want to replace
	// strSubString = The string you want it replaced with
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
 
	// Keep looping while an instance of the target string still exists in the string.
	while (intIndexOfMatch != -1)
	{
		// Replace out the current instance.
		strText = strText.replace( strTarget, strSubString )
	 
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}

	// Return the updated string with ALL the target strings replaced out with the new substring.
	return( strText );
}


// Trims the whitespace from a string
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
