///broken out into several sections
///constants used for various things
///arrays used to create toolbuttons
////generic functions
////process button click/tool used/mouse events
///DHTML utilities

var goodIE = ( document.all ) ? 1 : 0;
var netscape6 = ( document.getElementById && ! document.all ) ? 1 : 0;
var opera = ( navigator.userAgent.indexOf('Opera') != -1 );
if ( opera ) goodIE = false;

var bUserDoubleClicked = false; 

var cMillisecondsForDoubleClick =250;
var TimeOfLastClick = 0;

// Global vars to save mouse position
var mouseX = 0;
var mouseY = 0;
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;
var firstx = 0;
var firsty = 0;
var secondx = 0;
var secondy = 0;
var zleft = 0;
var zright = 0;
var ztop = 0;
var zbottom = 0;
var dragging = false;
var bInUse = false;
var strHoldCursor = '';

// Layers names
var innerlayer = "zBoxInner";

// Tool names
var zoomInTool        = 'zoomin';
var zoomOutTool       = 'zoomout';
var panTool           = 'pan';

//  HTML elements
var mapForm;

function submitzoom() {
	var ControlDocForm = document.getElementById(mapForm);
	if ( checkNumeric('zoomLevel','Zoom') )
	{
		if( ! checkEmpty('zoomLevel','Zoom') )
		{
			ControlDocForm.zoomLevel.value = document.getElementById('zoomLevel').value;
			ControlDocForm.whyDidISubmit.value = "newzoom";
			ChangeStyleForMapSubmission();
			ControlDocForm.submit();
		}
	}
}

// Prevent the return key from submitting the zoom level
function blockEnter(evt) {
    evt = ( evt ) ? evt : event;
    var charCode = ( evt.charCode ) ? evt.charCode :
        ( (evt.which) ? evt.which : evt.keyCode );
    if (charCode == 13 || charCode == 3) 
    {
        return false;
    } 
    else 
    {
        return true;
    }
}


////////////////////////////
// Dynamic Map
/////////////////////////////

// Create a DHTML layer
function createLayer(name, left, top, width, height, visible, content) {
	var layer, str;
	if ( goodIE ) 
	{
		str = '<div id="' + name +
			'" style="z-index:100;border-style:solid;border-width:1px;border-top-color:#FF0000;border-left-color:#FF0000;border-bottom-color:#FF0000;border-right-color:#FF0000;position:absolute; background-color:#cccccc; filter: alpha(Opacity=50); overflow:hidden; left:' + left +
			'px; top:' + top + 'px; width:' + width + 'px; height:' + height +
			'px;' + ' visibility:' + (visible ? 'visible;' : 'hidden;') +  '">';
		document.writeln(str);
		document.writeln(content);
		document.writeln('</div>');
	} 
	else if ( netscape6 ) 
	{
		str = '<div id="' + name +
			'" style="z-index:100;border-style:solid;border-width:1px;border-top-color:#FF0000;border-left-color:#FF0000;border-bottom-color:#FF0000;border-right-color:#FF0000; position:absolute; background-color:#cccccc; -moz-opacity: 0.50; overflow:hidden; left:' + left +
			'px; top:' + top + 'px; width:' + width + 'px; height:' + height +
			'px;' + ' visibility:' + (visible ? 'visible;' : 'hidden;') +  '">';
		document.writeln(str);
		document.writeln(content);
		document.writeln('</div>');
	} 
	else 
	{
    	return null;
  	}
}

// get the layer object called "name"
function getLayer(name) {
	if ( goodIE )		// IE 
	{            
		if (eval('document.all.' + name) != null) 
		{
			layer = eval('document.all.' + name + '.style');
			return layer;
		} 
		else 
		{
			return null;
		}
	} 
	else if ( netscape6 ) 
	{
		if ( eval('document.getElementById("' + name + '")') != null ) 
		{
			layer = eval('document.getElementById("' + name + '").style');
			return layer;
		} 
		else 
		{
			return null;
		}
	} 
	else 	// Don't know
	{                              
		return null;
	}
}


// toggle layer to visible
function showLayer(name) {
	var layer = getLayer(name);
	if (layer != null ) 
	{
		if ( goodIE || netscape6 )  // IE
		{          
			layer.visibility = "visible";
		}
	}
}

function hideLayer(name) {
	var layer = getLayer(name);
	if ( layer != null ) {
		if ( goodIE || netscape6 ) 	// IE
		{          
			layer.visibility = "hidden";
			layer.top = 0 + "px";
			layer.left = 0 + "px";
			layer.width = 0 + "px";
			layer.height = 0 + "px";
		}
	}
}

// clip layer display to clipleft, cliptip, clipright, clipbottom
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {
	var layer = getLayer(name);
	if ( layer != null ) 
	{
		if ( goodIE )	// IE 
		{                  
      		layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft + ')';
		} 
		else if ( netscape6 )	// Netscape 6
		{		
			layer.clip = 'rect(' + cliptop + 'px ' + clipright + 'px ' + clipbottom + 'px ' + clipleft + 'px)';

		}
	}
}

function InitMouseEvents() {
	// Set up event capture for mouse movement
	document.onmousemove = getMouse;
	document.onmousedown = mapTool;
	document.onmouseup = chkMouseUp;
	document.ondblclick='';
}

function setClipLayers() {
	var content = '';
	createLayer("zBoxInner", 0, 0, 0, 0, false, content);
}

// check for mouseup
function chkMouseUp(e) {

	if ( dragging ) 
	{
		mouseX = Math.min(Math.max(mouseX, 0), mapWidth);
		mouseY = Math.min(Math.max(mouseY, 0), mapHeight);
		mapTool(e);
	}
  
	//return false;
}

// Mouse down / drag
function mapTool(e) {
	
	// check if left mouse button is clicked
	var clicked = true;
	if ( goodIE ) 
	{
		clicked = window.event.button == 1;
	}
	else {
		clicked = e.which == 1 || e.button == 0;
	}
	
	if ( clicked )	//left click  
	{ 
		getImageXY(e);

		if ( ! InUse() && ! dragging && insideMap() )
		{
			var ControlDocForm = document.getElementById(mapForm);
			if ( toolbar.getCurrentToolName() == zoomInTool)
			{
				startClickAndDrag(e);
			}
			else if ( toolbar.getCurrentToolName() == zoomOutTool)
			{
				
				if( ControlDocForm != null ) { 
					ControlDocForm.x.value = mouseX;
					ControlDocForm.y.value = mouseY;
					ControlDocForm.x2.value = 0;
					ControlDocForm.y2.value = 0;
				
					SingleClickAndSubmit();
				}
			}
			else if ( toolbar.getCurrentToolName() == panTool )
			{
				startPan(e);
			}
			return false;
		}
		else if ( dragging )
		{
			getMouse(e);
			if ( toolbar.getCurrentToolName() == zoomInTool )
			{
				stopClickAndDrag(e);
			}
			else if (toolbar.getCurrentToolName() == panTool)
			{
				stopPan(e);
			}
		}
		return true;
	}
	
	return true;
}


function getImageXY(e) {
	if ( netscape6 )	// Netscape
	{                
		mouseX = e.pageX;
		mouseY = e.pageY;
	} 
	else if ( goodIE )	// IE 
	{            
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	} 
	else				// Don't know
	{                              
		mouseX = mouseY = 0;
	}
	// subtract offsets from page left and top
	mouseX = mouseX - mapLeft - 2;
	mouseY = mouseY - mapTop - 2;
}

// Mouse move
// get the coords at mouse position
function getMouse(e) {

	if ( dragging ) 
	{
		getImageXY(e);
		x2 = mouseX = Math.min(Math.max(mouseX, 0), mapWidth);
		y2 = mouseY = Math.min(Math.max(mouseY, 0), mapHeight);
		if ( toolbar.getCurrentToolName() == zoomInTool ) 
		{
			setClip();
		} 
		else if ( toolbar.getCurrentToolName() == panTool ) 
		{
			setClipPan();
		}
		return false;
	} 
	else 
	{
		return true;
	}
	
	return true;
}

function insideMap() {

	return ( (mouseX >= 0) && (mouseX < mapWidth) &&
				(mouseY >= 0) && (mouseY < mapHeight) );
}

function startClickAndDrag(e) {

	getImageXY(e);
	
	// keep it within the MapImage
	if ( ! dragging ) 
	{
		// capture values to pass to map server
		firstx = x1 = mouseX;
		firsty = y1 = mouseY;
		x2 = x1 + 1;
		y2 = y1 + 1;

		if ( toolbar.getCurrentToolName() == zoomInTool )
		{
			showLayer(innerlayer);
		}
		dragging = true;
	} 
	else 
	{
		stopClickAndDrag(e);
	}

	return false;
}

function ChangeStyleForMapSubmission() {
	if ( goodIE ) 
	{
		document.images["mapimage"].style.filter = 'alpha(Opacity=50);';
	}
	else 
	{
		document.images["mapimage"].style.MozOpacity = 0.5;
	}
	
	return true;
}

// stop clicking and dragging
function stopClickAndDrag(e) {
	dragging = false;

	secondx = x2;
	secondy = y2;

	// Zoom to box
	var tx1 = Math.min(firstx, secondx);
	var tx2 = Math.max(firstx, secondx);
	var ty1 = Math.min(firsty, secondy);
	var ty2 = Math.max(firsty, secondy);
	var ControlDocForm = document.getElementById(mapForm);
	if( ControlDocForm != null ) {
		ControlDocForm.x.value = tx1;
		ControlDocForm.y.value = ty1;
		ControlDocForm.x2.value = tx2;
		ControlDocForm.y2.value = ty2;

		ControlDocForm.whyDidISubmit.value = "toolused";
		ControlDocForm.submit();
		Using();
		hideLayer(innerlayer);
		ChangeStyleForMapSubmission();
	}
	return false;
}

function SetTimeOfClick() {	
	var d = new Date();
	TimeOfLastClick = d.getTime();
	return false;
}

function DidIDoubleClick() {

	var d =new Date();
	var NowIs = d.getTime();
	var delta = NowIs - TimeOfLastClick;

	TimeOfLastClick = NowIs;
	if ( delta <= cMillisecondsForDoubleClick ) 
	{
		return true;
	}
	else 
	{	 
		return false;
	}
}

function SubmitTheMapFromDoubleClick() {
	var ControlDocForm = document.getElementById(mapForm);
	Using();
	ChangeStyleForMapSubmission();
	ControlDocForm.whyDidISubmit.value = "toolused";
	ControlDocForm.submit();
}

// start pan
function startPan(e) {
	getImageXY(e);
	
	// keep it within the MapImage
	if ( ! dragging ) {

		// capture values to pass to map server
		firstx = x1 = mouseX;
		firsty = y1 = mouseY;
		x2 = x1 + 1;
		y2 = y1 + 1;

		dragging = true;
	} 
	else 
	{
		stopPan(e);
	}
	
	return false;
}


// stop pan
function stopPan(e) {
	dragging = false;

	secondx = x2;
	secondy = y2;
	var ControlDocForm = document.getElementById(mapForm);
	if( ControlDocForm != null ) {
		ControlDocForm.panOffsetX.value =  secondx - firstx;
		ControlDocForm.panOffsetY.value =  secondy - firsty;
		ControlDocForm.x.value = firstx;
		ControlDocForm.y.value = firsty;
		ControlDocForm.whyDidISubmit.value = "toolused";
		ControlDocForm.submit();
		Using();
		ChangeStyleForMapSubmission();
	}
	return false;
}

// clip zoom box layer to mouse coords
function setClip() {
	zright  = Math.max(x1, x2);
	zleft   = Math.min(x1, x2);
	zbottom = Math.max(y1, y2);
	ztop    = Math.min(y1, y2);

	if ( (x1 != x2) && (y1 != y2) ) 
	{
		var layer = getLayer(innerlayer);
		if ( layer )
		{
			layer.top = ztop + mapTop + "px";
			layer.left = zleft + mapLeft + "px";
			layer.width = zright-zleft + "px";
			layer.height = zbottom-ztop + "px";
		}
	}
	
}

// clip zoom box layer to mouse coords
function setClipPan() {

	var currentLeft, currentTop;

	// Calculate absolute current coordinates of the image
	currentLeft = (x2 - x1);
	currentTop = (y2 - y1);
	var mapimage = document.images["mapimage"];
	if( mapimage != null ) {
		var lyr = document.images["mapimage"].style;
		lyr.top = currentTop;
		lyr.left = currentLeft;
	}
}

function SingleClickAndSubmit() {
	var ControlDocForm = document.getElementById(mapForm);

	ControlDocForm.whyDidISubmit.value = "toolused";
	ControlDocForm.submit();
	Using();
	ChangeStyleForMapSubmission();
}


function InUse() {
	return bInUse;
}

function Using() {
	bInUse = true;
	var div = document.getElementById("mapCanvas");
	strHoldCursor = div.style.cursor;
	var div = document.getElementById("mapCanvas");
	var mapimage = document.getElementById("mapimage");
	mapimage.style.cursor = 'wait';
	div.style.cursor = 'wait';
}

function NotUsing() {
	bInUse = false;
	var div = document.getElementById("mapCanvas");
	div.style.cursor = strHoldCursor;
	var mapimage = document.getElementById("mapimage");
	mapimage.style.cursor = strHoldCursor;
	return true;
}

function checkNumeric(objName, name) {
	var numberfield = document.getElementById(objName);
	if ( chkNumeric(numberfield,'-','.',name) == false )
	{
		numberfield.select();
		numberfield.focus();
		return false;
	}
	else 
	{
		return true;
	}
}

function chkNumeric(objName, dash, period, name) {
	// only allow 0-9 be entered, plus any values passed
	// (can be in any order, and don't have to be comma, period, or hyphen)
	// if all numbers allow commas, periods, hyphens or whatever,
	// just hard code it here and take out the passed parameters
	var checkOK = "0123456789" + dash + period;
	var checkStr = objName;
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

	for ( i = 0;  i < checkStr.value.length; i++ ) 
	{
		ch = checkStr.value.charAt(i);
		for (j = 0;  j < checkOK.length;  j++) {
			if (ch == checkOK.charAt(j))
			{
				break;
			}
			if ( j == checkOK.length-1 )
			{
				allValid = false;
				break;
			}
		}
	}

	if ( ! allValid )
	{
		alert("Only numeric values are allowed in the \"" + name + "\" field.");
		return (false);
	}
}

function checkEmpty(obj, name) {
	var value = document.getElementById(obj).value;
	if ( value == "" )
	{
		alert(name + ' cannot be empty.');
		obj.select();
		obj.focus();
		return true;
	}
	else
	{
		return false;
	}
}

function getAbsolutePosition(el) {
	//generic function to get absolute position of specified element
	var lx=0,ly=0;
	while ( el != null ) 
	{
		lx+=el.offsetLeft;
		ly+=el.offsetTop;
		el=el.offsetParent;
	}
	return {x:lx,y:ly}
}

function findForm(elem_id) {
	if(document.forms != null) {
		var form_id = null;
		for(var k=0; k<document.forms.length; k++) {
			var form_elem = document.forms[k];
			if(findChild(form_elem, elem_id, false)) {
				form_id = form_elem.id;
				break;
			}
	    } 
	}
	//cannot find, fall to default one
	if(form_id == null) {
		form_id = 'mapForm';
	}
	return form_id;
}

function findChild(parent, child_id, found) {
	if(! found) {
		if(parent && parent.hasChildNodes()) {
			for(var i=0; i<parent.childNodes.length; i++) { 
				var elem_id = parent.childNodes[i].id;
				if(elem_id == child_id) {
					found = true;
					break;
				}
				else {
					found = findChild(parent.childNodes[i], child_id, found);
				}
			}
		}
	}
	return found;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Toolbar class
////////////////////////////////////////////////////////////////////////////////////////////////////

Toolbar.prototype.addTool = Toolbar_addTool;
Toolbar.prototype.changeTools = Toolbar_changeTools;
Toolbar.prototype.submitTool = Toolbar_submitTool;
Toolbar.prototype.toolMouseOver = Toolbar_toolMouseOver;
Toolbar.prototype.toolMouseOut = Toolbar_toolMouseOut;
Toolbar.prototype.getCurrentToolName = Toolbar_getCurrentToolName;
Toolbar.prototype.setCurrentToolName = Toolbar_setCurrentToolName;
Toolbar.prototype.render = Toolbar_render;

function Toolbar()
{
	this.tools = new Object();
	this.currentToolName = null;
}

function Toolbar_addTool(tool)
{
	this.tools[tool.name] = tool;
	tool.render();
}

function Toolbar_changeTools(newToolName)
{
	var oldToolName = this.currentToolName;

	// if this tool is already the current tool, don't do anything
	if ( oldToolName != newToolName )
	{
		this.setCurrentToolName(newToolName);

		// set old tool to not be pressed
		var oldTool = this.tools[oldToolName];
		document.images[oldToolName].src = oldTool.imageInactive;
	}
}

function Toolbar_submitTool(newToolName)
{
	document.getElementById("whyDidISubmit").value = "toolused";
	document.getElementById(mapForm).submit();
}

function Toolbar_toolMouseOver(toolName)
{
	var tool = this.tools[toolName];
	// if we mouse over a tool that's not the current tool, set to the roll-over image
	if ( toolName != this.getCurrentToolName() )
	{
		document.images[toolName].src = tool.imageRollOver;
	}
}

function Toolbar_toolMouseOut(toolName)
{
	var tool = this.tools[toolName];
	// if we mouse out of a tool that's not the current tool, set to the inactive image
	if ( toolName != this.getCurrentToolName() )
	{
		document.images[toolName].src = tool.imageInactive;
	}
}

function Toolbar_getCurrentToolName()
{
	return this.currentToolName;
}

function Toolbar_setCurrentToolName(name)
{
	var tool = this.tools[name];
	document.images[name].src = tool.imageActive;
	var mapImage = document.getElementById("mapimage");
	var mapcanvas = document.getElementById("mapCanvas");
        if(mapImage != null) {
		mapImage.className = tool.mapStyle;
	}
	if ( goodIE )
	{
		mapcanvas.className = tool.mapStyle;
	}
	else
	{
		mapcanvas.style.cursor = getMozillaCursor(name); 
	}
	document.getElementById("maptool").value = name;
	this.currentToolName = name;
}

function Toolbar_render()
{
	document.writeln('<table class=toolbar border=0 cellspacing=0 cellpadding=0 width=' + (mapWidth + 2) + '><tr><td>');
	for ( tool in this.tools )
	{
		this.tools[tool].render();
	}
	document.writeln('</td></tr></table>');
}

function getMozillaCursor(toolname) 
{
	var cursorname;
	if ( toolname == panTool ) 
	{
		cursorname = 'move';
	} 
	else if ( toolname == zoomInTool ) 
	{
		cursorname = '-moz-zoom-in';		
	}
	else if ( toolname == zoomOutTool ) 
	{
		cursorname = '-moz-zoom-out';		
	}
	else 
	{
		cursorname = 'crosshair';
	}
	
	return cursorname;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// MapTool class - only one of these can be selected at a time.
////////////////////////////////////////////////////////////////////////////////////////////////////

MapTool.prototype.toString = MapTool_toString;
MapTool.prototype.render = MapTool_render;

function MapTool(name, toolTip)
{
	this.name = name;
	// contextPath must be dynamically defined globally
	var imageBase = contextPath + '/skins/' + skin + '/images/' + name;
	this.imageInactive = imageBase + '.gif';
	this.imageRollOver = imageBase + '_roll.gif';
	this.imageActive = imageBase + '_on.gif';
	this.toolTip = toolTip;
	this.mapStyle = 'mapborder' + name;
}

function MapTool_toString()
{
	document.writeln('name: ' + this.name + '<br/>');
	document.writeln('imageInactive: ' + this.imageInactive + '<br/>');
	document.writeln('imageRollOver: ' + this.imageRollOver + '<br/>');
	document.writeln('imageActive: ' + this.imageActive + '<br/>');
	document.writeln('toolTip: ' + this.toolTip + '<br/>');
	document.writeln('mapStyle: ' + this.mapStyle + '<br/>');
}

function MapTool_render()
{
	document.write('<a href="javascript:toolbar.changeTools(\'' + this.name + '\');" title="'+ this.toolTip + '"alt="' +
			this.name + '"><img id="' + this.name + '" name="' + this.name +
			'" onmouseout="toolbar.toolMouseOut(\'' + this.name + '\')" ' +
			'onmouseover="toolbar.toolMouseOver(\'' + this.name + '\')" title="'+ this.toolTip + '"alt="' + this.toolTip +
			'" border="0" src="' + this.imageInactive + '" vspace="0" hspace="0" align="absbottom"/></a>');
}

