/*
 * Compiled Tue Feb 26 20:54:00 CST 2008 with the GeoMOOSE compiler.
 */

var CSV_DELIMITER=',';var CSV_ENCLOSURE='"';function ParseCSV(str){var rows=new Array();var length=str.length;var quoted=false;var row=0, col=0;rows[0]=new Array();for(var i=0; i<length; i++){var ch=str.substring(i,i+1);var nextCh=str.substring(i+1,i+2);if(!rows[row][col]){rows[row][col]='';}
if(ch.match(/\n/)&&!quoted){col=0;row++;rows[row]=new Array();} else if(ch==CSV_ENCLOSURE&&!quoted){quoted=true;} else if(ch==CSV_ENCLOSURE&&quoted&&nextCh==CSV_DELIMITER){quoted=false;} else if(ch==CSV_DELIMITER&&!quoted){col++;quoted=false;} else if(quoted&&ch==CSV_ENCLOSURE&&nextCh==CSV_ENCLOSURE){rows[row][col]+=CSV_ENCLOSURE;i++;} else {rows[row][col]+=ch;}}
return rows;}
function strfdate(fDate, fFormat){var days=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');var months=new Array('January','February','March','April','May','June','July','August','September','October','November','December');var formatString=new String(fFormat);var replacementStrings=new Array();var currentToken=new String();var readToken=false;for(var i=0; i<formatString.length; i++){var currentChar=formatString.substring(i,i+1);if(currentChar=='%'){readToken=true;currentToken=new String();} else if(readToken){var formatWidth;var widthSpecified=currentToken.length != 0;if(!widthSpecified){formatWidth=0;} else {formatWidth=parseInt(currentToken);}
currentToken += currentChar;var dateValue=false;if(currentChar=='M'){dateValue=fDate.getMonth()+1;} else if(currentChar=='D'){dateValue=fDate.getDate();} else if(currentChar=='Y'){dateValue=fDate.getFullYear();} else if(currentChar=='A'){dateValue=days[fDate.getDay()];} else if(currentChar=='B'){dateValue=months[fDate.getMonth()];} else if(currentChar=='H'){dateValue=fDate.getHours()+1;} else if(currentChar=='I'){var hours=fDate.getHours()+1;if(hours>12){hours -= 12}
dateValue=hours;} else if(currentChar=='m'){dateValue=fDate.getMinutes();} else if(currentChar=='S'){dateValue=fDate.getSeconds();}
if(dateValue){var subString=new String(dateValue);var strLength=subString.length;for(var m=0; m<formatWidth-strLength; m++){subString='0'+subString;}
if(formatWidth<strLength&&widthSpecified){subString=subString.substring(subString.length-formatWidth);}
replacementStrings['%'+currentToken]=subString;}} else {readToken=false;}}
for(var s in replacementStrings){formatString=formatString.replace(s,replacementStrings[s]);}
return formatString;}
function BTreeNode(px,py,po){this.x=px; this.y=py; this.o=po;var sameLevel=new Array();sameLevel[0]=this;var leftNode, rightNode;var MySelf=this;function bTreeNodeInsert(node){if(node.x==MySelf.x){sameLevel.push(node);} else if(node.x<MySelf.x){if(leftNode){leftNode.insert(node);}
else {leftNode=node;}} else {if(rightNode){rightNode.insert(node);}
else {rightNode=node;}}}
MySelf.insert=function (node){bTreeNodeInsert(node);}
MySelf.searchByRange=function(min,max){return bTreeSearchByRange(min,max);}
MySelf.searchByRange2D=function(minx, miny, maxx, maxy){return bTreeSearchByRange2D(minx,miny,maxx,maxy);}
function bTreeSearchByRange2D(minx,miny,maxx,maxy){var returnArray=new Array();var x=MySelf.x;var xmin=(x>minx);var xmax=(x<maxx);if(xmin&&xmax){for(var i=0; i<sameLevel.length; i++){if(sameLevel[i].y>miny&&sameLevel[i].y<maxy){returnArray.push(sameLevel[i]);}}}
if(leftNode&&(minx<x||maxx<x)){var leftArray=leftNode.searchByRange2D(minx,miny,maxx,maxy);if(leftArray){returnArray=returnArray.concat(leftArray);}}
if(rightNode&&(minx>x||maxx>x)){var rightArray=rightNode.searchByRange2D(minx,miny,maxx,maxy);if(rightArray){returnArray=returnArray.concat(rightArray);}}
return returnArray;}
function bTreeSearchByRange(min,max){var returnArray=new Array();var x=MySelf.x;var xmin=(x>min);var xmax=(x<max);if(xmin&&xmax){returnArray=sameLevel;}
if(leftNode&&(min<x||max<x)){var leftArray=leftNode.searchByRange(min,max);if(leftArray){returnArray=returnArray.concat(leftArray);}}
if(rightNode&&(min>x||max>x)){var rightArray=rightNode.searchByRange(min,max);if(rightArray){returnArray=returnArray.concat(rightArray);}}
return returnArray;}}
function BTree(){var root=null;function bTreeInsert(node){if(root){root.insert(node);} else {root=node;}}
this.insert=function(x,y,o){bTreeInsert(new BTreeNode(x,y,o));}
this.searchByRange=function(min,max){if(!root){alert('B-Tree has no elements to search!'); return null;}
return root.searchByRange(min,max);}
this.searchByRange2D=function(minx,miny,maxx,maxy){if(!root){alert('B-Tree has no elements to search!'); return null;}
return root.searchByRange2D(minx,miny,maxx,maxy);}}
var CoordinateSystemFiles=new Array();CoordinateSystemFiles['UTM']='projections/utm.js';CoordinateSystemFiles['MNCOUNTY']='projections/mncounty.js';function loadCoordinateSystem(){var CoordSys=new String(MAP_COORDINATE_SYSTEM).split('-');var theHead=document.getElementsByTagName('head')[0];var scriptTag =document.createElement('script');scriptTag.src=CoordinateSystemFiles[CoordSys[0]];theHead.appendChild(scriptTag);}
loadCoordinateSystem();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 menuIsVisible(submenu){if(submenu.style.visibility=='visible') return true;return false;}
function showSubMenu(parent, submenu){submenu.style.visibility='visible';submenu.style.left=parent.offsetLeft+parent.offsetWidth+'px';submenu.style.top=parent.offsetTop+'px';}
function onoverShowSubMenu(){showSubMenu(this, this.getElementsByTagName('ul')[0]);}
function hideMenu(submenu){if(!submenu){submenu=this.submenu;}
if(submenu){submenu.style.visibility='hidden';}}
function toggleCheckMark(){var checkMark=this.checkMark;if(checkMark.style.width=='0px'){checkMark.style.width='auto';} else {checkMark.style.width='0px';}}
function hideDoubleParent(){hideMenu(this.parentNode.parentNode);}
function hideFirstUL(){hideMenu(this.getElementsByTagName('ul')[0]);}
var MENUBAR_INSTANCE=0;function Menubar(){var Tree;var Parent;var MenuId='Menu'+MENUBAR_INSTANCE;MENUBAR_INSTANCE++;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');branch.appendChild(item);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=hideDoubleParent;itemLink.appendChild(document.createTextNode(items[i].getAttribute('title')));item.appendChild(itemLink);itemLink.style.marginLeft='22px';if(items[i].getAttribute('toggle')&&items[i].getAttribute('toggle').match(/true/i)){var checkMark=document.createElement('img');checkMark.src=MENU_TOGGLE_ICON;checkMark.style.verticalAlign='middle';checkMark.style.position='absolute';checkMark.style.left='2px';if(items[i].getAttribute('default')&&items[i].getAttribute('default').match(/true/i)){checkMark.style.width='auto';;} else {checkMark.style.width='0px';}
itemLink.checkMark=checkMark;itemLink.onclick=toggleCheckMark;itemLink.appendChild(checkMark);}
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=onoverShowSubMenu;item.onmouseout=hideFirstUL;}
if(document.all){}}}
return branch;}
var MySelf=this;function rootHideAll(event){if(window.event){event=window.event;}
var allMenus=this.getElementsByTagName('ul');for(var m=0; m<allMenus.length; m++){hideMenu(allMenus[m]);}}
this.populateMenuBar=function(xml){var root=document.createElement('ul');root.className='menubar';root.hideAll=rootHideAll;root.setAttribute('id',MenuId);var menus=xml.getElementsByTagName('menu');for(var m=0; m<menus.length; m++){var menu=document.createElement('li');root.appendChild(menu);menu.className='menu';var menuLink=document.createElement('a');menu.appendChild(menuLink);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');}
var branch=this.createBranch(menus[m]);menu.appendChild(branch);branch=null;function focusFunction(event){if(window.event){event=window.event;}
if(this.getElementsByTagName('ul')[0]){var subItems=this.getElementsByTagName('ul')[0].getElementsByTagName('li');if(subItems.length>0){showMenu(this, this.getElementsByTagName('ul')[0]);}}}
menu.onfocus=focusFunction;menu.onblur=hideFirstUL;if(document.all){function f(){this.parentNode.hideAll();this.onfocus();}
menu.onclick=f;}
menu=null;}
if(document.all){document.attachEvent('onclick',IEonBlurSim);}
if(Parent){document.getElementById(Parent).appendChild(root);}
root=null;}
function IEonBlurSim(event){if(window.event){event=  window.event;}
var menuItem=event.srcElement.parentNode;var menuElements=document.getElementById(Parent).getElementsByTagName('li');for(var i=0; i<menuElements.length; i++){if(menuItem != menuElements[i]){if(menuElements[i].onblur){menuElements[i].onblur();}}}}
this.setParent=function(p){Parent=p;if(Tree){document.getElementById(Parent).appendChild(Tree);}}}
function toggleReferenceMap(){var ref_map=document.getElementById('reference_map');var state='hidden';if(ref_map.style.visibility=='hidden'){state='visible';}
ref_map.style.visibility=state;RefMap.setVisibility(state);onResize();}
function toggleMapNavigator(){if(Navigator.getVisibility() != 'hidden'){Navigator.hideNavigator();} else {Navigator.showNavigator();}}
function setTheme(color){var THEMED_HEADER_URL=(new String(HEADER_URL)).replace(/%THEME%/i, color);document.getElementById('header_container').src=THEMED_HEADER_URL;var allImages=document.getElementsByTagName('img');for(var i=0; i<allImages.length; i++){if(allImages[i].getAttribute('psrc')){var imgString=allImages[i].getAttribute('psrc').replace(/%THEME%/i, color);allImages[i].src=imgString;}}
var head=document.getElementsByTagName('head')[0];var allLinks=document.getElementsByTagName('link');for(var i=0; i<allLinks.length; i++){allLinks[i].setAttribute('remove','1');}
var styles=new Array();styles[0]="skins/%THEME%/styles.css";styles[1]="skins/%THEME%/menubar.css";styles[2]="skins/%THEME%/navigator.css";styles[3]="shared/styles.css";styles[4]="shared/control.css";styles[5]="shared/popup.css";for(var i=0; i<styles.length; i++){var link=document.createElement('link');link.setAttribute('rel','stylesheet');link.setAttribute('type','text/css');styles[i]=new String(styles[i]).replace(/%THEME%/i, color);link.setAttribute('href',styles[i]);head.appendChild(link);}
allLinks=document.getElementsByTagName('link');for(var i=allLinks.length-1; i>=0; i--){if(allLinks[i].getAttribute('remove')){head.removeChild(allLinks[i]);}}}
function linkToMe(){var cgi=new CGI();var loc=new String(window.location);loc=loc.split('?')[0];loc=loc+'?';var mapbook=cgi.param('mapbook');if(mapbook){loc=loc+'mapbook='+mapbook+'&';}
var mapLocation=Map.getCenterPoint().toString(',')+','+Map.getScale();loc=loc+'zoomto=' +mapLocation+'&';var layers=Map.getLayerTitles();loc=loc+'layers=';for(var i=0; i<layers.length; i++){loc=loc+escape(layers[i])+',';}
loc=loc.substring(0,loc.length-1);window.location=loc;}
function hideDisclaimer(){var toRemove=['Disclaimer-Background', 'Disclaimer-Content'];for(var i=0; i<toRemove.length; i++){var elm=document.getElementById(toRemove[i]);var p=elm.parentNode;p.removeChild(elm);}}
function showDisclaimer(mapbook){var disclaimers=mapbook.getElementsByTagName('disclaimer');if(disclaimers.length<1){return false;}
var discBg=document.createElement('div');var discContent=document.createElement('div');var body=document.getElementsByTagName('body')[0];discBg.setAttribute('id','Disclaimer-Background');discContent.setAttribute('id','Disclaimer-Content');body.appendChild(discBg);body.appendChild(discContent);var discMessage='';for(var i=0; i<disclaimers.length; i++){discMessage=discMessage+disclaimers[i].firstChild.nodeValue+'<br/>';}
discContent.innerHTML=discMessage;var discButtonBar=document.createElement('center');discButtonBar.style.width='100%';discContent.appendChild(discButtonBar);var discClose=document.createElement('input');discClose.setAttribute('type','button');discClose.setAttribute('value', 'Accept');discButtonBar.appendChild(discClose);discClose.onclick=hideDisclaimer;}
var DebuggerWindow=null;var DebuggerQueuedMessages=new Array();function startDebugger(func){DebuggerWindow=window.open('lib/libs/Debugger.html', 'Debugger', 'width=640,height=480,toolbar=0,resizable=1,status=0,menubar=0,location=0,scrollbars=0');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 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.insertBefore(DebuggerQueuedMessages[i], debugBody.firstChild);}
DebuggerQueuedMessages=new Array();}
debugBody.insertBefore(message, debugBody.firstChild);} else {DebuggerQueuedMessages[DebuggerQueuedMessages.length]=message;}}
function stopDebugger(){DebuggerWindow.close();DebuggerWindow=null;}
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;}
function round(number,X){X=(!X ? 2 : X);var n=new String(number);var loc=n.indexOf('.');var whole=n.substring(0,loc);var decimal=n.substring(loc+1, loc+1+X);return(whole+'.'+decimal);}
function getKeyCode(event){var KeyString='';if(event.ctrlKey){KeyString=KeyString+'CTRL+';}
if(event.shiftKey){KeyString=KeyString+'SHIFT+';}
var key;if(event.which){key=event.which;}
if(event.keyCode){key=event.keyCode;}
return KeyString=KeyString+String.fromCharCode(key);}
function stripCommas(v){v=new String(v);while(v.match(/\,/)){v=v.replace(',','');}
return v;}
function commifyNumber(number){var numberOrig=new String(number);var numberArr=new String(number).split('.');number=numberArr[0]; number=''+number; if (number.length>3){var mod=number.length % 3;  var output=(mod>0 ? (number.substring(0,mod)) : '');  for (i=0 ; i<Math.floor(number.length/3); i++){if((mod==0)&&(i==0))
    output += number.substring(mod+ 3*i, mod+3*i+3);   else
    output+= ','+number.substring(mod+3*i, mod+3*i+3);}} else {output=number;}
 if(numberOrig.match('.')&&numberArr[1]){output=output+'.'+numberArr[1];}
 return output;}
function parseBoolean(s, def){if(!s) return def;s=s.toString().toLowerCase();return s=="true"||s=="yes"||parseInt(s)>0;}
var UNITS_STRINGS=new Array();UNITS_STRINGS['M']='Meters';UNITS_STRINGS['IN']='Inches';UNITS_STRINGS['MI']='Miles';UNITS_STRINGS['FT']='Feet';var UNITS_SQ_STRINGS=new Array();UNITS_SQ_STRINGS['SQIN']='Square Inches';UNITS_SQ_STRINGS['SQFT']='Square Feet';UNITS_SQ_STRINGS['SQMI']='Square Miles';UNITS_SQ_STRINGS['SQM']='Square Meters';UNITS_SQ_STRINGS['SQACRE']='Acres';var UNIT_CONVERSION=new Array();UNIT_CONVERSION['IN']=new Array();UNIT_CONVERSION['IN']['FT']=0.083333333;UNIT_CONVERSION['IN']['MI']=0.000015783;UNIT_CONVERSION['IN']['M']=0.0254;UNIT_CONVERSION['IN']['IN']=1;UNIT_CONVERSION['FT']=new Array();UNIT_CONVERSION['FT']['IN']=12;UNIT_CONVERSION['FT']['MI']=0.000189394;UNIT_CONVERSION['FT']['M']=0.3048;UNIT_CONVERSION['FT']['FT']=1;UNIT_CONVERSION['MI']=new Array();UNIT_CONVERSION['MI']['IN']=63360;UNIT_CONVERSION['MI']['FT']=5280;UNIT_CONVERSION['MI']['M']=1609.344;UNIT_CONVERSION['MI']['MI']=1;UNIT_CONVERSION['M']=new Array();UNIT_CONVERSION['M']['FT']=3.280839895;UNIT_CONVERSION['M']['MI']=0.000621371;UNIT_CONVERSION['M']['IN']=39.37007874;UNIT_CONVERSION['M']['M']=1;UNIT_CONVERSION['SQIN']=new Array();UNIT_CONVERSION['SQIN']['SQIN']=1;UNIT_CONVERSION['SQIN']['SQFT']=0.006944;UNIT_CONVERSION['SQIN']['SQMI']=.000000000249;UNIT_CONVERSION['SQIN']['SQM']=0.000645;UNIT_CONVERSION['SQIN']['SQACRE']=0.000000159422;UNIT_CONVERSION['SQFT']=new Array();UNIT_CONVERSION['SQFT']['SQIN']=144;UNIT_CONVERSION['SQFT']['SQFT']=1;UNIT_CONVERSION['SQFT']['SQMI']=.0000000358;UNIT_CONVERSION['SQFT']['SQM']=0.092903;UNIT_CONVERSION['SQFT']['SQACRE']=0.000022957;UNIT_CONVERSION['SQMI']=new Array();UNIT_CONVERSION['SQMI']['SQIN']=4014489600;UNIT_CONVERSION['SQMI']['SQFT']=27878288.486594;UNIT_CONVERSION['SQMI']['SQMI']=1;UNIT_CONVERSION['SQMI']['SQM']=2589988.110336;UNIT_CONVERSION['SQMI']['SQACRE']=640;UNIT_CONVERSION['SQM']=new Array();UNIT_CONVERSION['SQM']['SQIN']=1550.0031;UNIT_CONVERSION['SQM']['SQFT']=10.763867;UNIT_CONVERSION['SQM']['SQMI']=.0000003861;UNIT_CONVERSION['SQM']['SQM']=1;UNIT_CONVERSION['SQM']['SQACRE']=0.000247105;UNIT_CONVERSION['SQACRE']=new Array();UNIT_CONVERSION['SQACRE']['SQIN']=6272614.883;UNIT_CONVERSION['SQACRE']['SQFT']=43559.825;UNIT_CONVERSION['SQACRE']['SQMI']=0.0015625;UNIT_CONVERSION['SQACRE']['SQM']=4046.856;UNIT_CONVERSION['SQACRE']['SQACRE']=1;function populateUnitConversionSelection(mType, obj){var selectedArray;if(mType=='area'){selectedArray=UNITS_SQ_STRINGS;} else {selectedArray=UNITS_STRINGS;}
var options=obj.getElementsByTagName('option');for(var i=options.length-1; i>=0; i--){obj.removeChild(options[i]);}
for(var unit in selectedArray){var opt=document.createElement('option');opt.value=unit;if(unit==MEASURE_LENGTH_UNITS||unit==MEASURE_AREA_UNITS){opt.setAttribute('selected', 'true');opt.selected=true;}
opt.appendChild(document.createTextNode(selectedArray[unit]));obj.appendChild(opt);opt=null;}
obj=null;}
function pixelScaleToInchScale(scMap, v){var w=scMap.getMapSize().x;return((v*w)/(w-1))*MAP_PIXELS_PER_INCH*UNIT_CONVERSION[MAP_GROUND_UNITS]['IN'];}
function inchScaleToPixelScale(scMap, v){var w=scMap.getMapSize().x;return((v*(w-1))/w)*(1/MAP_PIXELS_PER_INCH)*(UNIT_CONVERSION['IN'][MAP_GROUND_UNITS])+.000001;}
function LegendObj(id, legend){this.id=id;this.legend=legend;}
function getEventTarget(e){var targ;if (!e) var e=window.event;if (e.target) targ=e.target;else if (e.srcElement) targ=e.srcElement;if(targ.nodeType==3) 
targ=targ.parentNode;return targ;}
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 preventDefaultEvent(event){if(window.event){event=window.event;}
event.returnValue=false;if(event.preventDefault){event.preventDefault();}
return false;}
function attachEvent(obj, eventname, workingFn){if(!obj){return false;}
if(document.all){obj.attachEvent('on'+eventname, workingFn);} else {var retValue=true;if(eventname=='mousewheel'){eventname='DOMMouseScroll'; retValue=false;}
obj.addEventListener(eventname, workingFn, retValue);}
obj=null;}
function removeEvent(obj, eventname, workingFn){if(!obj){return false;}
if (document.all){obj.detachEvent("on"+eventname, workingFn);} else {obj.removeEventListener(eventname, workingFn, true);}
obj=null;}
function getBrowser(){return new String(navigator.appName).toLowerCase();}
function getBrowserVersion(){return parseInt(navigator.appVersion);}
function createIcon(EventManager, src,eventTrigger,mapTitle,iconTitle){var newIcon=document.createElement('img');newIcon.setAttribute('src', src);newIcon.style.verticalAlign='middle';newIcon.EventManager=EventManager;newIcon.eventTrigger= eventTrigger;newIcon.mapTitle=mapTitle;if(iconTitle){newIcon.title=iconTitle;}
newIcon.onclick=triggerSelfEvent;return newIcon;}
function getElementsByTagNameNS(obj, nameSpaceURI, nameSpacePrefix, tagName){if(window.ActiveXObject){if(nameSpacePrefix=='*'){return obj.getElementsByTagName(tagName);}
return obj.getElementsByTagName(nameSpacePrefix+':'+tagName);} else {return obj.getElementsByTagNameNS(nameSpaceURI, tagName);}}
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.length=this.getLength;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 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;}
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]);var newPoly=new Polygon();for(var i=0; i<newLines.length; i++){newPoly.addLine(newLines[i]);}
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);}
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 {}
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);}
var newLineSeg=new LineSegment(pointsArray[pointsArray.length-1], pointsArray[0]);this.addLine(newLineSeg);}
this.toString=function(delim, short){var myStr='';for(var i=0; i<this.Lines.length; i++){myStr += this.Lines[i].pointA.toString(delim)+delim;}
if(!short){myStr += this.Lines[this.Lines.length-1].pointB.toString(delim);} else {myStr=myStr.substring(0,myStr.length-1);}
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);var u= b/a;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;}}
function getWindowSize(){var myWidth=0, myHeight=0;  if( typeof( window.innerWidth )=='number' ){myWidth=window.innerWidth;    myHeight=window.innerHeight;} else if( document.documentElement&&( document.documentElement.clientWidth||document.documentElement.clientHeight ) ){myWidth=document.documentElement.clientWidth;    myHeight=document.documentElement.clientHeight;} else if( document.body&&( document.body.clientWidth||document.body.clientHeight ) ){myWidth=document.body.clientWidth;    myHeight=document.body.clientHeight;}
var winSize=new Point(myWidth, myHeight);return winSize;}
function setOpacity(elm, opaqueness){var opacity=parseInt(opaqueness);if(opacity>=100){if(typeof elm.style.filter=="string"){elm.style.filter='';} else {elm.style.opacity='';}} else {if(typeof elm.style.filter=="string"){elm.style.filter="alpha(opacity="+opaqueness+")";} else {elm.style.opacity='0.'+opaqueness;}}
elm=null;}
function getOpacity(elm){var styleString='';if(typeof elm.style.filter=="string"){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==0){styleString="0";}}
if(!styleString){styleString="100";}
elm=null;return parseFloat(styleString);}
function setOpacityById(id, opacity){var check=document.getElementById(id);if(!check){return false;}
setOpacity(check, opacity);}
function fadeObject(id, opacStart, opacEnd, millisec,remove){var speed=Math.round(millisec/100);    var timer=0;    if(opacStart>opacEnd){for(i=opacStart; i>=opacEnd; i--){setTimeout('setOpacityById("'+id+'",'+i+')',(timer*speed));            timer++;}} else if(opacStart<opacEnd){for(i=opacStart; i<=opacEnd; i++){setTimeout('setOpacityById("'+id+'",'+i+')',(timer*speed));            timer++;}}
    if(remove){timer++;setTimeout('removeObject("'+id+'")', (timer*speed));}} 
function removeObject(id){var obj=document.getElementById(id);if(obj){var p=obj.parentNode;if(p){p.removeChild(obj);}
p=null;}
obj=null;}
function Draggable(objSrc, 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; event.which=event.button;}
if(event.which>1){return false;}
var obj=document.getElementById(objSrc);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;}
var obj=document.getElementById(objSrc);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;}
var obj=document.getElementById(objSrc);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();var parent=obj.parentNode;winSize.x=parent.offsetWidth;if(parent.offsetHeight){winSize.y=parent.offsetHeight;}
var newLeft=obj.offsetLeft;if(obj.offsetLeft<0){newLeft=0;}
if(newLeft+obj.offsetWidth>winSize.x){newLeft=(winSize.x-obj.offsetWidth);}
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)+'%';}
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;function mousedownFn(event){if(window.event){event=window.event;}
startDrag(event);if(this._onmousedown){this._onmousedown(event);}}
trigger.onmousedown=mousedownFn;trigger=null;}
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 CGI (){this.param=function(theArgName){var sArgs=location.search.slice(1).split('&');var r='';for(var i=0; i<sArgs.length; i++){if(sArgs[i].slice(0,sArgs[i].indexOf('='))==theArgName){r=sArgs[i].slice(sArgs[i].indexOf('=')+1);break;}}
return (r.length>0 ? unescape(r).split(',') : null)}
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);}}
function boundingBoxStringToLineSegment(bbox,delim){var line=new LineSegment();line.fromString(bbox, delim);return line;}
function boundingBoxToPointScale(bboxLine, mapDimensions){var diffX=bboxLine.getWidth();var diffY=bboxLine.getHeight();var centerPoint=new Point(bboxLine.minX()+diffX/2, bboxLine.minY()+diffY/2);var scaleX=diffX/mapDimensions.x;var scaleY=diffY/mapDimensions.y;var selectedScale=Math.max(scaleX, scaleY);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);}
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 interfaceElements=xmlObj.getElementsByTagName('interface');for(var i=0; i<interfaceElements.length; i++){var params=interfaceElements[i].getElementsByTagName('param');for(var p=0; p<params.length; p++){var name=params[p].getAttribute('name');var value=params[p].getAttribute('value');var type=params[p].getAttribute('type');var evalString;if(type&&!type.match(/string/i)){evalString=name+"="+value+";";} else {evalString=name+"='"+value+"';";}
eval(evalString);logDebugMessage('Override Variable', true, evalString);}}
var foundView=false;if(DEFAULT_VIEW){DEFAULT_VIEW=false;foundView=true;}
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');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 selection=xmlObj.getElementsByTagName('selection');for(var s=0; s<selection.length; s++){EventManager.triggerEvent('addselection', selection[s]);}
var layersToAdd=new Array();for(var m=0 ; m<allMaps.length; m++){var name=allMaps[m].getAttribute('title');var def=new String(allMaps[m].getAttribute('default'));if(def.match(/true/i)){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 title=allServices[s].getAttribute('title');servicesToAdd[title]=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){loadDefaultsFromMapBook(xmlObj, xmlObj,EventManager,objMap);}
function downloadAndAppendMapbook(mapBook, parentDocument, parentGroup){var http=getHTTPObject();if(document.all){http.open("GET", mapBook, false);} else {http.open("GET", mapBook);}
http.onreadystatechange=function (){if(http.readyState==4){if(http.responseXML){try {var nGroup=importNode(parentDocument, http.responseXML.getElementsByTagName('mapbook')[0], true);var nodes=nGroup.childNodes;while(nodes[0]){parentGroup.appendChild(nodes[0]);}} catch(e){alert('There was an error importing "'+parentGroup.getAttribute('title')+'" ignoring and moving on.');}} else {alert('Mapbook '+mapBook+' failed to return valid XML!');}}}
http.send(null);}
function getMapbook(mapBook, EventManager, objMap){var http=getHTTPObject();if(document.all){http.open("GET", mapBook, false);} else {http.open("GET", mapBook);}
http.onreadystatechange=function (){if(http.readyState==4){xmlDoc=http.responseXML;if(xmlDoc){var groups=xmlDoc.getElementsByTagName('group');for(var g=0; g<groups.length; g++){if(groups[g].getAttribute('src')){downloadAndAppendMapbook(groups[g].getAttribute('src'), xmlDoc, groups[g]);}}
groups=xmlDoc.getElementsByTagName('group');if(MAP_MAPBOOK_ORDER){var allMaps=xmlDoc.getElementsByTagName('map');for(var m=0; m<allMaps.length; m++){allMaps[m].setAttribute('zindex', m);}}
EventManager.onLoadedMapbook(xmlDoc, objMap);} else {alert('Mapbook '+mapBook+' failed to return XML!');}
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 mapbookFromURL=util.param('mapbook');var MapBook=MAPBOOK_FILE;if(mapbookFromURL){MapBook=mapbookFromURL;}
EventManager.addEventListener('loadedmapbook', 'URLLayers', 
function (xmlDoc){EventManager.removeEventListener('loadedmapbook', 'URLLayers');mapbookLoadedEvents(xmlDoc);});getMapbook(MapBook,EventManager,oMap);}
function mapbookLoadedEvents(xmlDoc){var cgi=new CGI();var layers=new String(cgi.param('layers'));var layersArr=layers.split(',');for(var i=0; i<layersArr.length; i++){var map=getObjectByTitle(xmlDoc, 'map', unescape(layersArr[i]));if(map){Events.triggerEvent('addlayer',map);}}
var title=cgi.param('call');if(title&&title != 'null'){var services=xmlDoc.getElementsByTagName('service');var knownServices=new Array();for(var s=0; s<services.length; s++){knownServices[services[s].getAttribute('title')]=services[s];}
var serviceXML=knownServices[title];if(serviceXML){var inputs=serviceXML.getElementsByTagName('input');var url=serviceXML.getElementsByTagName('url')[0].firstChild.nodeValue;url=url+'?';for(var i=0; i<inputs.length; i++){var iType=inputs[i].getAttribute('type');var iName=inputs[i].getAttribute('name');if(iType.match(/user/i)){if(cgi.param(iName)){inputs[i].setAttribute('value', cgi.param(iName));}}}
Events.triggerEvent('callservice', serviceXML);} else {alert('Cannot Find Service '+title);}}}
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]&&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, scaleMap, markup){var circ=new Circle();circ.Radius=scale;circ.Center=centerPoint;circ.Markup=markup;this.triggerEvent('navigate',circ);}}
var MAP_MAX_ZINDEX=500;var MAP_CONTROL_INDEX=1000;var MAP_DRAWING_INDEX=900;var MAP_POPUP_ZINDEX=5000;var GMAP_INSTANCE=0;var MAP_LOAD_IMAGE=0;var MAP_LOAD_DATA=1;var MAP_LOAD_LEGEND=2;function GMap(EventManager){var MySelf=this;var MapId='Map'+GMAP_INSTANCE+'-';var LayerId=MapId+'Layer-';GMAP_INSTANCE++;var MapParentId;var ImageParentId=MapId+'ImageParent';var ScaleFactor=1;var MapReference=null;var CoordinateObjectId=null;var ImageControlId;var ImageMapControlId;var ReferenceIndicatorId=MapId+'ReferenceIndicator';var DrawBoxId=MapId+'DrawBox';var PopupMenuId=MapId+'PopupMenu';var ImageControlCanvasId=MapId+'Canvas'
var FunctionOffset=new Point();var FunctionSemaphore=false;var DrawnPoints=new Array();var PreviousViews=new Array();function refreshDrawBox(){var DrawBox=document.getElementById(DrawBoxId);if(!DrawBox){DrawBox=document.createElement('div');}
if(!DrawBox.parentNode){document.getElementById(MapParentId).appendChild(DrawBox);}
DrawBox.setAttribute('id', DrawBoxId);DrawBox.style.position='absolute';DrawBox.style.border='solid 2px red';DrawBox.style.zIndex=MAP_DRAWING_INDEX;DrawBox.style.visibility='hidden';DrawBox.style.overflow='hidden';DrawBox.style.width='1px';DrawBox.style.height='1px';DrawBox=null;}
var MapCenterPoint=new Point(576000, 157909.5);var MapScale=25;var LayerURLs=new Array();var LayerLoadData=new Array();var LayerLegends=new Array();var LayerImages=new Array();var LayerParameters=new Array();var LayerSelections=new Array();var LayerMinScale=new Array();var LayerMaxScale=new Array();var LayerDebug=new Array();var min_z_index=MAP_MAX_ZINDEX;var VisibilityState='visible';function setVisibility(state){for(var t in LayerImages){var img=document.getElementById(LayerId+t);if(img){img.style.visibility=state;}
img=null;}
VisibilityState=state;}
this.setVisibility=setVisibility;this.hideMap=function(){setVisibility('hidden');}
this.showMap=function(){setVisibility('visible');}
this.setCoordinateObject=function(objId){CoordinateObjectId=objId;}
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;}
var MapViewSet=false;var MAP_MARKUP_RADIUS=25;this.onChangePointScale=function(psc){if(MapReference&&!REFERENCE_MAP_DYNAMIC&&MapViewSet){return true;}
MapViewSet=true;MySelf.clearDrawingArea();if(psc.Markup){var imageControlCanvas=document.getElementById(ImageControlCanvasId);var ctx=imageControlCanvas.getContext("2d");var mSize=MySelf.getMapSize();ctx.save();ctx.beginPath();ctx.strokeStyle="rgba(255,0,0,.75)";ctx.lineWidth=1;ctx.moveTo(mSize.x/2,mSize.y/2-MAP_MARKUP_RADIUS);ctx.lineTo(mSize.x/2,mSize.y/2+MAP_MARKUP_RADIUS);ctx.stroke();ctx.moveTo(mSize.x/2-MAP_MARKUP_RADIUS, mSize.y/2);ctx.lineTo(mSize.x/2+MAP_MARKUP_RADIUS, mSize.y/2);ctx.stroke();ctx.closePath();ctx.restore();ctx.save();ctx.beginPath();ctx.strokeStyle='rgba(255,0,0,.75)';ctx.lineWidth=3;ctx.arc(mSize.x/2, mSize.y/2, MAP_MARKUP_RADIUS, 0, Math.PI*2,true);ctx.stroke();ctx.closePath();ctx.restore();}
PreviousViews[PreviousViews.length]=psc;MapScale=psc.Radius*ScaleFactor;MapCenterPoint=psc.Center;MySelf.refreshLayers();}
var DrawingShape='point';var PointDrawingSemaphore=true;function startDrawing(event){var DrawBox=document.getElementById(DrawBoxId);DrawBox.style.left='0px';DrawBox.style.top='0px';DrawBox.style.height='1px';DrawBox.style.width='1px';if(window.event){event=window.event; event.which=event.button;}
if(event.which != 1){return false;}
FunctionOffset=objectClientPosition(document.getElementById(ImageControlId));DrawnPoints=new Array();attachEvent(document, 'mouseup',stopDrawing);if(DrawingShape=='box'||DrawingShape=='evenbox'||DrawingShape=='scalebox'){DrawnPoints[0]=new Point(event.clientX-FunctionOffset.x, event.clientY-FunctionOffset.y);} else {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 drawPointOnly(event){if(PointDrawingSemaphore){whileDrawing(event);PointDrawingSemaphore=false;}}
function whileDrawingBox(event){if(window.event){event=window.event;}
if(FunctionSemaphore){var DrawBox=document.getElementById(DrawBoxId);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;var mSize=MySelf.getMapSize();var perspective=mSize.x/mSize.y;if(DrawingShape=='evenbox'){perspective=1;}
if(DrawingShape =='scalebox'||DrawingShape=='evenbox'){if(width>height){width=Math.abs(height*perspective)*width/Math.abs(width);}
else {height=Math.abs(width*1/perspective)*height/Math.abs(height);}}
if(width<0){left=left+width;width=Math.abs(width);}
if(height<0){top=top+height;height=Math.abs(height);}
width=width;height=height;DrawBox.style.top=top+'px';DrawBox.style.left=left+'px';DrawBox.style.height=height+'px';DrawBox.style.width=width+'px';DrawBox=null;}}
function cancelDrawing(){if(document.all){document.detachEvent("onmouseup",   stopDrawing);} else {document.removeEventListener("mouseup",   stopDrawing, true);}
if(FunctionSemaphore){FunctionSemaphore=false;var DrawBox=document.getElementById(DrawBoxId);DrawBox.style.visibility='hidden';DrawBox.style.left='0px';DrawBox.style.top='0px';DrawBox.style.height='1px';DrawBox.style.width='1px';var divPoints=document.getElementById(MapParentId).getElementsByTagName('div');for(var i=divPoints.length; i>=0; i--){if(divPoints[i]&&divPoints[i].parentNode&&divPoints[i].className=='DrawnPoint'){var p=divPoints[i].parentNode;p.removeChild(divPoints[i]);}}}}
function stopDrawing(){if(document.all){document.detachEvent("onmouseup",   stopDrawing);} else {document.removeEventListener("mouseup",   stopDrawing, true);}
if(FunctionSemaphore){FunctionSemaphore=false;var DrawBox=document.getElementById(DrawBoxId);var GroundUnits=new Array();if(DrawBox.offsetWidth>7){var ptA=new Point(DrawBox.offsetLeft, DrawBox.offsetTop);var ptB=new Point(ptA.x+DrawBox.offsetWidth, ptA.y+DrawBox.offsetHeight);DrawnPoints[0]=ptA;DrawnPoints[1]=new Point(ptB.x, ptA.y);DrawnPoints[2]=ptB;DrawnPoints[3]=new Point(ptA.x, ptB.y);}
for(var i=0; i<DrawnPoints.length; i++){GroundUnits[i]=MySelf.pointToGroundUnits(new Point(DrawnPoints[i].x,DrawnPoints[i].y));}
EventManager.triggerEvent('finishdrawing', GroundUnits);DrawBox.style.visibility='hidden';DrawBox.style.left='0px';DrawBox.style.top='0px';DrawBox.style.height='1px';DrawBox.style.width='1px';DrawBox=null;var divPoints=document.getElementById(MapParentId).getElementsByTagName('div');for(var i=divPoints.length; i>=0; i--){if(divPoints[i]&&divPoints[i].parentNode&&divPoints[i].className=='DrawnPoint'){var p=divPoints[i].parentNode;p.removeChild(divPoints[i]);}}}
PointDrawingSemaphore=true;}
this.mapStats=function(){logDebugMessage('Map Statistics', false, MapCenterPoint.toString(",")+' '+MapScale);}
this.getCenterPoint=function(){return MapCenterPoint;}
this.getScale=function(){return MapScale;}
this.pointToGroundUnits=function(p){var ImageControl=document.getElementById(ImageControlId);MapCenterPoint.clean();p.x=(MapCenterPoint.x-(ImageControl.offsetWidth/2-p.x)*MapScale);p.y=(MapCenterPoint.y-(p.y-ImageControl.offsetHeight/2)*MapScale);ImageControl=null;return p;}
this.pointDrawTool=function(callFn){this.loadDrawTool('poly', true);}
var DrawingArea=new Array();this.addSelection=function(s){DrawingArea[s.getAttribute('title')]=s.getAttribute('id');}
this.getDrawingAreas=function(){return DrawingArea;}
this.resetDrawingArea=function(){MySelf.clearDrawingArea();DrawnPoints=new Array();}
this.clearDrawingArea=function(){refreshCanvas();document.getElementById(ImageControlCanvasId).getContext("2d").clearRect(0,0,1000,1000);EventManager.triggerEvent('measuredlength', 0);}
function measureLines(){var linesInGroundUnits=0;for(var i=1; i<DrawnPoints.length ; i++){var gA=MySelf.pointToGroundUnits(new Point(DrawnPoints[i-1].x, DrawnPoints[i-1].y));var gB=MySelf.pointToGroundUnits(new Point(DrawnPoints[i].x, DrawnPoints[i].y));var gUnitSeg =new LineSegment(gA,gB);linesInGroundUnits += gUnitSeg.getLength();}
EventManager.triggerEvent('measuredlength', linesInGroundUnits);}
function measureArea(){var groundUnits=new Array();for(var i=0; i<DrawnPoints.length ; i++){var gA=MySelf.pointToGroundUnits(new Point(DrawnPoints[i].x, DrawnPoints[i].y));groundUnits[i]=gA;}
var poly=new Polygon();groundUnits[groundUnits.length]=new Point(groundUnits[0].x, groundUnits[0].y);poly.buildFromPoints(groundUnits);EventManager.triggerEvent('measuredlength', Math.abs(poly.area()));}
function clearImageControlFn(){var ImageControl=document.getElementById(ImageControlId);ImageControl.onmousedown=null;ImageControl.onmouseup=null;ImageControl.onmousemove=null;ImageControl.onclick=null;ImageControl.dblclick=null;ImageControl.onmouseout=null;removeEvent(ImageControl, 'click', measureLines);removeEvent(ImageControl, 'click', measureArea);removeEvent(ImageControl, 'mousedown', startDrawing);removeEvent(ImageControl, 'mouseup', stopDrawing);removeEvent(ImageControl, 'mousemove', whileDrawing);removeEvent(ImageControl, 'mousemove', whileDrawingBox);ImageControl=null;}
this.onChangeTool=function(){clearImageControlFn();}
this.loadMeasureTool=function(mType){var ImageControl=document.getElementById(ImageControlId);if(mType=='length'){MySelf.loadDrawTool('measureline',true);attachEvent(ImageControl, 'click', measureLines);} else if(mType=='area'){MySelf.loadDrawTool('measurearea',true);attachEvent(ImageControl, 'click', measureArea);} else {alert('Unknown Measure Tool Type!');}}
this.setMapCursor=function(pCursor){var ImageControl=document.getElementById(ImageControlId);ImageControl.style.cursor=pCursor;ImageControl=null;}
this.loadDrawTool=function(shape,override){var ImageControl=document.getElementById(ImageControlId);refreshDrawBox();ImageControl.style.zIndex=MAP_CONTROL_INDEX;document.getElementById(ImageMapControlId).style.zIndex=MAP_CONTROL_INDEX-1;ImageControl.style.cursor=CURSOR_DRAW;if(!override){EventManager.triggerEvent('changetool', 'Draw');}
EventManager.addEventListener('changetool','MapDrawingTools', function (){removeEvent(ImageControl, 'mousedown', startDrawing);removeEvent(ImageControl, 'mousemove', whileDrawing);removeEvent(ImageControl, 'mousemove', whileDrawingBox);removeEvent(ImageControl, 'mouseup', stopDrawing);EventManager.removeEventListener('changetool','MapDrawingTools');EventManager.removeEventListener('finishdrawing','MapZoomTool');});clearImageControlFn();DrawingShape=shape;if(shape=='box'||shape=='evenbox'||shape=='scalebox'){attachEvent(ImageControl, 'mousedown', startDrawing);attachEvent(ImageControl, 'mousemove', whileDrawingBox);attachEvent(ImageControl, 'mouseup', stopDrawing);} else if(shape=='measureline'){ImageControl.style.cursor=CURSOR_MEASURE;DrawnPoints=new Array();MySelf.clearDrawingArea();ImageControl.onclick=function(event){if(window.event){event=window.event;}
refreshCanvas();FunctionOffset=objectClientPosition(document.getElementById(ImageControlId));ZoomPoint.x=event.clientX-FunctionOffset.x;ZoomPoint.y=event.clientY-FunctionOffset.y;var ctx=document.getElementById(ImageControlCanvasId).getContext("2d");ctx.strokeStyle="red";ctx.save();ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(1000,1000);ctx.stroke();ctx.closePath();ctx.restore();if(DrawnPoints.length<=0){ctx.beginPath();}
DrawnPoints[DrawnPoints.length]=new Point(ZoomPoint.x, ZoomPoint.y);MySelf.clearDrawingArea();ctx.strokeStyle="red";for(var i=1; i<DrawnPoints.length; i++){ctx.save();ctx.beginPath();ctx.moveTo(DrawnPoints[i-1].x, DrawnPoints[i-1].y);ctx.lineTo(DrawnPoints[i].x, DrawnPoints[i].y);ctx.stroke();ctx.closePath();ctx.restore();}
for(var i=0; i<DrawnPoints.length; i++){ctx.save();ctx.strokeStyle="red";ctx.fillStyle="red";ctx.arc(DrawnPoints[i].x, DrawnPoints[i].y, 3, 0, Math.PI*2, true);ctx.fill();ctx.closePath();ctx.restore();}}
ImageControl.ondblclick=function(event){for(var i=0; i<DrawnPoints.length; i++){DrawnPoints[i]=MySelf.pointToGroundUnits(DrawnPoints[i]);}
Events.triggerEvent('finishdrawing', DrawnPoints);DrawnPoints=new Array();}} else if(shape=='measurearea'){ImageControl.style.cursor=CURSOR_MEASURE;DrawnPoints=new Array();MySelf.clearDrawingArea();ImageControl.onclick=function(event){if(window.event){event=window.event;}
refreshCanvas();FunctionOffset=objectClientPosition(document.getElementById(ImageControlId));ZoomPoint.x=event.clientX-FunctionOffset.x;ZoomPoint.y=event.clientY-FunctionOffset.y;var ctx=document.getElementById(ImageControlCanvasId).getContext("2d");if(DrawnPoints.length<=0){ctx.beginPath();}
DrawnPoints[DrawnPoints.length]=new Point(ZoomPoint.x, ZoomPoint.y);MySelf.clearDrawingArea();ctx.save();ctx.fillStyle="rgba(0,200,0,.5)";ctx.beginPath();ctx.moveTo(DrawnPoints[0].x, DrawnPoints[0].y);for(var i=1; i<DrawnPoints.length; i++){ctx.lineTo(DrawnPoints[i].x,DrawnPoints[i].y);}
ctx.closePath();ctx.fill();ctx.restore();ctx.save();ctx.strokeStyle="red";ctx.lineWidth=2;if(DrawnPoints.length==1){ctx.save();ctx.fillStyle="red";ctx.beginPath();ctx.arc(DrawnPoints[0].x, DrawnPoints[0].y, 2,0,Math.PI*2,true);ctx.fill();ctx.closePath();ctx.restore();}
ctx.beginPath();ctx.moveTo(DrawnPoints[0].x, DrawnPoints[0].y);for(var i=1; i<DrawnPoints.length; i++){ctx.lineTo(DrawnPoints[i].x,DrawnPoints[i].y);}
ctx.closePath();ctx.stroke();ctx.restore();}
ImageControl.ondblclick=function(event){for(var i=0; i<DrawnPoints.length; i++){DrawnPoints[i]=MySelf.pointToGroundUnits(DrawnPoints[i]);}
Events.triggerEvent('finishdrawing', DrawnPoints);DrawnPoints=new Array();}} else if (shape=='point'){attachEvent(ImageControl, 'mousedown', startDrawing);attachEvent(ImageControl, 'mousemove', drawPointOnly);attachEvent(ImageControl, 'mouseup', stopDrawing);} else {attachEvent(ImageControl, 'mousedown', startDrawing);attachEvent(ImageControl, 'mousemove', whileDrawing);attachEvent(ImageControl, 'mouseup', stopDrawing);}
ImageControl=null;}
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);}
function zoomTrackMouse(event){var ImageControl=document.getElementById(ImageControlId);if(window.event){event=window.event;}
if(ImageControl&&objectClientPosition){} else {return false;}
FunctionOffset=objectClientPosition(ImageControl);ZoomPoint.x=event.clientX-FunctionOffset.x;ZoomPoint.y=event.clientY-FunctionOffset.y;var CoordinateObject=document.getElementById(CoordinateObjectId);if(CoordinateObject){ZoomPoint.clean();var gUnit=MySelf.pointToGroundUnits(new Point(ZoomPoint.x, ZoomPoint.y));var llString='';var sysArr=(new String(MAP_COORDINATE_SYSTEM)).split('-');if(window.toLatLong){var unitConversion=new Point(gUnit.x, gUnit.y);var llPoint=window.toLatLong(sysArr[1], unitConversion);llPoint.x=round(llPoint.x,4);llPoint.y=round(llPoint.y,4);var temp=llPoint.x;llPoint.x=llPoint.y;llPoint.y=temp;llString=' <b>Lat, Long:</b> '+llPoint.toString(",");}
var mSize=MySelf.getMapSize();mSize.x=Math.round(mSize.x*MapScale);mSize.y=Math.round(mSize.y*MapScale);CoordinateObject.innerHTML='<B>X,Y:</B> '+round(gUnit.x,2)+","+round(gUnit.y,2)+llString;if(SHOW_MAP_WIDTH){CoordinateObject.innerHTML += " <b>Width, Height: </b>"+mSize.toString(',')+" "+MAP_GROUND_UNITS;}}
ImageControl=null;return preventDefaultEvent(event);}
var ZoomDirection=1;var ZoomPoint=new Point();function zoomToPoint(event){var ImageControl=document.getElementById(ImageControlId);if(window.event){event=window.event;}
FunctionOffset=objectClientPosition(ImageControl);MySelf.zoomTo(ZoomPoint.x, ZoomPoint.y, ZoomDirection);ImageControl=null;}
this.recenterImage=function(x,y,v){var ImageControl=document.getElementById(ImageControlId);if(!v){v=1;}
var PanPoint=new Point(x,y);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){var img=document.getElementById(LayerId+l);img.style.left=img.offsetLeft+shiftX-(newW-oldW)/2+'px';img.style.top=img.offsetTop+shiftY-(newH-oldH)/2+'px';img.style.width=newW+'px';img.style.height=newH+'px';img=null;}
MySelf.zoomTo(0,0,1);ImageControl=null;}
this.recenterOnZoomPoint=function(v){MySelf.recenterImage(ZoomPoint.x, ZoomPoint.y, v);}
var PanPoint=new Point(0,0);function startPan(e){if(window.event){e=window.event; e.which=e.button;}
if(e.which != 1){return false;} 
var ImageControl=document.getElementById(ImageControlId);ImageControl.Origin=new Point(e.clientX, e.clientY);for(var l in LayerImages){var img=document.getElementById(LayerId+l);img.originalLeft=img.offsetLeft;img.originalTop=img.offsetTop;img=null;}
PanPoint.x=0;PanPoint.y=0;ImageControl=null;}
function whilePanning(e){if(window.event){e=window.event;}
var ImageControl=document.getElementById(ImageControlId);if(ImageControl&&ImageControl.Origin){for(var l in LayerImages){var img=document.getElementById(LayerId+l);img.style.left=img.originalLeft+(e.clientX-ImageControl.Origin.x)+'px';img.style.top=img.originalTop+(e.clientY-ImageControl.Origin.y)+'px';img=null;}
PanPoint.x=e.clientX-ImageControl.Origin.x;PanPoint.y=e.clientY-ImageControl.Origin.y;} else {return false;}
ImageControl=null;return preventDefaultEvent(e);}
function endPan(e){var ImageControl=document.getElementById(ImageControlId);if(window.event){e=window.event; e.which=e.button;}
if(e.which != 1){return false;}
MySelf.zoomTo(ImageControl.offsetWidth/2-PanPoint.x, ImageControl.offsetHeight/2-PanPoint.y, 1);ImageControl.Origin=null;ImageControl=null;}
function cancelPan(event){var ImageControl=document.getElementById(ImageControlId);if(window.event){event=window.event;}
var keyCode=getKeyCode(event);if(keyCode=='CTRL+z'){ImageControl.Origin=null;for(var l in LayerImages){var img=document.getElementById(LayerId+l);img.style.left=img.originalLeft+'px';img.style.top=img.originalTop+'px';img=null;}}
ImageControl=null;}
this.loadZoomTool=function(v){var ImageControl=document.getElementById(ImageControlId);if(!ImageControl){return false;}
clearImageControlFn();if(v==1){ImageControl.style.cursor=CURSOR_ZOOM_PAN;ImageControl.onmousedown=startPan;ImageControl.onmouseup=endPan;ImageControl.onmousemove=whilePanning;ImageControl.onkeypress=cancelPan;ImageControl.onmouseout=endPan;} else if(v != 1){MySelf.loadDrawTool(ZOOM_BOX_SHAPE,true);if(v<1){ImageControl.style.cursor=CURSOR_ZOOM_IN;} else {ImageControl.style.cursor=CURSOR_ZOOM_OUT;}
EventManager.addEventListener('finishdrawing', 'MapZoomTool', function (ZoomPoints){var ImageControl=document.getElementById(ImageControlId);var DrawBox=document.getElementById(DrawBoxId);var Ratio=DrawBox.offsetWidth/ImageControl.offsetWidth;var hRatio=DrawBox.offsetHeight/ImageControl.offsetHeight;if(hRatio>Ratio){Ratio=hRatio;}
if(DrawBox.offsetWidth<7){MySelf.recenterImage(DrawnPoints[0].x, DrawnPoints[0].y, v);} 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){var img=document.getElementById(LayerId+l);if(l=='NAVIGATION'||MAP_ZOOMIN_STYLE=='scale'||v>1){img.style.left=img.offsetLeft+shiftX-(newW-oldW)/2+'px';img.style.top=img.offsetTop+shiftY-(newH-oldH)/2+'px';img.style.width=newW+'px';img.style.height=newH+'px';} else if(MAP_ZOOMIN_STYLE=='clip'){var x2=DrawBox.offsetLeft+DrawBox.offsetWidth;var y2=DrawBox.offsetTop+DrawBox.offsetHeight;img.style.clip='rect('+DrawBox.offsetTop+'px,'+x2+'px,'+y2+'px,'+DrawBox.offsetLeft+'px)';} else if(MAP_ZOOMIN_STYLE=='blank'){img.src=BLANK_IMAGE;}
img=null;}
MySelf.zoomTo(0,0,1);}
ImageControl=null;});EventManager.addEventListener('changetool', 'MapZoomTool', function (){EventManager.removeEventListener('finishdrawing','MapZoomTool');EventManager.removeEventListener('changetool', 'MapZoomTool');});}
ImageControl.style.zIndex=MAP_CONTROL_INDEX;if(ImageMapControlId){document.getElementById(ImageMapControlId).style.zIndex=MAP_CONTROL_INDEX-1;}
ZoomDirection=v;ImageControl=null;}
this.clearLayerSelection=function(mapTitle){LayerSelections[mapTitle]=new Array();}
this.addLayerSelection=function(mapTitle, selectionValue){if(!LayerSelections[mapTitle]){LayerSelections[mapTitle]=new Array();}
LayerSelections[mapTitle].push(selectionValue);}
this.getLayerSelection=function(mapTitle){return LayerSelections[mapTitle];}
this.clearLayerParams=function(mapTitle){LayerParameters[mapTitle]=new Array();}
this.setLayerParam=function(mapTitle,paramName,paramValue){if(!LayerParameters[mapTitle]){LayerParameters[mapTitle]=new Array();}
LayerParameters[mapTitle][paramName]=new Array(paramValue);}
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.getLayerParam=function(mapTitle, paramName){return LayerParameters[mapTitle][paramName];}
this.getLayerParameters=function(mapTitle){if(!LayerParameters[mapTitle]){return false;}
return LayerParameters[mapTitle];}
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 mapTitle=mapXMLObj.getAttribute('title');var mapFile;if(!MapReference&&new String(mapXMLObj.getAttribute('reference')).match(/only/i)){return false;}
if(mapXMLObj.getElementsByTagName('file')[0]){mapFile=mapXMLObj.getElementsByTagName('file')[0].firstChild.nodeValue;mapFile=trim(mapFile);LayerURLs[mapTitle]=mapFile;}
var mapOpacity=mapXMLObj.getAttribute('opacity');var mapData=mapXMLObj.getAttribute('popups');var zIndex=parseInt(mapXMLObj.getAttribute('zindex'));if(!mapData){mapData=MAP_ASSUME_DATA;} else {if(mapData.match(/true/i)){mapData=true;} else {mapData=false;}}
LayerLoadData[mapTitle]=mapData;var newLayer=document.getElementById(LayerId+mapTitle);var isNewLayer=false;if(!newLayer){isNewLayer=true;LayerImages[mapTitle]=1;newLayer=document.createElement('img');newLayer.style.position='absolute';newLayer.setAttribute('id', LayerId+mapTitle);if(ImageParentId){document.getElementById(ImageParentId).appendChild(newLayer);}}
if(mapOpacity){if(OPACITY_CONTROLS != 'none'){setOpacity(newLayer, mapOpacity);}} else {setOpacity(newLayer, 100);}
if(MAP_MAPBOOK_ORDER){if(zIndex){newLayer.style.zIndex=MAP_MAX_ZINDEX-parseInt(zIndex);} else if(isNewLayer){newLayer.style.zIndex=MAP_MAX_ZINDEX;}} else {if(!zIndex||zIndex>0){newLayer.style.zIndex=MAP_MAX_ZINDEX;for(var title in LayerImages){var img=document.getElementById(LayerId+title);img.style.zIndex=parseInt(img.style.zIndex)-1;img=null;}
min_z_index--;} else {min_z_index--;newLayer.style.zIndex=min_z_index;}}
MySelf.autoFitLayer(mapTitle);MySelf.clearLayerParams(mapTitle);var mapParams=mapXMLObj.getElementsByTagName('param');for(var i=0; i<mapParams.length; i++){if(mapParams[i].getAttribute('type')){var paramType=new String(mapParams[i].getAttribute('type')).toLowerCase();if(paramType=='today'){var formatString=mapParams[i].getAttribute('format');if(!formatString){formatString='%M/%D/%Y';}
var offset=mapParams[i].getAttribute('offset');if(offset){offset=parseInt(offset)*86400000;} else {offset=0;}
var d=new Date();var dateString=mapParams[i].getAttribute('date');if(dateString){d=new Date(dateString);}
mapParams[i].setAttribute('value',strfdate(new Date(d.getTime()+offset), formatString));}}
MySelf.addLayerParam(mapTitle, mapParams[i].getAttribute('name'), mapParams[i].getAttribute('value'));}
var layers=mapXMLObj.getElementsByTagName('layer');var defSubLayers=new Array();for(var i=0; i<layers.length; i++){if(parseBoolean(layers[i].getAttribute('default'),true)){defSubLayers.push(layers[i].getAttribute('name'));}}
MySelf.setLayerParam(mapTitle, 'layers', defSubLayers.join(' '));MySelf.clearLayerSelection();var mapSelection=mapXMLObj.getElementsByTagName('selected');for(var i=0; i<mapSelection.length; i++){MySelf.addLayerSelection(mapTitle, mapSelection[i].getAttribute('id'));}
if(mapXMLObj.getAttribute('minscale')){LayerMinScale[mapTitle]=mapXMLObj.getAttribute('minscale');}
if(mapXMLObj.getAttribute('maxscale')){LayerMaxScale[mapTitle]=mapXMLObj.getAttribute('maxscale');}
if(mapXMLObj.getAttribute('debug')&&mapXMLObj.getAttribute('debug').match(/true/i)){LayerDebug[mapTitle]=1;}
if(mapXMLObj.getElementsByTagName('legend')[0]&&mapXMLObj.getElementsByTagName('legend')[0].firstChild.nodeValue){LayerLegends[mapTitle]=mapXMLObj.getElementsByTagName('legend')[0].firstChild.nodeValue;}
newLayer=null;Events.triggerEvent('refreshlayer', mapTitle);}
this.confirmRemoveLayer=function(mapTitle){MySelf.removeLayer(mapTitle);}
this.removeLayer=function(mapTitle){var imageMap=document.getElementById(MapId+'ImageMap-'+mapTitle);if(imageMap){var areas=imageMap.getElementsByTagName('area');for(var a=areas.length-1; a>=0; a--){var p=document.getElementById(areas[a].popup[0]).parentNode;for(var pop=0; pop<areas[a].popup.length; pop++){p.removeChild(document.getElementById(areas[a].popup[pop]));}
imageMap.removeChild(areas[a]);}
var p=imageMap.parentNode;p.removeChild(imageMap);}
if(LayerImages[mapTitle]){var img=document.getElementById(LayerId+mapTitle);if(img&&img.parentNode){var p=img.parentNode;p.removeChild(img);}
delete LayerImages[mapTitle];delete LayerURLs[mapTitle];if(DrawingArea[mapTitle]){delete DrawingArea[mapTitle];}
var loadingImage=document.getElementById(LayerId+mapTitle+'-Loading');if(loadingImage&&loadingImage.parentNode){var p=loadingImage.parentNode;p.removeChild(loadingImage);}
img=null;}
MySelf.clearLayerParams(mapTitle);MySelf.clearLayerSelection(mapTitle);}
this.getLayerURLs=function(){var zOrdered=MySelf.getLayersByZIndex();var urls=new Array();for(var i=0; i<zOrdered.length; i++){if(zOrdered[i] != 'NAVIGATION'){urls[zOrdered[i]]=LayerURLs[zOrdered[i]];}}
return urls;}
this.getLayerTitles=function(){var layers=new Array();for(var title in LayerImages){if(title != 'NAVIGATION'){layers[layers.length]=title;}}
return layers;}
this.isRelativeLayer=function(maptitle){if(LayerURLs[maptitle]){return LayerURLs[maptitle].match(/relative/i);}
return false;}
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=document.getElementById(LayerId+orderedLayers[i]);var jImage=document.getElementById(LayerId+orderedLayers[j]);if(parseInt(iImage.style.zIndex)<parseInt(jImage.style.zIndex)){var temp=orderedLayers[i];orderedLayers[i]=orderedLayers[j];orderedLayers[j]=temp;}
iImage=null;jImage=null;}}
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=document.getElementById(LayerId+mapTitle);var targetImage=null;if(direction>0&&selectedLayerIndex>0){targetImage=orderedLayers[selectedLayerIndex-1];} else if(direction<0&&selectedLayerIndex<orderedLayers.length-1){targetImage=orderedLayers[selectedLayerIndex+1];}
if(targetImage){targetImage=document.getElementById(LayerId+targetImage);var tempIndex=baseImage.style.zIndex;baseImage.style.zIndex=targetImage.style.zIndex;targetImage.style.zIndex=tempIndex;}}}
var REFRESH_LOCKOUT=false;this.zoomToScaledImage=function(){var ImageControl=document.getElementById(ImageControlId);var zoomLayer=document.getElementById(LayerId+'NAVIGATION');var imageTop=zoomLayer.offsetTop;var imageLeft=zoomLayer.offsetLeft;var imageWidth=zoomLayer.offsetWidth;var imageHeight=zoomLayer.offsetHeight;var viewportTop=ImageControl.offsetTop;var viewportLeft=ImageControl.offsetLeft;var viewportWidth=ImageControl.offsetWidth;var viewportHeight=ImageControl.offsetHeight;var scale=viewportWidth/imageWidth*MapScale;var groundTop=MapCenterPoint.y-MapScale*viewportHeight/2;var groundLeft=MapCenterPoint.x-MapScale*viewportWidth/2;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;var groundCenterX=groundLeft+unscaledImageX*MapScale;var groundCenterY=groundTop+unscaledImageY*MapScale;if(MapCenterPoint.x != groundCenterX||MapCenterPoint.y != groundCenterY||scale != 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){var ImageControl=document.getElementById(ImageControlId);if(REFRESH_LOCKOUT) return false;var zoomLayer=document.getElementById(LayerId+'NAVIGATION');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;var imgSizeFactor=1/direction;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=document.getElementById(LayerId+layer);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=null;}}
window.triggerMapRefresh=function(time){REFRESH_LOCKOUT=true;if(time==LastActionTime){MySelf.zoomToScaledImage();LastActionTime=0;}
REFRESH_LOCKOUT=false;}
LastActionTime ++;setTimeout("window.triggerMapRefresh("+LastActionTime+")", MAP_NAVIGATION_DELAY);ImageControl=null;}
this.drawPoint=function(x,y){var lastPoint=DrawnPoints[DrawnPoints.length-1];if(lastPoint){var distx=(lastPoint.x-x);var disty=(lastPoint.y-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.style.zIndex=MAP_DRAWING_INDEX;newPoint.className='DrawnPoint';document.getElementById(ImageParentId).appendChild(newPoint);newPoint=null;DrawnPoints[DrawnPoints.length]=new Point(x,y);}
this.getMapSize=function(){var ImageControl=document.getElementById(ImageControlId);var SizeObject=ImageControl;if(!SizeObject.offsetWidth){SizeObject=document.getElementById(MapParentId);}
var point=new Point(SizeObject.offsetWidth, SizeObject.offsetHeight);ImageControl=null;return point;}
function showPopupMenuFn(popupDivId){return function(event){var ReferenceIndicator=document.getElementById(ReferenceIndicatorId);if(ReferenceIndicator){return true;}
popupDiv=document.getElementById(popupDivId);if(window.event){event=window.event; event.which=event.button;}
if(event.which>1){if(popupDiv.style.visibility=='hidden'){var objLocation=objectClientPosition(document.getElementById(MapParentId));popupDiv.style.left=ZoomPoint.x+objLocation.x+5+'px';popupDiv.style.top=ZoomPoint.y+objLocation.y+5+'px';popupDiv.style.visibility='visible';} else {popupDiv.style.visibility='hidden';}}
return preventDefaultEvent(event);}}
function hidePopupMenuFn(popupMenuId){return function(){document.getElementById(popupMenuId).style.visibility='hidden';}}
this.clearMenu=function (event){if(window.event){event=window.event;}
var popupDiv=document.getElementById(PopupMenuId);if(popupDiv.style.visibility=='visible'){popupDiv.style.visibility='hidden';}
popupDiv=null;}
function createOrReplaceCanvas(w,h){var MapParent=document.getElementById(MapParentId);var testForCanvas=document.getElementById(ImageControlCanvasId);if(testForCanvas){MapParent.removeChild(testForCanvas);}
var imageControlCanvas=document.createElement('canvas');imageControlCanvas.style.position='absolute';imageControlCanvas.style.border='none';imageControlCanvas.style.left='0px';imageControlCanvas.style.top='0px';imageControlCanvas.style.zIndex=MAP_CONTROL_INDEX-2;imageControlCanvas.width=w;imageControlCanvas.height=h;if(document.all){imageControlCanvas.style.width=w+'px';imageControlCanvas.style.height=h+'px';}
imageControlCanvas.setAttribute('id', ImageControlCanvasId);MapParent.appendChild(imageControlCanvas);}
this.setParent=function(p){MapParentId=p;if(MAP_ZOOMIN_STYLE=='auto'&&getBrowser().match(/microsoft/i)&&parseInt(getBrowserVersion())<=MAP_IE_SCALE_STYLE_SWITCH){MAP_ZOOMIN_STYLE='clip';} else if(MAP_ZOOMIN_STYLE=='auto'){MAP_ZOOMIN_STYLE='scale';}
var MapParent=document.getElementById(MapParentId);var ImageParent=document.createElement('div');ImageParent.setAttribute('id', ImageParentId);ImageParent.style.position='absolute';ImageParent.style.left='0px';ImageParent.style.top='0px';var ImageControl=document.createElement('img');ImageControlId=MapId+'ImageControl';ImageControl.setAttribute('id',ImageControlId);ImageControl.type='Image';ImageControl.src=BLANK_IMAGE;ImageControl.style.zIndex=MAP_CONTROL_INDEX;ImageControl.style.position='absolute';ImageControl.style.border='none';ImageControl.style.left='0px';ImageControl.style.top='0px';var ImageMapControl=document.createElement('img');ImageMapControlId=MapId+'ImageMapControl';ImageMapControl.setAttribute('id', ImageMapControlId);ImageMapControl.src=BLANK_IMAGE;ImageMapControl.style.zIndex=MAP_CONTROL_INDEX-1;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);createOrReplaceCanvas(100,100);ImageParent=null;if(MAP_POPUP_MENU){var popupMenu=document.createElement('div');document.getElementsByTagName('body')[0].appendChild(popupMenu);popupMenu.setAttribute('id',PopupMenuId);popupMenu.style.position='absolute';popupMenu.style.zIndex=MAP_POPUP_ZINDEX;popupMenu.style.background='#EEE';popupMenu.style.border='solid 1px #333';popupMenu.style.borderLeft='solid 1px #AAA';popupMenu.style.borderTop='solid 1px #AAA';popupMenu.style.cursor='pointer';popupMenu.style.visibility='hidden';popupMenu.style.left='100px';popupMenu.style.top='100px';for(menu in MAP_POPUP_FUNCTIONS){var newItem=document.createElement('a');newItem.appendChild(document.createTextNode(menu));newItem.style.display='block';newItem.style.textDecoration='none';newItem.style.color='black';newItem.setAttribute('id', MapId+'Popup-'+menu);newItem.setAttribute('href', MAP_POPUP_FUNCTIONS[menu]);newItem.onclick=hidePopupMenuFn(PopupMenuId);popupMenu.appendChild(newItem);newItem=null;}
popupMenu=null;attachEvent(ImageMapControl, 'mousedown', showPopupMenuFn(PopupMenuId));attachEvent(ImageControl, 'mousedown', showPopupMenuFn(PopupMenuId));attachEvent(document, 'click', MySelf.clearMenu);}
ImageMapControl.oncontextmenu=preventPopupMenu;ImageControl.oncontextmenu=preventPopupMenu;ImageControl.onmousemove=preventDefaultEvent;ImageControl.onmousedown=preventDefaultEvent;attachEvent(ImageControl, 'mousemove', zoomTrackMouse);attachEvent(ImageMapControl, 'mousemove', zoomTrackMouse);if(MAP_DYNAMIC_ZOOM){attachEvent(ImageControl, 'mousewheel', zoomWheel);}
refreshDrawBox();MapParent.style.overflow='hidden';ImageControl=null;ImageMapControl=null;MapParent=null;imageControlCanvas=null;var navMap=document.createElement('map');var mapFile=document.createElement('file');navMap.appendChild(mapFile);mapFile.appendChild(document.createTextNode('relative://'+BLANK_IMAGE+'?'));navMap.setAttribute('title','NAVIGATION');MySelf.addLayer(navMap);mapFile=null;navMap=null;this.autoFitLayers();}
this.getExtent=function (delim){var mapSize=MySelf.getMapSize();var gisOffsetW=mapSize.x/2*MapScale;var gisOffsetH=mapSize.y/2*MapScale;MapCenterPoint.clean();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 mSize=this.getMapSize();var extent=MapCoords.toString(delim);return extent;}
function onloadNewImage(){var layerName=this.getAttribute('layerName');var img=document.getElementById(LayerId+layerName);if(img){var p=img.parentNode;var zIndex=img.style.zIndex;this.style.zIndex=zIndex;this.style.visibility=img.style.visibility;var origOpacity=getOpacity(img);if(MAP_FADE_EFFECTS){setOpacity(this, 0);img.setAttribute('id',LayerId+layerName+'-old');fadeObject(LayerId+layerName+'-old', origOpacity, 0, MAP_FADE_EFFECTS_DURATION, true);fadeObject(LayerId+layerName, 0, origOpacity, MAP_FADE_EFFECTS_DURATION, false);} else {setOpacity(this, origOpacity);}
this.setAttribute('id',LayerId+layerName);p.removeChild(img);img=null;this.onload=null;} else {var MapParent=document.getElementById(MapParentId);this.setAttribute('id',LayerId+layerName);MapParent.appendChild(this);MapParent=null;}
EventManager.triggerEvent('imagelayer', layerName);LayerImages[layerName]=1;MySelf.autoFitLayer(layerName);}
var abortCounter=0;function onAbortNewImage(){abortCounter++;var url=new String(this.src);var sep='?';if(url.indexOf('?')>0){sep='&';}
this.src=url+sep+'='+abortCounter;}
this.refreshLayer=function(mapTitles){var mapSize=MySelf.getMapSize();var mSize=this.getMapSize();var extent=this.getExtent(" ");var size=this.getMapSize().toString(" ");for(var i=0; i<mapTitles.length; i++){if(!LayerURLs[mapTitles[i]]){break;}
var imageMap=document.getElementById(MapId+'-'+mapTitles[i]+'-Imagemap');if(imageMap){var areas=imageMap.getElementsByTagName('area');for(var a=areas.length-1; a>=0; a--){var p=document.getElementById(areas[a].popup[0]).parentNode;for(var pop=0; pop<areas[a].popup.length; pop++){p.removeChild(document.getElementById(areas[a].popup[pop]));}
imageMap.removeChild(areas[a]);}}
var imageURL=MAPSERVER_IMAGE_URL;var legendURL=MAPSERVER_LEGEND_URL;var additionalInputs=new Array();additionalInputs['MAPFILE']=LayerURLs[mapTitles[i]];if(MAP_TIMESTAMP_REQ){additionalInputs['MOOSETIME']=(new Date()).getTime();imageURL += '&MOOSETIME=%MOOSETIME%';}
var parameters=MySelf.getLayerParamString(mapTitles[i]);if(parameters&&parameters != 'null'){var imageSep='?';var dataSep='?';var legendSep='?';if(imageURL.indexOf('?')>0){imageSep='&';} 
if(legendURL.indexOf('?')>0){legendSep='&';} 
imageURL=imageURL+imageSep+parameters;legendURL=legendURL+legendSep+parameters;}
if(LayerURLs[mapTitles[i]].match(/http/i)){imageURL=LayerURLs[mapTitles[i]];if(MAP_TIMESTAMP_REQ){imageURL += '&MOOSETIME=%MOOSETIME%';}
legendURL=false;} else if(LayerURLs[mapTitles[i]].match(/relative/i)){imageURL=new String(LayerURLs[mapTitles[i]]).replace('relative://','');legendURL=false;}
if(!MapReference){if(MAP_LEGENDS_ENABLED&&(legendURL||LayerLegends[mapTitles[i]])){if(LayerLegends[mapTitles[i]]){legendURL=LayerLegends[mapTitles[i]];} else {additionalInputs['MODE']='legend';legendURL=ProcessURLString(this, legendURL, new Array(), additionalInputs,' ',' ');}
var obj=new LegendObj(mapTitles[i], legendURL);EventManager.triggerEvent('legendlayer', obj);logDebugMessage('Legend URL', false, legendURL);}}
var layerMode='map';if(imageURL.indexOf('mapshape')>0){layerMode='nquerymap';}
if(MySelf.getLayerParam(mapTitles[i], 'MOOSEMODE')){layerMode=MySelf.getLayerParam(mapTitles[i], 'MOOSEMODE');}
additionalInputs['MODE']=layerMode;imageURL=ProcessURLString(this, imageURL, new Array(), additionalInputs,' ',' ');var newImage=document.createElement('img');newImage.setAttribute('layerName',mapTitles[i]);newImage.setAttribute('id',LayerId+mapTitles[i]+'-Loading');newImage.style.position='absolute';newImage.style.visibility='hidden';document.getElementById(ImageParentId).appendChild(newImage);newImage.width=1;newImage.height=1;newImage.onload=onloadNewImage;if(document.all){newImage.onabort=onAbortNewImage;}
if(!MySelf.isLayerVisible(mapTitles[i])){imageURL=BLANK_IMAGE+'?rtime='+(new Date()).getTime();}
if(LayerDebug[mapTitles[i]]||MAP_DEBUG_LAYERS){debugLayer(mapTitles[i], imageURL);} else {newImage.src=imageURL;}
logDebugMessage('Image URL', false, imageURL);newImage=null;}}
this.isLayerVisible=function(mapTitle,overrideMin, overrideMax){var inchScale=pixelScaleToInchScale(MySelf, MapScale);var layerMinScale=LayerMinScale[mapTitle];var layerMaxScale=LayerMaxScale[mapTitle];if(overrideMin){layerMinScale=overrideMin;}
if(overrideMax){layerMaxScale=overrideMax;}
return !((layerMinScale&&inchScale<layerMinScale)||(layerMaxScale&&inchScale>layerMaxScale));}
function debugLayer(mapTitle, imageURL){var debugLayer=getHTTPObject();if(imageURL.match('http://')||imageURL.match('relative://')){document.getElementById(LayerId+mapTitle).src=imageURL;EventManager.triggerEvent('imagelayer', mapTitle);LayerImages[mapTitle]=1;return true;}
debugLayer.open('GET', imageURL, true);debugLayer.onreadystatechange=function (){if(debugLayer.readyState==4){if(!debugLayer.getResponseHeader('Content-type').match(/image/)){var LAYER_BROKEN_MESSAGE='The layer "%LAYER%" is broken, would you like to debug it?';var msg=LAYER_BROKEN_MESSAGE.replace('%LAYER%',mapTitle);if(confirm(msg)){window.open(imageURL);}}
LayerImages[mapTitle]=1;EventManager.triggerEvent('imagelayer', mapTitle);document.getElementById(LayerId+mapTitle).src=imageURL;}}
debugLayer.send();}
this.debugLayerOn=function(title){LayerDebug[title]=true;}
this.debugLayerOff=function(title){LayerDebug[title]=false;}
var Popups=new Array();this.getPopupData=function(i){return Popups[i];}
this.getPointScale=function(){return new Circle(MapCenterPoint, MapScale);}
this.clearPopups=function(){var p=document.getElementById(MapParentId);var d=p.getElementsByTagName('div');for(var i=0; i<d.length; i++){if(d[i].className=='popupParent'){d[i].style.visibility='hidden';}}}
function popupAreaMove(event){if(window.event){event=window.event;}
var area=getEventTarget(event);if(!area.popupMove){return false;}
var ImageControl=document.getElementById(ImageControlId);var offsetPoint=objectClientPosition(ImageControl);var mouseY=event.clientY-offsetPoint.y;var mouseX=event.clientX-offsetPoint.x;var offsetX=5;var offsetY=5;for(var i=0; i<area.popup.length; i++){popup=document.getElementById(area.popup[i]);popup.style.zIndex=MAP_POPUP_ZINDEX;if(mouseY<ImageControl.offsetHeight/2){popup.style.top=mouseY+offsetY+'px';popup.style.bottom='auto';} else {popup.style.bottom=(ImageControl.offsetHeight-mouseY)+offsetY+5+'px';popup.style.top='auto';}
if(mouseX<ImageControl.offsetWidth /2 ){popup.style.left=mouseX+offsetX+'px';popup.style.right='auto';} else {popup.style.right=(ImageControl.offsetWidth-(mouseX-offsetX))+'px';popup.style.left='auto';}
popup.style.visibility='visible';offsetY += 10;offsetX += 10;}
area=null;ImageControl=null;}
function popupAreaOut(event){if(window.event){event=window.event;}
var area=getEventTarget(event);if(area.popup){for(var i=0; i<area.popup.length; i++){document.getElementById(area.popup[i]).style.visibility='hidden';}}
area=null;}
function popupAreaUp(event,area){if(event||window.event){area=getEventTarget(event);} 
if(!area){area=this;}
if(area.popupMove){removeEvent(area, 'mouseout', popupAreaOut);area.popupMove=false;} else {attachEvent(area, 'mouseout', popupAreaOut);area.popupMove=true;}
area=null;}
function closePopup(event){if(window.event){event=window.event;}
var area=getEventTarget(event).parentNode;var myArea=document.getElementById(area.parentNode.getAttribute('AreaId'));area.parentNode.style.visibility='hidden';if(myArea){popupAreaUp(null,myArea);}
area=null;}
this.preprocessURL=function(type, mapTitle){var layerURL=MAPSERVER_IMAGE_URL;layerURL=layerURL.replace('%MODE%','map')
if(type=='legend'){layerURL=MAPSERVER_LEGEND_URL;layerURL=layerURL.replace('%MODE%','legend')} else if(type=='data'){layerURL=MAPSERVER_DATA_URL;}
if(LayerURLs[mapTitle].match(/http/i)){layerURL=LayerURLs[mapTitle];} else if(LayerURLs[mapTitle].match(/relative/i)){layerURL=new String(LayerURLs[mapTitle]).replace('relative://','');} else {layerURL=layerURL.replace('%MAPFILE%', LayerURLs[mapTitle]);}
var parameters=MySelf.getLayerParamString(mapTitle);if(!parameters){parameters='';}
if(parameters){layerURL=layerURL+'&'+parameters;}
return layerURL;}
this.getId=function(){return MapId;}
this.getParentId=function(){return MapParentId;}
this.getImageControlId=function(){return ImageControlId;}
this.clearActiveLayer=function(){var ImageMapControl=document.getElementById(ImageMapControlId);ImageMapControl.setAttribute('usemap', '');ImageMapControl.setAttribute('useMap', '');ImageMapControl=null;}
this.onActivateLayer=function(mapTitle){var imageMapName=MapId+mapTitle+'-Imagemap';var ImageMapControl=document.getElementById(ImageMapControlId);var imageControlCanvas=document.getElementById(ImageControlCanvasId);var ImageControl=document.getElementById(ImageControlId);if(POPUP_LAYERCHANGE_CLEAR){MySelf.clearPopups();}
if(POPUPS_TRIGGER_CHANGETOOL){ImageMapControl.setAttribute('usemap', '#'+imageMapName);ImageMapControl.setAttribute('useMap', '#'+imageMapName);ImageMapControl.ismap=true;ImageMapControl.style.zIndex=MAP_CONTROL_INDEX;ImageControl.style.zIndex=MAP_CONTROL_INDEX-1;imageControlCanvas.style.zIndex=MAP_CONTROL_INDEX-2;} else {ImageControl.style.zIndex=MAP_CONTROL_INDEX;ImageControl.setAttribute('usemap', '#'+imageMapName);ImageControl.setAttribute('useMap', '#'+imageMapName);ImageControl.ismap=true;}
ImageControl=null;ImageMapControl=null;imageControlCanvas=null;}
function refreshCanvas(){var imageControlCanvas=document.getElementById(ImageControlCanvasId);imageControlCanvas.style.zIndex=MAP_CONTROL_INDEX-2;imageControlCanvas.style.position='absolute';imageControlCanvas.style.top='0px';imageControlCanvas.style.left='0px';imageControlCanvas=null;}
this.autoFitLayers=function(){var MapParent=document.getElementById(MapParentId);var mapSize=new Point(MapParent.offsetWidth, MapParent.offsetHeight);var ImageParent=document.getElementById(ImageParentId);var ImageControl=document.getElementById(ImageControlId);var ImageMapControl=document.getElementById(ImageMapControlId);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';if(ImageMapControl){ImageMapControl.style.width=mapSize.x+'px';ImageMapControl.style.height=mapSize.y+'px';}
if(getBrowser().match(/microsoft/i)){var imageControlCanvas=document.getElementById(ImageControlCanvasId);imageControlCanvas.width=mapSize.x;imageControlCanvas.height=mapSize.y;imageControlCanvas.style.width=mapSize.x+'px';imageControlCanvas.style.height=mapSize.y+'px';} else {createOrReplaceCanvas(mapSize.x, mapSize.y);}}
this.autoFitLayer=function(mapTitle){var mapSize=this.getMapSize();this.resizeLayer(mapTitle,mapSize.x,mapSize.y);}
this.resizeLayer=function(mapTitle,w,h){var img=document.getElementById(LayerId+mapTitle);img.style.top='0px';img.style.left='0px';img.style.width=w+'px';img.style.height=h+'px';img=null;}
this.reloadLayers=function(){MySelf.autoFitLayers();MySelf.refreshLayers();}
function toggleReferenceIndicatorFunction(event){if(window.event){event=window.event; event.which=event.button;}
if(event.which>1){var ReferenceIndicator=document.getElementById(ReferenceIndicatorId);event.returnValue=false;if(ReferenceIndicator.style.zIndex<MAP_CONTROL_INDEX){ReferenceIndicator.style.zIndex=MAP_CONTROL_INDEX+1;} else {ReferenceIndicator.style.zIndex=MAP_CONTROL_INDEX-1;}
var currentBg=ReferenceIndicator.style.background;ReferenceIndicator.style.background=ReferenceIndicator.swapBG;ReferenceIndicator.swapBG=currentBg;var currentBorder=ReferenceIndicator.style.border;ReferenceIndicator.style.border=ReferenceIndicator.swapBorder;ReferenceIndicator.swapBorder=currentBorder;ReferenceIndicator=null;} else {if(this._onmousedown){this._onmousedown(event);}}
return preventDefaultEvent(event);}
function preventPopupMenu(event){return preventDefaultEvent(event);}
this.refreshLayers=function(){var ImageControl=document.getElementById(ImageControlId);var ImageMapControl=document.getElementById(ImageControlId);if(MapReference){var WorkingScale=ScaleFactor;var oldMap=MapReference.getMapSize();var newW=oldMap.x/WorkingScale;var newH=oldMap.y/WorkingScale;var MySize=MySelf.getMapSize();var left=(MySize.x-newW)/2;var top=(MySize.y-newH)/2;var ReferenceIndicator=document.getElementById(ReferenceIndicatorId);if(!ReferenceIndicator){ReferenceIndicator=document.createElement('div');ReferenceIndicator.setAttribute('id', ReferenceIndicatorId);ReferenceIndicator.gDRAGGER=new Draggable(ReferenceIndicatorId, ReferenceIndicator, true, true, true);ImageControl._onmousedown=ImageControl.onmousedown;attachEvent(ImageControl,'mousedown', toggleReferenceIndicatorFunction);ImageControl.oncontextmenu=preventPopupMenu;ReferenceIndicator.oncontextmenu=preventPopupMenu;attachEvent(ReferenceIndicator, 'mousedown', toggleReferenceIndicatorFunction);ReferenceIndicator.gDRAGGER.onDrop=function (trig,obj){trig=obj;var diffX=trig.offsetLeft-left;var diffY=trig.offsetTop-top;for(var l in LayerImages){var img=document.getElementById(LayerId+l);img.style.left=img.offsetLeft-diffX+'px';img.style.top=img.offsetTop-diffY+'px';img=null;}
MySelf.zoomToScaledImage();}}
ReferenceIndicator.style.position='absolute';ReferenceIndicator.style.top=top+'px';ReferenceIndicator.style.left=left+'px';ReferenceIndicator.style.background='white';ReferenceIndicator.style.border='solid 1px black';ReferenceIndicator.style.width=newW+'px';ReferenceIndicator.style.height=newH+'px';ReferenceIndicator.style.zIndex=MAP_POPUP_ZINDEX;ReferenceIndicator.style.overflow='hidden';ReferenceIndicator.swapBG='';ReferenceIndicator.swapBorder='solid 3px #A0A';setOpacity(ReferenceIndicator, 75);document.getElementById(MapParentId).appendChild(ReferenceIndicator);ReferenceIndicator.style.zIndex=MAP_CONTROL_INDEX+1;ImageControl=null;ReferenceIndicator=null;}
if(POPUPS_TRIGGER_CHANGETOOL){if(ImageMapControl){ImageMapControl.setAttribute('usemap', '');ImageMapControl.setAttribute('useMap', '');ImageMapControl.ismap=false;}} else {if(ImageControl){ImageControl.setAttribute('usemap', '');ImageControl.setAttribute('useMap', '');ImageControl.ismap=false;}}
var arr=new Array();for(var title in LayerImages){arr[arr.length]=title;}
MySelf.clearActiveLayer();MySelf.refreshLayer(arr);}
this.moveLayerUp=function(title){MySelf.shiftLayer(title, 1);}
this.moveLayerDown=function(title){MySelf.shiftLayer(title, -1);}
this.changeLayerOpacity=function(layerName, amount){var img=document.getElementById(LayerId+layerName);var opac=getOpacity(img);var oo=opac;opac+=amount;if(opac<=0){opac=0;}
if(opac>100){opac=100;}
setOpacity(img, opac);}
this.getOpacity=function(layerName){return getOpacity(document.getElementById(LayerId+layerName));}
function checkOpacityAbility(){if(OPACITY_CONTROLS=='prompt'||(OPACITY_CONTROLS=='auto'&&getBrowser().match(/microsoft/i)&&getBrowserVersion()<MAP_IE_SCALE_STYLE_SWITCH)){if(OPACITY_CONTROLS_DISABLED_MESSAGE){alert(OPACITY_CONTROLS_DISABLED_MESSAGE);}
return false;} else if(OPACITY_CONTROLS=='auto'){return true;}
if(OPACITY_CONTROLS=='none'){return false;}
return true;}
this.fadeLayer=function(title){if(checkOpacityAbility()){MySelf.changeLayerOpacity(title, -10);}}
this.unfadeLayer=function(title){if(checkOpacityAbility()){MySelf.changeLayerOpacity(title, 10);}}
this.reloadLayer=function(title){var arr=new Array();arr[0]=title;MySelf.refreshLayer(arr);}
this.clearLayer=function(title){if(LayerURLs[title]){LayerURLs[title]='relative://'+BLANK_IMAGE;}
MySelf.reloadLayer(title);}
this.itemQueryLayer=function(title, queryLayer, columnName, queryValue, queryFile){if(queryFile){LayerURLs[title]=queryFile;}
this.clearLayerParams(title);this.addLayerParam(title, 'MOOSEMODE', 'itemquerymap');this.addLayerParam(title, 'qitem', columnName);this.addLayerParam(title, 'qstring', queryValue);this.addLayerParam(title, 'qlayer', queryLayer);MySelf.reloadLayer(title);}}
function PopupManager(EventManager, PopupMap){var LayersToLoad=new Array();var HTTPObjects=new Array();var MapId=PopupMap.getId();var Myself=this;this.onAddLayer=function(mapXMLObj){if(MAP_ASSUME_DATA||new String(mapXMLObj.getAttribute('data')).match(/true/i)){LayersToLoad[mapXMLObj.getAttribute('title')]=mapXMLObj.getElementsByTagName('file')[0].firstChild.nodeValue;loadLayerData(mapXMLObj.getAttribute('title'));}}
this.onRemoveLayer=function(layerTitle){if(LayersToLoad[layerTitle]){Myself.cleanupHTTPObject(layerTitle);LayersToLoad[layerTitle]=null;}}
this.cleanupHTTPObject=function(id){if(HTTPObjects[id]){HTTPObjects[id].abort();HTTPObjects[id]=null;}}
this.cleanupAllHTTPObjects=function(){for(var v in HTTPObjects){this.cleanupHTTPObject(v);}}
function loadLayerData(id){var additionalInputs=new Array();additionalInputs['MAPFILE']=LayersToLoad[id];additionalInputs['MODE']='nquery';var dataURL=ProcessURLString(PopupMap, MAPSERVER_DATA_URL, new Array(), additionalInputs,' ',' ');if(dataURL){Myself.loadData(id, dataURL);logDebugMessage('Data URL', false, dataURL);}}
this.onNavigate=function(){if(MAP_POPUPS_ENABLED){Myself.cleanupAllHTTPObjects();for(var id in LayersToLoad){loadLayerData(id);}}}
this.loadData=function(id, dataCall){var http=getHTTPObject();HTTPObjects[id]=http;var postData=true;var postGet='GET';if(dataCall.length>1000){var arr=dataCall.split('?');dataCall=arr[0];postData=arr[1];postGet='POST';}
http.open(postGet, dataCall, true);http.onreadystatechange=function(){if(http&&http.readyState==4){if(http.responseXML){var imagemapElements=http.responseXML.getElementsByTagName('imagemap');if(imagemapElements.length<1){return false;}
imagemapElements[0].setAttribute('layerid', MapId+id);var d=document.getElementById(MapId+id+'-ImageMapParent');if(!d){d=document.createElement('div');document.getElementById(PopupMap.getParentId()).appendChild(d);d.setAttribute('id',MapId+id+'-ImageMapParent');d.className='ImageMapParent';}
processXMLWithXSLT(http.responseXML, XSL_IMAGEMAP, d.getAttribute('id'), correlateImagemap);if(http.responseXML.getElementsByTagName('popup').length>0){EventManager.triggerEvent('datalayer',id);}}}}
http.send(postData);}
function correlateImagemap(containerId){var container=document.getElementById(containerId);var areas=container.getElementsByTagName('area');var circles=new Array();var b2dTree=new BTree();for(var i=0; i<areas.length; i++){var shape=new String(areas[i].getAttribute('shape')).toLowerCase();if(shape=='circle'){var coords=areas[i].getAttribute('coords').split(',');var index=areas[i].getAttribute('index');b2dTree.insert(parseInt(coords[0]), parseInt(coords[1]), index);}}
for(var i=0; i<areas.length; i++){areas[i].popups=new Array();areas[i].onmouseover=showPopups;areas[i].onclick=toggleSticky;areas[i].onmouseout=toggledHidePopups;areas[i].popups[0]=parseInt(areas[i].getAttribute('index'));var shape=new String(areas[i].getAttribute('shape')).toLowerCase();if(shape=='circle'){var coords=areas[i].getAttribute('coords').split(',');var x=parseInt(coords[0]);var y=parseInt(coords[1]);var r=parseInt(coords[2]);var relatedNodes=b2dTree.searchByRange2D(x-r,y-r,x+r,y+r);if(relatedNodes){for(var n=0; n<relatedNodes.length; n++){areas[i].popups[n]=relatedNodes[n].o;}}} else if(shape=='line'||shape=='rect'){var coords=areas[i].getAttribute('coords').split(/[, ]/);for(var c=0; c<coords.length; c++){coords[c]=parseInt(coords[c]);}
var ptA=new Point(coords[0],coords[1]), ptB=new Point(coords[2], coords[3]);var seg=new LineSegment(ptA, ptB);seg=seg.buffer(3);areas[i].setAttribute('shape','poly');areas[i].setAttribute('coords', seg.toString(',',true));areas[i].onmousemove=showPopups;logDebugMessage('Imagemap-Line', false, areas[i].getAttribute('coords')+' '+areas[i].getAttribute('shape'));} else if(shape=='poly'){areas[i].onmousemove=showPopups;}}
if(document.evaluate){var ximages=document.evaluate("//div[@id='"+containerId+"']//img[@class='closeButton']", document, null, XPathResult.ANY_TYPE, null);var obj;while(obj=ximages.iterateNext()){obj.onclick=hidePopupSelf;}
var xdivs=document.evaluate("//div[@id='"+containerId+"']//div[@class='popupParent']", document, null, XPathResult.ANY_TYPE, null);while(obj=xdivs.iterateNext()){obj.draggable=new Draggable(obj.getAttribute('id'), obj.getElementsByTagName('div')[0], true,true,true);}} else {var images=container.getElementsByTagName('img');for(var i=0; i<images.length; i++){if(images[i].className&&images[i].className.match(/closeButton/)){images[i].onclick=hidePopupSelf;}}
var divs=container.getElementsByTagName('div');for(var d=0; d<divs.length; d++){if(divs[d].className=='popupParent'){divs[d].draggable=new Draggable(divs[d].getAttribute('id'), divs[d].getElementsByTagName('div')[0], true,true,true);}}}}
function showPopup(id,l,r,t,b,z){var d=document.getElementById(id);if(!z){z=1;}
if(d){d.style.visibility='visible';d.style.left=l;d.style.right=r;d.style.top=t;d.style.bottom=b;d.style.zIndex=z;} else {logDebugMessage('Map-Popups', false, 'Trying to display a popup that does not exists: '+id);}
d=null;}
function hidePopup(id){var d=document.getElementById(id);if(d){d.style.visibility='hidden';} else {logDebugMessage('Map-Popups', false, 'Trying to hide a popup that does not exist: '+id);}}
function hidePopups(event,popups,root){if(!popups){popups=this.popups;}
if(!root){root=this.getAttribute('root');}
for(var i=0; i<popups.length; i++){hidePopup(root+'-Popup-'+popups[i]);}}
function toggledHidePopups(event){if(this.sticky){} else {hidePopups(event, this.popups, this.getAttribute('root'));}}
function hidePopupSelf(){hidePopup(this.getAttribute('relation'));}
function toggleSticky(){this.sticky=!this.sticky;}
function showPopups(event){if(window.event){event=window.event;}
var area=getEventTarget(event);var ImageControlId=PopupMap.getImageControlId();var ImageControl=document.getElementById(ImageControlId);var offsetPoint=objectClientPosition(ImageControl);var mouseY=event.clientY-offsetPoint.y;var mouseX=event.clientX-offsetPoint.x;var offsetX=5;var offsetY=5;var root=this.getAttribute('root');if(!area.popups){return false;}
for(var i=0; i<area.popups.length; i++){var z=MAP_POPUP_ZINDEX+i;var left='auto', right='auto', top='auto', bottom='auto';if(mouseY<ImageControl.offsetHeight/2){top=mouseY+offsetY+'px';} else {bottom=(ImageControl.offsetHeight-mouseY)+offsetY+5+'px';}
if(mouseX<ImageControl.offsetWidth /2 ){left=mouseX+offsetX+'px';} else {right=(ImageControl.offsetWidth-(mouseX-offsetX))+'px';}
if(!this.sticky){showPopup(root+'-Popup-'+area.popups[i], left,right,top,bottom,z);} else {document.getElementById(root+'-Popup-'+area.popups[i]).style.visibility='visible';}
offsetY += 10;offsetX += 10;}
area=null;ImageControl=null;}}
var TREEVIEW_INSTANCE=0;function TreeView(EventManager, TreeMap){var MySelf=this;var TreeViewId='TreeView'+TREEVIEW_INSTANCE+'-';TREEVIEW_INSTANCE++;var MapBookData=null;var Parent;function hideLegend(obj){obj.className=obj.className +' BLANK';}
function showLegend(obj){obj.src='';var classNames=new String(obj.className);classNames=classNames.replace('BLANK','');obj.className=classNames;}
this.removeLayer=function(id){MySelf.removeObject('Map',id);if(document.getElementById(TreeViewId+'TitleFont-'+id)){document.getElementById(TreeViewId+'TitleFont-'+id).className='TreeViewLayerVisible';}}
this.removeService=function(id){MySelf.removeObject('Service', id);}
this.removeView=function(id){MySelf.removeObject('View', id);}
this.addLayer=function(id){if(id.getAttribute('reference')&&id.getAttribute('reference').match(/only/i)){return false;}
MySelf.addObject('Map',id);var titleFont=document.getElementById(TreeViewId+'TitleFont-'+id.getAttribute('title'));var checkbox=document.getElementById(TreeViewId+'Map-'+id.getAttribute('title'));if(titleFont){if(TreeMap.isLayerVisible(id.getAttribute('title'))){titleFont.className='TreeViewLayerVisible';} else {titleFont.className='TreeViewLayerInvisible';if(TREEVIEW_CHECKBOX_RANGE_VISIBILITY){checkbox.disabled=true;}}}}
this.addService=function(id){MySelf.addObject('Service', id);}
this.addView=function(id){MySelf.addObject('View', id);}
this.removeObject=function(objType, id){var checkBox=document.getElementById(TreeViewId+objType+'-'+id);if(checkBox){checkBox.checked=false;var legendObj=document.getElementById(TreeViewId+'Legend-'+id);if(legendObj){hideLegend(legendObj);legendObj.src='';}}}
this.addObject=function(objType, mapXMLObj){var title=mapXMLObj.getAttribute('title');var checkBox=document.getElementById(TreeViewId+objType+'-'+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='0px';}
var visibilityOverride=false;this.setVisibilityOverride=function (v){visibilityOverride=v;}
function onclickLeaf(event){if(window.event){event=window.event;}
if(getEventTarget(event) != this){return true;}
var childTree=this.getElementsByTagName('ul')[0];var vis=childTree.style.visibility;if(childTree.style.height != '0px'){height='0px';var allUl=childTree.getElementsByTagName('ul');for(var u=0; u<allUl.length; u++){makeInvisible(allUl[u]);}} else {height='auto';}
childTree.style.height=height;event.returnValue=false;if(event.preventDefault){event.preventDefault();}
return false;}
var Branches=0;function createBranch(xmlObj){var root=document.createElement('ul');root.setAttribute('id',TreeViewId+'Branch-'+Branches);Branches++;if(document.all){root.style.marginLeft='24px';} else {root.style.paddingLeft='24px';}
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]);var underList=createBranch(xmlObj.childNodes[i]);underList.style.height='0px';underList.style.overflow='hidden';rootLeaf.appendChild(underList);root.appendChild(rootLeaf);rootLeaf.onclick=onclickLeaf;rootLeaf.onmouseup=preventDefaultEvent;rootLeaf.onmousedown=preventDefaultEvent;rootLeaf.ondblclick=preventDefaultEvent;if(xmlObj.childNodes[i].getAttribute('expand')&&xmlObj.childNodes[i].getAttribute('expand').match(/true/)){underList.style.height='auto';}} else if(xmlObj.childNodes[i].tagName != null&&xmlObj.childNodes[i].getAttribute('title') != null){root.appendChild(getLeaf(xmlObj.childNodes[i]));}}}
return root;}
function onclickLayer(){if(this.checked){EventManager.triggerEvent('addlayer', this.selfXML);} else {this.checked=true;if(EventManager.onRemoveLayer(this.selfXML.getAttribute('title'))){this.checked=false;}}}
function onclickService(){if(this.checked){EventManager.triggerEvent('addservice', this.selfXML);} else {this.checked=true;if(EventManager.onRemoveService(this.selfXML.getAttribute('title'))){this.checked=false;}}}
function onclickView(){if(this.checked){EventManager.triggerEvent('addview', this.selfXML);} else {this.checked=true;if(EventManager.triggerEvent('removeview',this.selfXML.getAttribute('title'))){this.checked=false;}}}
function updateLayerList(){var cbox=this.parentNode.getElementsByTagName('input');var activeLayers=new Array();for(var c=0; c<cbox.length; c++){if(cbox[c].checked){activeLayers.push(cbox[c].value);}}
TreeMap.setLayerParam(this.title, 'layers', activeLayers.join(' '));TreeMap.refreshLayer([this.title]);}
function getLeaf(obj){var newLi=document.createElement('li');var objTitle=obj.getAttribute('title');newLi.style.cursor='pointer';newLi.className='Folder';newLi.id=TreeViewId+'-List-'+objTitle;var objectTip=obj.getAttribute('tip');if(objectTip){newLi.title=objectTip;newLi.alt=objectTip;}
if(obj.getAttribute('icon')){var iconUrl=obj.getAttribute('icon');newLi.style.listStyleType='none';newLi.style.listStyleImage='url('+iconUrl+')';} else if(obj.tagName.match(/map/)){newLi.className='Map';} else if(obj.tagName.match(/service/)){newLi.className='Service';} else if(obj.tagName.match(/view/)){newLi.className='View';}
if(obj.tagName != 'group'){var layerCheckBox=document.createElement('input');layerCheckBox.setAttribute('type','checkbox');layerCheckBox.id=TreeViewId+newLi.className+'-'+objTitle;layerCheckBox.selfXML=obj;newLi.appendChild(layerCheckBox);if(obj.tagName.match(/map/i)){layerCheckBox.onclick=onclickLayer;} else if(obj.tagName.match(/service/i)){layerCheckBox.onclick=onclickService;} else if(obj.tagName.match(/view/i)){layerCheckBox.onclick=onclickView;}
var titleFont=document.createElement('font');titleFont.className='TreeViewLayerVisible';titleFont.id=TreeViewId+'TitleFont-'+objTitle;newLi.appendChild(titleFont);titleFont.appendChild(document.createTextNode(objTitle));} else {newLi.appendChild(document.createTextNode(objTitle));}
if(obj.getElementsByTagName('meta')[0]&&obj.getElementsByTagName('meta')[0].firstChild.nodeValue){if(obj.getElementsByTagName('meta')[0].parentNode==obj){var metaLink=document.createElement('a');newLi.appendChild(metaLink);metaLink.href=obj.getElementsByTagName('meta')[0].firstChild.nodeValue;var metaImage=document.createElement('img');metaImage.src=META_DEFAULT_ICON;metaLink.appendChild(metaImage);metaImage.title='Metadata for '+objTitle;metaImage.alt='Metadata for '+objTitle;metaLink.className='Metadata';metaLink.target='_blank';metaImage=null;metaLink=null;}}
if(obj.getElementsByTagName('help')[0]&&obj.getElementsByTagName('help')[0].firstChild.nodeValue){if(obj.getElementsByTagName('help')[0].parentNode==obj){var helpLink=document.createElement('a');newLi.appendChild(helpLink);helpLink.href=obj.getElementsByTagName('help')[0].firstChild.nodeValue;var helpImage=document.createElement('img');helpImage.src=HELP_DEFAULT_ICON;helpLink.appendChild(helpImage);helpImage.title='Help for '+objTitle;helpImage.alt='Help for '+objTitle;helpLink.className='Help';helpLink.target='_blank';helpImage=null;helpLink=null;}}
if(TREEVIEW_SHOW_CONTROLS&&obj.tagName=='map'){newLi.appendChild(document.createElement('br'));if(TREEVIEW_CONTROLS.up){newLi.appendChild(createIcon(EventManager, UP_ICON,'movelayerup', objTitle, 'Move this layer up in the stacking order.'));}
if(TREEVIEW_CONTROLS.down){newLi.appendChild(createIcon(EventManager, DOWN_ICON,'movelayerdown',objTitle, 'Move this layer down in the stacking order.'));}
if(TREEVIEW_CONTROLS.fade){newLi.appendChild(createIcon(EventManager, FADE_ICON,'fadelayer',objTitle, 'Fade this layer.'));}
if(TREEVIEW_CONTROLS.unfade){newLi.appendChild(createIcon(EventManager, UNFADE_ICON,'unfadelayer',objTitle, 'Unfade this layer.'));}
if(MAP_POPUPS_ENABLED&&obj.getAttribute('popups')&&obj.getAttribute('popups').match(/true/i)){var icon;if(POPUPS_TRIGGER_CHANGETOOL){icon=createIcon(EventManager, POPUP_UNAVAILABLE_ICON, ['changetool','activatelayer'], objTitle, POPUP_MESSAGE['PopupsUnavailable']);} else {icon=createIcon(EventManager, POPUP_UNAVAILABLE_ICON, 'activatelayer', objTitle, POPUP_MESSAGE['PopupsUnavailable']);}
icon.className='PopupsUnavailable';icon.title=POPUP_MESSAGE[icon.className];icon.id=TreeViewId+'Popups-'+objTitle;icon.eventTrigger=null;newLi.appendChild(icon);}
if(TREEVIEW_CONTROLS.refresh){newLi.appendChild(createIcon(EventManager, RELOAD_ICON,'refreshlayer', objTitle, 'Refresh this layer.'));}}
var layers=obj.getElementsByTagName('layer');if(layers.length>0){newLi.appendChild(document.createElement('br'));var layersDiv=document.createElement('div');layersDiv.className='TreeViewLayersList';newLi.appendChild(layersDiv);for(var i=0; i<layers.length; i++){var layersOpt=document.createElement('input');layersOpt.type='checkbox';layersDiv.appendChild(layersOpt);layersOpt.value=layers[i].getAttribute('name');layersOpt.title=obj.getAttribute('title');layersOpt.disabled=parseBoolean(layers[i].getAttribute('locked'), false);layersOpt.checked=parseBoolean(layers[i].getAttribute('default'), true);layersDiv.appendChild(document.createTextNode(layers[i].getAttribute('title')));layersDiv.appendChild(document.createElement('br'));layersOpt.onclick=updateLayerList;}}
if(TREEVIEW_SHOW_LEGENDS&&obj.tagName=='map'){newLi.appendChild(document.createElement('br'));var legendImage=document.createElement('img');legendImage.setAttribute('id', TreeViewId+'Legend-'+objTitle);hideLegend(legendImage);newLi.appendChild(legendImage);legendImage=null;}
return newLi;}
this.onNavigate=function(){var layers=TreeMap.getLayersByZIndex();for(var i=0; i<layers.length; i++){var cName='TreeViewLayerInvisible';var checkbox=document.getElementById(TreeViewId+'Map-'+layers[i]);if(!TREEVIEW_CHECKBOX_RANGE_VISIBILITY){checkbox=null;}
if(TreeMap.isLayerVisible(layers[i])){cName='TreeViewLayerVisible';if(checkbox){checkbox.disabled=false;}} else {if(checkbox){checkbox.disabled=true;}}
var titleElm=document.getElementById(TreeViewId+'TitleFont-'+layers[i]);if(titleElm){titleElm.className=cName;}}}
this.onActivateLayer=function(layerTitle){var tvParent=document.getElementById(Parent);var images=tvParent.getElementsByTagName('img');for(var i=0 ; i<images.length; i++){if(images[i].className.match(/PopupsActive/)){images[i].className='PopupsAvailable';images[i].src=POPUP_AVAILABLE_ICON;images[i].title=POPUP_MESSAGE[images[i].className];}}
if(TREEVIEW_SHOW_CONTROLS){var icon=document.getElementById(TreeViewId+'Popups-'+layerTitle);icon.src=POPUP_ACTIVE_ICON;icon.className='PopupsActive';icon.title=POPUP_MESSAGE[icon.className];}}
this.onLoadData=function(layerTitle){if(TREEVIEW_SHOW_CONTROLS){var icon=document.getElementById(TreeViewId+'Popups-'+layerTitle);if(POPUPS_TRIGGER_CHANGETOOL){icon.eventTrigger=['changetool','activatelayer'];} else {icon.eventTrigger=['activatelayer'];}
icon.src=POPUP_AVAILABLE_ICON;icon.className='PopupsAvailable';icon.title=POPUP_MESSAGE[icon.className];}}
this.onLayerRefresh=function(layerTitle){var icon=document.getElementById(TreeViewId+'Popups-'+layerTitle);if(icon){icon.eventTrigger=null;icon.src=POPUP_UNAVAILABLE_ICON;icon.className='PopupsUnavailable';icon.title=POPUP_MESSAGE[icon.className];}}
this.onLoadLegend=function(legendObj){var obj=document.getElementById(TreeViewId+'Legend-'+legendObj.id);if(obj){showLegend(obj);obj.src=legendObj.legend;}}
this.getTree=function(){return createBranch(parentXML);}
this.reloadMapbook=function(mbXML){document.getElementById(Parent).removeChild(Tree);this.loadMapbook(mbXML);}
this.loadMapbook=function(mbXML){MapBookData=mbXML.getElementsByTagName('mapbook')[0];if(Parent){document.getElementById(Parent).appendChild(createBranch(MapBookData));}}
this.setParent=function(p){Parent=p;if(MapBookData){document.getElementById(Parent).appendChild(createBranch(MapBookData));}}}
function triggerSelfEvent(){if(this.eventTrigger==null){return false;} 
if(typeof this.eventTrigger=="object"){for(var i=0; i<this.eventTrigger.length; i++){this.EventManager.triggerEvent(this.eventTrigger[i], this.mapTitle);}} else {this.EventManager.triggerEvent(this.eventTrigger, this.mapTitle);}}
var VISIBLE_LAYERS_INSTANCE=0;function VisibleLayers(EventManager,VisibleMap){var ListParent;var LayersListId='LayersList'+VISIBLE_LAYERS_INSTANCE+'-';VISIBLE_LAYERS_INSTANCE++;var LayerIcons=new Array();var MySelf=this;this.clearActiveLayerSelection=function(){var layersList=document.getElementById(LayersListId);var radios=layersList.getElementsByTagName('input');for(var i=0; i<radios.length; i++){radios[i].checked=false;if(radios[i].parentNode.className=='SelectedLayer'){radios[i].parentNode.className='ActiveLayer';}}}
function activateLayer(){var title=this.getAttribute('LayerName');EventManager.triggerEvent('changetool', title);EventManager.triggerEvent('activatelayer', title);if(!this.disabled){this.checked=true;this.parentNode.className='SelectedLayer';}}
this.sortListByZIndex=function(){var ordered=VisibleMap.getLayersByZIndex();var p=document.getElementById(LayersListId);for(var i=0; i<ordered.length; i++){var obj=document.getElementById(LayersListId+ordered[i]);if(obj){p.appendChild(obj);}}}
this.addLayer=function(mapXMLObj){var title=mapXMLObj.getAttribute('title');var ListItem=document.createElement('li');ListItem.id=LayersListId+title;var alreadyHere=document.getElementById(ListItem.id);if(alreadyHere) return false;layersList=document.getElementById(LayersListId);layersList.appendChild(ListItem);if(MAP_POPUPS_ENABLED){var ActivateLayer=document.createElement('input');ActivateLayer.type='radio';ActivateLayer.name='activateLayer';ActivateLayer.disabled=true;ActivateLayer.id='DataLayer-'+title;ActivateLayer.setAttribute('LayerName', title);ActivateLayer.onclick=activateLayer;ListItem.appendChild(ActivateLayer);}
var LegendImg=document.createElement('img');LegendImg.id='LayerLegend-'+title;LegendImg.style.visibility='hidden';if(mapXMLObj.getAttribute('icon')){LayerIcons[title]=mapXMLObj.getAttribute('icon');}
var titleLi=document.createElement('li');titleLi.id=LayersListId+'Icon-'+title;titleLi.className='VisibleLayersMap'
if(LayerIcons[title]){titleLi.style.listStyleImage='url('+LayerIcons[title]+')';}
ListItem.appendChild(titleLi);titleLi.appendChild(document.createTextNode(title));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'));ListItem.appendChild(createIcon(EventManager, UP_ICON,'movelayerup', title));ListItem.appendChild(createIcon(EventManager, DOWN_ICON,'movelayerdown',title));ListItem.appendChild(createIcon(EventManager, FADE_ICON,'fadelayer',title));ListItem.appendChild(createIcon(EventManager, UNFADE_ICON,'unfadelayer',title));ListItem.appendChild(createIcon(EventManager, RELOAD_ICON,'refreshlayer', title));if(!mapXMLObj.getAttribute('locked')||!mapXMLObj.getAttribute('locked').match(/true/i)){ListItem.appendChild(createIcon(EventManager, REMOVE_ICON,'removelayer',title));}
if(mapXMLObj.getElementsByTagName('meta')[0]&&mapXMLObj.getElementsByTagName('meta')[0].firstChild.nodeValue){var metaIcon=document.createElement('img');metaIcon.src=META_DEFAULT_ICON;metaIcon.style.verticalAlign='middle';metaIcon.onclick=function (){window.open(mapXMLObj.getElementsByTagName('meta')[0].firstChild.nodeValue);}
ListItem.appendChild(metaIcon);}
ListItem.appendChild(document.createElement('br'));ListItem.appendChild(LegendImg);if(parseInt(mapXMLObj.getAttribute('zindex'))==-1||!layersList.firstChild){layersList.appendChild(ListItem);} else {layersList.insertBefore(ListItem, layersList.firstChild);}
MySelf.sortListByZIndex();}
this.activateLayer=function(mapTitle){var opt=document.getElementById('DataLayer-'+mapTitle);if(opt){opt.disabled=false;opt.parentNode.className='ActiveLayer';}}
this.disableLayers=function(){var layersList=document.getElementById(LayersListId);if(layersList){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(LayersListId+mapTitle);if(LayerIcons[mapTitle]){delete LayerIcons[mapTitle];}
if(ListItem){var p=ListItem.parentNode;p.removeChild(ListItem);}}
this.showLegend=function(xmlObj){var title=xmlObj.id;var src=xmlObj.legend;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(LayersListId+title);var layersList=document.getElementById(LayersListId);if(listItem&&listItem.previousSibling){layersList.insertBefore(listItem, listItem.previousSibling);}
MySelf.sortListByZIndex();}
this.moveLayerDown=function(title){var listItem=document.getElementById(LayersListId+title);var layersList=document.getElementById(LayersListId);if(listItem&&listItem.nextSibling){layersList.insertBefore(listItem.nextSibling, listItem);}
MySelf.sortListByZIndex();}
function setIconClass(title, iconClass){var icon=document.getElementById(LayersListId+'Icon-'+ title);if(!icon){return false;} 
if(!iconClass){icon.className='VisibleLayersMap';} else {icon.className=iconClass;}}
function setIcon(title, iconSrc){var icon=document.getElementById(LayersListID+'Icon-'+ title);if(!iconSrc){icon.style.listStyleImage='';} else {icon.style.listStyleImage='url('+iconSrc+')';}}
this.setAllRefreshIcon=function (){for(var title in LayerIcons){setIconClass(title, 'VisibleLayersMapLoading');}}
this.setRefreshIcon=function(title){setIconClass(title, 'VisibleLayersMapLoading');}
this.setLoadedIcon=function(title){var icon=document.getElementById(LayersListId+'Icon-'+title);if(icon){icon.src=LayerIcons[title];}}
function enableOpacityControls(){if(confirm(OPACITY_CONTROLS_ENABLE_WARNING)){OPACITY_CONTROLS='full';this.onclick=null;this.style.color='black';this.innerHTML='Opacity Controls Enabled.';setTimeout("document.getElementById('"+this.id+"').style.visibility='hidden';", 2000);}}
this.setParent=function(parent){ListParent=parent;var layersList=document.createElement('ul');layersList.className='VisibleLayers';layersList.setAttribute('id',LayersListId);document.getElementById(ListParent).appendChild(layersList);if(OPACITY_CONTROLS=='prompt'||(OPACITY_CONTROLS=='auto'&&getBrowser().match(/microsoft/i)&&getBrowserVersion()<MAP_IE_SCALE_STYLE_SWITCH)){var a=document.createElement('a');document.getElementById(ListParent).appendChild(a);a.href='javascript:function nil(){}';a.appendChild(document.createTextNode('Enable Opacity Controls'));a.onclick=enableOpacityControls;a.setAttribute('id', LayersListId+'OpacityControl');with(a.style){display='block';position='absolute';bottom='20px';padding='5px';textDecoration='none';width='90%';color='red';textAlign='center';fontWeight='bold';}
a=null;}}}
var TOOLBAR_ITERATIONS=0;function GTools(EventManager){var ToolsParent;this.SHOW_TEXT=TOOLBAR_TEXT;this.SHOW_IMAGE=TOOLBAR_IMAGE;var ServiceLinkId='ServiceLink-'+TOOLBAR_ITERATIONS+'-';var ServiceToolId='ServiceTool-'+TOOLBAR_ITERATIONS+'-';var ToolsListId='ToolsList-'+TOOLBAR_ITERATIONS+'-';var ToolsListClassName='ToolList';TOOLBAR_ITERATIONS++;this.setType=function(cName){ToolsListClassName=cName;var toolsList=document.getElementById(ToolsListId);if(toolsList){toolsList.className=cName;}}
var MySelf=this;var ToolIcons=new Array();function showNone(link){if(link.highlightIcon){link.highlightIcon.style.visibility='hidden';link.highlightIcon.style.width='1px';link.highlightIcon.style.paddingLeft='0px';}
if(link.toolIcon){link.toolIcon.style.visibility='hidden';link.toolIcon.style.width='1px';link.toolIcon.style.paddingRight='0px';}}
function showUnselected(link){if(link.toolIcon){link.toolIcon.style.visibility='visible';link.toolIcon.style.width='auto';link.toolIcon.style.paddingRight='1px';}
if(link.highlightIcon){link.highlightIcon.style.visibility='hidden';link.highlightIcon.style.width='1px';link.highlightIcon.style.paddingLeft='0px';}}
function showSelected(link){if(link.toolIcon&&link.highlightIcon){link.toolIcon.style.visibility='hidden';link.toolIcon.style.width='1px';link.toolIcon.style.paddingRight='0px';}
if(link.highlightIcon){link.highlightIcon.style.visibility='visible';link.highlightIcon.style.width='auto';link.highlightIcon.style.paddingLeft='1px';}}
this.clearToolSelection=function(title){var links=document.getElementById(ToolsParent).getElementsByTagName('a');for(var i=0; i<links.length; i++){if(links[i].className=='Selected'){links[i].className='';}
showUnselected(links[i]);}}
this.showSelectedTool=function(toolName){var tool=document.getElementById(ServiceLinkId+toolName);MySelf.clearToolSelection();if(tool){showSelected(tool);}}
function onclickServiceLink(){var title=this.title;var sel=this.selectable;if(sel){EventManager.triggerEvent('changetool', title);if(TOOLS_SHOW_AS_SELECTED){this.className='Selected';}
showSelected(this);}
if(this.callService){this.callService();}}
function onclickCallService(){EventManager.triggerEvent('serviceform', this.selfXML);}
var KnownServices=new Array();var SelectToolAtStartup=null;this.addService=function(serviceXMLObj){var title=serviceXMLObj.getAttribute('title');KnownServices[title]=serviceXMLObj;var toolsList=document.getElementById(ToolsListId);if(toolsList){renderServiceInToolbar(title);}}
function renderServiceInToolbar(title){var serviceXMLObj=KnownServices[title];var rendered=serviceXMLObj.getAttribute(ToolsListId+'rendered');if(rendered&&rendered=='1'){return true;}
serviceXMLObj.setAttribute(ToolsListId+'rendered','1');var toolsList=document.getElementById(ToolsListId);var newTool=document.createElement('li');var ServiceLink=document.createElement('a');ServiceLink.selfXML=serviceXMLObj;toolsList.appendChild(newTool);newTool.appendChild(ServiceLink);var action='';var selectable=serviceXMLObj.getAttribute('selectable');if(selectable&&selectable.match(/false/i)){ServiceLink.selectable=false;} else {ServiceLink.selectable=true;}
if(serviceXMLObj.getAttribute('type')&&serviceXMLObj.getAttribute('type').match(/internal/i)){action='javascript:'+serviceXMLObj.getAttribute('command');} else {action='javascript:function nil(){return false;}';ServiceLink.callService=onclickCallService;}
ServiceLink.title=title;ServiceLink.href=action;ServiceLink.id=ServiceLinkId+title;ServiceLink.onclick=onclickServiceLink;var icon=serviceXMLObj.getAttribute('icon');if(!icon){icon=SERVICE_DEFAULT_ICON;}
var newToolIcon=document.createElement('img');newToolIcon.src=icon;newToolIcon.id=ServiceToolId+'Icon-'+title;ToolIcons[title]=icon;var altIcon=serviceXMLObj.getAttribute('highlight');if(MySelf.SHOW_IMAGE&&altIcon){ServiceLink.setAttribute('highlightIconSrc',altIcon);var highlightImg=document.createElement('img');highlightImg.src=altIcon;highlightImg.id=ServiceToolId+'Highlight-'+title;ServiceLink.appendChild(highlightImg);ServiceLink.highlightIcon=highlightImg;}
if(MySelf.SHOW_IMAGE){ServiceLink.appendChild(newToolIcon);ServiceLink.toolIcon=newToolIcon;ServiceLink.setAttribute('toolIconSrc',ToolIcons[title]);}
if(MySelf.SHOW_TEXT){ServiceLink.appendChild(document.createTextNode(title));}
ServiceLink.title=title;newTool.id=ServiceToolId+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 (){window.open(serviceXMLObj.getElementsByTagName('help')[0].firstChild.nodeValue);return false;}
ServiceLink.appendChild(helpButton);}
if(TOOLS_SHOW_REMOVE&&(!serviceXMLObj.getAttribute('locked')||!serviceXMLObj.getAttribute('locked').match(/true/i))){var removeButton=createIcon(EventManager, REMOVE_ICON,'removeservice',title);ServiceLink.appendChild(removeButton);}
showUnselected(ServiceLink);}
this.setParent=function(p){ToolsParent=p;var toolsList=document.createElement('ul');toolsList.setAttribute('id', ToolsListId);toolsList.className=ToolsListClassName;document.getElementById(ToolsParent).appendChild(toolsList);toolsList=null;for(var s in KnownServices){renderServiceInToolbar(s);}
if(SelectToolAtStartup){this.selectTool(SelectToolAtStartup);SelectToolAtStartup=null;}}
this.removeService=function(serviceTitle){var serv=document.getElementById(ServiceToolId+serviceTitle);if(serv){var p=serv.parentNode;p.removeChild(serv);if(KnownServices[serviceTitle]){delete KnownServices[serviceTitle];}}}
this.toolWaiting=function(serviceXMLObj){if(serviceXMLObj.getAttribute('type')&&serviceXMLObj.getAttribute('type').match(/search/i)){var title=serviceXMLObj.getAttribute('title');var link=document.getElementById(ServiceLinkId+title);if(link){showNone(link);link.waitIcon=document.createElement('img');link.waitIcon.src=MAP_LOADING_ICON;link.insertBefore(link.waitIcon,link.childNodes[0]);}}}
this.restoreTool=function(serviceXMLObj){var title=serviceXMLObj.getAttribute('title');if(!title){var root=serviceXMLObj.getElementsByTagName('results')[0];title=root.getAttribute('title');}
var link=document.getElementById(ServiceLinkId+title);if(link&&link.waitIcon){link.removeChild(link.waitIcon);showUnselected(link);}}
this.selectTool=function(toolName){var tool=document.getElementById(ServiceLinkId+toolName);if(tool){tool.onclick();if(tool.href){var js=tool.href;js=js.replace('javascript:','');eval(js);}} else {SelectToolAtStartup=toolName;}}}
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');p.appendChild(imgObj);}}
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='';}}
function renderResults(parent, resultsXML, EventManager){var title=resultsXML.getAttribute('title');var rows=resultsXML.getElementsByTagName('row');var header=resultsXML.getElementsByTagName('header')[0];var errors=resultsXML.getElementsByTagName('error');if(errors.length>0){var messageB=document.createElement('b');var errorFont=document.createElement('font');errorFont.style.color='red';parent.appendChild(messageB);parent.appendChild(errorFont);messageB.appendChild(document.createTextNode('The service returned the following errors:'));errorFont.appendChild(document.createElement('br'));for(var err=0; err<errors.length; err++){errorFont.appendChild(document.createTextNode(errors[err].firstChild.nodeValue));errorFont.appendChild(document.createElement('br'));}}
if(rows.length>LAYER_MAXIMUM_OBJECTS){alert(SERVICE_OVERLOAD_MESSAGE); return true;}
var titleElement=document.createElement('h3');if(title){titleElement.appendChild(document.createTextNode(title));}
parent.appendChild(titleElement);var resultsTable=document.createElement('table');var resultsBody=document.createElement('tbody');resultsTable.appendChild(resultsBody);if(header){var headerElms=header.getElementsByTagName('col');var headerRow=document.createElement('tr');var headerSpace=document.createElement('td');headerSpace.className='RowId';headerRow.appendChild(headerSpace);for(var i=0; i<headerElms.length; i++){var val=headerElms[i].getAttribute('value');var cell=document.createElement('th');cell.appendChild(document.createTextNode(val));headerRow.appendChild(cell);}
resultsBody.appendChild(headerRow);}
for(var i=0; i<rows.length; i++){var resultsRow=document.createElement('tr');var rowTitle=rows[i].getAttribute('value');if(!rowTitle){rowTitle=i+1;}
var rowId=document.createElement('td');rowId.className='RowId';rowId.appendChild(document.createTextNode(rowTitle));resultsRow.appendChild(rowId);var cols=rows[i].getElementsByTagName('col');for(var c=0; c<cols.length; c++){var resultsCell=document.createElement('td');var cellType=cols[c].getAttribute('type');var valueParent=resultsCell;if(!cellType){valueParent.appendChild(document.createTextNode(cols[c].getAttribute('value')));} else if(cellType.match(/pan/i)||cellType.match(/zoomto/i)){var panLink=document.createElement('a');valueParent.appendChild(panLink);var panX=cols[c].getAttribute('x');var panY=cols[c].getAttribute('y');var pVal=cols[c].getAttribute('label');if(pVal==null){pVal='Point of Interest';}
panLink.href='javascript:function nil(){return;}';panLink.pan_x=panX;panLink.pan_y=panY;panLink.onclick=function(){var modCirc=new Circle();modCirc.Center=new Point(this.pan_x, this.pan_y);modCirc.Radius=2;modCirc.Markup=true;EventManager.triggerEvent('navigate', modCirc);}
panLink.appendChild(document.createTextNode(cols[c].getAttribute('value')));} else if(cellType.match(/internal/i)){var panLink=document.createElement('a');panLink.href='javascript:'+cols[c].getAttribute('command');panLink.appendChild(document.createTextNode(cols[c].getAttribute('value')));valueParent.appendChild(panLink);} else if(cellType.match(/image/i)){var w=cols[c].getAttribute('width');var h=cols[c].getAttribute('height');var src=cols[c].getAttribute('src');var href=cols[c].getAttribute('href');var newImg=document.createElement('img');if(w){newImg.width=w;}
if(h){newImg.height=h;}
newImg.src=src;if(href){var link=document.createElement('a');link.href=href;link.target="_blank";link.appendChild(newImg);valueParent.appendChild(link);} else {valueParent.appendChild(newImg);}} else {valueParent.appendChild(document.createTextNode(cols[c].getAttribute('value')));}
resultsRow.appendChild(valueParent);}
resultsBody.appendChild(resultsRow);}
parent.appendChild(resultsTable);}
function ServiceForm (EventManager, serviceXMLObj, serviceMap){var ServiceFormId='ServiceForm-';var FormTableId=ServiceFormId+serviceXMLObj.getAttribute('title');this.clearForm=function(){var rootElement=document.getElementById(FormTableId);if(rootElement&&rootElement.parentNode){var p=rootElement.parentNode;p.removeChild(rootElement);}}
function createInputArray(tableId){var table=document.getElementById(tableId);var inputs=table.getElementsByTagName('input');var inputValues=new Array();for(var i=0; i<inputs.length; i++){inputValues[inputs[i].name]=inputs[i].value;}
inputs=null;var selects=table.getElementsByTagName('select');for(var i=0; i<selects.length; i++){var options=selects[i].getElementsByTagName('option');inputValues[selects[i].name]=options[selects[i].selectedIndex].value;options=null;}
selects=null;table=null;return inputValues;}
this.setParent=function(p){var divId=serviceXMLObj.getAttribute('div');if(divId){this.renderFromDiv(p, divId);} else {this.renderDefault(p);}}
this.renderFromDiv=function(p,divId){var parent=document.getElementById(p);var div=document.getElementById(divId);parent.innerHTML=div.innerHTML;var inputs=parent.getElementsByTagName('input');var searchButton=null, cancelButton=null;for(var i=0; i<inputs.length; i++){var inputType=new String(inputs[i].type);if(inputType.match(/submit/)){inputs[i].onclick=function (){var values=createInputArray(p);var submitInputs=serviceXMLObj.getElementsByTagName('input');for(var i=0; i<submitInputs.length; i++){submitInputs[i].setAttribute('value', values[submitInputs[i].getAttribute('name')]);}
if(this.getAttribute("url")){var urls=serviceXMLObj.getElementsByTagName('url');if(urls.length>0){urls[0].firstChild.nodeValue=this.getAttribute('url');} else {var parentDoc=serviceXMLObj.parentNode;while(parentDoc.parentNode){parentDoc=parentDoc.parentNode;}
var newUrl=parentDoc.createElement('url');newUrl.appendChild(parentDoc.createTextNode(this.getAttribute('url')));serviceXMLObj.appendChild(newUrl);}}
EventManager.triggerEvent('callservice', serviceXMLObj);}
searchButton=i;} else if(inputType.match(/reset/)){inputs[i].onclick=function(){EventManager.triggerEvent('cancelservice', serviceXMLObj);}} else if(inputType.match(/text/)){inputs[i].onkeyup=function(event){if(window.event){event= window.event;}
if(event.keyCode==13){if(searchButton){inputs[searchButton].onclick();}} else if(event.keyCode==27){if(cancelButton){inputs[cancelButton].onclick();}}}}}}
this.renderDefault=function(p){document.getElementById(p).innerHTML='';var formTable=document.createElement('table');document.getElementById(p).appendChild(formTable);formTable.setAttribute('id', FormTableId);var formBody=document.createElement('tbody');formTable.appendChild(formBody);var inputs=serviceXMLObj.getElementsByTagName('input');var userInputs=0;var invalids=0;for(var i=0; i<inputs.length; i++){var newInputRow=document.createElement('tr');var inputTitleCell=document.createElement('th');inputTitleCell.className='InputTitleCell';if(inputs[i].getAttribute('title')&&inputs[i].getAttribute('title') != 'null'){inputTitleCell.appendChild(document.createTextNode(inputs[i].getAttribute('title')));}
formBody.appendChild(newInputRow);var newInputCell=document.createElement('td');newInputRow.appendChild(inputTitleCell);newInputRow.appendChild(newInputCell);var inputType=new String(inputs[i].getAttribute('type')).toLowerCase();if(inputType=='user'){var inputObj=document.createElement('input');if(inputs[i].getAttribute('value')&&inputs[i].getAttribute('value') != 'null'){inputObj.value=inputs[i].getAttribute('value');}
inputObj.name=inputs[i].getAttribute('name');var validateType=inputs[i].getAttribute('validate');if(validateType&&validateType != 'null'){validateType=validateType.toUpperCase();if(VALIDATE_FUNCTIONS[validateType]){inputObj.onchange=function (event){if(window.event){event=window.event;}
var value=!eval(VALIDATE_FUNCTIONS[validateType]+'("'+this.value+'")');if(value){this.style.background=SERVICES_INVALID_BACKGROUND;this.setAttribute('invalid', 'true');invalids++;} else if(this.getAttribute('invalid')){this.style.background='';invalids--;}
return preventDefaultEvent(event);}}}
newInputCell.appendChild(inputObj);userInputs++;} else if(inputType=='select'){var selectObj=document.createElement('select');selectObj.name=inputs[i].getAttribute('name');var options=inputs[i].getElementsByTagName('option');for(var o=0; o<options.length; o++ ){var option=document.createElement('option');option.value=options[o].getAttribute('value');option.appendChild(document.createTextNode(options[o].firstChild.nodeValue));selectObj.appendChild(option);}
newInputCell.appendChild(selectObj);userInputs++;} else if(inputType=='hidden'){var newInput=document.createElement('input');newInput.type='hidden';newInput.name=inputs[i].getAttribute('name');newInput.value=inputs[i].getAttribute('value');formBody.appendChild(newInput);} else if(inputType=='checkbox'){var newInput=document.createElement('input');newInput.name=inputs[i].getAttribute('name');newInput.value=inputs[i].getAttribute('value');newInput.type='checkbox';newInputCell.appendChild(newInput);newInput.checked=parseBoolean(inputs[i].getAttribute('checked'));userInputs++;} else if(inputType=='radio'){var hiddenValue=document.createElement('input');hiddenValue.type='hidden';hiddenValue.name=inputs[i].getAttribute('name');formBody.appendChild(hiddenValue);var options=inputs[i].getElementsByTagName('option');var checked=true;for(var o=0; o<options.length; o++){var radio=document.createElement('input');radio.name=inputs[i].getAttribute('name');radio.value=options[o].getAttribute('value');radio.type='radio';radio.checked=checked;newInputCell.appendChild(radio);newInputCell.appendChild(document.createTextNode(options[o].firstChild.nodeValue));newInputCell.appendChild(document.createElement('br'));if(checked){hiddenValue.value=radio.value;}
radio.onclick=function (){hiddenValue.value=this.value;}
checked=false;}} else if(inputType=='layers'){var layers=serviceMap.getLayerURLs();var name=inputs[i].getAttribute('name');var delim=inputs[i].getAttribute('delim');var value='';for(var layer in layers){value=value+serviceMap.preprocessURL('image',layer)+delim;}
value=value.substring(0,value.length-1);var newInput=document.createElement('input');newInput.name=name;newInput.value=escape(value);newInput.type='hidden';formBody.appendChild(newInput);} else if(inputType=='legends'){var layers=serviceMap.getLayerURLs();var name=inputs[i].getAttribute('name');var delim=inputs[i].getAttribute('delim');var value='';for(var layer in layers){value=value+serviceMap.preprocessURL('legend',layer)+delim;}
value=value.substring(0,value.length-1);var newInput=document.createElement('input');newInput.name=name;newInput.value=escape(value);newInput.type='hidden';formBody.appendChild(newInput);} else if(inputType=='opacity'){var layers=serviceMap.getLayerURLs();var name=inputs[i].getAttribute('name');var delim=inputs[i].getAttribute('delim');var value='';for(var layer in layers){value=value+serviceMap.getOpacity(layer)+delim;}
value=value.substring(0,value.length-1);var newInput=document.createElement('input');newInput.name=name;newInput.value=escape(value);newInput.type='hidden';formBody.appendChild(newInput);} else if(inputType=='extent'){var newInput=document.createElement('input');var delim=inputs[i].getAttribute('delim');newInput.type='hidden';newInput.name=inputs[i].getAttribute('name');newInput.value=serviceMap.getExtent(delim);formBody.appendChild(newInput);} else if(inputType=='layertitles'){var newInput=document.createElement('input');var delim=inputs[i].getAttribute('delim');newInput.type='hidden';newInput.name=inputs[i].getAttribute('name');var layers=serviceMap.getLayerTitles();var str='';for(var l=0; l<layers.length; l++){if(delim==" "){layers[l]=layers[l].replace(' ','');}
str += delim+layers[l];}
str=str.substring(1);newInput.value=str;formBody.appendChild(newInput);} else if(inputType=='title'){var newInput=document.createElement('input');newInput.name=inputs[i].getAttribute('name');var v=inputs[i].getAttribute('value');if(v&&v != 'null'){newInput.value=v;}
newInputCell.appendChild(newInput);newInput.onchange=function (event){if(window.event){event=window.event;}
if(!this.value){alert ('Drawing objects must have a name!');}
var layers=serviceMap.getLayerTitles();for(var l=0; l<layers.length; l++){if(this.value==layers[l]){alert('Already a layer named '+this.value);this.value='';return preventDefaultEvent(event);}}
return true;}
userInput++;newInput=null;} else if(inputType=='selection'){var delim=inputs[i].getAttribute('delim');var layerName=inputs[i].getAttribute('layer');var name=inputs[i].getAttribute('name');if(layerName){var newInput=document.createElement('input');newInput.name=name;var selections=serviceMap.getLayerSelection(layerName);if(selections.length>0){var str=selections[0];for(var sel=1; sel<selections.length; sel++){str += delim+selections[sel];}
newInput.value=str;}
newInputCell.appendChild(newInput);newInput.type='hidden';} else {var selectObj=document.createElement('select');selectObj.name=name;var layers=serviceMap.getLayerTitles();var found=false;newInputCell.appendChild(selectObj);for(var layer=0; layer<layers.length; layer++){var selections=serviceMap.getLayerSelection(layers[layer]);if(selections&&selections.length>0){found=true;var opt=document.createElement('option');selectObj.appendChild(opt);var str=selections[0];for(var sel=1; sel<selections.length; sel++){str += delim+selections[sel];}
opt.appendChild(document.createTextNode(layers[layer]));opt.value=str;}}
if(!found){selectObj.disabled=true;var opt=document.createElement('option');selectObj.appendChild(opt);opt.appendChild(document.createTextNode('No Layers Selected!'));}
userInputs++;}} else if(inputType=='area'){var selectObj=document.createElement('select');selectObj.name=inputs[i].getAttribute('name');var areas=serviceMap.getDrawingAreas();for(var area in areas){var option=document.createElement('option');option.value=areas[area];option.appendChild(document.createTextNode(area));selectObj.appendChild(option);}
newInputCell.appendChild(selectObj);userInputs++;} else if(inputType=='visiblelayer'){var layers=serviceMap.getLayerTitles();var selectObj=document.createElement('select');selectObj.name=inputs[i].getAttribute('name');selectObj.style.width='150px';newInputCell.appendChild(selectObj);var nullOpt=document.createElement('option');selectObj.appendChild(nullOpt);nullOpt=null;for(var layer=0; layer<layers.length; layer++){var option=document.createElement('option');option.value=layers[layer];selectObj.appendChild(option);option.appendChild(document.createTextNode(layers[layer]));option=null;}
selectObj=null;userInputs++;} else if(inputType=='length'){var newInput=document.createElement('input');newInput.type='hidden';newInput.name=inputs[i].getAttribute('name');newInput.setAttribute('id','ServiceForm-'+newInput.name);var userInput=document.createElement('input');userInput.setAttribute('id', newInput.getAttribute('id')+'-Source');userInput.targetId=newInput.getAttribute('id');userInput.sourceId=userInput.getAttribute('id');var v=inputs[i].getAttribute('value');if(!v||v=='null'){userInput.setAttribute('value', '0');} else {userInput.setAttribute('value', v);}
newInput.setAttribute('value', userInput.getAttribute('value'));newInputCell.appendChild(newInput);newInputCell.appendChild(userInput);newInputCell.appendChild(document.createElement('br'));var groundUnits=document.createElement('select');groundUnits.setAttribute('id',newInput.getAttribute('id')+'-Units');newInputCell.appendChild(groundUnits);populateUnitConversionSelection('length', groundUnits);groundUnits.targetId=newInput.getAttribute('id');groundUnits.sourceId=userInput.getAttribute('id');groundUnits.unitId=groundUnits.getAttribute('id');userInput.unitId=groundUnits.getAttribute('id');groundUnits.onchange=function (){var src=document.getElementById(this.sourceId);var target=document.getElementById(this.targetId);var units=document.getElementById(this.unitId);var opts=units.getElementsByTagName('option');var v=src.value;if(units.selectedIndex>=0){var selOpt=opts[units.selectedIndex];var unitCheck=new String(selOpt.value);v=Math.round(v*UNIT_CONVERSION[selOpt.value][MAP_GROUND_UNITS]);target.value=v;}}
userInput.onchange=groundUnits.onchange;groundUnits=null;newInput=null;userInput=null;userInputs++;}
newInputCell=null;newInputRow=null;}
var cancelSubmitRow=document.createElement('tr');var cancelButton=document.createElement('button');cancelButton.appendChild(document.createTextNode('Cancel'));var searchButton=document.createElement('button');searchButton.appendChild(document.createTextNode('OK'));var cancelCell=document.createElement('td');var searchCell=document.createElement('td');searchCell.style.textAlign='right';cancelCell.appendChild(cancelButton);searchCell.appendChild(searchButton);cancelSubmitRow.appendChild(cancelCell);cancelSubmitRow.appendChild(searchCell);formBody.appendChild(cancelSubmitRow);cancelButton.onclick=function(){EventManager.triggerEvent('cancelservice', serviceXMLObj);}
searchButton.onclick=function (){if(invalids<=0){var values=createInputArray(FormTableId);var inputs=serviceXMLObj.getElementsByTagName('input');for(var i=0; i<inputs.length; i++){inputs[i].setAttribute('value', values[inputs[i].getAttribute('name')]);}
EventManager.triggerEvent('callservice', serviceXMLObj);} else {alert(SERVICES_INVALID_MESSAGE);}}
formBody.searchButton=searchButton;formBody.onkeyup=function (event){if(window.event){event=window.event;}
if(event.keyCode==13){if(invalids<=0){this.searchButton.onclick();}}}
if(userInputs<=0){searchButton.onclick();}
searchButton=null;cancelButton=null;cancelCell=null;searchCell=null;cancelSubmitRow=null;formBody=null;formTable=null;}}
function ServiceManager(EventManager, ServiceMap){var ServiceFormParent=null;var ServiceChildren=new Array();var activeServices=new Array();var knownServices=new Array();this.addService=function(servXMLobj){var title=servXMLobj.getAttribute('title');activeServices[title]=servXMLobj;}
this.removeService=function(servTitle){if(activeServices[servTitle]){delete activeServices[servTitle];}}
this.onloadMapbook=function(mapbookXML){var services=mapbookXML.getElementsByTagName('service');for(var s=0; s<services.length; s++){var title=services[s].getAttribute('title');knownServices[title]=services[s];}}
this.spawnParent=function(title){return document.getElementById(ServiceFormParent);}
this.clearParent=function(title){return false;}
var MySelf=this;function renderServiceForm(serviceXMLObj){var servTitle=serviceXMLObj.getAttribute('title');var serviceForm=new ServiceForm(EventManager, serviceXMLObj, ServiceMap);var formParent=MySelf.spawnParent(servTitle);if(formParent){ServiceChildren[servTitle]=serviceForm;serviceForm.setParent(formParent.getAttribute('id'));} else {alert('Service Form Parent not set! Unable to render service object!');}
serviceXMLObj=null;}
this.serviceForm=function(serviceXMLObj){var servTitle=serviceXMLObj.getAttribute('title');if(serviceXMLObj.getAttribute('shape')&&!serviceXMLObj.getAttribute('shape').match(/none/i)){var mapBook=serviceXMLObj;while(mapBook.parentNode){mapBook=mapBook.parentNode;}
if(ServiceFormParent){var shape=new String(serviceXMLObj.getAttribute('shape')).toLowerCase();if(!shape||shape=='null'){shape='point';}
document.getElementById(ServiceFormParent).innerHTML='<b>'+SHAPE_MESSAGES[shape]+'</b>';}
EventManager.addEventListener('changetool','ServInspect', function (){EventManager.removeEventListener('changetool','ServInspect');EventManager.removeEventListener('finishdrawing', 'ServInspect');});EventManager.addEventListener('finishdrawing','ServInspect', function(p){document.getElementById(ServiceFormParent).innerHTML='';EventManager.triggerEvent('changetab', servTitle.toUpperCase());var serviceXML=mapBook.createElement('service');var shape=serviceXMLObj.getAttribute('shape');var url=mapBook.createElement('url');url.appendChild(mapBook.createTextNode(serviceXMLObj.getElementsByTagName('url')[0].firstChild.nodeValue));serviceXML.appendChild(url);var inputs=serviceXMLObj.getElementsByTagName('input');var copyAttributes=['name','title','value','delim','display','return','selectable','shape','target','validate','div','checked'];for(var i=0; i<copyAttributes.length; i++){var v=serviceXMLObj.getAttribute(copyAttributes[i]);if(v){serviceXML.setAttribute(copyAttributes[i], v);}}
if(shape=='box'){shape='poly';}
var latLong=new Point();if(window.toLatLong){var sysArr=(new String(MAP_COORDINATE_SYSTEM)).split('-');var unitConversion=new Point(p[0].x, p[0].y);var llPoint=window.toLatLong(sysArr[1], unitConversion);latLong=llPoint;}
for(var i=0; i<inputs.length; i++){var newInput=mapBook.createElement('input');var inputType=new String(inputs[i].getAttribute('type')).toLowerCase();for(var attr=0; attr<copyAttributes.length; attr++){newInput.setAttribute(copyAttributes[attr], new String(inputs[i].getAttribute(copyAttributes[attr])));}
if(inputType=='point'){var delim=inputs[i].getAttribute('delim');if(!delim){delim=',';}
var pValue=p[0].toString(delim);newInput.setAttribute('type','hidden');newInput.setAttribute('value', pValue);} else if(inputType.match(/point.x/)){newInput.setAttribute('type','hidden');newInput.setAttribute('value', p[0].x);} else if(inputType.match(/point.y/)){newInput.setAttribute('type','hidden');newInput.setAttribute('value', p[0].y);} else if(inputType.match(/point.lat/)){newInput.setAttribute('type','hidden');newInput.setAttribute('value', latLong.y);} else if(inputType.match(/point.long/)){newInput.setAttribute('type','hidden');newInput.setAttribute('value', latLong.x);} else if(inputType.match(/multipoint/)){var delim=inputs[i].getAttribute('delim');var pairDelim=inputs[i].getAttribute('pointdelim');if(!delim){delim=',';}
if(!pairDelim){pairDelim=' ';}
var value='';if(shape&&(shape.match(/poly/i)||shape.match(/measurearea/i))){p[p.length]=p[0];}
for(var pi=0; pi<p.length; pi++){var pValue=p[pi].toString(delim);value=value+pairDelim+pValue;}
value=value.substring(1);newInput.setAttribute('type','hidden');newInput.setAttribute('value', value);} else if(inputType.match(/multipoint.x/)){var delim=inputs[i].getAttribute('delim');if(!delim){delim=',';}
var value='';p[p.length]=p[0];for(var pi=0; pi<p.length; pi++){var pValue=p[pi].x;value=value+delim+pValue;}
value=value.substring(1);newInput.setAttribute('type','hidden');newInput.setAttribute('value', value);} else if(inputType.match(/multipoint.y/)){var delim=inputs[i].getAttribute('delim');if(!delim){delim=',';}
var value='';p[p.length]=p[0];for(var pi=0; pi<p.length; pi++){var pValue=p[pi].y;value=value+delim+pValue;}
value=value.substring(1);newInput.setAttribute('type','hidden');newInput.setAttribute('value', value);} else if(inputType.match(/select$/i)){newInput.setAttribute('type', 'select');var options=inputs[i].getElementsByTagName('option');for(var o=0; o<options.length; o++){var opt=mapBook.createElement('option');newInput.appendChild(opt);opt.setAttribute('value', options[o].getAttribute('value'));opt.appendChild(mapBook.createTextNode(options[o].firstChild.nodeValue));}} else if(inputType.match(/today/i)||inputType.match(/date/i)){var formatString=inputs[i].getAttribute('format');if(!formatString){formatString='%M/%D/%Y';}
var offset=inputs[i].getAttribute('offset');if(offset){offset=parseInt(offset)*86400000;} else {offset=0;}
var d=new Date();var dateString=inputs[i].getAttribute('date');if(dateString){d=new Date(dateString);}
newInput.setAttribute('type','hidden');newInput.setAttribute('value',strfdate(new Date(d.getTime()+offset), formatString));} else {newInput.setAttribute('type', inputs[i].getAttribute('type'));}
serviceXML.appendChild(newInput);}
renderServiceForm(serviceXML);serviceXML=null;ServiceMap.clearDrawingArea();});if(!shape||shape=='null'){shape='poly';}
ServiceMap.loadDrawTool(shape, true);if(serviceXMLObj.getAttribute('cursor')){ServiceMap.setMapCursor(serviceXMLObj.getAttribute('cursor'));}
return false;}
renderServiceForm(serviceXMLObj);}
this.clearServiceForm=function(serviceXMLObj){var servTitle=serviceXMLObj.getAttribute('title');if(ServiceChildren[servTitle]){ServiceChildren[servTitle].clearForm();}
MySelf.clearParent(serviceXMLObj);}
this.setParent=function(p){ServiceFormParent=p;}
this.serviceCount=function(){var i=0;for(var l in activeServices){i++;}
alert(i+' active services.');}
this.startupService=function(title){var serviceXML=knownServices[title];var inputs=serviceXML.getElementsByTagName('input');var cgi=new CGI();var url=serviceXML.getElementsByTagName('url')[0].firstChild.nodeValue;url=url+'?';for(var i=0; i<inputs.length; i++){var iType=inputs[i].getAttribute('type');var iName=inputs[i].getAttribute('name');if(iType.match(/user/i)){inputs[i].setAttribute('value', cgi.param(iName));}}
EventManager.triggerEvent('callservice', serviceXML);}
var resultsContainerId='';this.setResultsContainerId=function (rid){resultsContainerId=rid;}
this.startService=function(title){EventManager.triggerEvent('serviceform', knownServices[title]);}
this.callService=function(serviceXMLObj){if(SERVICE_WAITING_DIV){var msg=document.getElementById(SERVICE_WAITING_DIV);if(msg){document.getElementById(ServiceFormParent).innerHTML=msg.innerHTML;}}
var url=ProcessURL(ServiceMap,serviceXMLObj);logDebugMessage('Service Call', false, url);var serviceType=new String(serviceXMLObj.getAttribute('type'));var returnType=serviceXMLObj.getAttribute('return');var displayType=serviceXMLObj.getAttribute('display');var postRequired=serviceType.match(/xmlpost/);if(!returnType||returnType=='null'){returnType='xml';}
if(!displayType||displayType=='null'){displayType='div';}
if(displayType.match(/window/i)){var elm=document.createElement('return');elm.setAttribute('display','window');elm.setAttribute('title', serviceXMLObj.getAttribute('title'));var winElm=document.createElement('window');var winTarget=serviceXMLObj.getAttribute('target');winElm.setAttribute('target', winTarget);winElm.appendChild(document.createTextNode(url));elm.appendChild(winElm);EventManager.triggerEvent('servicereturn', elm);winElm=null
elm=null;if(winTarget){window.open(url, winTarget);} else {window.open(url);}
EventManager.triggerEvent('lasttab','');} else {var http=getHTTPObject();var method='GET';var postInfo=null;if(url.length>1000||postRequired){method='POST';var urlArr=url.split('?');url=urlArr[0];postInfo=urlArr[1];}
if(postRequired){var xmlDoc=new xmlDocument();var inputs=serviceXMLObj.getElementsByTagName('input');for(var i=0; i<inputs.length; i++){var inputType=new String(inputs[i].getAttribute('type'));var root=xmlDoc.cleanPath(inputs[i].getAttribute('name'));if(inputType.match(/layerslist/)){var layers=ServiceMap.getLayersByZIndex();var urls=ServiceMap.getLayerURLs();var preprocessed=!(new String(inputs[i].getAttribute('processed')).match(/false/));for(var l=0; l<layers.length; l++){if(layers[l] != 'NAVIGATION'){var mapRoot=root+'/map['+l+']/';xmlDoc.buildPath(mapRoot+'@title', layers[l]);xmlDoc.buildPath(mapRoot+'@zindex', l+1);xmlDoc.buildPath(mapRoot+'@opacity', Map.getOpacity(layers[l]));if(preprocessed){xmlDoc.buildPath(mapRoot+'file[0]', ServiceMap.preprocessURL('image',layers[l]));xmlDoc.buildPath(mapRoot+'legend[0]', ServiceMap.preprocessURL('legend',layers[l]));} else {xmlDoc.buildPath(mapRoot+'file[0]', urls[layers[l]]);var params=ServiceMap.getLayerParameters(layers[l]);var p=0;for(var pName in params){xmlDoc.buildPath(mapRoot+'param['+p+']/@name', pName);xmlDoc.buildPath(mapRoot+'param['+p+']/@value', params[pName]);p++;}}}}} else if(inputType.match(/popups/)){var popupRoot=root+'/popups[0]/';var popups=ServiceMap.getVisiblePopupIds();for(var p=0; p<popups.length; p++){var popup=document.getElementById(popups[p]);var popupTitle=ServiceMap.getPopupTitle(popups[p]);var contents=document.getElementById(popups[p]+'-Contents');var title=document.getElementById(popups[p]+'-Title');var map=document.getElementById(ServiceMap.getParent());var mapXY=objectClientPosition(map);var popupXY=objectClientPosition(popup);var popupEntry=popupRoot+'popup['+p+']';var gXY=ServiceMap.pointToGroundUnits(new Point(popupXY.x-mapXY.x, popupXY.y-mapXY.y+40));var gmaxXY=ServiceMap.pointToGroundUnits(new Point(popup.offsetLeft+popup.offsetWidth, popup.offsetTop+popup.offsetHeight));var contentsString='';var waitingForValue=0;var xx=0;for(var node=0; node<contents.childNodes.length; node++){var n=contents.childNodes[node];if(n.className){if(n.className=='itemTitle'){contentsString += n.innerHTML;} else if(n.className=='itemValue'){contentsString += n.innerHTML+'\n';}
waitingForValue++;}
xx++;}
xmlDoc.buildPath(popupEntry, contentsString);xmlDoc.buildPath(popupEntry+'/@title', popupTitle);xmlDoc.buildPath(popupEntry+'/@x', gXY.x);xmlDoc.buildPath(popupEntry+'/@y', gXY.y);xmlDoc.buildPath(popupEntry+'/@maxx', gmaxXY.x);xmlDoc.buildPath(popupEntry+'/@maxy', gmaxXY.y);xmlDoc.buildPath(popupEntry+'/@contentscolor', contents.style.backgroundColor);xmlDoc.buildPath(popupEntry+'/@titlecolor', title.style.backgroundColor);}} else {xmlDoc.buildPath(root,inputs[i].getAttribute('value'));}}
postInfo=xmlDoc.getXMLText();}
http.open(method, url, true);if(method=='POST'&&!serviceType.match(/xmlpost/)){http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");} else if (serviceType.match(/xmlpost/)){http.setRequestHeader("Content-type", "text/xml");}
http.onreadystatechange=function (){if(http.readyState==4){var results=null;var contentType=http.getResponseHeader('Content-Type');if(returnType.match(/html/i)||contentType.match(/html/i)){var htmlSrc=http.responseText;try {var xmlObj=new xmlDocument();xmlObj.createXMLFromString(http.responseText);var xmlDoc=xmlObj.getDocument();if(xmlDoc){var mapbookFragment=getElementsByTagNameNS(xmlDoc, MAPBOOK_NAMESPACE_URI, MAPBOOK_NAMESPACE_PREFIX, 'mapbook');var mbXML=new xmlDocument();mbXML.setRoot(mapbookFragment[0]);mbXML.createXMLFromString(mbXML.stripNamespace(MAPBOOK_NAMESPACE_PREFIX));var mbDoc=mbXML.getDocument();loadDefaultsFromMapBook(mbDoc, mbDoc, EventManager, ServiceMap);var body=xmlDoc.getElementsByTagName('body')[0];if(body.childNodes[0].nodeName=='#cdata-section'){htmlSrc=xmlDoc.getElementsByTagName('body')[0].childNodes[0].data;} else {htmlSrc=xmlObj.getXMLText();}} else {htmlSrc=xmlObj.getXMLText();}} catch(e){}
var elm=document.createElement('return');elm.setAttribute('display','div');elm.setAttribute('title', serviceXMLObj.getAttribute('title'));EventManager.triggerEvent('servicereturn', elm);document.getElementById(resultsContainerId).innerHTML=htmlSrc;EventManager.triggerEvent('changetab', TABS_RESULTS_NAME);} else if(returnType.match(/text/i)||contentType.match(/plain/i)){var results=document.getElementById('content_results_form');var text=http.responseText;if(!(text.match(/\<html/))){text=text.replace(/\n/g,'<br/>\n');text='<tt>'+text+'</tt>';}
results.innerHTML=text;EventManager.triggerEvent('changetab',TABS_RESULTS_NAME);} else if(returnType.match(/csv/i)||contentType.match(/csv/i)){var results=document.getElementById(resultsContainerId);results.innerHTML='';var text=http.responseText;var arr=ParseCSV(text);var table=document.createElement('table');results.appendChild(table);var p=document.createElement('tbody');table.appendChild(p);var headerRow=document.createElement('tr');p.appendChild(headerRow);for(var col=0; col<arr[0].length; col++){var th=document.createElement('th');headerRow.appendChild(th);th.appendChild(document.createTextNode(arr[0][col]));th.innerHTML=th.innerHTML+'&nbsp;';th=null;}
headerRow=null;for(var row=1; row<arr.length-1; row++){var tr=document.createElement('tr');p.appendChild(tr);for(var col=0; col<arr[0].length; col++){var td=document.createElement('td');tr.appendChild(td);td.appendChild(document.createTextNode(arr[row][col]));td.innerHTML=td.innerHTML+'&nbsp;';td=null;}
tr=null;}
EventManager.triggerEvent('changetab',TABS_RESULTS_NAME);results=null;table=null;p=null;} else {var returnXML=http.responseXML;var servTitle=serviceXMLObj.getAttribute('title');if(http.responseXML){document.getElementById(resultsContainerId).innerHTML='';processXMLWithXSLT(http.responseXML, XSL_RESULTS, resultsContainerId);results=http.responseXML.getElementsByTagName('return')[0];if(!results){results=http.responseXML.getElementsByTagName('results')[0];}
var windowsToOpen=http.responseXML.getElementsByTagName('window');for(var i=0; i<windowsToOpen.length; i++){var url=windowsToOpen[i].firstChild.nodeValue;if(url){var target=windowsToOpen[i].getAttribute('target');if(target&&target != 'null'&&target != 'blank'){window.open(url, target);} else {window.open(url);}}}
loadDefaultsFromMapBook(http.responseXML, null, EventManager, ServiceMap);} else {alert('The service "'+servTitle+'" did not return XML!');}
results.setAttribute('title', serviceXMLObj.getAttribute('title'));if(serviceXMLObj.getAttribute('display')){results.setAttribute('display', serviceXMLObj.getAttribute('display'));}
var rows=returnXML.getElementsByTagName('row');var errors=returnXML.getElementsByTagName('error');var showTest=rows.length+errors.length;if(showTest>0){EventManager.triggerEvent('changetab',TABS_RESULTS_NAME);} else if(serviceXMLObj.getAttribute('display') != 'none'){EventManager.triggerEvent('lasttab','');}
EventManager.triggerEvent('servicereturn', results);}}};http.send(postInfo);}}}
var VIEWBOX_INSTANCE=0;function ViewBox(EventManager, ViewMap){var ViewListId='ViewBox'+VIEWBOX_INSTANCE+'-';VIEWBOX_INSTANCE++;var ViewBoxRendered=false;var KnownViews=new Array();var TargetFilter=false;this.setTargetFilter=function(filter){TargetFilter=new String(filter);}
this.addView=function(viewXMLObj){var title=viewXMLObj.getAttribute('title');var target=viewXMLObj.getAttribute('target');if(!TargetFilter||TargetFilter.match(target,'i')){KnownViews[title]=viewXMLObj;if(ViewBoxRendered){addViewToList(document.getElementById(ViewListId+'List'), viewXMLObj);} else {if(document.getElementById(ViewListId+'List')){refreshViewBox();ViewBoxRendered=true;}}}}
function addViewToList(viewList, viewXMLObj){var title=viewXMLObj.getAttribute('title');var option=document.createElement('option');option.appendChild(document.createTextNode(title));option.setAttribute('id',ViewListId+'Option-'+title);option.value=viewXMLObj.firstChild.nodeValue;viewList.appendChild(option);option=null;}
this.removeView=function(viewTitle){if(KnownViews[viewTitle]){delete KnownViews[viewTitle];}
refreshViewBox();}
function refreshViewBox(){if(document.getElementById(ViewListId+'List')){var vList=document.getElementById(ViewListId+'List');var vOptions=vList.getElementsByTagName('option');for(var i=vOptions.length-1; i>0; i--){vList.removeChild(vOptions[i]);}
for(view in KnownViews){addViewToList(vList, KnownViews[view]);}}}
function changeView(){var viewsList=this;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;}
this.setParent=function(p){var viewsList=document.createElement('select');viewsList.setAttribute('id', ViewListId+'List');viewsList.appendChild(document.createElement('option'));viewsList.onchange=changeView;refreshViewBox();p.appendChild(viewsList);viewsList=null;}}
var SCALE_BOX_INSTANCE=0;function ScaleBox(EventManager, ScaleMap){var ScaleCenterPoint;var ScaleBoxInstance='ScaleBox'+SCALE_BOX_INSTANCE+'-';var ScaleInputId=ScaleBoxInstance+'Input-';var ScaleJumperId=ScaleBoxInstance+'Jumper-';SCALE_BOX_INSTANCE++;function changeScale(){EventManager.changePointScale(ScaleCenterPoint, inchScaleToPixelScale(ScaleMap, stripCommas(document.getElementById(ScaleInputId).value)));}
function jumpToScale(){var ScaleInput=document.getElementById(ScaleInputId);ScaleInput.value=this.getAttribute('scale');ScaleInput.onblur();changeScale();}
function getBackgroundFunction(color){return function(){this.style.background=color;};}
function populateScaleJumper(scaleInput, scaleJumper){for(var i in SCALEBOX_JUMPER_INCREMENTS){var link=document.createElement('input');link.style.display='block';link.style.color='black';link.style.textAlign='right';var offsetW=0;if(document.all){offsetW -= 6;}
link.style.width=scaleInput.offsetWidth+offsetW+'px';link.style.border='none';link.value=i;link.setAttribute('scale',SCALEBOX_JUMPER_INCREMENTS[i]);link.style.cursor='default';link.onfocus=onFocus;link.onmouseover=getBackgroundFunction('#DDD');link.onmouseout=getBackgroundFunction('white');link.onclick=jumpToScale;scaleJumper.appendChild(link);link=null;}}
function onFocus(event){var ScaleInput=document.getElementById(ScaleInputId);var ScaleJumper=document.getElementById(ScaleJumperId);if(window.event){event=window.event;}
var left=ScaleInput.offsetLeft;var top=ScaleInput.offsetTop+ScaleInput.offsetHeight;var width=ScaleInput.offsetWidth;if(document.all){left=objectClientPosition(ScaleInput).x;top += 4;}
ScaleInput.style.background='#DDD';ScaleJumper.style.visibility='visible';ScaleJumper.style.top='auto';ScaleJumper.style.bottom=top+'px';ScaleJumper.style.left=left+'px';ScaleJumper.style.right='auto';ScaleJumper.style.zIndex=10000;}
function onBlur(event){if(window.event){event=window.event;}
var ScaleJumper=document.getElementById(ScaleJumperId);var ScaleInput=document.getElementById(ScaleInputId);if(document.all&&event.srcElement==ScaleJumper){return false;}
ScaleInput.style.background='white';ScaleJumper.style.visibility='hidden';}
function onKeyPress(event){if(window.event){event=window.event;} 
if(event.keyCode==13){EventManager.changePointScale(ScaleCenterPoint, inchScaleToPixelScale(ScaleMap, stripCommas(this.value)));}
if(event.keyCode==27){this.value=Math.round(this.originalValue);}}
var CurrentScale;this.onNavigate=function (psScale){var scale=Math.round(pixelScaleToInchScale(ScaleMap, psScale.Radius));var ScaleInput=document.getElementById(ScaleInputId);if(ScaleInput){ScaleInput.value=commifyNumber(scale);ScaleInput.originalValue=scale;}
CurrentScale=scale;ScaleCenterPoint=psScale.Center;}
this.setParent=function (p){p=document.getElementById(p);var ScaleInput=document.createElement('input');ScaleInput.style.textAlign='right';ScaleInput.style.height='15px';ScaleInput.style.fontSize='13px';ScaleInput.size='12';ScaleInput.onblur=onBlur;ScaleInput.onkeypress=onKeyPress;if(CurrentScale){ScaleInput.value=commifyNumber(CurrentScale);ScaleInput.originalValue=CurrentScale;}
ScaleInput.setAttribute('id', ScaleInputId);p.appendChild(ScaleInput);var ScaleGo=document.createElement('input');ScaleGo.onclick=changeScale;if(document.all){ScaleGo.style.height='22px';}
ScaleGo.style.fontSize='13px';ScaleGo.value='Go!';ScaleGo.type='button';p.appendChild(ScaleGo);ScaleGo=null;var ScaleJumper=document.createElement('div');ScaleJumper.style.zIndex=10000;ScaleJumper.style.border='solid 3px black';ScaleJumper.style.visibility='hidden';ScaleJumper.style.position='absolute';ScaleJumper.style.bottom='1px';ScaleJumper.style.height='auto';ScaleJumper.style.background='white';ScaleJumper.setAttribute('id', ScaleJumperId);if(document.all){document.getElementsByTagName('body')[0].appendChild(ScaleJumper);} else {p.appendChild(ScaleJumper);}
ScaleJumper.onfocus=onFocus;ScaleInput.onfocus=onFocus;populateScaleJumper(ScaleInput, ScaleJumper);ScaleInput=null;ScaleJumper=null;}}
var LOADING_BAR_INSTANCE=0;function GLoadingBar(EventManager, LoadingMap){var LayersInQueue=new Array();var LayersToIgnore={};var LoadingBarId;var MyInstance=LOADING_BAR_INSTANCE;LOADING_BAR_INSTANCE++;this.addLayer=function(mapObjXML){var title=mapObjXML.getAttribute('title');var reference=new String(mapObjXML.getAttribute('reference')).toLowerCase();if(reference != 'only'){LayersInQueue[title]=0;} else {LayersToIgnore[title]=true;}}
this.removeLayer=function (title){var deleted='no';if(LayersInQueue[title]||LayersInQueue[title]==0){delete LayersInQueue[title];deleted='yes';}
if(allLoaded()){hideLoadingPanel();}}
function allLoaded(){for(var l in LayersInQueue){if(LayersInQueue[l]>0){return false;}}
return true;}
function hideLoadingPanel(){if(document.getElementById(LoadingBarId)){document.getElementById(LoadingBarId).style.visibility='hidden';}
if(document.getElementById('LoadingBarDisableNav'+MyInstance)){document.getElementById('LoadingBarDisableNav'+MyInstance).style.visibility='hidden';}}
function showLoadingPanel(){positionLoadingPanel();if(document.getElementById(LoadingBarId)){document.getElementById(LoadingBarId).style.visibility='visible';}
if(document.getElementById('LoadingBarDisableNav'+MyInstance)){document.getElementById('LoadingBarDisableNav'+MyInstance).style.visibility='visible';}}
this.loadedLayer=function (title){LayersInQueue[title]=0;if(allLoaded()){hideLoadingPanel();}}
this.getUnloadedList=function (){var list=new String();for(var l in LayersInQueue){if(LayersInQueue[l]>0){list=list+l+'\n';}}
return list;}
function positionLoadingPanel(){if(!LoadingBarId||!LoadingMap){return false;} 
var loadingBar=document.getElementById(LoadingBarId);var barWidth=loadingBar.offsetWidth;var mapWidth=LoadingMap.getMapSize().x;var mapHeight=LoadingMap.getMapSize().y;var mapLeft=0;var barHeight=loadingBar.offsetHeight;var barLeft=mapLeft+(mapWidth-barWidth )/2;var barTop=(mapHeight-barHeight)/2;loadingBar.style.left=barLeft+'px';loadingBar.style.top=barTop+'px';var disableNav=document.getElementById('LoadingBarDisableNav'+MyInstance);disableNav.style.top='0px';disableNav.style.left='0px';disableNav.style.width=mapWidth+'px';disableNav.style.height=mapHeight+'px';disableNav.className='LoadingBarDisableNav';}
var ReloadIteration=0;this.reloadAll=function (){for(var l in LayersInQueue){if(!LoadingMap.isRelativeLayer(l)){if(!LayersToIgnore[l]){LayersInQueue[l]=1;}}}
showLoadingPanel();ReloadIteration++;setTimeout("document.getElementById('"+LoadingBarId+"').timeout("+ReloadIteration+")",LOADING_TIMEOUT);}
this.reloadLayer=function (title){if(!LoadingMap.isRelativeLayer(title)){if(!LayersToIgnore[title]){LayersInQueue[title]=1;}}
showLoadingPanel();}
MySelf=this;function timeoutCheck(iteration){if(iteration==ReloadIteration&&!allLoaded()){var timeoutInSeconds=LOADING_TIMEOUT/1000;var unloadedList=MySelf.getUnloadedList();if(confirm('Timeout! The following layers took longer than '+timeoutInSeconds+' seconds to load:\n'+unloadedList+'Would you like me to remove it?')){var arr=unloadedList.split('\n');for(var i=0; i<arr.length; i++){EventManager.onRemoveLayer(arr[i]);}}
hideLoadingPanel();}}
this.setParent=function (p){var parent=document.getElementById(p);var loadingBar=document.createElement('div');loadingBar.className='LoadingBar';parent.appendChild(loadingBar);LoadingBarId='LoadingBar'+MyInstance;loadingBar.setAttribute('id', LoadingBarId);loadingBar.appendChild(document.createTextNode(LOADING_MESSAGE));loadingBar.appendChild(document.createElement('br'));loadingBar.timeout=timeoutCheck;var loadingImage=document.createElement('img');loadingImage.src=LOADING_IMAGE;loadingBar.appendChild(loadingImage);var disableNav=document.createElement('div');parent.appendChild(disableNav);disableNav.style.top='0px';disableNav.style.left='0px';disableNav.style.width=parent.offsetWidth+'px';disableNav.style.height=parent.offsetHeight+'px';disableNav.className='LoadingBarDisableNav';disableNav.setAttribute('id', 'LoadingBarDisableNav'+MyInstance);disableNav=null;loadingImage=null;loadingBar=null;positionLoadingPanel();}}
function createTab(name, title){var tab=document.createElement('a');tab.id="tab-"+name;tab.href="javascript:Events.triggerEvent('changetab','"+name+"')";tab.appendChild(document.createTextNode(title));return tab;}
function addTabPanel(parent){if(TABS_SHOW_PANEL){for(var i=0; i<TABS_TITLES.length; i++){parent.appendChild(createTab(TABS_TITLES[i], TABS_TITLES[i]));}
parent.getElementsByTagName('a')[0].className='selected';parent.style.visibility='visible';}}
function TabManager(titleBarObj, hiddenClassName, visibleClassName, EventManager){var tabs=new Array();var MySelf=this;var lastTab;var currentTab;this.getFirstTab=function(){for(var t in tabs){return t;}}
this.addTab=function(tabName, tabObject){tabs[tabName]=tabObject;}
this.removeTab=function(tabName){MySelf.hideAllTabs();if(tabs[tabName]){delete tabs[tabName];}
MySelf.showLastTab();}
this.hideAllTabs=function(){for(var t in tabs){var tab=document.getElementById(tabs[t]);tab.className=hiddenClassName;tab.scrollTop=0;tab=null;}}
this.getLastTab=function(){return lastTab;}
this.getCurrentTab=function(){return currentTab;}
this.showTab=function(tabName){if(tabName==currentTab){return true;}
MySelf.hideAllTabs();if(tabs[tabName]){document.getElementById(tabs[tabName]).className=visibleClassName;document.getElementById(titleBarObj).innerHTML =new String(tabName).toUpperCase();lastTab= currentTab;currentTab=tabName;}}
this.showLastTab=function(){if(!tabs[lastTab]){lastTab=MySelf.getFirstTab();}
EventManager.triggerEvent('changetab', lastTab);}
this.checkTab=function(tName){return (tabs[tName]);}
this.alertTabs=function (){var message='';for(t in tabs){message=message+t+' '+tabs[t]+'\n';}
alert(message);}}
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;var ScaleInterval=1;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();if(scaleChange != 0){SliderControl.style.top=(SliderControl.offsetTop+scaleChange*ScaleInterval)+'px';pointScale.Radius=scaleFromSliderPosition();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){if(!SLIDER_MAX_SCALE){SLIDER_MAX_SCALE=pixelScaleToInchScale(Map,psScale.Radius);}
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=pixelScaleToInchScale(Map,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;ScaleInterval=(SLIDER_MAX_PX-SLIDER_MIN_PX)/10;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.id, 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);ScaleInterval=(SLIDER_MAX_PX-SLIDER_MIN_PX)/10;increaseScale.onclick=function (event){MySelf.navigate(0,0,-1);}
decreaseScale.onclick=function (event){MySelf.navigate(0,0,1);}
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';function changeVisibility(vis){n.style.visibility=vis;e.style.visibility=vis;w.style.visibility=vis;s.style.visibility=vis;slider.style.visibility=vis;sliderControl.style.visibility=vis;}
this.getVisibility=function (){return(n.style.visibility);}
this.hideNavigator=function(){changeVisibility('hidden');}
this.showNavigator=function(){changeVisibility('visible');}
n.onclick=function (){MySelf.navigate(0,NORTH_SOUTH_PERCENTAGE,0);}
s.onclick=function (){MySelf.navigate(0,-1*NORTH_SOUTH_PERCENTAGE,0);}
e.onclick=function (){MySelf.navigate(EAST_WEST_PERCENTAGE,0,0);}
w.onclick=function (){MySelf.navigate(-1*EAST_WEST_PERCENTAGE,0,0);}
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();mapScale.Radius=scaleFromSliderPosition();EventManager.triggerEvent('navigate', mapScale);}}
function scaleFromSliderPosition(){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<.01){percent=0;}
if(percent>1){percent=1;}
return inchScaleToPixelScale(Map, scaleLen*percent+SLIDER_MIN_SCALE);}}
function NavigatorHistory(EventManager){var ViewHistory=new Array();var currentIndex=-1;this.onNavigate=function(viewCirc){if(!viewCirc.navigatorLog){currentIndex++;ViewHistory[currentIndex]=viewCirc;ViewHistory[currentIndex].navigatorLog=true;}}
this.previous=function (){currentIndex--;if(ViewHistory[currentIndex]){EventManager.triggerEvent('navigate', ViewHistory[currentIndex]);} else {currentIndex++;}}
this.next=function (){currentIndex++;if(currentIndex>=ViewHistory.length){currentIndex--;} else {EventManager.triggerEvent('navigate', ViewHistory[currentIndex]);}}}
function newDocument(rootTagName, namespaceURL){if (!rootTagName) rootTagName="";  if (!namespaceURL) namespaceURL="";  if(document.implementation&&document.implementation.createDocument){return document.implementation.createDocument(namespaceURL, rootTagName, null);}
  else {var doc=new ActiveXObject("MSXML2.DOMDocument");    if (rootTagName){var prefix="";      var tagname=rootTagName;      var p=rootTagName.indexOf(':');      if (p != -1){prefix=rootTagName.substring(0, p);        tagname=rootTagName.substring(p+1);}
      if (namespaceURL){if (!prefix) prefix="a0";}
      else prefix="";      var text="<"+(prefix?(prefix+":"):"")+tagname+(namespaceURL
           ?(" xmlns:"+prefix+'="'+namespaceURL +'"')
           :"")+"/>";      doc.loadXML(text);}
    return doc;}};function xmlDocument(root,namespace){var doc;if(root){doc=newDocument(root,namespace);}
this.cleanNode=function (node){var attr=node.split('@');var workingString=attr[0];if(!attr[0].match(/[a-zA-Z]+\[[0-9]+\]/)){var split=attr[0].split(/\[/);if(split[0]&&split[0] != 'null'){workingString=(split[0]+'[0]');}}
if(attr[1]&&attr[1] != 'null'){var attrDelim='/@';if(!attr[0]||attr[0]=='null'){attrDelim='@';}
workingString=workingString+attrDelim+attr[1];}
return workingString;}
this.cleanPath=function(path){var splitPath=path.split('/');var newPath="/";for(var i=1; i<splitPath.length; i++){newPath=newPath+this.cleanNode(splitPath[i])+'/';}
newPath=newPath.substring(0, newPath.length-1);return newPath;}
this.getNodeIndex=function(node){var nodeIndex=node.split('[')[1];nodeIndex=nodeIndex.replace(']','','g');return parseInt(nodeIndex);}
this.getNodeTag=function(node){return node.split('[')[0];}
this.buildPath=function (path,value){var splitPath=path.split('/');if(!doc){doc=newDocument(this.getNodeTag(splitPath[1]));}
var currentNode=doc.documentElement;for(var depth=2; depth<splitPath.length; depth++){var tagName=this.getNodeTag(splitPath[depth]);if(!tagName.match(/^@/)){var index=this.getNodeIndex(splitPath[depth]);var children=currentNode.getElementsByTagName(tagName);for(var i=0; i<=index; i++){if(!children[index]){currentNode.appendChild(doc.createElement(tagName));}}
currentNode=currentNode.getElementsByTagName(tagName)[index];}}
var finalTag=this.getNodeTag(splitPath[splitPath.length-1]);if(value){if(finalTag.match(/^@/)){finalTag=finalTag.replace('@','','g');currentNode.setAttribute(finalTag,value);} else {currentNode.appendChild(doc.createTextNode(value));}}}
this.getXMLText=function (){var xmlText='';if(doc.documentElement.xml){xmlText=doc.documentElement.xml;} else {var serializer=new XMLSerializer();xmlText=serializer.serializeToString(doc);}
return xmlText;}
this.stripNamespace=function (nameSpacePrefix){nameSpacePrefix=nameSpacePrefix+':';var xmlText=this.getXMLText();var regExp=new RegExp('<'+nameSpacePrefix, 'gi');var closeRegExp=new RegExp('</'+nameSpacePrefix, 'gi');xmlText=xmlText.replace(regExp, '<');xmlText=xmlText.replace(closeRegExp, '</');return xmlText;}
this.createXMLFromString=function(xmlString){if(xmlString.indexOf('<?xml')<0){xmlString='<?xml version="1.0"?>'+xmlString;}
if(window.ActiveXObject){var obj=new ActiveXObject("Msxml2.DOMDocument");obj.loadXML(xmlString);doc=obj;} else if(XMLSerializer){doc=(new DOMParser()).parseFromString(xmlString, "text/xml");}
return doc.documentElement;}
this.getDocument=function (){return doc;}
this.setRoot=function (nRoot){if(!doc){doc=newDocument();}
doc.appendChild(nRoot);}}
function processXMLWithXSLT(responseXML, xslFile, containerId, onFinish){var outputHTML='';var swappableSection=document.getElementById(containerId);var xslDoc;if(window.XSLTProcessor){xslDoc=document.implementation.createDocument("","",null);}
if(window.ActiveXObject){xslDoc=new ActiveXObject("Microsoft.XMLDOM");}
xslDoc.onreadystatechange=function(){if(xslDoc.readyState==4){if(window.XSLTProcessor){var xsltProcessor=new XSLTProcessor();xsltProcessor.importStylesheet(xslDoc);outputHTML=xsltProcessor.transformToFragment(responseXML, document);swappableSection.innerHTML='';swappableSection.appendChild(outputHTML);} else {outputHTML=responseXML.transformNode(xslDoc);swappableSection.innerHTML=outputHTML;}
if(onFinish){onFinish(containerId);}}}
if(window.XSLTProcessor){xslDoc.readyState=4;xslDoc.addEventListener('load', xslDoc.onreadystatechange, false);}
xslDoc.load(xslFile);}
function importNode(toDoc, importedNode, deep){if(typeof toDoc.importNode=="function"){return toDoc.importNode(importedNode, deep);} else {var newNode;if(importedNode.nodeType==1){newNode=toDoc.createElement(importedNode.nodeName);    for(var i=0; i<importedNode.attributes.length; i++){var attr=importedNode.attributes[i];if(attr.nodeValue != null&&attr.nodeValue != ''){newNode.setAttribute(attr.name, attr.nodeValue);}}
    if (typeof importedNode.style != "undefined")
newNode.style.cssText=importedNode.style.cssText;} else if(importedNode.nodeType==3){newNode=toDoc.createTextNode(importedNode.nodeValue);}
if(deep&&importedNode.hasChildNodes()){for(var i=0; i<importedNode.childNodes.length; i++){try {newNode.appendChild(
    importNode(toDoc, importedNode.childNodes[i], true)
);} catch(e){;}}}
return newNode;}}
var SUBSTITUTE_VARS=new Array();var SUBSTITUE_REQUIERES_POINTS=new Array();SUBSTITUTE_VARS['IMGSIZE']=function (urlMap,delim){return urlMap.getMapSize().toString(delim);}
SUBSTITUTE_VARS['IMGSIZE.X']=function (urlMap){return urlMap.getMapSize().x;}
SUBSTITUTE_VARS['IMGSIZE.Y']=function (urlMap){return urlMap.getMapSize().y;}
SUBSTITUTE_VARS['SIZE']=SUBSTITUTE_VARS['IMGSIZE'];SUBSTITUTE_VARS['IMAGESIZE']=SUBSTITUTE_VARS['IMGSIZE'];SUBSTITUTE_VARS['WIDTH']=SUBSTITUTE_VARS['IMGSIZE.X'];SUBSTITUTE_VARS['HEIGHT']=SUBSTITUTE_VARS['IMGSIZE.Y'];SUBSTITUTE_VARS['EXTENT']=function (urlMap,delim){return urlMap.getExtent(delim);}
SUBSTITUTE_VARS['EXTENT.MINX']=function (urlMap){return urlMap.getExtent(' ').split(' ')[0];}
SUBSTITUTE_VARS['EXTENT.MINY']=function (urlMap){return urlMap.getExtent(' ').split(' ')[1];}
SUBSTITUTE_VARS['EXTENT.MAXX']=function (urlMap){return urlMap.getExtent(' ').split(' ')[2];}
SUBSTITUTE_VARS['EXTENT.MAXY']=function (urlMap){return urlMap.getExtent(' ').split(' ')[3];}
SUBSTITUTE_VARS['EXTENTS']=SUBSTITUTE_VARS['EXTENT'];SUBSTITUTE_VARS['MINX']=SUBSTITUTE_VARS['EXTENT.MINX'];SUBSTITUTE_VARS['MINY']=SUBSTITUTE_VARS['EXTENT.MINY'];SUBSTITUTE_VARS['MAXX']=SUBSTITUTE_VARS['EXTENT.MAXX'];SUBSTITUTE_VARS['MAXY']=SUBSTITUTE_VARS['EXTENT.MAXY'];SUBSTITUTE_VARS['CENTERPOINT']=function(urlMap,delim){return urlMap.getCenterPoint().toString(delim);}
SUBSTITUTE_VARS['CENTERPOINT.X']=function (urlMap){return urlMap.getCenterPoint().x;}
SUBSTITUTE_VARS['CENTERPOINT.Y']=function (urlMap){return urlMap.getCenterPoint().y;}
SUBSTITUTE_VARS['SCALE']=function (urlMap){return urlMap.getScale();}
SUBSTITUTE_VARS['POINT']=function(urlMap,urlPoints,delim){if(urlPoints&&urlPoints.length>0){return urlPoints[0].toString(delim);} else {return '';}}
SUBSTITUTE_VARS['POINT.X']=function (urlMap,urlPoints){return urlPoints[0].x;}
SUBSTITUTE_VARS['POINT.Y']=function (urlMap,urlPoints){return urlPoints[0].y;}
SUBSTITUE_REQUIERES_POINTS['POINT']=1;SUBSTITUE_REQUIERES_POINTS['POINT.X']=1;SUBSTITUE_REQUIERES_POINTS['POINT.Y']=1;SUBSTITUTE_VARS['LAYERTITLES']=function (urlMap,delim){var layers=urlMap.getLayerTitles();var str='';for(var l=0; l<layers.length; l++){if(delim==" "){layers[l]=layers[l].replace(/ /g,'');}
str += delim+layers[l];}
str=str.substring(1);return str;}
SUBSTITUTE_VARS['MULTIPOINT']=function (urlMap,urlPoints,delim, pointdelim){var mPoint=new String();mPoint='';for(var p=0; p<urlPoints.length; p++){mPoint=mPoint+pointdelim+urlPoints[p].toString(delim);}
mPoint=mPoint.substring(1);return mPoint;}
SUBSTITUTE_VARS['MULTIPOINT.X']=function (urlMap,urlPoints,delim){var mPoint=new String();mPoint='';for(var p=0; p<urlPoints.length; p++){mPoint=mPoint+delim+urlPoints[p].x;}
mPoint=mPoint.substring(1);return mPoint;}
SUBSTITUTE_VARS['MULTIPOINT.Y']=function (urlMap,urlPoints,delim){var mPoint=new String();mPoint='';for(var p=0; p<urlPoints.length; p++){mPoint=mPoint+delim+urlPoints[p].y;}
mPoint=mPoint.substring(1);return mPoint;}
SUBSTITUE_REQUIERES_POINTS['MULTIPOINT']=1;SUBSTITUE_REQUIERES_POINTS['MULTIPOINT.X']=1;SUBSTITUE_REQUIERES_POINTS['MULTIPOINT.Y']=1;SUBSTITUTE_VARS['MAPBOOK']=function (){return MAPBOOK_FILE;}
function ProcessURLString(serviceMap, url, points, addInputs, delim, sep){url=new String(url);if(!delim){delim=URL_DEFAULT_DELIM;}
if(!sep){sep=URL_DEFAULT_POINT_DELIM;}
for(var k in SUBSTITUTE_VARS){var re=new RegExp('%'+k+'%','gi');if(url.search(re)>0){if(SUBSTITUE_REQUIERES_POINTS[k]){url=url.replace(re, SUBSTITUTE_VARS[k](serviceMap, points, delim, sep));} else {url=url.replace(re, SUBSTITUTE_VARS[k](serviceMap, delim, sep));}}}
for(var k in addInputs){var re=new RegExp('%'+k+'%','gi');url=url.replace(re, addInputs[k]);}
return url;}
function ProcessURL(serviceMap, serviceXML, points, addInputs, returnXML){var url=serviceXML.getElementsByTagName('url')[0].firstChild.nodeValue;url=url+'?';var inputs=serviceXML.getElementsByTagName('input');var regExs=new Array();for(var k in SUBSTITUTE_VARS){regExs[k]=new RegExp('^'+k,'i');}
for(var i=0; i<inputs.length; i++){var iName=inputs[i].getAttribute('name');var iValue=inputs[i].getAttribute('value');var iType=inputs[i].getAttribute('type');var iDelim=inputs[i].getAttribute('delim');var iSeparator=inputs[i].getAttribute('pointdelim');if(!iType.match(/user/i)&&!iType.match(/hidden/i)){for(var k in SUBSTITUTE_VARS){if(iType.match(regExs[k])){if(SUBSTITUE_REQUIERES_POINTS[k]){iValue=SUBSTITUTE_VARS[k](serviceMap, points, iDelim, iSeparator);} else {iValue=SUBSTITUTE_VARS[k](serviceMap, iDelim, iSeparator);}}}}
inputs[i].setAttribute('value',iValue);url=url+iName+'='+(iValue)+'&';}
if(returnXML){return serviceXML;}
for(var k in addInputs){url=url+k+'='+(addInputs[k])+'&';}
return url;}
