/*
 *  Copyright 2006-2007 City of Saint Paul, MN, released under the City of Saint 
 *  Paul Open Source License.  Please see
 *  http://www.openmnnd.org/MOOSE_License.txt for the full text of the license.
 */

/*
 * Contains portions of Simple AJAX Code-Kit:
 * Simple AJAX Code-Kit (SACK) v1.6.1
 * �2005 Gregory Wild-Smith
 * www.twilightuniverse.com
 * Software licenced under a modified X11 licence,
 * see documentation or authors website for more details 
 */

/*
 * Contains portions of DHTML Suite for Applications:
 * Copyright �2006, www.dhtmlgoodies.com
 * Author Alf Magne Kalleland <post@dhtmlgoodies.com>
 */
/* ======================================================================    scripts/script.js
   ====================================================================== */


<!--
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
/* ======================================================================    scripts/date.js
   ====================================================================== */


<!--
				// Get today's current date.
				var now = new Date();
				// Array list of days.
				var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
				// Array list of months.
				var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
				// Calculate the number of the current day in the week.
				var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
				// Calculate four digit year.
				function fourdigits(number)	{
					return (number < 1000) ? number + 1900 : number;
												}
				// Join it all together
				today =  days[now.getDay()] + ", " +
							  months[now.getMonth()] + " " +
							   date + ", " +
								(fourdigits(now.getYear())) ;
//-->
/* ======================================================================    scripts/dropdown_nav.js
   ====================================================================== */

var disappeardelay=300  //menu disappear speed onMouseout (in miliseconds)
var enableanchorlink=0 //Enable or disable the anchor link when clicked on? (1=e, 0=d)
var hidemenu_onclick=1 //hide menu when user clicks within menu? (1=yes, 0=no)

/////No further editting needed

var ie5=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function showhide(obj, e, visible, hidden){
if (ie5||ns6)
dropmenuobj.style.left=dropmenuobj.style.top=-500
if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
obj.visibility=visible
else if (e.type=="click")
obj.visibility=hidden
}

function iecompattest(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
var edgeoffset=0
if (whichedge=="rightedge"){
var windowedge=ie5 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
edgeoffset=dropmenuobj.contentmeasure-obj.offsetWidth
}
else{
var topedge=ie5 && !window.opera? iecompattest().scrollTop : window.pageYOffset
var windowedge=ie5 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){ //move up?
edgeoffset=dropmenuobj.contentmeasure+obj.offsetHeight
if ((dropmenuobj.y-topedge)<dropmenuobj.contentmeasure) //up no good either?
edgeoffset=dropmenuobj.y+obj.offsetHeight-topedge
}
}
return edgeoffset
}

function dropdownmenu(obj, e, dropmenuID){
if (window.event) event.cancelBubble=true
else if (e.stopPropagation) e.stopPropagation()
if (typeof dropmenuobj!="undefined") //hide previous menu
dropmenuobj.style.visibility="hidden"
clearhidemenu()
if (ie5||ns6){
obj.onmouseout=delayhidemenu
dropmenuobj=document.getElementById(dropmenuID)
if (hidemenu_onclick) dropmenuobj.onclick=function(){dropmenuobj.style.visibility='hidden'}
dropmenuobj.onmouseover=clearhidemenu
dropmenuobj.onmouseout=ie5? function(){ dynamichide(event)} : function(event){ dynamichide(event)}
showhide(dropmenuobj.style, e, "visible", "hidden")
dropmenuobj.x=getposOffset(obj, "left")
dropmenuobj.y=getposOffset(obj, "top")
dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px"
dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px"
}
return clickreturnvalue()
}

function clickreturnvalue(){
if ((ie5||ns6) && !enableanchorlink) return false
else return true
}

function contains_ns6(a, b) {
while (b.parentNode)
if ((b = b.parentNode) == a)
return true;
return false;
}

function dynamichide(e){
if (ie5&&!dropmenuobj.contains(e.toElement))
delayhidemenu()
else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
delayhidemenu()
}

function delayhidemenu(){
delayhide=setTimeout("dropmenuobj.style.visibility='hidden'",disappeardelay)
}

function clearhidemenu(){
if (typeof delayhide!="undefined")
clearTimeout(delayhide)
}
/* ======================================================================    menubar.js
   ====================================================================== */

function showMenu(parent,submenu) {
	submenu.style.visibility = 'visible';
	submenu.style.left = parent.offsetLeft + 'px';
	if(document.all) {
		var trueTop = 0;
		var sumNode = parent;
		while(sumNode.offsetParent) {
			trueTop += sumNode.offsetTop;
			sumNode = sumNode.offsetParent;
		}
		submenu.style.top = trueTop + parent.offsetHeight + 'px';
	} else {
		submenu.style.top = parent.offsetTop + parent.offsetHeight + 'px';
	}
}

function showSubMenu(parent, submenu) {
	submenu.style.visibility = 'visible';
	submenu.style.left = parent.offsetLeft + parent.offsetWidth + 'px';
	submenu.style.top = parent.offsetTop + 'px';
}

function hideMenu(submenu) {
	submenu.style.visibility = 'hidden';
}


function Menubar() {
	var Tree;
	var Parent;

	this.createBranch = function(xml) {
		var items = xml.getElementsByTagName('item');	
		var branch = document.createElement('ul');
		branch.className = 'submenu';
		for(var i = 0; i < items.length; i++) {
			if(items[i].parentNode == xml) {
				var item = document.createElement('li');
				var itemLink = document.createElement('a');
				if(items[i].getAttribute('href')) {
					itemLink.href = items[i].getAttribute('href');
				} else {
					itemLink.href = '#';
				}

				if(items[i].getAttribute('target')) {
					itemLink.target = items[i].getAttribute('target');
				}

				if(items[i].getAttribute('id')) {
					itemLink.id = items[i].getAttribute('id');
				}

				itemLink.onclick = function () {
					hideMenu(branch);
				}
				itemLink.appendChild(document.createTextNode(items[i].getAttribute('title')));
				item.appendChild(itemLink);
				
				branch.appendChild(item);
				var submenus = items[i].getElementsByTagName('item');
				for(var sb = 0; sb <  submenus.length; sb++) {
					var subBranch = this.createBranch(items[i]);
					item.appendChild(subBranch);
					
					item.onmouseover = function() {
						showSubMenu(this, this.getElementsByTagName('ul')[0]);
					}
					item.onmouseout = function() {
						hideMenu(this.getElementsByTagName('ul')[0]);
					}
				}
			
			}
		}
		return branch;

	}

	var MySelf = this;
	this.populateMenuBar = function(xml) {
		var root = document.createElement('ul');
		root.className = 'menubar';
		var menus = xml.getElementsByTagName('menu');
		for(var m = 0; m < menus.length; m++) {
			var menu = document.createElement('li');
			menu.className = 'menu';
			var menuLink = document.createElement('a');
			menuLink.appendChild(document.createTextNode(menus[m].getAttribute('title')));
			if(menus[m].getAttribute('href')) {
				menuLink.href = menus[m].getAttribute('href');
			} else {
				menuLink.href = '#';
			}
			
			if(menus[m].getAttribute('target')) {
				menuLink.target = menus[m].getAttribute('target');
			}

			if(menus[m].getAttribute('id')) {
				menuLink.id = menus[m].getAttribute('id');
			}

			menu.appendChild(menuLink);
			root.appendChild(menu);
			var branch = this.createBranch(menus[m]);
			menu.appendChild(branch);
			menu.onmouseover = function () {
				if(this.getElementsByTagName('ul')[0]) {
					var subItems = this.getElementsByTagName('ul')[0].getElementsByTagName('li');
					if(subItems.length > 0) {
						showMenu(this, this.getElementsByTagName('ul')[0]);
					}
				}
			}
			menu.onmouseout = function () {
				hideMenu(this.getElementsByTagName('ul')[0]);
			}

		}
		if(Parent) {
			Parent.appendChild(root);
		}
		return root;

	}
	
	this.setParent = function(p) {
		Parent = p;
		if(Tree) {
			Parent.appendChild(Tree);
		}
	}
}
/* ======================================================================    libs/Debug.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Moose Debugging Layer
 */

var DebuggerWindow = null;

var DebuggerQueuedMessages = new Array();

function startDebugger(func) {
	DebuggerWindow = window.open('libs/Debugger.html', 'Debugger', 'width=640,height=480,toolbar=0,resizable=1,status=0,menubar=0,location=0,scrollbars=0');
	//DebuggerWindow = window.open();

	DebuggerWindow._onload = onload;
	DebuggerWindow.onload = function() {
		this._onload();
		func();
	}

	window._alert = window.alert;
	window.alert = function(msg) {
		logDebugMessage('Alert',true,msg);
		window._alert(msg);
	}
	window._confirm = window.confirm;
	window.confirm = function(msg) {
		var result = window._confirm(msg);
		logDebugMessage('Confirm',false,msg+' '+result);
		return result;
	}
}


function clearDebuggerLog() {
	var log = DebuggerWindow.document.getElementById('log');
	var p = log.parentNode;
	p.removeChild(log);

	var winBody = DebuggerWindow.document.getElementsByTagName('body')[0];
	var logger = DebuggerWindow.document.createElement('div');
	logger.id = 'log';
	winBody.appendChild(logger);


}

function logDebugMessage(unit, severe, msg, link) {
	if(DebuggerWindow == null || DebuggerWindow.closed) return false;

	//var time = new Date();
	//unit = time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()+'.'+time.getMilliseconds()+' '+unit;
	var doc = DebuggerWindow.document;
	var message;
	var message = doc.createElement('a');
	message.innerHTML = unit+': '+msg;
	if(severe) {
		message.style.fontWeight = 'bold';
	}

	if(link) {
		message.href = link;
		message.target = '_blank';
	}
	message.appendChild(doc.createElement('br'));
	if(DebuggerWindow.ready) {
		var debugBody = doc.getElementById('log');
		if(DebuggerQueuedMessages.length > 0) {
			for(var i = 0; i < DebuggerQueuedMessages.length; i++) {
//				debugBody.appendChild(DebuggerQueuedMessages[i]);
				debugBody.insertBefore(DebuggerQueuedMessages[i], debugBody.firstChild);
			}
			DebuggerQueuedMessages = new Array();
		}
		debugBody.insertBefore(message, debugBody.firstChild);
	} else {
		DebuggerQueuedMessages[DebuggerQueuedMessages.length] = message;
	}
}

function stopDebugger() {
	DebuggerWindow.close();
	DebuggerWindow = null;
}

/* ======================================================================    libs/util.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Useful Javascript Functions
 */

function trim(str) {
	while(str.substring(0,1).match(/\s/)) {
		str = str.substring(1, str.length);
	}
	while(str.substring(str.length-1,1).match(/\s/)) {
		str = str.substring(0, str.length-1);
	}
	str = str.replace(/\x0A/,'');
	return str;
}
function doNadda() { return false; }


function clearSelection () {
	if (document.selection)
	document.selection.empty();
	else if (window.getSelection)
	window.getSelection().removeAllRanges();
}

function roundUp(n) {
	var noDecimals = Math.round(n);
	if(n - noDecimals > 0) {
		noDecimals++;
	}
	return noDecimals;
}

/* ======================================================================    libs/Polygon.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

function Point(x, y) {
	this.x = x;
	this.y = y;

	this.type = 'point';
	
	this.fromString = function(str,delim) {
		var arr = str.split(delim);
		this.x = parseFloat(arr[0]);
		this.y = parseFloat(arr[1]);
	}

	this.toString = function(delim) {
		return this.x+delim+this.y;
	}

	this.equals = function(otherPoint) {
		return(this.x == otherPoint.x && this.y == otherPoint.y);
	}

	this.scale = function(s) {
		this.x = this.x * s;
		this.y = this.y * s;
	}

	this.clean = function() {
		this.x = parseFloat(this.x);
		this.y = parseFloat(this.y);
	}

	this.buffer = function(rad) {
		var newCirc = new Circle();
		newCirc.Center = new Point(this.x, this.y);
		newCirc.Radius = rad;
		return newCirc;
	}


	this.minX = function() {
		return x;
	}
	this.maxX = function() {
		return x;
	}

	this.minY = function() {
		return y;
	}

	this.maxY = function() {
		return y;
	}
}

function LineSegment(PointA, PointB) {
	this.pointA = PointA;
	this.pointB = PointB;

	this.type = 'line';
	
	this.slope = function() {
		return ((this.pointA.y - this.pointB.y) / (this.pointA.x - this.pointB.x));
	}

	this.eval = function(x) {
		if((x - this.pointA.x) == 0) { return this.pointA.y; }
		if((x - this.pointB.x) == 0) { return this.pointB.y; }
		return (this.slope() * (x - this.pointA.x) + this.pointA.y);
	}

	this.evalA = function () {
		return this.eval(this.pointA.x);
	}

	this.evalB = function () {
		return this.eval(this.pointB.x);
	}

	function returnGreater(A, B) {
		if(A > B) return A;
		return B;
	}

	function returnLesser(A, B) {
		if(A < B) return A;
		return B;
	}

	this.normalize = function() {
		if(this.pointA.x > this.pointB.x) {
			var t = this.pointA.x;
			this.pointA.x = this.pointB.x;
			this.pointB.x = t;
		}
		if(this.pointA.y > this.pointB.y) {
			var t = this.pointA.y;
			this.pointA.y = this.pointB.y;
			this.pointB.y = t;
		}

	}

	this.getLength = function() {
		if((this.pointA.x - this.pointB.x) == 0) { return this.maxY() - this.minY(); }
		if((this.pointA.y - this.pointB.y) == 0) { return this.maxX() - this.minX(); }
		return (Math.sqrt(Math.pow(this.getWidth(),2) + Math.pow(this.getHeight(),2)));
	}

	this.minX = function () {
		return returnLesser(this.pointA.x, this.pointB.x);
	}

	this.maxX = function () {
		return returnGreater(this.pointA.x, this.pointB.x);		
	}

	this.minY = function () {
		return returnLesser(this.pointA.y, this.pointB.y);
	}

	this.maxY = function () {
		return returnGreater(this.pointA.y, this.pointB.y);		
	}


	this.getWidth = function() {
		return this.maxX() - this.minX();
	}

	this.getHeight = function() {
		return this.maxY() - this.minY();
	}

	this.shift = function(x,y) {
		this.pointA.x = parseInt(this.pointA.x);
		this.pointA.y = parseInt(this.pointA.y);
		this.pointB.x = parseInt(this.pointB.x);
		this.pointB.y = parseInt(this.pointB.y);
		this.pointA.x += x;
		this.pointB.x += x;
		this.pointA.y += y;
		this.pointB.y += y;
	}

	this.scale = function(x, y) {
		this.pointA.x = this.pointA.x * x;
		this.pointA.y = this.pointA.y * y;
		this.pointB.x = this.pointB.x * x;
		this.pointB.y = this.pointB.y * y;
	}

	this.getMidPoint = function() {
		var oldMidX = (this.pointA.x + this.pointB.x) / 2;
		var oldMidY = this.eval(oldMidX);
		return new Point(oldMidX, oldMidY);
	}

	this.shiftMidPoint = function(newMidPoint) {
		var oldMidPoint = this.getMidPoint();
		this.shift(oldMidPoint.x-newMidPoint.x, oldMidPoint.y-newMidPoint.y);
	}

	this.getScaledPoint = function(fromLine, fromPoint) {
		var scaledPoint = new Point();
		scaledPoint.x = fromLine.getWidth() / (fromPoint.x - fromLine.minX());
		scaledPoint.x = (this.getWidth() / scaledPoint.x) + this.minX();
		scaledPoint.y = fromLine.getHeight() / (fromPoint.y - fromLine.minY());
		scaledPoint.y = (this.getHeight() / scaledPoint.y) + this.minY();
		return scaledPoint;
	}

	this.scaleAboutMidPoint = function(scale) {
		var oldMidPoint = this.getMidPoint();	
		this.scale(scale,scale);
		var newMidPoint = this.getMidPoint();
		this.shift((oldMidPoint.x-newMidPoint.x), oldMidPoint.y-newMidPoint.y);
	}

	this.toString = function(delim) {
		var retString = this.pointA.x+delim+this.pointA.y+delim+this.pointB.x+delim+this.pointB.y;
		return retString;
	}


	this.fromString = function(str, delim) {
		var coords = str.split(delim);
		for(var i = 0; i < coords.length; i++) {
			coords[i] = parseFloat(coords[i]);
		}
		this.pointA = new Point(coords[0], coords[1]);
		this.pointB = new Point(coords[2], coords[3]);
	}

	this.intersectEndPoint = function() {
	}
	
/*
this.intersects = function(testLine) {
		var minX = this.minX();
		var maxX = this.maxX();

		var testMinX = testLine.minX();
		var testMaxX = testLine.maxX();

		var minY = this.minY();
		var maxY = this.maxY();
		var testMinY = testLine.minY();
		var testMaxY = testLine.maxY();

		// This saves some time if the lines don't share a domain
		if(testMinX > maxX || testMaxX < minX) {
			return false;
		}

		// If the line is striaght up and down, it needs to be handled
		// In a special fashion, checking both the X and Y domain
		// using the end points.
		if((this.pointA.x - this.pointB.x) == 0) {
			var testLineY = testLine.eval(this.pointA.x);
			return (testLineY >= minY && testLineY <= maxY);
		}
		if(testMinX - testMaxX == 0) {
			return(testMinX >= minX && testMinX <= maxX);
		}

		// Do some domain normalization, narrows the test domain
		// to the smaller line segment.
		minX = returnGreater(testMinX, minX);
		maxX = returnLesser(testMaxX, maxX);


		return (
			(this.eval(minX) < testLine.eval(minX)) && (testLine.eval(maxX) <= this.eval(maxX))
			||
			(this.eval(minX) > testLine.eval(minX)) && (testLine.eval(maxX) >= this.eval(maxX))
		);

	}
*/

	this.intersects = function(testLine) {
		var X1 =  this.pointA.x;
		var Y1 =  this.pointA.y;
		var X2 =  this.pointB.x;
		var Y2 =  this.pointB.y;

		var X3 = testLine.pointA.x;
		var Y3 = testLine.pointA.y;
		var X4 = testLine.pointB.x;
		var Y4 = testLine.pointB.y;

		var dDenom = (((X2 - X1) * (Y4 - Y3)) - ((Y2 - Y1) * (X4 - X3)));

		if(dDenom == 0) {
			return false; // Line Segments are Parallel
		}
		var dSnum = (((Y1 - Y3) * (X4 - X3)) - ((X1 - X3) * (Y4 - Y3)));
		var dTnum = (((Y1 - Y3) * (X2 - X1)) - ((X1 - X3) * (Y2 - Y1)));

		var S = dSnum / dDenom;
		var T = dTnum / dDenom;
		var testS = (0 <= S && S <= 1);
		var testT = (0 <= T && T <= 1);

		return(testS && testT)
	}

	this.buffer = function(rad) {
		var slope = this.slope();
		var inverse_slope = -1 / slope;
		var x_shift = 0, y_shift = 0;

		if(!isFinite(slope)) {
			x_shift = rad;
		} else if(slope == 0) {
			y_shift = rad;
		} else {
			var theta = Math.atan(inverse_slope);
			x_shift = Math.round(Math.cos(theta) * rad);
			y_shift = Math.round(Math.sin(theta) * rad);
		}

		var newPoints = new Array();
		newPoints[0] = new Point(this.pointA.x + x_shift, this.pointA.y + y_shift);
		newPoints[1] = new Point(this.pointB.x + x_shift, this.pointB.y + y_shift);
		newPoints[2] = new Point(this.pointB.x - x_shift, this.pointB.y - y_shift);
		newPoints[3] = new Point(this.pointA.x - x_shift, this.pointA.y - y_shift);
		var pointsString = '';
		for(var i = 0; i < newPoints.length; i++) {
			pointsString += newPoints[i].toString(',')+' ';
		}

		var newLines = new Array();
		newLines[0] = new LineSegment(newPoints[0], newPoints[1]);
		newLines[1] = new LineSegment(newPoints[1], newPoints[2]);
		newLines[2] = new LineSegment(newPoints[2], newPoints[3]);
		newLines[3] = new LineSegment(newPoints[3], newPoints[0]);
		
		//logDebugMessage('Buffered Segment', true, pointsString);
		var newPoly = new Polygon();
		for(var i = 0; i < newLines.length; i++) {
			newPoly.addLine(newLines[i]);
		}
		//logDebugMessage('Buffered Segment', true, 'Lines: '+newPoly.toString(','));
		return newPoly;
	}
}


function Polygon() {
	this.Lines = new Array();

	this.origin = new Point(0,0);

	this.type = 'polygon';
	
	var MinX = 1000000, MaxX = -1, MinY = 1000000, MaxY = -1;

	this.addLine = function(line) {
		if(line.minX() < MinX) { MinX = line.minX(); }
		if(line.maxX() > MaxX) { MaxX = line.maxX(); }
		if(line.minY() < MinY) { MinY = line.minY(); }
		if(line.maxY() > MaxY) { MaxY = line.maxY(); }

		this.Lines[this.Lines.length] = line;
	}

	this.minX = function() {
		return MinX;
	}

	this.maxX = function() {
		return MaxX;
	}

	this.minY = function() {
		return MinY;
	}

	this.maxY = function() {
		return MaxY;
	}

	this.clearLines = function () {
		this.Lines = new Array();
	}

	this.countLines = function() {
		return this.Lines.length;
	}

	this.countIntersections = function(testLine) {
		var c = 0;
		for(var i = 0; i < this.Lines.length; i++) {
			if(this.Lines[i].intersects(testLine)) {
				c++;
			}
		}
		return c;
	}

	this.isMemberPoint = function(pointA) {
		if(pointA.x < MinX || pointA.x > MaxX) { return false; }
		if(pointA.y < MinY || pointA.y > MaxY) { return false; }
		var intersections = this.countIntersections(new LineSegment(new Point(0,pointA.y), pointA));
		var intersections2 = this.countIntersections(new LineSegment(new Point(0,0), pointA));
//		return((intersections % 2) == 1 || (intersections2 % 2) == 1);
//		return (intersections % 2 == 1);

		return((intersections % 2) == 1 && (intersections2 % 2) == 1);
	}

	this.intersectsPoly = function(poly) {
		var nIntersections = 0;
		var allLines = poly.Lines;
		for(var i = 0; i < allLines.length; i++) {
			nIntersections+=this.countIntersections(allLines[i]);
		}
		return nIntersections;
	}
	
	this.isMember = function(shape) {
		if(shape.type.match(/point/i)) {
			return this.isMemberPoint(shape);
		} else if(shape.type.match(/polygon/i)) {
			var points = shape.getPoints();
			for(var p = 0; p < points.length; p++) {
				if(this.isMemberPoint(points[p])) {
					return true;
				}
			}
			if(this.intersectsPoly(shape) > 0) {
				return true;
			} else {
				//logDebugMessage('Poly Test', true, 'Not Intersect');
			}
			return false;
		} else if(shape.type.match(/line/i)) {
			return(this.countIntersections(shape) > 0);
		}
	}

	
	this.buildFromPoints = function(pointsArray) {
		this.Lines = new Array();
		var lenLimit = (pointsArray.length % 2) + 1;
		for(var i = 0; i < pointsArray.length - 1; i++) {
			var newLineSeg = new LineSegment(pointsArray[i], pointsArray[i+1]);
			this.addLine(newLineSeg);
		}
		// Now Close the polygon
		var newLineSeg = new LineSegment(pointsArray[pointsArray.length-1], pointsArray[0]);
		this.addLine(newLineSeg);
	}

	this.toString = function(delim) {
		var myStr = '';
		for(var i = 0; i < this.Lines.length; i++) {
			myStr += this.Lines[i].pointA.toString(delim) + delim;
		}
		myStr += this.Lines[this.Lines.length-1].pointB.toString(delim);
		return myStr;
	}

	this.area = function() {
		var myPoints = this.getPoints();
		myPoints[myPoints.length ] = myPoints[0];
		var sum = 0;
		for(var i = 0; i < myPoints.length - 1; i++) {
			myPoints[i].clean(); myPoints[i+1].clean();
			sum += (myPoints[i].x*myPoints[i+1].y - myPoints[i+1].x*myPoints[i].y);
		}
		sum *= .5;
		return sum;
	}

	this.centroid = function() {
		var myPoints = this.getPoints();
		myPoints[myPoints.length ] = myPoints[0];
		var area = 1 / (6 * this.area());
		var x = 0;
		var y = 0;
		for(var i = 0; i < myPoints.length -1; i++) {
			myPoints[i].clean(); myPoints[i+1].clean();
			var f = (myPoints[i].x*myPoints[i+1].y - myPoints[i+1].x*myPoints[i].y);
			x += ((myPoints[i].x + myPoints[i+1].x)*f);
			y += ((myPoints[i].y + myPoints[i+1].y)*f);
		}
		return new Point(x*area,y*area);
	}

	this.getPoints = function() {
		var retArr = new Array();
		for(var i = 0; i < this.Lines.length; i++) {
			retArr[retArr.length] = this.Lines[i].pointA;
		}
		return retArr;
	}

	this.buffer = function(rad) {
		var center = this.centroid();
		var bufferedPoints = new Array();
		var myPoints = this.getPoints();
		myPoints[myPoints.length] = myPoints[0];

		var elimBuffers = new Array();

		elimBuffers[0] = this;

		for(var i = 0; i < myPoints.length -1; i++) {
			var line = new LineSegment(myPoints[i], myPoints[i+1]);
			elimBuffers[elimBuffers.length] = line.buffer(rad);
			var circ = new Circle();
			circ.Center = myPoints[i];
			circ.Radius = rad;
			elimBuffers[elimBuffers.length] = circ;
		}
		return elimBuffers;
	}
}


function Circle(cCenter, cRadius) {
	this.Center = cCenter;
	this.Radius = cRadius;

	this.type = 'circle';

	this.isMemberPoint = function(P) {
		var line = new LineSegment(this.Center, P);
		var len = line.getLength();
		return(len < this.Radius);
	}

	function square(x) {
		return (x*x);
	}


	this.minX = function() {
		return (this.Center.x - this.Radius);
	}

	this.maxX = function() {
		return(this.Center.x + this.Radius);
	}

	this.minY = function() {
		return (this.Center.y - this.Radius);
	}

	this.maxY = function() {
		return (this.Center.y + this.Radius);
	}

	this.isMember = function(Poly) {
		if(Poly.type.match(/point/i)) {
			return this.isMemberPoint(Poly);
		} else if(Poly.type.match(/circle/i)) {
			var testLine = new LineSegment(this.Center, Poly.Center);
			var totalLength = this.Radius + Poly.Radius;
			return(testLine.getLength() <= totalLength);
		} else if(Poly.type.match(/line/i)) {
			var x1 = Poly.pointA.x;
			var y1 = Poly.pointA.y;
			var x2 = Poly.pointB.x;
			var y2 = Poly.pointB.y;

			var x3 = this.Center.x;
			var y3 = this.Center.y;

			var r = parseFloat(this.Radius);
			var diffX = x2-x1;
			var diffY = y2-y1;
			var diffXSquared = square(diffX);
			var diffYSquared = square(diffY);
			var a = diffXSquared + diffYSquared;
			var b = 2* (diffX*(x1 - x3) + diffY*(y1 - y3));
			var c = square(x3) + square(y3) +  square(x1) + square(y1)  - 2* ( x3*x1 + y3*y1 ) - square(r);

			var det = b * b - 4 * a * c;


			if(det <= 0) { return false; }

			b = (x3 - x1)*(x2 - x1) + (y3 - y1)*(y2 - y1);
			//b = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1);
			var u= b/a;

			//logDebugMessage('Determinate', false, u);
			return(0 <= u && u <= 1);
		} else if(Poly.type.match(/poly/i)) {
			var points = Poly.getPoints();
			var member = false;
			for(var i = 0; i < points.length && !member; i++) {
				if(this.isMemberPoint(points[i])) {
					return true;
				}
			}

			var theLines = Poly.Lines;
			for(var i = 0; i < theLines.length && !member; i++) {
				if(this.isMember(theLines[i])) {
					return true;
				}
			}
			return false;
		}
		return false;
	}

	this.toString = function(delim) {
		var PointA = new Point(this.Center.x - this.Radius, this.Center.y - this.Radius);
		var PointB = new Point(this.Center.x + this.Radius, this.Center.y + this.Radius);
		return(PointA.toString(delim)+delim+PointB.toString(delim));
	}

	this.buffer = function(rad) {
		var newCirc = new Circle();
		newCirc.Center = this.Center;
		newCirc.Radius = this.Radius + rad;
		return newCirc;
	}
}
/* ======================================================================    libs/WindowSize.js
   ====================================================================== */



/* 
 * This determines the window size.
 * I wrote this because there is differences between standard and quirks mode.
 */

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

	var winSize = new Point(myWidth, myHeight);
	return winSize;
}
/* ======================================================================    libs/opacity.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * I wrote this function as a generic function
 * to change the Opacity of different objects
 * It works in both Mozilla and IE.
 */

function setOpacity(elm, opaqueness) {
	if(opaqueness == '100' || opaqueness == '1') {
		elm.style.opacity = '1.00';
	} else {
		elm.style.opacity = '0.' + opaqueness; // The Standard
	}
	if(document.all) {
		elm.style.filter = "alpha(opacity="+opaqueness+")"; // IE
	}

}

function getOpacity(elm) {
	var styleString = '';
	if(document.all) {
		var str = elm.style.filter;
		str = str.replace('alpha(opacity=','');
		str = str.replace(')','');
		styleString = str;
	} else {
		var str = elm.style.opacity;
		var f = parseFloat(str);
		f = f * 100;
		styleString = f;
	}

	if(!styleString) {
		styleString = 100;
	}

	return parseFloat(styleString);
}


/* ======================================================================    libs/Draggable2.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/
function Draggable(obj, trigger, dirX, dirY, pixelOverride) {

	this.onDrop = function(trigger,obj) { }

	this.whileDrag = function(trigger,obj) {  return false; }

	var cursorPosition;
	var firstXY;
	
	var DragObj = this;

	function startDrag(event) {
		if(window.event) { event = window.event; }
		StartPoint = new Point(obj.offsetLeft, obj.offsetTop);
		cursorPosition = new Point(event.clientX - StartPoint.x, event.clientY - StartPoint.y);
		firstXY = new Point(event.clientX, event.clientY);
		if(document.all) {	
			document.attachEvent("onmousemove", whileDragging);
			document.attachEvent("onmouseup",   endDrag);
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		} else {
			document.addEventListener("mousemove",whileDragging,true);
			document.addEventListener("mouseup",endDrag,true);
		}
		if(event.preventDefault) { event.preventDefault(); }
		return false;
	}


	function whileDragging(event) {
		if(window.event) { event = window.event; }
		if(cursorPosition != null) {
			if(dirX) { obj.style.left = (event.clientX - cursorPosition.x)+'px'; }
			if(dirY) { obj.style.top = (event.clientY - cursorPosition.y)+'px'; }
			obj.style.bottom = 'auto';
			obj.style.right = 'auto';
		}
		DragObj.whileDrag(trigger,obj);

		if(event.preventDefault) { event.preventDefault(); }
		return false;
	}

	function endDrag(event) {
		if(window.event) { event = window.event; }
		if (document.all) {
			document.detachEvent("onmousemove", whileDragging);
			document.detachEvent("onmouseup",   endDrag);
		} else {
			document.removeEventListener("mousemove", whileDragging,   true);
			document.removeEventListener("mouseup",   endDrag, true);
		}

		cursorPosition = null;
		if(obj.offsetTop < 0) { obj.style.top = '0px'; }

		var winSize = getWindowSize(); // From WindowSize.js
		var parent = obj.parentNode;
		winSize.x = parent.offsetWidth;
		if(parent.offsetHeight) {
			winSize.y = parent.offsetHeight;
		}
		/** Align the Leftness of the Draggable Object **/
		var newLeft = obj.offsetLeft;
		if(obj.offsetLeft < 0) { newLeft = 0; }
		if(newLeft+obj.offsetWidth > winSize.x) { newLeft = (winSize.x - obj.offsetWidth); }
		/* By Aligning to Percentages the Boxes will keep the same relative position 
			no matter the window size.
			Setting the pixel over-ride prevents Draggable from approximating a percentage.
		*/
		if(!pixelOverride) {
			if(newLeft > winSize.y/2) {
				newLeft += obj.offsetWidth;
				obj.style.left = 'auto';
				obj.style.right = ((winSize.x - newLeft) / winSize.x) * 100 + '%';
			} else {
				obj.style.right = 'auto';
				obj.style.left = ((newLeft / winSize.x) * 100)+'%';
			}
		
			/** Align the Topness of the Draggable Object **/
			var newTop = obj.offsetTop;
			if(obj.offsetTop < 0 || !obj.offsetTop) { newTop = 0; }
			else if((obj.offsetTop + obj.offsetHeight) > winSize.y) { newTop = (winSize.y - obj.offsetHeight); }

			if(newTop > winSize.y/2) {
				newTop += obj.offsetHeight;
				obj.style.top = 'auto';
				obj.style.bottom = ((winSize.y - newTop) / winSize.y) * 100 + '%';
			} else {
				obj.style.bottom = 'auto';
				obj.style.top = ((newTop / winSize.y) * 100)+'%';
				if(newTop==0) { obj.style.top = '0%'; }
			}
		}
		DragObj.onDrop(trigger,obj);

	
		if(event.preventDefault) { event.preventDefault(); }
		return false;
	}
	
	trigger._onmousedown = trigger.onmousedown;
	trigger.onmousedown = function(event) {
		if(window.event) { event = window.event; }
		startDrag(event);
		if(trigger._onmousedown) {
			trigger._onmousedown(event);
		}
	}

}

/* ======================================================================    libs/http.js
   ====================================================================== */

/*
 * Creates an XML HTTP Object
 */

function getHTTPObject() {
	var xmlhttp;

	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(E) {
			try {
			xmlhttp = new XMLHttpRequest();
			} catch(ee) {
			return false;
			}
		}
	}
	return xmlhttp;

}

function getHTTPObject2() {
  var xmlhttp;
  /*@cc_on

  @if (@_jscript_version >= 5)

    try {

      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

    } catch (e) {

      try {

        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

      } catch (E) {

        xmlhttp = false;

      }

    }

  @else

  xmlhttp = false;

  @end @*/

  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {

    try {

      xmlhttp = new XMLHttpRequest();

    } catch (e) {

      xmlhttp = false;

    }

  }
  return xmlhttp;
}
/* ======================================================================    libs/CGI.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Processes URL Arguements
 * This is really pretty simple.  It takes in a parameter name
 * parses the URL for it, then returns the value of the contents
 * It lets Javascript do some of the things once required by a CGI-script
 */

function CGI () {
	this.param = function(theArgName) {
		var sArgs = location.search.slice(1).split('&'); // Split up the parameters from the URL
		var r = '';
		for(var i = 0; i < sArgs.length; i++) {		// Loop through each parameter
			if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName) {	// once the new one is found get the answer(s)
				r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
				break;
			}
		}
		return (r.length > 0 ? unescape(r).split(',') : null) // split up the answers based on commas and return
	}

	this.getCookie = function(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) { 
				c_start=c_start + c_name.length+1;
				c_end=document.cookie.indexOf(";",c_start);
				
				if (c_end==-1) c_end=document.cookie.length
					return unescape(document.cookie.substring(c_start,c_end));
			} 
	        }
		return null;
	}

	this.setCookie = function(c_name,value,expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate);
	}
}
/* ======================================================================    libs/Views.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Collection of Functions for dealing with Views in the Main Application
 */

function boundingBoxStringToLineSegment(bbox,delim) {
	var line = new LineSegment();
	line.fromString(bbox, delim);
	return line;
}

function boundingBoxToPointScale(bboxLine, mapDimensions) {
	var diffX = bboxLine.getWidth(); // Width in Ground Units
	var diffY = bboxLine.getHeight(); // Height of Map in Ground Units

	// The center point of the extents
	var centerPoint = new Point(bboxLine.minX() + diffX / 2, bboxLine.minY() + diffY / 2);

	// Scale in Ground Units per Pixel
	var scaleX = diffX / mapDimensions.x;
	var scaleY = diffY / mapDimensions.y;
	// Pick the "larger" scale
	var selectedScale = Math.max(scaleX, scaleY);
	// Return it in a useful fashion for other functions
	var retArr = new Array();
	retArr[0] = centerPoint; retArr[1] = selectedScale;
	return retArr;
}

function pointScaleStringToPointScale(psString, delim) {
	var psArr = psString.split(delim);
	for(var i = 0; i < psArr.length; i++) {
		psArr[i] = parseFloat(psArr[i]);
	}
	var centerPoint = new Point(psArr[0], psArr[1]);
	var scale = psArr[2];
	var retArr = new Array();
	retArr[0] = centerPoint; retArr[1] = scale;
	return retArr;
}

function convertViewString(viewString, viewSize) {
	viewString = viewString.replace(' ','');
	var viewSplit = viewString.split(',');
	var psArr = new Array();
	if(viewSplit.length == 3) {
		psArr = pointScaleStringToPointScale(viewString,',');
	} else if(viewSplit.length == 4) {
		psArr = boundingBoxToPointScale(boundingBoxStringToLineSegment(viewString, ','), viewSize);
	}
	return new Circle(psArr[0], psArr[1]);
}

function getViewStringFromXML(xmlView) {
	var viewString = xmlView.firstChild.nodeValue;
	return convertViewString(viewString);

}

function getViewStringFromMapbook(mapBook, title) {
	var xmlObj = getObjectByTitle(mapBook, 'view', title);
	return getViewStringFromXML(xmlObj);
}


/*
function loadBoundingBox(bbox) {
	var pointScaleArr =  boundingBoxToPointScale(boundingBoxStringToLineSegment(bbox, ','), mapSize);
	changePointScale(pointScaleArr[0],pointScaleArr[1]);
	logDebugMessage('Load Bounding Box', true, mapCenterPoint.toString(',')+' '+mapScale);
}

function loadPointScale(psString) {
	var pointScaleArr =  pointScaleStringToPointScale(psString,',');
	changePointScale(pointScaleArr[0],pointScaleArr[1]);
	logDebugMessage('Load Point Scale', true, mapCenterPoint.toString(',')+' '+mapScale);
}

function loadViewString(viewString) {
	viewString = viewString.replace(' ','');
	var viewSplit = viewString.split(',');
	if(viewSplit.length == 3) {
		//logDebugMessage('Load View', false, 'Load Point/Scale Type');
		loadPointScale(viewString);
	} else if(viewSplit.length == 4) {
		//logDebugMessage('Load View', false, 'Load BBOX Type');
		loadBoundingBox(viewString);
	}
}

function loadView(viewName) {
	var view = getObjectByTitle(xmlDoc, 'view', viewName);
	loadViewXML(view);
}

function loadViewXML(view) {
	var viewString = view.firstChild.nodeValue;
	loadViewString(viewString);

}
*/
/* ======================================================================    libs/MapbookUtils.js
   ====================================================================== */

/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following terms and conditions:

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Default Layers have a little more dimension in GISmo3 than they have in previous version
 * This file is here because G3 will also use a stored cookie in order to save default information.
 */

var DEFAULT_VIEW;

function loadDefaultsFromMapBook(xmlObj, sourceObj, EventManager, objMap) {
	var allMaps = xmlObj.getElementsByTagName('map');
	var allServices = xmlObj.getElementsByTagName('service');
	var allViews = xmlObj.getElementsByTagName('view');


	var foundView = false;
	if(DEFAULT_VIEW) {
		DEFAULT_VIEW = false;
		foundView = true;
	} else {
		for(var v = 0 ; v < allViews.length; v++) {
			var def = new String(allViews[v].getAttribute('default'));
			if(def.match(/true/i)) {
				var name = allViews[v].getAttribute('title');
				//loadViewXML(allViews[v]);
				if(!foundView) {
					var circView = convertViewString(allViews[v].firstChild.nodeValue, objMap.getMapSize());
					EventManager.changePointScale(circView.Center,circView.Radius);
					logDebugMessage('Defaults', true, 'Loaded Default View');
				}
				EventManager.triggerEvent('addview', allViews[v]);
				foundView = true;
			}
		}
	}

	var layersToAdd = new Array();

	for(var m = 0 ; m < allMaps.length; m++) {
		var name = allMaps[m].getAttribute('title');
		var title = allMaps[m].getAttribute('display');
		var def = new String(allMaps[m].getAttribute('default'));
		var found = false;
			if(def.match(/true/i) || found) {
			if(!title) { title = name; }
			layersToAdd[name] = allMaps[m];
		}
	}

	for(var l in layersToAdd) {
		EventManager.triggerEvent('addlayer', layersToAdd[l]);
	}

	var servicesToAdd = new Array();
	for(var s = 0; s < allServices.length; s++) {
		var def = new String(allServices[s].getAttribute('default'));
		var sel = new String(allServices[s].getAttribute('selected'));
		if(def.match(/true/i)) {
			var display = allServices[s].getAttribute('display');
			var title = allServices[s].getAttribute('title');
			if(!display) { display = title; }
			servicesToAdd[display] = allServices[s];
		}
	}
	for(var s in servicesToAdd) {
		EventManager.triggerEvent('addservice', servicesToAdd[s]);
		if(servicesToAdd[s].getAttribute('selected') && servicesToAdd[s].getAttribute('selected').match(/true/i)) {
			EventManager.triggerEvent('selecttool', s);
		}
	}

}

function loadDefaults(xmlObj, EventManager, objMap) {
/*	if(checkState()) {
		loadDefaultsFromMapBook(getState(), xmlObj);
	} else {*/
		loadDefaultsFromMapBook(xmlObj, xmlObj,EventManager,objMap);
/*	}*/
}

function getMapbook(mapBook, EventManager, objMap) {
	var http = getHTTPObject();
	http.open("GET", mapBook);
	http.onreadystatechange = function () { 
		if(http.readyState == 4) {
			xmlDoc = http.responseXML;
			EventManager.onLoadedMapbook(xmlDoc, objMap);
			return xmlDoc;
		}
	};
	http.send(null);
}

function getObjectByTitle(xmlDoc, objType, objTitle) {
	var objs = xmlDoc.getElementsByTagName(objType);
	for(var i = 0; i < objs.length; i++) {
		if(objs[i].getAttribute('title') && objs[i].getAttribute('title') == objTitle) {
			return objs[i];
		}
	}
	return null;
}


function getDefaultMapbook(EventManager,oMap) {
	var util = new CGI();

	var viewFromURL = util.param('view');
	var mapbookFromURL = util.param('mapbook');
	if(!viewFromURL) { viewFromURL = util.param('zoomto'); }

	if(viewFromURL) {
		var circView = convertViewString(new String(viewFromURL), oMap.getMapSize());
		EventManager.changePointScale(circView.Center,circView.Radius);
		DEFAULT_VIEW = true;
	}

	var MapBook = MAPBOOK_FILE;
	if(mapbookFromURL) {
		MapBook = mapbookFromURL;
	}


	EventManager.addEventListener('loadedmapbook', 'URLLayers', 
		function (xmlDoc) {
			EventManager.removeEventListener('loadedmapbook', 'URLLayers');
			var layers = new String(util.param('layers'));
			var layersArr = layers.split(',');
			for(var i = 0; i < layersArr.length; i++) {
				var map = getObjectByTitle(xmlDoc, 'map', layersArr[i]);
				if(map) {
					EventManager.triggerEvent('addlayer',map);
				}
			}
		});

	getMapbook(MapBook,EventManager,oMap);
	/*DEFAULT_VIEW = false;*/
}

/* ======================================================================    objects/GEvents.js
   ====================================================================== */

var CONFIRM_REMOVE = false;

function GEvents() {
	var events = new Array();
	
	this.addEventListener = function(eventType, eventName, action) {
		if(!events[eventType]) {
			events[eventType] = new Array();
		} 
		events[eventType][eventName] = action;
	}

	this.removeEventListener = function(eventType, eventName) {
		if(events[eventType][eventName]) {
			delete events[eventType][eventName];
		}
	}
	this.triggerEvent = function(eventName, object) {
		if(eventName == 'removelayer') {
			return this.onRemoveLayer(object);
		} else if(eventName == 'removeservice') {
			return this.onRemoveService(object);
		}
		var eventArray = events[eventName];
		for(var i in eventArray) {
			eventArray[i](object);
		}

	}

	this.onRemoveLayer = function(layerName) {
		var eventArray = events['removelayer'];
		if(!CONFIRM_REMOVE || confirm('Do you want to remove layer '+layerName+'?')) {
			for(var i in eventArray) {
				eventArray[i](layerName);
			}
			return true;
		} else {
			return false;
		}
		return false;
		
	}

	this.onRemoveService = function(serviceName) {
		var eventArray = events['removeservice'];
		if(!CONFIRM_REMOVE || confirm('Do you want to remove service '+serviceName+'?')) {
			for(var i in eventArray) {
				eventArray[i](serviceName);
			}
			return true;
		} else {
			return false;
		}
		
	}



	this.onLoadedMapbook = function(mapBookXML,objMap) {
		var eventArray = events['loadedmapbook'];
		for(var i in eventArray) {
			eventArray[i](mapBookXML, this, objMap);
		}

	}

	this.changePointScale = function(centerPoint, scale) {
		var circ = new Circle();
		circ.Radius = scale;
		circ.Center = centerPoint;
		this.triggerEvent('navigate',circ);
	}
}
/* ======================================================================    objects/Map.js
   ====================================================================== */

var MAP_MAX_ZINDEX = 500;
var MAP_CONTROL_INDEX = 1000;
var MAP_DRAWING_INDEX = 999;
var MAP_POPUP_ZINDEX = 5000;

function objectClientPosition(obj) {
	var position = new Point(obj.offsetLeft, obj.offsetTop);
	var parent = obj.parentNode;

	while(parent && parent.tagName == 'DIV') {
		if(parent.offsetLeft) {
			position.x += parent.offsetLeft;
		}
		if(parent.offsetTop) {
			position.y += parent.offsetTop;
		}
		parent = parent.parentNode;
	}
	return position;
}

function GMap (EventManager) {
	var MySelf = this;
	var MapParent;
	var ImageParent = document.createElement('div');
	var ImageControl = document.createElement('input');
	var ImageImageMaps = document.createElement('map');
	var ScaleFactor = 1;
	var MapReference = null; 

	ImageControl.type = 'Image';

	var ImageMapControl = document.createElement('img');
	ImageMapControl.src = BLANK_IMAGE;
	ImageMapControl.style.zIndex = MAP_CONTROL_INDEX - 1;

	ImageControl.src = BLANK_IMAGE;
	ImageControl.style.zIndex = MAP_CONTROL_INDEX;

	var FunctionOffset = new Point();
	var FunctionSemaphore = false;

	var DrawnPoints = new Array();
	var PreviousViews = new Array();
	var DrawBox = document.createElement('div');
	DrawBox.style.position = 'absolute';
	DrawBox.style.border = 'solid 2px red';
	DrawBox.style.zIndex = MAP_DRAWING_INDEX;
	DrawBox.style.visibility = 'hidden';
	DrawBox.style.overflow = 'hidden';

	var MapCenterPoint = new Point(576000, 157909.5);
	var MapScale = 25;


	var LayerURLs = new Array();
	var LayerLegends = new Array();
	var LayerImages = new Array();
	var LayerParameters = new Array();

	var min_z_index = MAP_MAX_ZINDEX;

	this.setScaleFactor = function(scF) {
		ScaleFactor = scF;
	}
	
	this.setMapReference = function(m) {
		MapReference = m;
	}

	this.changePointScale = function(point,scale) {
		var circ = new Circle(point,scale);
		PreviousViews[PreviousViews.length] = circ;
		MapScale = scale;
		MapCenterPoint = point;
	}

	var LastActionTime = 0;

	this.setLastActionTime = function() {
		var d = new Date();
		LastActionTime = d.getTime();
		return LastActionTime;
	}

	this.getLastActionTime = function() {
		return LastActionTime;
	}


	/*
	 * This will refresh the map when a coordinate change happens
	 */
	this.onChangePointScale = function(psc) {
		PreviousViews[PreviousViews.length] = psc;
		MapScale = psc.Radius * ScaleFactor;
		MapCenterPoint = psc.Center;
		MySelf.refreshLayers();
	}

	/* Drawing Tools! */

	var DrawingShape = 'point';

	function startDrawing(event) {
		if(window.event) { event = window.event; }

		FunctionOffset = objectClientPosition(this);
		DrawnPoints = new Array();
		if(document.all) {	
			document.attachEvent("onmouseup", stopDrawing);
		} else {
			document.addEventListener("mouseup",stopDrawing,true);
		}
		if(DrawingShape == 'box' || DrawingShape=='evenbox') {
			DrawnPoints[0] = new Point(event.clientX-FunctionOffset.x, event.clientY-FunctionOffset.y);
		}
		MySelf.drawPoint(event.clientX-FunctionOffset.x, event.clientY-FunctionOffset.y);
		FunctionSemaphore = true;
	}

	function whileDrawing(event) {
		if(window.event) { event = window.event; }
		if(FunctionSemaphore) {
			MySelf.drawPoint(event.clientX-FunctionOffset.x, event.clientY-FunctionOffset.y);
		}
	}

	function whileDrawingBox(event) {
		if(window.event) { event = window.event; }
		if(FunctionSemaphore) {
			DrawBox.style.visibility = 'visible';
			var currentPoint = new Point(event.clientX-FunctionOffset.x, event.clientY-FunctionOffset.y);
			var left = DrawnPoints[0].x - 2;
			var width = currentPoint.x - left;
			var top = DrawnPoints[0].y - 2;
			var height = currentPoint.y - top;

			if(DrawingShape == 'evenbox') {
				if(width > height) { width = Math.abs(height) * width / Math.abs(width); }
				else { height = Math.abs(width) * height / Math.abs(height); }
			}

			if(width < 0) {
				left = left + width;
				width = -width;
			}

			if(height < 0) {
				top = top + height;
				height = -height;
			}

			DrawBox.style.top = top+'px';
			DrawBox.style.left = left+'px';
			DrawBox.style.height = height+'px';
			DrawBox.style.width = width+'px';
		}
	}
	
	function stopDrawing() {
		if (document.all) {
			document.detachEvent("onmouseup",   stopDrawing);
		} else {
			document.removeEventListener("mouseup",   stopDrawing, true);
		}

		if(FunctionSemaphore) {
			FunctionSemaphore = false;
			/* Convert Drawn Points into Ground Units */
			var GroundUnits = new Array();
			for(var i = 0; i < DrawnPoints.length; i++) {
				GroundUnits[i] = MySelf.pointToGroundUnits(new Point(DrawnPoints[i].offsetLeft,DrawnPoints[i].offsetTop));
			}
			EventManager.triggerEvent('finishdrawing', GroundUnits);
	/*		EventManager.triggerEvent('finishdrawing', DrawnPoints);*/
			DrawBox.style.visibility = 'hidden';
			DrawBox.style.left = '0px';
			DrawBox.style.top = '0px';
			DrawBox.style.height = '1px';
			DrawBox.style.width = '1px';
			for(var i = DrawnPoints.length; i >= 0; i--) {
				if(DrawnPoints[i] && DrawnPoints[i].parentNode) {
					var p = DrawnPoints[i].parentNode;
					p.removeChild(DrawnPoints[i]);
				}
			}
		}
	}

	this.mapStats = function() {
		logDebugMessage('Map Statistics', false, MapCenterPoint.toString(",")+' '+MapScale);
	}
	
	this.pointToGroundUnits = function(p) {
		p.x = (MapCenterPoint.x - (ImageControl.offsetWidth / 2 - p.x) * MapScale);
		p.y = (MapCenterPoint.y - (p.y - ImageControl.offsetHeight / 2) * MapScale);
		return p;
		
	}

	this.pointDrawTool = function(callFn) {
		this.loadDrawTool('poly', true);
	}

	var DrawingArea = new Array();

	this.polyDrawTool = function(shape, title) {
		this.loadDrawTool('poly',true);
		EventManager.addEventListener('finishdrawing', 'MapZoomTool', function () { 
			/* Ground Unit String is in WKT/GML Format */
			var groundUnitString = '';
			for(var i = 0; i < DrawnPoints.length; i++) {
				var p = new Point(DrawnPoints[i].offsetLeft,DrawnPoints[i].offsetTop);
				groundUnitString = groundUnitString + MySelf.pointToGroundUnits(p).toString(",") + ' ';
			}
			/* Close the polygon */
			if(shape == 'poly' || shape == 'circle') {
				groundUnitString = groundUnitString + MySelf.pointToGroundUnits(new Point(DrawnPoints[0].offsetLeft,DrawnPoints[0].offsetTop)).toString(",");
			}
			/*logDebugMessage('Points', false, groundUnitString);*/

			var pass = false;
			if(!title) {
				var msg = '';
				while(!pass) {
					title = prompt(msg+"Name for the object?", "Title");
					pass = true;
					if(LayerImages[title]) {
						pass = false;
						msg  = 'LAYER ALREADY EXISTS --';
					}
				}
				
			}

			if(title) {
				var bufferSize = prompt('Buffer Size?','0');
				if(!bufferSize) { bufferSize = 0; }
				
				/*var saveDrawingURL = '/mapscript/cgi-bin/saveDrawing.pl?coords=%COORDS%&shape=%SHAPE%&buffer=%BUFFER%&title=%TITLE%';*/
				var saveDrawingURL = DRAWING_URL;
				saveDrawingURL = saveDrawingURL.replace('%COORDS%', groundUnitString);
				saveDrawingURL = saveDrawingURL.replace('%SHAPE%', shape);
				saveDrawingURL = saveDrawingURL.replace('%BUFFER%', bufferSize);
				saveDrawingURL = saveDrawingURL.replace('%TITLE%', title);

				var DrawingMethod = 'GET';
				var DrawingPostInfo = true;
				if(saveDrawingURL.length > 1000) {
					DrawingMethod = 'POST';
					var saveDrawingArr = saveDrawingURL.split('?');
					saveDrawingURL = saveDrawingArr[0];
					DrawingPostInfo = saveDrawingArr[1];
				}

				var titleCopy = title;

				var saveDrawingControl = getHTTPObject();
				logDebugMessage('Drawing URL', false, saveDrawingURL);
				saveDrawingControl.open(DrawingMethod, saveDrawingURL, true);
				if(DrawingMethod == 'POST') {
					saveDrawingControl.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				}


				saveDrawingControl.onreadystatechange = function() {
					if(saveDrawingControl.readyState == 4) {
						if(saveDrawingControl.responseXML) {
							loadDefaultsFromMapBook(saveDrawingControl.responseXML, null, EventManager);
							var selection = saveDrawingControl.responseXML.getElementsByTagName('selection');
							for(var s = 0; s < selection.length; s++) {
								DrawingArea[selection[s].getAttribute('title')] = selection[s].getAttribute('id');
							}

						}
					}
				}
				saveDrawingControl.send(DrawingPostInfo);
			}
			title = '';
		});

	}

	this.getDrawingAreas = function() {
		return DrawingArea;
	}

	this.loadDrawTool = function(shape,override) {
		ImageControl.style.zIndex = MAP_CONTROL_INDEX;
		ImageMapControl.style.zIndex = MAP_CONTROL_INDEX - 1;
		ImageMapControl.style.cursor = CURSOR_DRAW;
		if(!override) {
			EventManager.triggerEvent('changetool', 'Draw');
		}

		EventManager.addEventListener('changetool','MapDrawingTools', function () {
			EventManager.removeEventListener('changetool','MapDrawingTools');
			EventManager.removeEventListener('finishdrawing','MapZoomTool');
		});
		DrawingShape = shape;
		ImageControl.onmousedown = startDrawing;
		if(shape == 'box' || shape == 'evenbox') {
			ImageControl.onmousemove = whileDrawingBox;
		} else {
			ImageControl.onmousemove = whileDrawing;
		}
		ImageControl.onmouseup = stopDrawing;
	}


	ImageControl.onmousedown = function() {
	}

	ImageControl.onmouseup = function(event) {
		if(window.event) { event = window.event; }
		}

	function zoomWheel(event) {
		if(window.event) { event = window.event; }
		var dir = 2;
		var delta = 0;
		if(event.wheelDelta) {
			delta = event.wheelDelta/120;
		} else if(event.detail) {
			delta = -event.detail/3;
		}
		if(delta > 0) {
			dir = .7;
		} else if (delta < 0) {
			dir = 1.5;
		}
		MySelf.zoomTo(ZoomPoint.x, ZoomPoint.y, dir);
		
	}

	/*
	 * Zooming Related Code
	 */

	function zoomTrackMouse(event) {
		if(window.event) { event = window.event; }
		FunctionOffset = objectClientPosition(ImageControl);
		ZoomPoint.x = event.clientX - FunctionOffset.x;
		ZoomPoint.y = event.clientY - FunctionOffset.y;

	}
	var ZoomDirection = 1;
	var ZoomPoint = new Point();	
	function zoomToPoint(event) {
		if(window.event) { event = window.event; }
		FunctionOffset = objectClientPosition(ImageControl);
		//alert(FunctionOffset.toString(' '));
		MySelf.zoomTo(ZoomPoint.x, ZoomPoint.y, ZoomDirection);
	}
		

	this.loadZoomTool = function(v) {
		if(v == 1) { /* Pan */
			var PanPoint = new Point(0,0);

			ImageControl.style.cursor = CURSOR_ZOOM_PAN;
			ImageControl.onmousedown = function (e) {
				if(window.event) { e = window.event; }
				ImageControl.Origin = new Point(e.clientX, e.clientY);
				for(var l in LayerImages) {
					LayerImages[l].originalLeft = LayerImages[l].offsetLeft;
					LayerImages[l].originalTop = LayerImages[l].offsetTop;
				}
				PanPoint.x = 0;
				PanPoint.y = 0;
			}
			ImageControl.onmouseup = function (e) {
				if(window.event) { e = window.event; }
				MySelf.zoomTo(ImageControl.offsetWidth / 2 - PanPoint.x, ImageControl.offsetHeight / 2 - PanPoint.y, 1);
				/*delete ImageControl.Origin;*/
				ImageControl.Origin = null;
			}
			ImageControl.onmousemove = function (e) {
				if(window.event) { e = window.event; }
				zoomTrackMouse(e);
				if(ImageControl.Origin) {
					for(var l in LayerImages) {
						LayerImages[l].style.left = LayerImages[l].originalLeft + (e.clientX - ImageControl.Origin.x) + 'px';
						LayerImages[l].style.top = LayerImages[l].originalTop + (e.clientY - ImageControl.Origin.y) + 'px';
					}
					PanPoint.x = e.clientX - ImageControl.Origin.x;
					PanPoint.y = e.clientY - ImageControl.Origin.y;
				}
				return false;
			}
		} else if(v != 1) { /* Zoom In */
			MySelf.loadDrawTool('box',true);
			ImageControl.style.cursor = CURSOR_ZOOM_IN;
			ImageControl._onmousemove = ImageControl.onmousemove;
			ImageControl.onmousemove = function(event) {
				if(window.event) { event = window.event; }
				zoomTrackMouse(event);
				this._onmousemove(event);
			}
			EventManager.addEventListener('finishdrawing', 'MapZoomTool', function () { 
				var Ratio = DrawBox.offsetWidth / ImageControl.offsetWidth;
				var hRatio = DrawBox.offsetHeight / ImageControl.offsetHeight;
				if(hRatio > Ratio) { Ratio = hRatio; }
				if(DrawBox.offsetWidth < 10) {
					var PanPoint = DrawnPoints[0];
					var shiftX = ImageControl.offsetWidth / 2 - PanPoint.x;
					var shiftY = ImageControl.offsetHeight / 2 - PanPoint.y;
					var oldW = ImageControl.offsetWidth;
					var oldH = ImageControl.offsetHeight;
					var newW = oldW * (1/v);
					var newH = oldH * (1/v);
					shiftX *= (1/v);
					shiftY *= (1/v);
					for(var l in LayerImages) {
						LayerImages[l].style.left = LayerImages[l].offsetLeft + shiftX - (newW - oldW) / 2 + 'px';
						LayerImages[l].style.top = LayerImages[l].offsetTop + shiftY - (newH - oldH) / 2 + 'px';
						LayerImages[l].style.width = newW + 'px';
						LayerImages[l].style.height = newH + 'px';
					}
					MySelf.zoomTo(0,0,1);
				} else {	
					var PanPoint = new Point(DrawBox.offsetLeft + DrawBox.offsetWidth / 2, DrawBox.offsetTop + DrawBox.offsetHeight / 2);
					if(v > 1) { v = 1 / Ratio; }
					else { v = Ratio; }
					var shiftX = ImageControl.offsetWidth / 2 - PanPoint.x;
					var shiftY = ImageControl.offsetHeight / 2 - PanPoint.y;
					var oldW = ImageControl.offsetWidth;
					var oldH = ImageControl.offsetHeight;
					var newW = oldW * (1/v);
					var newH = oldH * (1/v);
					shiftX *= (1/v);
					shiftY *= (1/v);
					for(var l in LayerImages) {
						LayerImages[l].style.left = LayerImages[l].offsetLeft + shiftX - (newW - oldW) / 2 + 'px';
						LayerImages[l].style.top = LayerImages[l].offsetTop + shiftY - (newH - oldH) / 2 + 'px';
						LayerImages[l].style.width = newW + 'px';
						LayerImages[l].style.height = newH + 'px';
					}
					MySelf.zoomTo(0,0,1);

				}
			});
			EventManager.addEventListener('changetool', 'MapZoomTool', function () {
				EventManager.removeEventListener('finishdrawing','MapZoomTool');
				EventManager.removeEventListener('changetool', 'MapZoomTool');
			});
		}

		ImageControl.style.zIndex = MAP_CONTROL_INDEX;
		ImageMapControl.style.zIndex = MAP_CONTROL_INDEX - 1;
		if(document.all) {
			ImageControl.onmousewheel = zoomWheel;
		} else {
			ImageControl.addEventListener('DOMMouseScroll', zoomWheel, false);
		}
		ZoomDirection = v;
	}
	


	this.clearLayerParams = function(mapTitle) {
		LayerParameters[mapTitle] = new Array();
	}

	this.addLayerParam = function(mapTitle,paramName,paramValue) {
		if(!LayerParameters[mapTitle]) { LayerParameters[mapTitle] = new Array(); }
		if(!LayerParameters[mapTitle][paramName]) {
			LayerParameters[mapTitle][paramName] = new Array();
		}
		LayerParameters[mapTitle][paramName].push(paramValue);
	}

	this.getLayerParamString = function(mapTitle) {
		if(!LayerParameters[mapTitle]) { return false; }
		var urlString = '';
		for(var p in LayerParameters[mapTitle]) {
			if(LayerParameters[mapTitle][p]) {
				for(var i = 0; i < LayerParameters[mapTitle][p].length; i++) {
					urlString += p+'='+LayerParameters[mapTitle][p][i]+'&';
				}
			}
		}
		urlString = urlString.substring(0,urlString.length - 1);
		return urlString;
	}

	this.addLayer = function (mapXMLObj) {
		var mapFile = mapXMLObj.getElementsByTagName('file')[0].firstChild.nodeValue;
		var mapTitle = mapXMLObj.getAttribute('title');
		var mapOpacity = mapXMLObj.getAttribute('opacity');

		mapFile = trim(mapFile);
		LayerURLs[mapTitle] = mapFile;/*+'?mode=map&mapext=%EXTENTS%&mapsize=%SIZE%';*/

		if(!LayerImages[mapTitle]) {
			LayerImages[mapTitle] = document.createElement('img');
			LayerImages[mapTitle].style.position = 'absolute';
			LayerImages[mapTitle].id = 'LayerImage-'+mapTitle;
		}
		if(mapOpacity) {
			setOpacity(LayerImages[mapTitle], mapOpacity);
		}
		

		var zIndex = mapXMLObj.getAttribute('zindex');
		if(!zIndex || zIndex > 0) {
			LayerImages[mapTitle].style.zIndex = MAP_MAX_ZINDEX;
			for(var title in LayerImages) {
				LayerImages[title].style.zIndex = parseInt(LayerImages[title].style.zIndex)-1;
			}
			min_z_index--;
		} else {
			min_z_index--;
			LayerImages[mapTitle].style.zIndex = min_z_index;
		}
		ImageParent.appendChild(LayerImages[mapTitle]);
		MySelf.autoFitLayer(mapTitle);
		LayerImages[mapTitle].onload = function() {
			this.isLoaded = true;
			var allVisible = true;
			MySelf.autoFitLayer(mapTitle);
			for(var l in LayerImages) {
				LayerImages[l].style.visibility = 'hidden';
				if(!LayerImages[l].isLoaded) {
					allVisible = false;
				}
			}
			if(allVisible) {
				for(var l in LayerImages) {
					LayerImages[l].style.visibility = 'visible';
				}
			}
			EventManager.triggerEvent('imagelayer', mapTitle);
		}

		MySelf.clearLayerParams(mapTitle);
		var mapParams = mapXMLObj.getElementsByTagName('param');
		for(var i = 0; i < mapParams.length; i++) {
			MySelf.addLayerParam(mapTitle, mapParams[i].getAttribute('name'), mapParams[i].getAttribute('value'));
		}
		/*
		 * Custom Legend settings
		 */
		if(mapXMLObj.getElementsByTagName('legend')[0] && mapXMLObj.getElementsByTagName('legend')[0].firstChild.nodeValue) {
			LayerLegends[mapTitle] = mapXMLObj.getElementsByTagName('legend')[0].firstChild.nodeValue;
		}
		Events.triggerEvent('refreshlayer', mapTitle);
	}

	this.confirmRemoveLayer = function(mapTitle) {
		MySelf.removeLayer(mapTitle);
	}

	this.removeLayer = function(mapTitle) {
		var imageMap = document.getElementById('ImageMap-'+mapTitle);
		if(imageMap) {
			var areas = imageMap.getElementsByTagName('area');
			for(var a = areas.length - 1; a >= 0; a--) {
				var p = areas[a].popup[0].parentNode;
				for(var pop = 0; pop < areas[a].popup.length; pop++) {
					p.removeChild(areas[a].popup[pop]);
				}
				imageMap.removeChild(areas[a]);
			}
			var p = imageMap.parentNode;
			p.removeChild(imageMap);
		}
		var p = LayerImages[mapTitle].parentNode;
		p.removeChild(LayerImages[mapTitle]);
		delete LayerImages[mapTitle];
		delete LayerURLs[mapTitle];
		if(DrawingArea[mapTitle]) {
			delete DrawingArea[mapTitle];
		}
	}

	this.getLayerURLs = function() {
		var zOrdered = MySelf.getLayersByZIndex();
		var urls = new Array();
		for(var i = 0; i < zOrdered.length; i++) {
			urls[zOrdered[i]] = LayerURLs[zOrdered[i]];
		}
		return urls;
	}
	
	this.getLayersByZIndex = function() {
		var orderedLayers = new Array();
		for(var title in LayerImages) {
			orderedLayers[orderedLayers.length] = title;
		}
		for(var i = 0; i < orderedLayers.length; i++) {
			for(var  j = i; j < orderedLayers.length; j++) {
				var iImage = LayerImages[orderedLayers[i]];
				var jImage = LayerImages[orderedLayers[j]];
				if(parseInt(iImage.style.zIndex) < parseInt(jImage.style.zIndex)) {
					var temp = orderedLayers[i];
					orderedLayers[i] = orderedLayers[j];
					orderedLayers[j] = temp;
				}
			}
		}
		return orderedLayers;
	}

	this.showOrderedLayers = function() {
		var str = '';
		var layers = this.getLayersByZIndex();
		for(var i = 0; i < layers.length; i++) {
			str = str+layers[i]+'('+LayerImages[layers[i]].style.zIndex+'),';
		}
	}
	
	this.shiftLayer = function(mapTitle, direction) {
		var orderedLayers = this.getLayersByZIndex();
		var selectedLayerIndex = -1;
		
		for(var i = 0; i < orderedLayers.length && selectedLayerIndex < 0; i++) {
			if(orderedLayers[i] == mapTitle) {
				selectedLayerIndex = i;
			}
		}
		if(selectedLayerIndex >= 0) {
			var baseImage = LayerImages[mapTitle];
			var targetImage = null; 
			/* Move the layer up, if it's not at the top*/
			if(direction > 0 && selectedLayerIndex > 0) {
				targetImage = LayerImages[orderedLayers[selectedLayerIndex-1]];
			/* Move the layer down, if it's not at the bottom */
			} else if(direction < 0 && selectedLayerIndex < orderedLayers.length - 1) {
				targetImage = LayerImages[orderedLayers[selectedLayerIndex+1]];
			}
			if(targetImage) {
				var tempIndex = baseImage.style.zIndex;
				baseImage.style.zIndex = targetImage.style.zIndex;
				targetImage.style.zIndex = tempIndex;
			}
		}
	}

	var REFRESH_LOCKOUT = false;

	this.zoomToScaledImage = function() {
		var orderedLayers = MySelf.getLayersByZIndex();
		/* zoomLayer will be Scaled to whatever the new image should be */
		var zoomLayer = LayerImages[orderedLayers[0]];
		var imageTop = zoomLayer.offsetTop;
		var imageLeft = zoomLayer.offsetLeft;

		var imageWidth = zoomLayer.offsetWidth;
		var imageHeight = zoomLayer.offsetHeight;

		/* ImageControl never changes size */
		var viewportTop = ImageControl.offsetTop;
		var viewportLeft = ImageControl.offsetLeft;
		var viewportWidth = ImageControl.offsetWidth;
		var viewportHeight = ImageControl.offsetHeight;

		/* Scale Change between the two images */
		var scale = viewportWidth / imageWidth * MapScale; 
		
		var groundTop = MapCenterPoint.y - MapScale * viewportHeight / 2;
		var groundLeft = MapCenterPoint.x - MapScale * viewportWidth / 2;

		/* Find the new Centerpoint in Pixel Space */
		var viewportMidX = (viewportLeft - imageLeft) + viewportWidth / 2;
		var viewportMidY = (viewportTop - imageTop) + viewportHeight / 2;
		var imagePercentX = viewportMidX / imageWidth;
		var imagePercentY = 1 - (viewportMidY / imageHeight);	

		var unscaledImageX = imagePercentX*viewportWidth;
		var unscaledImageY = imagePercentY*viewportHeight;

		/* Convert to ground units */
		var groundCenterX = groundLeft + unscaledImageX * MapScale;
		var groundCenterY = groundTop + unscaledImageY * MapScale; 
		EventManager.changePointScale(new Point(groundCenterX, groundCenterY), scale / ScaleFactor);
	}

	this.zoomToViewString = function(str) {
		var psC = convertViewString(str,MySelf.getMapSize());
		EventManager.changePointScale(psC.Center, psC.Radius);
	}
	
	this.zoomTo = function(x,y,direction) {
		if(REFRESH_LOCKOUT) return false;

		var orderedLayers = MySelf.getLayersByZIndex();
		var zoomLayer = LayerImages[orderedLayers[0]];
		var imgW = zoomLayer.offsetWidth;
		var imgH = zoomLayer.offsetHeight;

		var mapSize = MySelf.getMapSize();
		var diffY = ImageControl.offsetTop - zoomLayer.offsetTop;
		var diffX = ImageControl.offsetLeft - zoomLayer.offsetLeft;
		
		var PointImageX = diffX + x;
		var PointImageY = diffY + y;

		var wPercent = PointImageX / imgW;
		var hPercent = PointImageY / imgH;
		// Do some zooming tricks
		var imgSizeFactor = 1 / direction; // Inverse of the scale change
		var newW = imgSizeFactor * imgW;
		var newH = imgSizeFactor * imgH;

		var xLoc = x-(mapSize.x / 2);
		var yLoc = ((mapSize.y / 2) - y);
		var wRatio = newW / ImageControl.offsetWidth;
		var hRatio = newH / ImageControl.offsetHeight;
		if(hRatio > wRatio) { wRatio = hRatio; }

		var newScale = MapScale * wRatio;

		if(newScale < .01) {
			return false;
		}
				
		if(direction != 1) {
			for(var layer in LayerImages) {
				var img = LayerImages[layer];
				//img.style.visibility = 'hidden';
				img.style.width = newW + 'px';
				img.style.height = newH + 'px';
				img.style.left = (newW * wPercent * -1 +  x)+'px';
				img.style.top = (newH * hPercent * -1 +  y)+'px';
				//img.style.visibility = 'visible';
			}
		}

		

		window.triggerMapRefresh = function(time) {
			REFRESH_LOCKOUT = true;
			if(time == LastActionTime) {
				MySelf.zoomToScaledImage();
				LastActionTime = 0;
			}
			REFRESH_LOCKOUT = false;
		}
		LastActionTime ++;
		setTimeout("window.triggerMapRefresh("+LastActionTime+")", 1000);
	}

		
	this.drawPoint = function(x,y) {
		var lastPoint = DrawnPoints[DrawnPoints.length-1];
		if(lastPoint) {
			var distx = (lastPoint.offsetLeft - x);
			var disty = (lastPoint.offsetTop - y);
			
			var dist = distx*distx + disty*disty;
			if(dist < 100) {
				return false;
			}
		}

		var newPoint = document.createElement('div');
		newPoint.style.position = 'absolute';
		newPoint.style.background = 'red';
		newPoint.style.border = 'none';
		newPoint.style.overflow = 'hidden';
		newPoint.style.width = '5px';
		newPoint.style.height = '5px';
		newPoint.style.left = x+'px';
		newPoint.style.top = y+'px';
		newPoint.className = 'DrawnPoint';
		DrawnPoints[DrawnPoints.length] = newPoint;
		ImageParent.appendChild(newPoint);
	}

	this.getMapSize = function() {
		var SizeObject = ImageControl;
		if(!SizeObject.offsetWidth) {
			SizeObject = MapParent;
		}
		var point = new Point(SizeObject.offsetWidth, SizeObject.offsetHeight);
		return point;
	}

	this.setParent = function(p) {
		MapParent = p;
		ImageParent.style.position = 'absolute';
		ImageParent.style.left = '0px';
		ImageParent.style.top = '0px';

		ImageControl.style.position = 'absolute';
		ImageControl.style.border = 'none';
		ImageControl.style.left = '0px';
		ImageControl.style.top = '0px';

		ImageMapControl.style.position = 'absolute';
		ImageMapControl.style.border = 'none';
		ImageMapControl.style.left = '0px';
		ImageMapControl.style.top = '0px';

		MapParent.appendChild(ImageParent);
		MapParent.appendChild(ImageControl);
		MapParent.appendChild(ImageMapControl);

		MapParent.appendChild(DrawBox);
		MapParent.style.overflow = 'hidden';

		this.autoFitLayers();	
	}

	this.processURL = function(url, extents, mSize, mapfile) {
		url = url.replace("%EXTENTS%",extents);
		var extentsArr = extents.split(' ');
		url = url.replace("%MINX%", extentsArr[0]);
		url = url.replace("%MINY%", extentsArr[1]);
		url = url.replace("%MAXX%", extentsArr[2]);
		url = url.replace("%MAXY%", extentsArr[3]);
		url = url.replace("%SIZE%", mSize.toString(" "));
		url = url.replace("%WIDTH%", mSize.x);
		url = url.replace("%HEIGHT%", mSize.y);
		url = url.replace("%MAPBOOK%", MAPBOOK_FILE);
		url = url.replace("%MAPFILE%", mapfile);
		return url;

	}

	this.preprocessURL = function(type, mapTitle) {
		var layerURL = MAPSERVER_IMAGE_URL;
		if(type == 'legend') {
			layerURL = MAPSERVER_LEGEND_URL;
		} else if(type == 'data') {
			layerURL = MAPSERVER_DATA_URL;
		}

		if(LayerURLs[mapTitle].match(/http/i)) {
			layerURL = LayerURLs[mapTitles[i]];
		} else {
			layerURL = layerURL.replace('%MAPFILE%', LayerURLs[mapTitle]);
		}
		var parameters = MySelf.getLayerParamString(mapTitle);
		if(!parameters) { parameters = ''; }

		return layerURL + '&' + parameters;
	}
	
	this.refreshLayer = function(mapTitles) {
		var mapSize = MySelf.getMapSize();
		var gisOffsetW = mapSize.x / 2 * MapScale;
		var gisOffsetH = mapSize.y / 2 * MapScale;
		var minPoint = new Point(MapCenterPoint.x - gisOffsetW, MapCenterPoint.y - gisOffsetH);
		var maxPoint = new Point(MapCenterPoint.x + gisOffsetW, MapCenterPoint.y + gisOffsetH);
		var MapCoords = new LineSegment(minPoint,maxPoint);

		var mySelf = this;
		var mSize = this.getMapSize();

		var extent = MapCoords.toString(" ");
		var size = this.getMapSize().toString(" ");


		for(var i = 0; i < mapTitles.length; i++) {
			if(!LayerURLs[mapTitles[i]]) {
				break;
			}

			/*
			 * Do a little clean up on the Layer Image Maps 
			 */
			var imageMap = document.getElementById('ImageMap-'+mapTitles[i]);
			if(imageMap) {
				var areas = imageMap.getElementsByTagName('area');
				for(var a = areas.length - 1; a >= 0; a--) {
					var p = areas[a].popup[0].parentNode;
					for(var pop = 0; pop < areas[a].popup.length; pop++) {
						p.removeChild(areas[a].popup[pop]);
					}
					imageMap.removeChild(areas[a]);
				}
			}

			
			var imageURL = MAPSERVER_IMAGE_URL;
			if(LayerURLs[mapTitles[i]].match(/http/i)) {
				imageURL = LayerURLs[mapTitles[i]];
			}
			imageURL = this.processURL(imageURL, extent, mSize, LayerURLs[mapTitles[i]]);
			var parameters = MySelf.getLayerParamString(mapTitles[i]);
			LayerImages[mapTitles[i]].src = imageURL+'&'+parameters;
			logDebugMessage('Image URL', false, imageURL);

			if(!LayerURLs[mapTitles[i]].match(/http/i)) {
				var dataURL = MAPSERVER_DATA_URL;
				dataURL = this.processURL(dataURL, extent, mSize, LayerURLs[mapTitles[i]]);
				if(parameters) {
					dataURL = dataURL + '&' + parameters;
				}
				this.loadData(mapTitles[i], dataURL);
				logDebugMessage('Data URL', false, dataURL);
			}

			if(!LayerURLs[mapTitles[i]].match(/http/i) || LayerLegends[mapTitles[i]]) {
				var legendURL = MAPSERVER_LEGEND_URL;
				if(LayerLegends[mapTitles[i]]) {
					legendURL = LayerLegends[mapTitles[i]];
				}
				legendURL = this.processURL(legendURL, extent, mSize, LayerURLs[mapTitles[i]]);
				if(parameters) {
					legendURL = legendURL + '&' + parameters;
				}
				
				var obj = document.createElement('layer');
				obj.setAttribute('legend', legendURL);
				obj.setAttribute('id',mapTitles[i]);
				EventManager.triggerEvent('legendlayer', obj);

				logDebugMessage('Legend URL', false, legendURL);
			}
		}

	}

	var Popups = new Array();
	this.getPopupData = function(i) {
		return Popups[i];
	}

	this.getPointScale = function() {
		return new Circle(MapCenterPoint, MapScale);
	}
	
	this.clearPopups = function() {
		var p = MapParent; //ImageControl.parentNode;
		var d = p.getElementsByTagName('div');
		for(var i = 0; i < d.length; i++) {
			if(d[i].className == 'Popup') {
				d[i].style.visibility = 'hidden';
			}
		}
	}

	this.loadData = function(id, dataCall) {
		var http = getHTTPObject();
		/*var xmlhttp = getHTTPObject();
		xmlhttp.open('HEAD', dataCall, true);
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState == 4) {
				if(xmlhttp.status == 200) {
					//alert(xmlhttp.getAllResponseHeaders());
				} else {
					return false;
				}
			}
		}
		xmlhttp.send(null);*/

		http.open('GET', dataCall, true);
		http.onreadystatechange = function() {
			if(http.readyState == 4) {
				if(http.responseXML) {
					var imageMap = document.createElement('map');
					var imageMapName = 'ImageMap-'+id;
					imageMap.id = imageMapName;
					if(document.all) {
						imageMap = document.createElement('<map name="'+imageMapName+'">');
					} else {
						imageMap.name = imageMapName;
					}
					var imageMapTest = document.getElementById(imageMapName);

					imageMap.className = 'ImageMaps';
					if(imageMapTest) { imageMap = imageMapTest; }
					var popups = http.responseXML.getElementsByTagName('popup');
					var popups = http.responseXML.getElementsByTagName('popup');
					var offsetPoint = objectClientPosition(ImageControl);

					var styleObject = http.responseXML.getElementsByTagName('style')[0];
					var contentsFunction = function () { };
					var titleFunction = function () { };
					
					if(styleObject) {
						contentsFunction = getStyleFunction('contents', styleObject);
						titleFunction = getStyleFunction('title', styleObject);
					}
					var xCoord = new Array();
					var yCoord = new Array();
					var allShapes = new Array();

					var bin = new Array();
					for(var i = 0; i < popups.length; i++) {
						var coords = popups[i].getAttribute('coords');
							var coordsArr = coords.split(',');
							var found = false;

							for(var x in xCoord) {
								var w = Math.pow(xCoord[x] - coordsArr[0],2);
								var h = Math.pow(yCoord[x] - coordsArr[1],2);
								if(w+h < 49) {
									found = true;
									bin[x][bin[x].length] = popups[i];
								}
							}
							if(!found) {
								xCoord[coords] = coordsArr[0];
								yCoord[coords] = coordsArr[1];
								bin[coords] = new Array();
								bin[coords][0] = popups[i];
								allShapes[coords] = popups[i].getAttribute('shape');
							}

					}

					for(var b in bin) {
						var area = document.createElement('area');
						area.shape = allShapes[b];
						area.coords = b;

						area.popup = new Array();
						for(var i = 0; i < bin[b].length; i++) {
							var myPopup = document.createElement('div');
							myPopup.className = 'Popup';
							var myPopupTitle = document.createElement('div');
							myPopupTitle.appendChild(document.createTextNode(bin[b][i].getElementsByTagName('title')[0].firstChild.nodeValue));

							myPopup.appendChild(myPopupTitle);

							myPopup.draggable = new Draggable(myPopup, myPopupTitle, true,true,true);

							titleFunction(myPopupTitle);
							contentsFunction(myPopup);
							var items = bin[b][i].getElementsByTagName('item');

							for(var item = 0; item < items.length; item++) {
								var title = items[item].getAttribute('title');
								var val = '';
								if(items[item].firstChild) {
									val = items[item].firstChild.nodeValue;
								}
								var titleObj = document.createElement('span');
								titleObj.style.fontWeight = 'bold';
								var valObj = document.createElement('span');
								if(title) {
									titleObj.appendChild(document.createTextNode(title));
								}
								if(items[item].getAttribute('href')) {
									var link = document.createElement('a');
									link.href = items[item].getAttribute('href');
									var tgt = items[item].getAttribute('target');
									if(!tgt) { tgt = '_blank'; }
									link.setAttribute('target',tgt);
									link.innerHTML = val;
									valObj.appendChild(link);
								} else {
									valObj.innerHTML = val;
								}
								myPopup.appendChild(titleObj);
								myPopup.appendChild(valObj);
								myPopup.appendChild(document.createElement('br'));
							}

							var closeL = document.createElement('a');
							var closeImg = document.createElement('img');
							closeImg.src = REMOVE_ICON;
							closeL.appendChild(closeImg);
							closeL.style.position = 'absolute';
							closeL.style.right = '0px';
							closeL.style.top = '0px';
							closeImg.style.width = '8px';
							closeImg.style.height = '8px';

							closeL.onclick = function () {
								this.parentNode.style.visibility = 'hidden';
								this.area.onmouseup();
							}
							myPopup.appendChild(closeL);
							ImageControl.parentNode.appendChild(myPopup);
							area.popup[area.popup.length] = myPopup;
							closeL.area = area;
						}
						area.popupMove = true;
						area.onmousemove = function (event) {  
							if(window.event) { event = window.event; }
							if(!this.popupMove) { return false; }
							var mouseY = event.clientY-offsetPoint.y;
							var mouseX = event.clientX-offsetPoint.x;
							var offsetX = 4;
							var offsetY = 4;
							for(var i = 0; i < this.popup.length; i++) {
								this.popup[i].style.zIndex =  MAP_POPUP_ZINDEX;
								/*if(mouseY + this.popup[i].offsetHeight < ImageControl.offsetHeight) {*/
								if(mouseY < ImageControl.offsetHeight / 2) {
									this.popup[i].style.top = mouseY+offsetY+'px';
									this.popup[i].style.bottom = 'auto';
								} else {
									this.popup[i].style.bottom = (ImageControl.offsetHeight - mouseY)+offsetY+'px';
									this.popup[i].style.top = 'auto';
								}
								/*if(mouseX + this.popup[i].offsetWidth < ImageControl.offsetWidth) {*/
								if(mouseX < ImageControl.offsetWidth /2 ) {
									this.popup[i].style.left = mouseX+offsetX+'px';
									this.popup[i].style.right = 'auto';
								} else {
									this.popup[i].style.right = (ImageControl.offsetWidth - mouseX)+offsetX+'px';
									this.popup[i].style.left = 'auto';
								}

								this.popup[i].style.visibility = 'visible';
								offsetY += 10;
								offsetX += 10;
							}
						}
						area.onmouseup = function () {
							if(this.onmouseout) {
								this._onmouseout = this.onmouseout;
								this.onmouseout = null;
								this.popupMove = false;
							} else {
								this.onmouseout = this._onmouseout;
								this._onmouseout = null;
								this.popupMove = true;
							}
						}
		
						area.onmouseout = function (event) {
							for(var i = 0; i < this.popup.length; i++) {
								this.popup[i].style.visibility = 'hidden';
							}
						}
						imageMap.appendChild(area);
					}
					if(!imageMapTest) {
						document.getElementsByTagName('body')[0].appendChild(imageMap);
					}
					if(popups.length > 0) {
						EventManager.triggerEvent('datalayer',id);
					}
				}
			}
		}
		http.send(true);
	}

	this.activateLayer = function(mapTitle) {
		var imageMapName = 'ImageMap-'+mapTitle;
		ImageMapControl.setAttribute('usemap', '#'+imageMapName);
		ImageMapControl.setAttribute('useMap', '#'+imageMapName);
		ImageMapControl.ismap = true;
		ImageMapControl.style.zIndex = MAP_CONTROL_INDEX;
		ImageControl.style.zIndex = MAP_CONTROL_INDEX - 1;
	}



	this.autoFitLayers = function() {
		var mapSize = new Point(MapParent.offsetWidth, MapParent.offsetHeight);
		ImageParent.style.width = mapSize.x+'px';
		ImageParent.style.height = mapSize.y+'px';
		for(var title in LayerImages) {
			MySelf.autoFitLayer(title);
		}
		ImageControl.style.width = mapSize.x+'px';
		ImageControl.style.height = mapSize.y+'px';
		ImageMapControl.style.width = mapSize.x+'px';
		ImageMapControl.style.height = mapSize.y+'px';

	}

	this.autoFitLayer = function(mapTitle) {
		var mapSize = this.getMapSize();
		this.resizeLayer(mapTitle,mapSize.x,mapSize.y);
	}

	this.resizeLayer = function(mapTitle,w,h) {
		//LayerImages[mapTitle].style.visibility = 'hidden';
		LayerImages[mapTitle].style.top = '0px';
		LayerImages[mapTitle].style.left = '0px';
		LayerImages[mapTitle].style.width = w+'px';
		LayerImages[mapTitle].style.height = h+'px';
		//LayerImages[mapTitle].style.visibility = 'visible';
	}

	this.reloadLayers = function() {
		MySelf.autoFitLayers();
		MySelf.refreshLayers();
	}

	var ReferenceIndicator = null;
	
	this.refreshLayers = function() {
		if(MapReference) {
			var oldMap = MapReference.getMapSize();
			var newW = oldMap.x / ScaleFactor;
			var newH = oldMap.y / ScaleFactor;
			var MySize = MySelf.getMapSize();
			var left = (MySize.x - newW) / 2;
			var top = (MySize.y - newH) / 2;
			if(!ReferenceIndicator) { 
				ReferenceIndicator = document.createElement('div');
				ReferenceIndicator.gDRAGGER = new Draggable(ReferenceIndicator, ReferenceIndicator, true, true, true);
			}
				ReferenceIndicator.gDRAGGER.onDrop = function (trig,obj) {
					var diffX = trig.offsetLeft - left;
					var diffY = trig.offsetTop - top;
					for(var l in LayerImages) {
						LayerImages[l].style.left = LayerImages[l].offsetLeft - diffX + 'px';
						LayerImages[l].style.top = LayerImages[l].offsetTop - diffY + 'px';
					}
					MySelf.zoomToScaledImage();
				}
			
			var drawDiv = ReferenceIndicator;
			drawDiv.style.position = 'absolute';
			drawDiv.style.top = top + 'px';
			drawDiv.style.left = left + 'px';
			drawDiv.style.background = 'white';
			drawDiv.style.border = 'solid 1px black';
			drawDiv.style.width = newW+'px';
			drawDiv.style.height = newH+'px';
			drawDiv.style.zIndex = MAP_POPUP_ZINDEX;
			drawDiv.style.overflow = 'hidden';
		/*	if(document.addEventListener) {
				drawDiv.addEventListener('keypress', function () { alert('hi'); }, true);
			}

			if(document.attachEvent) {
				document.attachEvent('onkeypress', ControlKeys);
			}*/
			drawDiv.ondblclick = function () {
				alert('hh');
			}
			setOpacity(drawDiv, 75);
			MapParent.appendChild(drawDiv);
		}
		var arr = new Array();
		for(var title in LayerImages) {
			arr[arr.length] = title;
			LayerImages[title].isLoaded = false;
		}
	/*	for(var i = 0; i < arr.length; i++) {
			Events.triggerEvent('refreshlayer', arr[i]);
		}*/
		MySelf.refreshLayer(arr);
	}

	function getStyleFunction(tagType, styleXML) {
		if(!styleXML) { return function(obj) { }; }
		var tag = styleXML.getElementsByTagName(tagType);
		var evalString = '';

		for(var t = 0; t < tag.length; t++) {
			var attrs = tag[t].getElementsByTagName('attr');
			for(var a = 0; a < attrs.length; a++) {
				evalString += ('obj.style.'+attrs[a].getAttribute('name')+'="'+attrs[a].getAttribute('value')+'";');
			}
		}	
		return function(obj) { eval(evalString); };
	}

	this.moveLayerUp = function(title) {
		MySelf.shiftLayer(title, 1);
	}

	this.moveLayerDown = function(title) {
		MySelf.shiftLayer(title, -1);

	}

	this.changeLayerOpacity = function(layerName, amount) {
		var img = LayerImages[layerName];
		var opac = getOpacity(img);
		opac+=amount;
		setOpacity(img, opac);
	}

	this.getOpacity = function(layerName) {
		return getOpacity(LayerImages[layerName]);
	}
	
	this.fadeLayer = function(title) {
		MySelf.changeLayerOpacity(title, -10);
	}

	this.unfadeLayer = function(title) {
		MySelf.changeLayerOpacity(title, 10);
	}

	this.reloadLayer = function(title) {
		var arr = new Array();
		arr[0] = title;
		MySelf.refreshLayer(arr);
	}
	
}
/* ======================================================================    objects/TreeView.js
   ====================================================================== */

/*
 * Initial Version of the Tree Viewer
 */

function TreeView(EventManager) {
	var MySelf = this;
	var parentXML = '';

	var Tree;
	var Parent;

	this.removeObject = function(id) {
		var checkBox = document.getElementById('TreeView-'+id);
		if(checkBox) {
			checkBox.checked = false;
		}
	}

	this.addObject = function(mapXMLObj) {
		var title = mapXMLObj.getAttribute('title');
		var checkBox = document.getElementById('TreeView-'+title);
		if(checkBox) {
			checkBox.checked = true;
		}
	}

	this.clearAll = function() {
		var inputs = document.getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++) {
			inputs[i].checked = false;
		}
	}

	function makeInvisible(elm) {
		elm.style.height = '1px';
	}

	var visibilityOverride = false;

	this.setVisibilityOverride = function (v) {
		visibilityOverride = v;
	}
	function createBranch(xmlObj) { // Assumes the Element Has Children
		var root = document.createElement('ul');
		root.className = 'TreeView';
		/*root.style.marginLeft = '5px';
		root.style.paddingLeft = '5px';*/
		for(var i = 0; i < xmlObj.childNodes.length; i++) {
			if(xmlObj.childNodes[i].tagName != null && (!xmlObj.childNodes[i].getAttribute('invisible') || !xmlObj.childNodes[i].getAttribute('invisible').match(/true/i) || visibilityOverride)) {
				if(xmlObj.childNodes[i].tagName == 'group') {
					var rootLeaf = getLeaf(xmlObj.childNodes[i], 0);
					var underList = createBranch(xmlObj.childNodes[i]);
					underList.style.height = '1px';
					underList.style.overflow = 'hidden';
					root.appendChild(rootLeaf);
					root.appendChild(underList);
					rootLeaf.childTree = underList;
					rootLeaf.onclick = function() {
						var vis = this.childTree.style.visibility;
						if(this.childTree.style.height != '1px') {
							height = '1px';
							var allUl = this.childTree.getElementsByTagName('ul');
							for(var u = 0; u < allUl.length; u++) {
								makeInvisible(allUl[u]);
							}
						} else {
							height = 'auto';
						}
						this.childTree.style.height = height;
						return false;
					}
				} else if(xmlObj.childNodes[i].tagName != null && xmlObj.childNodes[i].getAttribute('title') != null) {
					var newItem = getLeaf(xmlObj.childNodes[i], 0);	
					root.appendChild(newItem);
				}
			}
		}
		return root;
	}


	function getLeaf(obj, depth) {
		var newLi = document.createElement('span');
		var imgIcon = document.createElement('img');
		/*newLi.onmousedown = clearSelection;*/
		newLi.style.cursor = 'pointer';

		var metaIcon, helpIcon;

		if(obj.tagName == 'group') {
			newLi.onclick = function () {
				if(this.parentNode.className == 'Selected') {
					alert('Add All Children of '+this.parentNode.id);
				}
			}
			imgIcon.src = FOLDER_ICON;
		} else {
			var layerCheckBox = document.createElement('input');
			layerCheckBox.setAttribute('type','checkbox');
			var objTitle = obj.getAttribute('title');

			layerCheckBox.id = 'TreeView-'+objTitle;
	
			/*if(layerObjs[obj.getAttribute('title')]) {
				checked = true;
				layerCheckBox.defaultChecked = true;
				layerCheckBox.setAttribute('checked', 'true');
				if(obj.getAttribute('locked') && obj.getAttribute('locked').match(/true/i)) {
					layerCheckBox.disabled = true;
				}

			}*/


			if(obj.tagName.match(/map/i)) {
				layerCheckBox.onclick = function() {
					if(this.checked) {
					//	addMapLayer(parentXML, objTitle, objTitle, true);
						EventManager.triggerEvent('addlayer', obj);
					} else {
						this.checked=true;
						if(EventManager.onRemoveLayer(objTitle)) {
							this.checked=false;
						}
					}

				}
			} else if(obj.tagName.match(/service/i)) {
				layerCheckBox.onclick = function() {
					if(this.checked) {
						//addService(objTitle,objTitle);
						EventManager.triggerEvent('addservice',obj);
					} else {
						this.checked=true;
						if(EventManager.onRemoveService(objTitle)) {
							this.checked=false;
						}
					}

				}
			} else if(obj.tagName.match(/view/i)) {
				layerCheckBox.onclick = function() {
					if(this.checked) {
						EventManager.triggerEvent('addview', obj);
					} else {
						this.checked=true;
						EventManager.triggerEvent('removeview', objTitle);
						this.checked = false;
					}
				}
			}




			//function addService(serviceName, serviceTitle) {
			//layerCheckBox = createCheckBox(checked,enabled,onAction,doNadda);
			newLi.appendChild(layerCheckBox);
			if(obj.getAttribute('locked') && obj.getAttribute('locked').match(/true/i)) {
				layerCheckBox.disabled = true;
			}

			var iconUrl = UNKNOWN_DEFAULT_ICON;
			/* If no custom icon is specified - then use a default one */
			if(obj.getAttribute('icon')) {
				iconUrl = obj.getAttribute('icon');
			} else if(obj.tagName.match(/map/)) {
				iconUrl = MAP_DEFAULT_ICON;
			} else if(obj.tagName.match(/service/)) {
				iconUrl = SERVICE_DEFAULT_ICON;
			} else if(obj.tagName.match(/view/)) {
				iconUrl = VIEW_DEFAULT_ICON;
			}
			imgIcon.style.paddingTop = '1px';
			imgIcon.style.marginTop = '1px';
			imgIcon.src = iconUrl;

			/*newLi.onclick = function(event) {
				if(window.event) {
					event = window.event;
				}
			}*/

			if(obj.getElementsByTagName('meta')[0] && obj.getElementsByTagName('meta')[0].firstChild.nodeValue) {
				metaIcon = document.createElement('img');
				metaIcon.src = META_DEFAULT_ICON;
				metaIcon.style.paddingTop = '1px';
				metaIcon.style.marginTop = '1px';
				metaIcon.onclick = function () {
					window.open(obj.getElementsByTagName('meta')[0].firstChild.nodeValue);
				}
			}

			if(obj.getElementsByTagName('help')[0] && obj.getElementsByTagName('help')[0].firstChild.nodeValue) {
				helpIcon = document.createElement('img');
				helpIcon.src = HELP_DEFAULT_ICON;
				helpIcon.style.paddingTop = '1px';
				helpIcon.style.marginTop = '1px';
				helpIcon.onclick = function () {
					window.open(obj.getElementsByTagName('help')[0].firstChild.nodeValue);
				}
			}

		}
		newLi.appendChild(imgIcon);
		var titleText = obj.getAttribute('title');
		newLi.appendChild(document.createTextNode(titleText));

		if(metaIcon) { newLi.appendChild(metaIcon); }
		if(helpIcon) { newLi.appendChild(helpIcon); }

		//newLi.innerHTML = newLi.innerHTML + titleText;

		newLi.appendChild(document.createElement('br'));
		return newLi;
	}

	this.getTree = function() {
		return createBranch(parentXML);
	}

	this.reloadMapbook = function(mbXML) {
		Parent.removeChild(Tree);
		this.loadMapbook(mbXML);
	}

	this.loadMapbook = function(mbXML) {
		parentXML = mbXML.getElementsByTagName('mapbook')[0];
		Tree = MySelf.getTree();
		if(Parent) {
			Parent.appendChild(Tree);
		}
	}

	this.setParent = function(p) {
		Parent = p;
		if(Tree) {
			p.appendChild(Tree);
		}
	}
}
/* ======================================================================    objects/VisibleLayers.js
   ====================================================================== */


	function createIcon(EventManager, src,eventTrigger,mapTitle) {
		var newIcon = document.createElement('img');
		newIcon.setAttribute('src', src);
		newIcon.style.verticalAlign = 'middle';
		newIcon.onclick = function () {
			EventManager.triggerEvent(eventTrigger, mapTitle);
		}
		return newIcon;
	}
	

function VisibleLayers(EventManager) {
	var ListParent;
	var LayersList = document.createElement('ul');
	LayersList.className = 'VisibleLayers';

	var LayerIcons = new Array();
	var LayerIconObjs = new Array();


	this.clearActiveLayerSelection = function() {
		var radios = LayersList.getElementsByTagName('input');
		for(var i = 0; i < radios.length; i++) {
			radios[i].checked = false;
		/*	radios[i].parentNode.style.border = 'none';*/
			if(radios[i].parentNode.className == 'SelectedLayer') {
				radios[i].parentNode.className = 'ActiveLayer';
			}
		}
	}

	this.addLayer = function(mapXMLObj) {
		var title = mapXMLObj.getAttribute('title');

		var ListItem = document.createElement('li');
		ListItem.id = 'LayersList-'+title;

		var alreadyHere = document.getElementById(ListItem.id);
		if(alreadyHere) return false;

		var ActivateLayer = document.createElement('input');
		ActivateLayer.type = 'radio';
		ActivateLayer.name = 'activateLayer';
		ActivateLayer.disabled = true;
		ActivateLayer.id = 'DataLayer-'+title;
		ActivateLayer.onclick = function() {
			EventManager.triggerEvent('changetool', title);
			EventManager.triggerEvent('activatelayer', title);
			/** Old Selection is Cleared by the Event Manager **/
			if(!this.disabled) {
				this.checked = true;
				/*this.parentNode.style.border = 'solid 1px black';*/
				this.parentNode.className = 'SelectedLayer';
			}
		}

		var LegendImg = document.createElement('img');
		LegendImg.id = 'LayerLegend-'+title;
		//LegendImg.src = BLANK_IMAGE;
		LegendImg.style.visibility = 'hidden';

		var LayerIcon = document.createElement('img');
		if(mapXMLObj.getAttribute('icon')) {
			LayerIcons[title] = mapXMLObj.getAttribute('icon');
		} else {
			LayerIcons[title] = MAP_DEFAULT_ICON;
		}
		LayerIcon.src = LayerIcons[title];
		LayerIcon.id = 'LayerIcon-'+title;
		LayerIconObjs[title] = LayerIcon;

		ListItem.appendChild(ActivateLayer);
		ListItem.appendChild(LayerIcon);
		ListItem.appendChild(document.createTextNode(title));
		if(mapXMLObj.getElementsByTagName('meta')[0] && mapXMLObj.getElementsByTagName('meta')[0].firstChild.nodeValue) {
			var metaIcon = document.createElement('img');
			metaIcon.src = META_DEFAULT_ICON;
			metaIcon.onclick = function () {
				window.open(mapXMLObj.getElementsByTagName('meta')[0].firstChild.nodeValue);
			}
			ListItem.appendChild(metaIcon);
		}
		if(mapXMLObj.getElementsByTagName('help')[0] && mapXMLObj.getElementsByTagName('help')[0].firstChild.nodeValue) {
			var helpIcon = document.createElement('img');
			helpIcon.src = HELP_DEFAULT_ICON;
			helpIcon.onclick = function () {
				window.open(mapXMLObj.getElementsByTagName('help')[0].firstChild.nodeValue);
			}
			ListItem.appendChild(helpIcon);
		}

		ListItem.appendChild(document.createElement('br'));

		var upButton = createIcon(EventManager, UP_ICON,'movelayerup', title);
		var downButton = createIcon(EventManager, DOWN_ICON,'movelayerdown',title);
		var fadeButton = createIcon(EventManager, FADE_ICON,'fadelayer',title);
		var unfadeButton = createIcon(EventManager, UNFADE_ICON,'unfadelayer',title);
		var removeButton = createIcon(EventManager, REMOVE_ICON,'removelayer',title);
		var refreshButton = createIcon(EventManager, RELOAD_ICON,'refreshlayer', title);

		ListItem.appendChild(upButton);
		ListItem.appendChild(downButton);
		ListItem.appendChild(fadeButton);
		ListItem.appendChild(unfadeButton);
		ListItem.appendChild(refreshButton);
		if(!mapXMLObj.getAttribute('locked') || !mapXMLObj.getAttribute('locked').match(/true/i)) {
			ListItem.appendChild(removeButton);
		}
		ListItem.appendChild(document.createElement('br'));
		ListItem.appendChild(LegendImg);

		LayersList.appendChild(ListItem);	
		if(parseInt(mapXMLObj.getAttribute('zindex')) == -1 || !LayersList.firstChild) {
			LayersList.appendChild(ListItem);
		} else {
			LayersList.insertBefore(ListItem, LayersList.firstChild);
		}

	}

	this.activateLayer = function(mapTitle) {
		var opt = document.getElementById('DataLayer-'+mapTitle);
		if(opt) {
			opt.disabled = false;
			opt.parentNode.className = 'ActiveLayer';
		}
	}

	this.disableLayers = function() {
		var opts = LayersList.getElementsByTagName('input');
		for(var i = 0; i < opts.length; i++) {
			if(opts[i].type == 'radio') {
				opts[i].disabled = true;
				opts[i].checked = false;
				opts[i].parentNode.className = '';
			}
		}
	}

	this.removeLayer = function(mapTitle) {
		var ListItem = document.getElementById('LayersList-'+mapTitle);
		LayersList.removeChild(ListItem);
	}

	this.showLegend = function(xmlObj) {
		var title = xmlObj.getAttribute('id');
		var src = xmlObj.getAttribute('legend');
		

		// This is hack for IE, it does not properly resize the image upon
		// loading.
		var tempImage = new Image();
		tempImage.onload = function () {
			var LegendImg = document.getElementById('LayerLegend-'+title);
			if(!LegendImg) {
				return false;
			}
			LegendImg.style.visibility = 'visible';
			LegendImg.style.width = 'auto';
			LegendImg.style.height = 'auto';
			LegendImg.src = src;
			LegendImg.style.width = this.width+'px';
			LegendImg.style.height = this.height+'px';
		}
		tempImage.src=  src;
	}
	
	this.moveLayerUp = function(title) {
		var listItem = document.getElementById('LayersList-'+title);
		if(listItem && listItem.previousSibling) {
			LayersList.insertBefore(listItem, listItem.previousSibling);
		}
	}

	this.moveLayerDown = function(title) {
		var listItem = document.getElementById('LayersList-'+title);
		if(listItem && listItem.nextSibling) {
			LayersList.insertBefore(listItem.nextSibling, listItem);
		}
	}

	this.setAllRefreshIcon = function () {
		for(var title in LayerIcons) {
			LayerIconObjs[title].src = MAP_LOADING_ICON;
		}
	}
	
	this.setRefreshIcon = function(title) {
		var icon = document.getElementById('LayerIcon-'+title);
		if(icon) {
			icon.src = MAP_LOADING_ICON;
		}
	}
	
	this.setLoadedIcon = function(title) {
		var icon = document.getElementById('LayerIcon-'+title);
		if(icon) {
			icon.src = LayerIcons[title];
		}
	}



	
	this.setParent = function(parent) {
		ListParent = parent;
		ListParent.appendChild(LayersList);
	}
}
/* ======================================================================    objects/Tools.js
   ====================================================================== */

/*
 * 
 */

var TOOLBAR_TEXT = false;
var TOOLBAR_IMAGE = true;

function Tools(EventManager) {
	var ToolsParent;

	var ToolsList = document.createElement('ul');
	ToolsList.className = 'ToolList';

	var ToolIcons = new Array();
	var HighlightIcons = new Array();

	this.clearToolSelection = function(title) {
		var links = ToolsList.getElementsByTagName('a');
		for(var i = 0; i < links.length; i++) {
			if(links[i].className == 'Selected') {
				links[i].className = '';
			}
			if(links[i].toolIcon) {
				if(links[i].toolIcon.src.match(links[i].highlightIconSrc)) {
					links[i].toolIcon.src = links[i].toolIconSrc;
				}
			}
		}
	}
	
	this.addService = function(serviceXMLObj) {
		var title = serviceXMLObj.getAttribute('title');
		var newTool = document.createElement('li');

		var ServiceLink = document.createElement('a');

		var action = '';
		if(serviceXMLObj.getAttribute('type') && serviceXMLObj.getAttribute('type').match(/internal/i)) {
			action = 'javascript:'+serviceXMLObj.getAttribute('command');
		} else if(!serviceXMLObj.getAttribute('type') || !serviceXMLObj.getAttribute('type').match(/internal/i)) {
			action = 'javascript:function nil() {return false; }';
			ServiceLink.callService = function () { EventManager.triggerEvent('serviceform', serviceXMLObj	); }
		}
		ServiceLink.href = action;
		ServiceLink.id = 'ServiceLink-'+title;
		ServiceLink.onclick = function () {
			EventManager.triggerEvent('changetool', title);
			this.className = 'Selected';
			if(this.toolIcon) {
				if(this.highlightIconSrc) {
					/* This prevents any weird caching problems when
						swapping images.  They are particularly notable in IE
					*/
					var img = new Image();
					var self = this;
					img.onload = function () {
						self.toolIcon.src = self.highlightIconSrc;
					}
					img.src = this.highlightIconSrc;
				}
			}
			if(this.callService) {
				this.callService();
			}
		}
		var icon = serviceXMLObj.getAttribute('icon');
		if(!icon) { icon = SERVICE_DEFAULT_ICON; }
		var newToolIcon = document.createElement('img');
		newToolIcon.src = icon;
		newToolIcon.id = 'ServiceIcon-'+title;
		ToolIcons[title] = icon;

		var altIcon = serviceXMLObj.getAttribute('highlight');
		if(altIcon) {
			HighlightIcons[title] = altIcon;
			ServiceLink.highlightIconSrc = altIcon;
		}

		if(TOOLBAR_IMAGE) {
			ServiceLink.appendChild(newToolIcon);
			ServiceLink.toolIcon = newToolIcon;
			ServiceLink.toolIconSrc = ToolIcons[title];
		}
		if(TOOLBAR_TEXT) {
			ServiceLink.appendChild(document.createTextNode(title));
		}
		ServiceLink.title = title;
		newTool.appendChild(ServiceLink);
		newTool.id = 'ServiceTool-'+title;
		if(serviceXMLObj.getElementsByTagName('help')[0] && serviceXMLObj.getElementsByTagName('help')[0].firstChild.nodeValue) {
			var helpButton = document.createElement('img');
			helpButton.src = HELP_DEFAULT_ICON;
			helpButton.onclick = function f() {
				window.open(serviceXMLObj.getElementsByTagName('help')[0].firstChild.nodeValue);
				return false;
			}
			ServiceLink.appendChild(helpButton);
		}	

		if(!serviceXMLObj.getAttribute('locked') || !serviceXMLObj.getAttribute('locked').match(/true/i)) {
			var removeButton = createIcon(EventManager, REMOVE_ICON,'removeservice',title);
			ServiceLink.appendChild(removeButton);
		}
		ToolsList.appendChild(newTool);

	}
	
	this.setParent = function(p) {
		ToolsParent = p;
		ToolsParent.appendChild(ToolsList);
	}

	this.removeService = function(serviceTitle) {
		var serv = document.getElementById('ServiceTool-'+serviceTitle);
		if(serv) {
			ToolsList.removeChild(serv);
		}
	}

	this.toolWaiting = function(serviceXMLObj) {
		if(serviceXMLObj.getAttribute('type') && serviceXMLObj.getAttribute('type').match(/search/i)) {
			var title = serviceXMLObj.getAttribute('title');
			var icon = document.getElementById('ServiceIcon-'+title);
			icon.src = MAP_LOADING_ICON;
		}
	}
	
	this.restoreTool = function(serviceXMLObj) {
		var root = serviceXMLObj.getElementsByTagName('return')[0];
		if(!root) { root = serviceXMLObj.getElementsByTagName('results')[0]; }
		var title = root.getAttribute('title');
		var icon = document.getElementById('ServiceIcon-'+title);
		icon.src = ToolIcons[title];
	}

	this.selectTool = function(toolName) {
		var tool = document.getElementById('ServiceLink-'+toolName);	
		tool.onclick();
		if(tool.href) {
			var js = tool.href;
			js = js.replace('javascript:','');
			eval(js);
		}
	}
}
/* ======================================================================    objects/Scalebar.js
   ====================================================================== */

var SCALEBAR_WIDTH = 200;
var SCALEBAR_HEIGHT = 20;

function Scalebar(EventManager, sbMap, sbWidth, sbHeight) {
	var MySelf = this;
	
	var imgObj;
	
	function buildURL(sbCenterPoint, sbScale, mapWidth,mapHeight) {
		var url = SCALEBAR_CALL;
		var gisW = mapWidth / 2 * sbScale;
		var gisH = mapHeight / 2 * sbScale;
		var minCoords = new Point(sbCenterPoint.x - gisW, sbCenterPoint.y - gisH);
		var maxCoords = new Point(sbCenterPoint.x + gisW, sbCenterPoint.y + gisH);

		var sizeString = mapWidth+'+'+mapHeight;
		var coordsString = minCoords.toString('+')+'+'+maxCoords.toString('+');
		url = url.replace('[SIZE]',sizeString);
		url = url.replace('[EXTENTS]',coordsString);
		return url;
	}

	this.update = function(circ) {
		var cp = circ.Center;
		var scale = circ.Radius;
		var mapSize = sbMap.getMapSize();
		imgObj.src = buildURL(cp, scale, mapSize.x, mapSize.y);
	}

	this.setParent = function(p) {
		imgObj = document.createElement('img');
		/*imgObj.style.width = sbWidth+'px';
		imgObj.style.height = sbHeight+'px';*/
		p.appendChild(imgObj);
	}

}
/* ======================================================================    objects/Message.js
   ====================================================================== */

function Message(EventManager) {
	var Parent;
	var MessageContainer = document.createElement('span');

	MessageContainer.className = 'Message';
	MessageContainer.style.display = 'block';

	this.setParent = function(p) {
		Parent = p;
		p.appendChild(MessageContainer);		
	}

	this.changeMessage = function(msg) {
		MessageContainer.innerHTML = msg;
	}
	this.clearMessage = function() {
		MessageContainer.innerHTML = '';
	}
}
/* ======================================================================    objects/Search.js
   ====================================================================== */

function Search() {
	var MySelf = this;

	var SearchServiceURLs = new Array();
	var SearchServiceIDs = new Array();

	var SearchList;
	
	var masterControl = document.createElement('div');	
	var mapBook;
	
	this.addSearchService = function(name,url,id) {
		SearchServiceURLs[name] = url;
		SearchServiceIDs[name] = id;
	}

	this.setMapBook = function (mBook) {
		mapBook = mBook;
	}

	this.addSearchServicesFromMapbook = function(paramMapBook) {
		mapBook = paramMapBook;
		var services = mapBook.getElementsByTagName('service');
		for(var i = 0; i < services.length; i++) {
			if(services[i].getAttribute('searchbox')) {
				var serviceURL = services[i].getElementsByTagName('url')[0];
				var url = serviceURL.firstChild.nodeValue;

				var firstInput = services[i].getElementsByTagName('input')[0];
				
				MySelf.addSearchService(services[i].getAttribute('title'),url,firstInput.getAttribute('name'));
			}
		}
		MySelf.refreshSearchList();
	}
	
	this.refreshSearchList = function() {
		var currentOpts = SearchList.getElementsByTagName('option');
		for(var i = currentOpts.length - 1; i >= 0; i--) {
			SearchList.removeChild(currentOpts[i]);
		}
		for(var name in SearchServiceURLs) {
			var opt = document.createElement('option');
			opt.appendChild(document.createTextNode(name));
			opt.setAttribute('value', name);
			SearchList.appendChild(opt);
		}
	}

	this.getActiveSearchService = function () {
		var currentOpts = SearchList.getElementsByTagName('option');
		for(var i = currentOpts.length - 1; i >= 0; i--) {
			if(currentOpts[i].selected) {
				return currentOpts[i].getAttribute('value');
			}
		}
		return null;
	}


	this.getSearchBox = function() {
		masterControl.appendChild(document.createTextNode('Search:'));
		var searchBox = document.createElement('input');
		searchBox.setAttribute('subtype','user');

		masterControl.appendChild(searchBox);
		var searchSubmit = document.createElement('input');
		searchSubmit.value = 'Search';
		searchSubmit.type = 'submit';

		searchSubmit.onclick = function() {
			var currentService = MySelf.getActiveSearchService();
			if(currentService) {
				searchBox.name = SearchServiceIDs[currentService];
				var myService = new Service(getServiceByTitle(mapBook,currentService), AllResults);
				myService.setForm(masterControl);
				alert(myService.createURL());
				myService.getResults();
			}
			
			alert(MySelf.getActiveSearchService());		
		}
		
		masterControl.appendChild(searchSubmit);
		masterControl.appendChild(document.createElement('br'));

		SearchList = document.createElement('select');
		masterControl.appendChild(SearchList);
		this.refreshSearchList();

		return masterControl;
	}

}
/* ======================================================================    sandbox/viewBox3.js
   ====================================================================== */

function ViewBox(EventManager, ViewMap) {
	var viewsList = document.createElement('select');
	viewsList.appendChild(document.createElement('option'));

	this.addView = function(viewXMLOBj) {
		var title = viewXMLOBj.getAttribute('title');

		var option = document.createElement('option');
		option.appendChild(document.createTextNode(title));
		option.id = 'ViewBoxOption-'+title;
		option.value = viewXMLOBj.firstChild.nodeValue;
		viewsList.appendChild(option);
	}

	this.removeView = function(viewTitle) {
		viewsList.removeChild(document.getElementById('ViewBoxOption-'+viewTitle));
	}

	viewsList.onchange = function() {
		var viewOptions = viewsList.getElementsByTagName('option');
		var circView = convertViewString(viewOptions[viewsList.selectedIndex].value, ViewMap.getMapSize());
		EventManager.changePointScale(circView.Center, circView.Radius);
		for(var i = 0; i < viewOptions.length; i++) {
			viewOptions.selected = false;
		}
		viewOptions[0].selected = true;
	/*
		var circView = convertViewString(allViews[v].firstChild.nodeValue, new Point(500,500));
		Events.changePointScale(circView.Center,circView.Radius);
	*/
	}

	this.setParent = function(p) {
		p.appendChild(document.createTextNode('Jump To:'));
		p.appendChild(viewsList);
	}
}
/* ======================================================================    custom/navigator.js
   ====================================================================== */

function MapNavigator (EventManager, Map) {
	var SLIDER_MIN_PX = 140;
	var SLIDER_MAX_PX = 22;

	var SLIDER_SCALE_PER_PX = (SLIDER_MIN_PX - SLIDER_MAX_PX) / (SLIDER_MAX_SCALE - SLIDER_MIN_SCALE);


	var Parent;
	var SliderControl;
	var IncreaseScale;
	var DecreaseScale;

	this.createNavIcon = function(alt) {
		var obj = document.createElement('div');
		obj.title = alt;
		obj.alt = alt;
		obj.style.position = 'absolute';
		return obj;
	}

	this.navigate = function(percentEast, percentNorth,scaleChange) {
		var pointScale = Map.getPointScale();
		pointScale.Radius *= scaleChange;
		if(pointScale.Radius > SLIDER_MAX_SCALE) { pointScale.Radius = SLIDER_MAX_SCALE; }	
		if(pointScale.Radius < SLIDER_MIN_SCALE) { pointScale.Radius = SLIDER_MIN_SCALE; }	
		var mapDimension = Map.getMapSize();
		pointScale.Center.x += (mapDimension.x*percentEast*pointScale.Radius);
		pointScale.Center.y += (mapDimension.y*percentNorth*pointScale.Radius);

		EventManager.triggerEvent('navigate', pointScale);
	}

	this.onNavigate = function(psScale) {
		var Bottom = SLIDER_MIN_PX;
		if(SLIDER_MIN_PX > SLIDER_MAX_PX) { Bottom = SLIDER_MAX_PX; }
		var length = Math.abs(SLIDER_MAX_PX - SLIDER_MIN_PX - SliderControl.offsetHeight);
		var scaleLen = SLIDER_MAX_SCALE - SLIDER_MIN_SCALE;
		var percent =  psScale.Radius / scaleLen;
		if(percent > 1) { percent = 1; }
		SliderControl.style.top = Bottom+(percent*length) + 'px';	
	}

	var MySelf = this;

	this.onResize = function() {
		SLIDER_MAX_PX = DecreaseScale.offsetTop;
		SLIDER_MIN_PX = IncreaseScale.offsetTop + IncreaseScale.offsetHeight;
		SLIDER_SCALE_PER_PX = (SLIDER_MIN_PX - SLIDER_MAX_PX) / (SLIDER_MAX_SCALE - SLIDER_MIN_SCALE);
	}

	this.setParent = function(p) {
		Parent = p;
		var slider = this.createNavIcon('Scale Slider Bar');
		slider.style.border = '0px';
		Parent.appendChild(slider);

		var sliderControl = document.createElement('div');
		sliderControl.id = 'navigatorSliderControl';
		SliderControl = sliderControl;

		var draggable = new Draggable(sliderControl, sliderControl, false, true, true);
		slider.onclick = function (event) {
			if(window.event) { event = window.event; }
			var pos = objectClientPosition(this);
			var top = event.clientY-pos.y + this.offsetTop;
			sliderControl.style.top = top + 'px';
			draggable.onDrop();

			if(event.preventDefault) { event.preventDefault(); }
		}
		Parent.appendChild(sliderControl);
		SliderControl = sliderControl;

		var increaseScale = document.createElement('div');
		increaseScale.id = 'navigatorIncreaseScale';
		increaseScale.title = 'Zoom In';
		Parent.appendChild(increaseScale);
		IncreaseScale = increaseScale;

		var decreaseScale = document.createElement('div');
		decreaseScale.id = 'navigatorDecreaseScale';
		decreaseScale.title = 'Zoom Out';
		Parent.appendChild(decreaseScale);
		DecreaseScale = decreaseScale;
		
		SLIDER_MAX_PX = decreaseScale.offsetTop;
		SLIDER_MIN_PX = increaseScale.offsetTop + increaseScale.offsetHeight;
		SLIDER_SCALE_PER_PX = (SLIDER_MIN_PX - SLIDER_MAX_PX) / (SLIDER_MAX_SCALE - SLIDER_MIN_SCALE);
		

		increaseScale.onclick = function (event) {
			MySelf.navigate(0,0,.7);
		}
		decreaseScale.onclick = function (event) {
			MySelf.navigate(0,0,1.2);
		}


//		sliderControl.style.top = Top + SLIDER_MAX_PX + 'px';

		var n = this.createNavIcon('North');
		var s = this.createNavIcon('South');
		var e = this.createNavIcon('East');
		var w = this.createNavIcon('West');
		Parent.appendChild(n);
		Parent.appendChild(s);
		Parent.appendChild(e);
		Parent.appendChild(w);

		n.id = 'navigatorNorth';
		e.id = 'navigatorEast';
		w.id = 'navigatorWest';
		s.id = 'navigatorSouth';
		slider.id = 'navigatorBar';

		n.onclick = function () {
			MySelf.navigate(0,.25,1);
		}

		s.onclick = function () {
			MySelf.navigate(0,-.25,1);
		}

		e.onclick = function () {
			MySelf.navigate(.25,0,1);
		}

		w.onclick = function () {
			MySelf.navigate(-.25,0,1);
		}
	

		draggable.whileDrag = function(trigger,obj) {
			if(obj.offsetTop < SLIDER_MIN_PX - 5) {
				obj.style.top = SLIDER_MIN_PX - 3 + 'px';
			}
			if(obj.offsetTop+obj.offsetHeight > SLIDER_MAX_PX + 3) {
				obj.style.top = SLIDER_MAX_PX-obj.offsetHeight+'px';
			}
		}
		draggable.onDrop = function(trigger,obj) {
			var mapScale = Map.getPointScale();
			var scaleLen = SLIDER_MAX_SCALE - SLIDER_MIN_SCALE;
			var length = Math.abs(SLIDER_MAX_PX - SLIDER_MIN_PX);
			var slTop = SliderControl.offsetTop+SliderControl.offsetHeight;
			var percent = slTop - SLIDER_MIN_PX;
			percent = percent / length;
			if(percent < 0) { percent = 0; }
			if(percent > 1) { percent = 1; }
			mapScale.Radius = scaleLen * percent + SLIDER_MIN_SCALE;
			EventManager.triggerEvent('navigate', mapScale);
		}
	}


}
