/*
 * Copyright (c) 2005-2006, Image Matters LLC. All Rights Reserved.
 * 
 * This software is distributed under the terms of the LICENSE file
 * included with the program and available here:
 * 
 * http://www.imagemattersllc.com/legal-notice/LICENSE-userSmartsGX.html
 */
namespace("userSmarts.Map");userSmarts.Map.EXPORT=["fixE"];userSmarts.Map.EXPORT_TAGS={":common":userSmarts.Map.EXPORT};var PI=Math.PI;var HALF_PI=PI*0.5;var TWO_PI=PI*2.0;var EPSLN=1.0e-10;var R2D=57.2957795131;var D2R=0.0174532925199;var R=6370997.0;function lccinit(param){this.r_major=param[0];this.r_minor=param[1];var lat1=param[2]*D2R;var lat2=param[3]*D2R;this.center_lon=param[4]*D2R;this.center_lat=param[5]*D2R;this.false_easting=param[6];this.false_northing=param[7];if(Math.abs(lat1+lat2)<EPSLN){alert("Equal Latitiudes for St. Parallels on opposite sides of equator - lccinit");return;}
var temp=this.r_minor/this.r_major;this.e=Math.sqrt(1.0-temp*temp);var sin1=Math.sin(lat1);var cos1=Math.cos(lat1);var ms1=msfnz(this.e,sin1,cos1);var ts1=tsfnz(this.e,lat1,sin1);var sin2=Math.sin(lat2);var cos2=Math.cos(lat2);var ms2=msfnz(this.e,sin2,cos2);var ts2=tsfnz(this.e,lat2,sin2);var ts0=tsfnz(this.e,this.center_lat,Math.sin(this.center_lat));if(Math.abs(lat1-lat2)>EPSLN){this.ns=Math.log(ms1/ms2)/Math.log(ts1/ts2);}else{this.ns=sin1;}
this.f0=ms1/(this.ns*Math.pow(ts1,this.ns));this.rh=this.r_major*this.f0*Math.pow(ts0,this.ns);}
function ll2lcc(coords){var lon=coords[0];var lat=coords[1];if(lat<=90.0&&lat>=-90.0&&lon<=180.0&&lon>=-180.0){lat*=D2R;lon*=D2R;}else{alert("*** Input out of range ***: lon: "+lon+" - lat: "+lat);return null;}
var con=Math.abs(Math.abs(lat)-HALF_PI);var ts;if(con>EPSLN){ts=tsfnz(this.e,lat,Math.sin(lat));rh1=this.r_major*this.f0*Math.pow(ts,this.ns);}else{con=lat*this.ns;if(con<=0){alert("Point can not be projected - ll2lcc");return null;}
rh1=0;}
var theta=this.ns*adjust_lon(lon-this.center_lon);var x=rh1*Math.sin(theta)+this.false_easting;var y=this.rh-rh1*Math.cos(theta)+this.false_northing;return[x,y];}
function lcc2ll(coords){var rh1,con,ts;var lat,lon;x=coords[0]-this.false_easting;y=this.rh-coords[1]+this.false_northing;if(this.ns>0){rh1=Math.sqrt(x*x+y*y);con=1.0;}else{rh1=-Math.sqrt(x*x+y*y);con=-1.0;}
var theta=0.0;if(rh1!==0){theta=Math.atan2((con*x),(con*y));}
if((rh1!==0)||(this.ns>0.0)){con=1.0/this.ns;ts=Math.pow((rh1/(this.r_major*this.f0)),con);lat=phi2z(this.e,ts);if(lat==-9999){return null;}}else{lat=-HALF_PI;}
lon=adjust_lon(theta/this.ns+this.center_lon);return[R2D*lon,R2D*lat];}
function msfnz(eccent,sinphi,cosphi){var con=eccent*sinphi;return cosphi/(Math.sqrt(1.0-con*con));}
function tsfnz(eccent,phi,sinphi){var con=eccent*sinphi;var com=0.5*eccent;con=Math.pow(((1.0-con)/(1.0+con)),com);return(Math.tan(0.5*(HALF_PI-phi))/con);}
function phi2z(eccent,ts){var eccnth=0.5*eccent;var con,dphi;var phi=HALF_PI-2*Math.atan(ts);for(i=0;i<=15;i++){con=eccent*Math.sin(phi);dphi=HALF_PI-2*Math.atan(ts*(Math.pow(((1.0-con)/(1.0+con)),eccnth)))-phi;phi+=dphi;if(Math.abs(dphi)<=0.0000000001){return phi;}}
alert("Convergence error - phi2z");return-9999;}
function sign(x){return(x<0.0)?-1:1;}
function adjust_lon(x){x=(Math.abs(x)<PI)?x:(x-(sign(x)*TWO_PI));return(x);}
userSmarts.Map.LatLonProjection=function(params){this.units=params.units;this.unitsAbbr=params.unitsAbbr;this.title=params.title;this.bounds={minX:-180.0,minY:-90.0,maxX:180.0,maxY:90};this.boundsCheck=false;};userSmarts.Map.LatLonProjection.prototype.project=function(arg1,arg2){return[arg1,arg2];};userSmarts.Map.LatLonProjection.prototype.unproject=function(arg1,arg2){return[arg1,arg2];};userSmarts.Map.LCCProjection=function(params){this.r_major=params.majorAxis;this.r_minor=params.minorAxis;var lat1=params.firstStandardParallel*D2R;var lat2=params.secondStandardParallel*D2R;this.center_lon=params.centerLongitude*D2R;this.center_lat=params.centerLatitude*D2R;this.false_easting=params.falseEasting;this.false_northing=params.falseNorthing;this.units=params.units;this.unitsAbbr=params.unitsAbbr;this.title=params.title;this.bounds={minX:-32820917671486.5,minY:-25338353776102.9,maxX:3650389000.07957,maxY:7718697.93197062};this.boundsCheck=false;if(Math.abs(lat1+lat2)<EPSLN){alert("Standard Parallels cannot be equal and on opposite sides of the equator");return;}
var temp=this.r_minor/this.r_major;this.e=Math.sqrt(1.0-temp*temp);var sin1=Math.sin(lat1);var cos1=Math.cos(lat1);var ms1=msfnz(this.e,sin1,cos1);var ts1=tsfnz(this.e,lat1,sin1);var sin2=Math.sin(lat2);var cos2=Math.cos(lat2);var ms2=msfnz(this.e,sin2,cos2);var ts2=tsfnz(this.e,lat2,sin2);var ts0=tsfnz(this.e,this.center_lat,Math.sin(this.center_lat));if(Math.abs(lat1-lat2)>EPSLN){this.ns=Math.log(ms1/ms2)/Math.log(ts1/ts2);}else{this.ns=sin1;}
this.f0=ms1/(this.ns*Math.pow(ts1,this.ns));this.rh=this.r_major*this.f0*Math.pow(ts0,this.ns);};userSmarts.Map.LCCProjection.prototype.project=function(arg1,arg2){var lon=arg1;var lat=arg2;if(lat<=90.0&&lat>=-90.0&&lon<=180.0&&lon>=-180.0){lat*=D2R;lon*=D2R;}else{alert("Coordinate out of range - lon: "+lon+" - lat: "+lat);return[arg1,arg2];}
var con=Math.abs(Math.abs(lat)-HALF_PI);var ts;if(con>EPSLN){ts=tsfnz(this.e,lat,Math.sin(lat));rh1=this.r_major*this.f0*Math.pow(ts,this.ns);}else{con=lat*this.ns;if(con<=0){alert("Point can not be projected - ",arg1+','+arg2);return[arg1,arg2];}
rh1=0;}
var theta=this.ns*adjust_lon(lon-this.center_lon);var x=rh1*Math.sin(theta)+this.false_easting;var y=this.rh-rh1*Math.cos(theta)+this.false_northing;return[x,y];};userSmarts.Map.LCCProjection.prototype.unproject=function(arg1,arg2){var rh1,con,ts;var lat,lon;x=arg1-this.false_easting;y=this.rh-arg2+this.false_northing;if(this.ns>0){rh1=Math.sqrt(x*x+y*y);con=1.0;}else{rh1=-Math.sqrt(x*x+y*y);con=-1.0;}
var theta=0.0;if(rh1!==0){theta=Math.atan2((con*x),(con*y));}
if((rh1!==0)||(this.ns>0.0)){con=1.0/this.ns;ts=Math.pow((rh1/(this.r_major*this.f0)),con);lat=phi2z(this.e,ts);if(lat==-9999){return null;}}else{lat=-HALF_PI;}
lon=adjust_lon(theta/this.ns+this.center_lon);return[R2D*lon,R2D*lat];};function identity(coords){return coords;}
userSmarts.Map.ProjectionFactory=function(){};userSmarts.Map.ProjectionFactory.prototype={};userSmarts.Map.ProjectionFactory.instance=function(srs){srs=srs.toUpperCase();switch(srs){case"EPSG:4326":case"EPSG:4269":case"CRS:84":case"EPSG:4965":return userSmarts.Map.ProjectionFactory.ESPG4326;case"EPSG:9802":case"EPSG:98020":return userSmarts.Map.ProjectionFactory.ESPG98020;case"EPSG:42101":return userSmarts.Map.ProjectionFactory.ESPG42101;case"EPSG:42304":return userSmarts.Map.ProjectionFactory.ESPG42304;case"EPSG:26986":return userSmarts.Map.ProjectionFactory.ESPG26986;case"EPSG:27561":return userSmarts.Map.ProjectionFactory.ESPG27561;case"EPSG:27562":return userSmarts.Map.ProjectionFactory.ESPG27562;case"EPSG:27572":case"EPSG:27582":return userSmarts.Map.ProjectionFactory.ESPG27572;case"EPSG:27563":return userSmarts.Map.ProjectionFactory.ESPG27563;case"EPSG:27564":return userSmarts.Map.ProjectionFactory.ESPG27564;case"EPSG:2154":return userSmarts.Map.ProjectionFactory.EPSG2154;default:return new userSmarts.Map.LatLonProjection({units:'degrees',title:'Latitude/Longitude'});}};userSmarts.Map.ProjectionFactory.ESPG4326=new userSmarts.Map.LatLonProjection({units:"degrees",unitsAbbr:"\u00b0",title:"Latitude/Longitude"});userSmarts.Map.ProjectionFactory.ESPG98020=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378137.0,minorAxis:6356752.314245,firstStandardParallel:33.0,secondStandardParallel:45.0,centerLongitude:-97.0,centerLatitude:40.0,falseEasting:0.0,falseNorthing:0.0});userSmarts.Map.ProjectionFactory.ESPG42101=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378137.0,minorAxis:6356752.314245,firstStandardParallel:49.0,secondStandardParallel:77.0,centerLongitude:-95.0,centerLatitude:0.0,falseEasting:0.0,falseNorthing:-8000000});userSmarts.Map.ProjectionFactory.ESPG42304=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378137.0,minorAxis:6356752.314,firstStandardParallel:49.0,secondStandardParallel:77.0,centerLongitude:-95.0,centerLatitude:49.0,falseEasting:0.0,falseNorthing:0});userSmarts.Map.ProjectionFactory.ESPG26986=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Massachusetts Mainland (LCC)',majorAxis:6378137.0,minorAxis:6356752.314,firstStandardParallel:42.68333333333333,secondStandardParallel:41.71666666666667,centerLongitude:-71.5,centerLatitude:41.0,falseEasting:200000,falseNorthing:750000});userSmarts.Map.ProjectionFactory.ESPG27561=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378249.2,minorAxis:6356515.0,firstStandardParallel:49.50,secondStandardParallel:49.50,centerLongitude:2.33722916655,centerLatitude:49.50,falseEasting:600000.0,falseNorthing:200000.0});userSmarts.Map.ProjectionFactory.ESPG27562=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378249.2,minorAxis:6356515.0,firstStandardParallel:46.80,secondStandardParallel:46.80,centerLongitude:2.33722916655,centerLatitude:46.8,falseEasting:600000.0,falseNorthing:200000.0});userSmarts.Map.ProjectionFactory.ESPG27572=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378249.2,minorAxis:6356515.0,firstStandardParallel:46.80,secondStandardParallel:46.80,centerLongitude:2.33722916655,centerLatitude:46.8,falseEasting:600000.0,falseNorthing:2200000.0});userSmarts.Map.ProjectionFactory.ESPG27563=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378249.2,minorAxis:6356515.0,firstStandardParallel:44.10,secondStandardParallel:44.10,centerLongitude:2.33722916655,centerLatitude:44.10,falseEasting:600000.0,falseNorthing:200000.0});userSmarts.Map.ProjectionFactory.ESPG27564=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378249.2,minorAxis:6356515.0,firstStandardParallel:42.17,secondStandardParallel:42.17,centerLongitude:2.33722916655,centerLatitude:42.17,falseEasting:234.358,falseNorthing:185861.369});userSmarts.Map.ProjectionFactory.EPSG2154=new userSmarts.Map.LCCProjection({units:'meters',unitsAbbr:"m",title:'Lambert Conformal Conic',majorAxis:6378137.0,minorAxis:6356752.3141,firstStandardParallel:44.00,secondStandardParallel:49.00,centerLongitude:3.00000000001,centerLatitude:46.50,falseEasting:700000.0,falseNorthing:6600000.0});function loadImage(properties){var deferred=null;deferred=new Deferred();deferred.image=null;if(!properties.url){return deferred;}
var image=null;image=document.createElement("IMG");image.setAttribute("src","");image.src=null;if(properties.width){image.setAttribute('width',properties.width);}
if(properties.height){image.setAttribute('height',properties.height);}
image.style.position=(properties.position)?properties.position:'absolute';image.style.top=(properties.top)?properties.top+"px":'0px';image.style.left=(properties.left)?properties.left+"px":'0px';image.style.visibility='visible';image.onmousedown=function(e){return false;};image.ondrag=function(e){return false;};if(properties.opacity&&typeof(properties.opacity)=='number'){image.style.opacity=(properties.opacity*1.0);image.style.filter='alpha(opacity='+(properties.opacity*100)+')';}
image.deferred=deferred;connect(image,'onload',onImageLoad);connect(image,'onerror',onImageError);image.src=properties.url;return{deferred:deferred,image:image};}
function onImageLoad(evt){var img=evt.src();disconnectAll(img);var deferred=img.deferred;deferred.callback(img);img.deferred=undefined;if(typeof(evt.dispose)=='function'){evt.dispose();}}
function onImageError(evt){var img=evt.src();var deferred=img.deferred;img.deferred=undefined;disconnectAll(img);deferred.errback("Error loading image "+img.src);if(typeof(evt.dispose)=='function'){evt.dispose();}}
function disposeImage(image){if(image){image.id="deleted!";image.src=null;image.title=null;disconnectAll(image);image.onmouseout=null;image.onmouseover=null;image.onmousedown=null;image.onmouseup=null;image.ondrag=null;image=null;}}
function fixE(e){if(typeof e=='undefined'){e=window.event;}
if(typeof e.layerX=='undefined'){e.layerX=e.offsetX;}
if(typeof e.layerY=='undefined'){e.layerY=e.offsetY;}
return e;}
userSmarts.Map.fixE=fixE;function getDistance(x1,y1,x2,y2){var radius=6378.137;var diam=12756.3;var pi=3.141529;var deg2rad=0.0174532925;var x1r=x1*deg2rad;var x2r=x2*deg2rad;var y1r=y1*deg2rad;var y2r=y2*deg2rad;var sin1=Math.sin(y1r)*Math.sin(y2r);var cos1=Math.cos(y1r)*Math.cos(y2r);var cos2=Math.cos(x2r-x1r);var acos1=Math.acos(sin1+cos1*cos2);var dist=radius*acos1;dist=dist*1000*3.2808399/5280;return dist;}
function distanceToDegrees(dist){var result=dist*1*0.54;result=(result*63360);result=(result*0.0254);result=(result/1852);result=(result/60);return result;}
function nearestDistanceFactor(d){var d1=0.00001;var d2=0.00002;var d3=0.00005;var factor=1;while(d1*Math.pow(10,factor)<d){++factor;}
var upperFactor=factor;var lowerFactor=factor-1;var lowerDiff=Math.abs(d-d3*Math.pow(10,lowerFactor));var upperDiff=Math.abs(d1*Math.pow(10,upperFactor)-d);if(lowerDiff<upperDiff){d1*=Math.pow(10,lowerFactor);d2*=Math.pow(10,lowerFactor);d3*=Math.pow(10,lowerFactor);}else{d1*=Math.pow(10,upperFactor);d2*=Math.pow(10,upperFactor);d3*=Math.pow(10,upperFactor);}
var dt1=Math.abs(d1-d);var dt2=Math.abs(d2-d);var dt3=Math.abs(d3-d);if(dt1<dt2){return d1;}else if(dt2<dt3){return d2;}else{return d3;}}
function convertUnits(value,fromUnits,toUnits){if(typeof(value)!='number'){return value;}
if(fromUnits=='mi'){if(toUnits=='km'){return 1.609344*value;}else if(toUnits=='m'){return 1609.344*value;}else if(toUnits=='ft'){return 5280*value;}else if(toUnits=='yd'){return 1760*value;}else{toUnits='mi';return value;}}else if(fromUnits=='km'){if(toUnits=='mi'){return 0.621371192*value;}else if(toUnits=='m'){return 1000.0*value;}else if(toUnits=='ft'){return 3280.8399*value;}else if(toUnits=='yd'){return 1093.6133*value;}else{toUnits='km';return value;}}else if(fromUnits=='m'){if(toUnits=='mi'){return 0.000621371192*value;}else if(toUnits=='km'){return 0.001*value;}else if(toUnits=='ft'){return 3.2808399*value;}else if(toUnits=='yd'){return 1.0936133*value;}else{toUnits='m';return value;}}else if(fromUnits=='ft'){if(toUnits=='mi'){return 0.000189393939*value;}else if(toUnits=='km'){return 0.0003048*value;}else if(toUnits=='m'){return 0.3048*value;}else if(toUnits=='yd'){return 0.333*value;}else{toUnits='ft';return value;}}else if(fromUnits=='yd'){if(toUnits=='mi'){return 0.000568181818*value;}else if(toUnits=='km'){return 0.0009144*value;}else if(toUnits=='m'){return 0.9144*value;}else if(toUnits=='ft'){return 3*value;}else{toUnits='yd';return value;}}else{return value;}}
function formatNumberWithCommas(amount){var temp=amount+'';var finalStr='';var start=temp.length-1;for(var i=0;i<temp.length;i++){if(temp.substring(i,i+1)=='.'){start=i-1;break;}}
var j=0;for(var i=start;i>=0;i--){if(j>0&&((j+1)%3)===0&&i!==0){finalStr=','+temp.substring(i,i+1)+finalStr;}else{finalStr=temp.substring(i,i+1)+finalStr;}
j++;}
return finalStr+temp.substring(start+1,temp.length);}
function formatNumber(val,wd,dd){val=val*1;if(dd>0){val=val.toFixed(dd);}
var strval=val+'';var arr=strval.split('.');var whole=(val<0)?(arr[0]*-1)+'':arr[0];if(dd>0){var decimal=arr[1];}
if(whole.length<wd){var padding='';for(var i=0;i<(wd-whole.length);++i){padding+='0';}
whole=padding+whole;}else if(whole.length>wd){}
return((val<0)?'-':'')+whole+((dd>0)?'.'+decimal:'');}
function makeLabel(x,y,width,height,text){var div=DIV({'class':'map-label'},text);div.style.position="absolute";var left=((width)?Math.ceil(x-(width/2)):x);var top=((height)?Math.ceil(y-(height/2)):y);div.style.left=left+'px';div.style.top=top+'px';if(width){div.style.width=width+'px';}
if(height){div.style.height=height+'px';}
return div;}
function spliceArray(arr1,index,numDeletedItems,arr2){if(index>=arr1.length){var resultArr=[];for(var i=0;i<arr1.length;i++){resultArr.push(arr1[i]);}
for(var i=0;i<arr2.length;i++){resultArr.push(arr2[i]);}
return resultArr;}else if(index>=0&&index<arr1.length){var resultArr=[];for(var i=0;i<index;i++){resultArr.push(arr1[i]);}
for(var i=0;i<arr2.length;i++){resultArr.push(arr2[i]);}
var i=Math.min(arr1.length,index+numDeletedItems);for(;i<arr1.length;i++){resultArr.push(arr1[i]);}
return resultArr;}else{return arr1;}}
function parseQueryString(){var params={};var href=location.href;var qsi=href.indexOf("?");if(qsi>0){var qs=href.substring(qsi,href.length);var args=qs.split("&");var arg;var argParts;for(var i=0;i<args.length;i++){arg=args[i];argParts=arg.split("=");if(argParts.length==2){params[argParts[0]]=argParts[1];}}}
return params;}
function getViewportScrollX(){var scrollX=0;if(document.documentElement&&document.documentElement.scrollLeft){scrollX=document.documentElement.scrollLeft;}
else if(document.body&&document.body.scrollLeft){scrollX=document.body.scrollLeft;}
else if(window.pageXOffset){scrollX=window.pageXOffset;}
else if(window.scrollX){scrollX=window.scrollX;}
return scrollX;}
function getViewportScrollY(){var scrollY=0;if(document.documentElement&&document.documentElement.scrollTop){scrollY=document.documentElement.scrollTop;}
else if(document.body&&document.body.scrollTop){scrollY=document.body.scrollTop;}
else if(window.pageYOffset){scrollY=window.pageYOffset;}
else if(window.scrollY){scrollY=window.scrollY;}
return scrollY;}
userSmarts.Map.Widget=function(properties){properties=setdefault(properties,{id:'map-'+Math.random(),width:500,height:400,components:{},componentIds:[]});Bean.call(this,properties);if(this.canvas){this.register('canvas',this.canvas);}
this.layout=DIV({'class':'map-widget',id:this.id});this.layout.style.width=this.width+"px";this.layout.style.height=this.height+"px";this.layout.widget=this;this.overlays=new userSmarts.Map.OverlayManager();this.register('overlays',this.overlays);this.progressBar=new ProgressBar({adapter:this});this.manager=new userSmarts.Map.Manager(this);connect(this,"context",this,function(event){this.setContext(event.newValue);});};userSmarts.Map.Widget.inheritsFrom(Bean);userSmarts.Map.Widget.prototype.paint=function(context){var cx=this.width-136;var cy=this.height-40;this.progressBar.setPosition(cx,cy);this.progressBar.setSize(128,32);this.progressBar.paint();if(this.canvas){this.layout.appendChild(this.canvas.paint(context));}
return this.layout;};userSmarts.Map.Widget.prototype.repaint=function(context){if(this.canvas){this.canvas.repaint(context);}};userSmarts.Map.Widget.prototype.register=function(id,component){var comp=new userSmarts.Map.ComponentAdapter({id:id,component:component,widget:this});this.components[id]=comp;this.componentIds.push(id);return comp;};userSmarts.Map.Widget.prototype.unregister=function(id){this.components[id]=null;this.componentIds.splice(this.componentIds.indexOf(id),1);};userSmarts.Map.Widget.prototype.locate=function(id){var adapter=this.components[id];if(adapter){return adapter.component;}
else{return null;}};userSmarts.Map.Widget.prototype.applyProperty=function(propertyName,value){if(userSmarts.Map.DEBUG_FLAG){logDebug("Map.Widget : Applying '"+propertyName+"' to "+this.componentIds.length+" registered component(s)");}
var adapter;for(var i=0;i<this.componentIds.length;i++){adapter=this.components[this.componentIds[i]];if(adapter){if(typeof(adapter.applyProperty)=='function'){adapter.applyProperty(propertyName,value);}}}};userSmarts.Map.Widget.prototype.setContext=function(context){context.width=this.width-(window.ActiveXObject?2:0);context.height=this.height-(window.ActiveXObject?2:0);this.setProperty("aspectRatio",context.correctAspectRatio());this.context=context;this.applyProperty('context',context);};userSmarts.Map.Widget.prototype.getManager=function(){return this.manager;};userSmarts.Map.Widget.prototype.getGeometryRenderer=function(){return this.renderer;};userSmarts.Map.Widget.prototype.getOverlayManager=function(){return this.overlays;};userSmarts.Map.Widget.prototype.dispose=function(){var adapter;var comp;for(var i=this.componentIds.length-1;i>=0;i--){adapter=this.components[this.componentIds[i]];if(adapter){comp=adapter.component;try{if(typeof comp.dispose==="function"){comp.dispose();}}catch(e){}
this.unregister(adapter.id);}}
this.progressBar.dispose();this.layout=null;};userSmarts.Map.ComponentAdapter=function(properties){Bean.call(this,properties);if(this.component.onWidgetChange){this.addChangeListener(bind(function(){this.onWidgetChange();},this.component),'modified');this.widget.addChangeListener(bind(function(){this.setProperty('modified',true);},this),'modified');}
this.applyProperty("adapter",this);};userSmarts.Map.ComponentAdapter.inheritsFrom(Bean);userSmarts.Map.ComponentAdapter.prototype.applyProperty=function(propertyName,value){if(typeof(this.component.setProperty)=='function'){this.component.setProperty(propertyName,value);}else{this.component[propertyName]=value;}};userSmarts.Map.ComponentAdapter.prototype.getProperty=function(propertyName){if(propertyName=='widget'||propertyName=='map'){return this.widget;}else{var result=this.widget.getProperty(propertyName);if(!result){result=this.widget.locate(propertyName);}
return result;}};userSmarts.Map.Canvas=function(properties){properties=setdefault(properties,{id:'mapCanvas_'+Math.random(),width:500,height:400,timeout:5000,debug:false,recenterEnabled:true});Bean.call(this,properties);connect(this,'context',this,'onContextChange');};userSmarts.Map.Canvas.inheritsFrom(Bean);userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT='loadingComplete';userSmarts.Map.Canvas.prototype.paint=function(context){if(!this.layout){this.layout=DIV({'class':'map-canvas',id:this.id});this.layout.style.position="absolute";this.layout.style.top='0px';this.layout.style.left='0px';this.layout.style.width=this.width+"px";this.layout.style.height=this.height+"px";if(this.mouseMoveListener){this.layout.onmousemove=this.mouseMoveListener;this.mouseMoveListener=null;}
this.content=DIV({'class':'map-canvas-buffer',id:this.id+'_LAYERS'});this.content.style.position="relative";this.content.style.top='0px';this.content.style.left='0px';this.content.style.width=this.width+"px";this.content.style.height=this.height+"px";this.layout.appendChild(this.content);if(this.recenterEnabled){this.enableRecenter();}}
this.repaint(context);return this.layout;};userSmarts.Map.Canvas.prototype.repaint=function(context){this.renderLayers();};userSmarts.Map.Canvas.prototype.renderLayers=function(){if(this.adapter){var renderer=this.adapter.getProperty("layer-renderer");if(renderer){if(!this.rendererCallback){this.rendererCallback=bind(this.onImagesLoaded,this);renderer.addCallback(this.rendererCallback);}
renderer.render(this.context);}else{logWarning("Warning! Map.Canvas has no renderer to generate layer images!");}}else{logWarning("Warning! Map.Canvas is not registered with Map.Widget! Skipping layer rendering...");}};userSmarts.Map.Canvas.prototype.onImagesLoaded=function(layers){if(!this.content){return;}
for(var i=0;i<layers.length;i++){layers[i].style.width=this.context.width+"px";}
replaceChildNodes(this.content,null);replaceChildNodes(this.content,layers);this.setProperty(userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,new Date().getTime());};userSmarts.Map.Canvas.prototype.onContextChange=function(event){var oldCtx=event.oldValue;if(this.contextListener){disconnect(this.contextListener);}
var newCtx=event.newValue;if(newCtx){this.contextListener=connect(newCtx,userSmarts.Map.ViewContext.CHANGE_EVENT_PROPERTY,this,'repaint');}
this.repaint();};userSmarts.Map.Canvas.onWidgetChange=function(event){this.repaint();};userSmarts.Map.Canvas.prototype.recenter=function(evt){e=evt.event();var point=elementPosition(this.layout);point.x=e.clientX-point.x;point.y=e.clientY-point.y;var px=point.x/this.width;var py=1.0-(point.y/this.height);if(px<0.5){px=0.0-(0.5-px);}else{px=px-0.5;}
if(py<0.5){py=0-(0.5-py);}else{py=py-0.5;}
this.context.scaledPan(px,py);};userSmarts.Map.Canvas.prototype.projectPoint=function(point){var px=point.x/this.width;var py=1.0-(point.y/this.height);var p=this.context.boundingBox.getCoordinate(px,py);p.x=p.x.toFixed(5)*1;p.y=p.y.toFixed(5)*1;return p;};userSmarts.Map.Canvas.prototype.unprojectPoint=function(point){if(!this.context){return point;}
var pc=this.context.boundingBox.getCoordinatePercentage(point.x,point.y);var y=(1.0-pc.y)*this.height;var x=pc.x*this.width;pc.x=x;pc.y=y;return pc;};userSmarts.Map.Canvas.prototype.getPointOnCanvas=function(point){var pos=elementPosition(this.layout);var scrollOffset=Coerce.toInteger(this.layout.scrollOffset,0);var scrollLeft=0;var scrollTop=0;if(document.documentElement.scrollLeft){scrollLeft=Coerce.toInteger(document.documentElement.scrollLeft,0);scrollTop=Coerce.toInteger(document.documentElement.scrollTop,0);}else{scrollLeft=Coerce.toInteger(document.body.scrollLeft,0);scrollTop=Coerce.toInteger(document.body.scrollTop,0);}
point.x=point.x-pos.x+scrollLeft;point.y=(point.y-scrollOffset)-pos.y+scrollTop;return point;};userSmarts.Map.Canvas.prototype.setMouseMoveListener=function(func){if(this.layout){this.layout.onmousemove=func;}else{this.mouseMoveListener=func;}};userSmarts.Map.Canvas.prototype.enableRecenter=function(){if(this.layout){this.recenterListener=connect(this.layout,"ondblclick",this,this.recenter);this.recenterEnabled=true;}};userSmarts.Map.Canvas.prototype.disableRecenter=function(){if(this.recenterListener){disconnect(this.recenterListener);this.recenterListener=null;}
this.recenterEnabled=false;};userSmarts.Map.Canvas.prototype.dispose=function(){disconnectAll(this);if(this.contextListener){disconnect(this.contextListener);this.contextListener=null;}
if(this.content){this.disposeLayerImages();replaceChildNodes(this.content,null);this.layout.removeChild(this.content);this.content=null;}
if(this.recenterListener){disconnect(this.recenterListener);this.recenterListener=null;}
if(this.adapter){this.adapter=null;}
if(this.layout){this.layout.onmousemove=null;this.layout=null;}};userSmarts.Map.Canvas.prototype.disposeLayerImages=function(arr){var shouldBeDisposed=true;var child;var len=this.content.childNodes.length;for(var i=len-1;i>=0;i--){child=this.content.childNodes[i];if(arr&&arr.length){for(var j=0;j<arr.length;j++){if(child==arr[j]){shouldBeDisposed=false;break;}}}
if(shouldBeDisposed){this.content.removeChild(child);try{disposeImage(child);}catch(e){}}else{shouldBeDisposed=true;}}};userSmarts.Map.ScaleLegend=function(properties){if(isPrototype(arguments))return;properties=setdefault(properties,{id:'mapScaleLegend',uom:'mi',distanceScaleFactor:0.0,position:new Point(0,0)});userSmarts.wt.widgets.Control.call(this,properties);connect(this,'adapter',this,this.onAdapterChange);};userSmarts.Map.ScaleLegend.inheritsFrom(userSmarts.wt.widgets.Control);userSmarts.Map.ScaleLegend.prototype.onAdapterChange=function(event){if(this.canvasListener){disconnect(this.canvasListener);}
var adapter=event.newValue;var canvas=adapter.getProperty('canvas');this.canvasListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};userSmarts.Map.ScaleLegend.prototype.paint=function(){return this.getNode();};userSmarts.Map.ScaleLegend.prototype.getNode=function(){if(!this.content){this.content=DIV({'id':this.id,'class':'map-scale-legend'});}
this.repaint();if(this.adapter){this.overlay=new userSmarts.Map.Overlay({id:this.id});var overlay=this.overlay;overlay.setContent(this.content);overlay.setPosition(this.position);var overlays=this.adapter.getProperty("overlays");overlays.add(overlay);}
return this.content;};userSmarts.Map.ScaleLegend.prototype.repaint=function(){this.update();};userSmarts.Map.ScaleLegend.prototype.update=function(){if(!this.content){return;}
var result=this.determineScale();replaceChildNodes(this.content,result);};userSmarts.Map.ScaleLegend.prototype.determineScale=function(){var result=null;if(this.adapter){var canvas=this.adapter.getProperty('canvas');this.maxWidth=parseInt(canvas.width);this.distanceScaleFactor=100.0/this.maxWidth;var position={x:25,y:canvas.height-45};this.setPosition(position.x,position.y);var context=this.adapter.getProperty('context');if(context){var view=context.getView();var centerLatitude=Math.round((view.points[1].y*1-view.points[0].y*1)/2+view.points[0].y*1);var dist=getDistance(view.points[0].x,centerLatitude,view.points[1].x,centerLatitude);dist*=this.distanceScaleFactor;dist=convertUnits(dist,'mi',this.uom);if(dist<0.00001){return result;}
var worldSpaceDist=nearestDistanceFactor(dist);worldSpaceDist=worldSpaceDist.toFixed(2);var worldSpaceDistPercentage=worldSpaceDist/dist;var screenSpaceDistPixels=100*(worldSpaceDistPercentage);var offset=5;var x1=0;var x2=screenSpaceDistPixels;var y=0;var x=Math.floor((x2-x1)/2+x1);var holder=DIV({'class':'scale-holder'});if(this.adapter){var renderer=this.adapter.getProperty("renderer");holder.appendChild(renderer.renderLine({x:x1,y:y-offset},{x:x1,y:y+offset},2));holder.appendChild(renderer.renderLine({x:x1,y:y},{x:x2-1,y:y},2));holder.appendChild(renderer.renderLine({x:x2,y:y-offset},{x:x2,y:y+offset},2));}
var labelText=' '+formatNumberWithCommas(worldSpaceDist)+' '+this.uom+' at '+centerLatitude+' deg';var labelwidth=Math.ceil(labelText.length*5.0);var label=makeLabel(x,y+5,labelwidth,null,labelText);holder.appendChild(label);var screenSpaceDist=screenSpaceDistPixels/(96*12*5280);var ratio=worldSpaceDist/screenSpaceDist;if(isNaN(ratio)){ratio="NaN";}else{ratio=formatNumberWithCommas(ratio.toFixed(0));}
holder.appendChild(makeLabel(x,y+20,labelwidth,null,"1 : "+ratio));result=holder;}}
return result;};userSmarts.Map.ScaleLegend.prototype.setCanvasSize=function(width,height){if(width<100){width=100;}
this.unitPercentage=100/width;};userSmarts.Map.ScaleLegend.prototype.setPosition=function(x,y){this.position.x=x;this.position.y=y;if(this.overlay){this.overlay.setPosition(this.position);}};userSmarts.Map.ScaleLegend.prototype.setUnits=function(uom){this.uom=uom;};userSmarts.Map.ScaleLegend.prototype.toggleVisibility=function(){};userSmarts.Map.ScaleLegend.prototype.dispose=function(){disconnectAll(this);if(this.canvasListener){disconnect(this.canvasListener);this.canvasListener=null;}
if(this.content){replaceChildNodes(this.content,null);this.content=null;}
if(this.overlay){replaceChildNodes(this.overlay,null);this.overlay=null;}
if(this.adapter){this.adapter=null;}};userSmarts.Map.LocationBar=function(properties){properties=setdefault(properties,{id:'mapLocationBar',height:15,units:userSmarts.Map.LocationBar.DECIMAL_DEGREES});Bean.call(this,properties);this.canvasListener=bind(this.update,this);this.adapterListener=connect(this,'adapter',this,this.onAdapterChange);};userSmarts.Map.LocationBar.inheritsFrom(Bean);userSmarts.Map.LocationBar.DECIMAL_DEGREES="decimal degrees";userSmarts.Map.LocationBar.DEG_MIN_SEC="degrees_minutes_seconds";userSmarts.Map.LocationBar.DEFAULT='default';userSmarts.Map.LocationBar.prototype.paint=function(context){if(!this.layout){this.layout=DIV({'id':this.id,'class':'map-location-bar'});this.layout.title="Cursor Location in <longitude,latitude>";connect(this.layout,'onclick',this,'toggleUnits');}
return this.layout;};userSmarts.Map.LocationBar.prototype.repaint=function(context){};userSmarts.Map.LocationBar.prototype.show=function(){if(this.layout.style.display=='none'){this.layout.style.display='block';}};userSmarts.Map.LocationBar.prototype.hide=function(){if(this.layout.style.display!='none'){this.layout.style.display='none';}};userSmarts.Map.LocationBar.prototype.update=function(e){e=fixE(e);var mouseX=e.clientX;var mouseY=e.clientY;if(this.adapter){var canvas=this.adapter.getProperty("canvas");var context=this.adapter.getProperty("context");if(!canvas||!context){return;}
var point=canvas.getPointOnCanvas({x:mouseX,y:mouseY});var pos=canvas.projectPoint(point);var text="";if(this.units==userSmarts.Map.LocationBar.DEFAULT){text=pos.x.toFixed(4)+context.boundingBox.projection.unitsAbbr+", "+
pos.y.toFixed(4)+context.boundingBox.projection.unitsAbbr;}else{var coord=context.unproject(pos.x,pos.y);var lon=coord[0]*1.0;var lat=coord[1]*1.0;if(this.units==userSmarts.Map.LocationBar.DEG_MIN_SEC){coord=decDegToDegMinSec(lon,lat);text='longitude: '+coord.longitude.degrees+'\u00b0 '+
coord.longitude.minutes+'\' '+
coord.longitude.seconds+'\" , '+'latitude: '+coord.latitude.degrees+'\u00b0 '+
coord.latitude.minutes+'\' '+
coord.latitude.seconds+'\"';}else{text='longitude: '+lon.toFixed(4)+'\u00b0 , latitude: '+lat.toFixed(4)+'\u00b0';}}
this.setProperty("location",text);var textNode=document.createTextNode(text);if(this.layout){replaceChildNodes(this.layout,textNode);}}
return false;};userSmarts.Map.LocationBar.prototype.setUnits=function(units){if(units==userSmarts.Map.LocationBar.DECIMAL_DEGREES||units==userSmarts.Map.LocationBar.DEG_MIN_SEC||units==userSmarts.Map.LocationBar.DEFAULT){this.units=units;}};userSmarts.Map.LocationBar.prototype.toggleVisibility=function(){this.layout.style.display=(this.layout.style.display=='none')?'block':'none';};userSmarts.Map.LocationBar.prototype.toggleUnits=function(){if(this.units==userSmarts.Map.LocationBar.DECIMAL_DEGREES){this.setUnits(userSmarts.Map.LocationBar.DEG_MIN_SEC);}else if(this.units==userSmarts.Map.LocationBar.DEG_MIN_SEC){this.setUnits(userSmarts.Map.LocationBar.DEFAULT);}else{this.setUnits(userSmarts.Map.LocationBar.DECIMAL_DEGREES);}};userSmarts.Map.LocationBar.prototype.onAdapterChange=function(event){var adapter=event.newValue;var canvas=adapter.getProperty("canvas");canvas.setMouseMoveListener(this.canvasListener);};userSmarts.Map.LocationBar.prototype.dispose=function(){if(this.adapterListener){disconnect(this.adapterListener);}
this.canvasListener=null;if(this.layout){disconnectAll(this.layout);replaceChildNodes(this.layout,null);this.layout=null;}
this.location=null;this.adapter=null;};function decDegToDegMinSec(lon,lat){var dlon=lon.toFixed(5);var lonwhole=Math.ceil(dlon);var decimal=(dlon-lonwhole);var dmin=decimal*60;dmin=dmin.toFixed(5);var lonminutes=Math.ceil(dmin);decimal=(dmin-lonminutes);lonminutes=Math.abs(lonminutes);var lonseconds=Math.abs(decimal*60);lonseconds=lonseconds.toFixed(3);var dlat=lat.toFixed(5);var latwhole=Math.floor(dlat);decimal=(dlat-latwhole);dmin=decimal*60;dmin=dmin.toFixed(5);var latminutes=Math.floor(dmin);decimal=(dmin-latminutes);latminutes=Math.abs(latminutes);var latseconds=Math.abs(decimal*60);latseconds=latseconds.toFixed(3);lonwhole=formatNumber(lonwhole,3,0);latwhole=formatNumber(latwhole,3,0);lonminutes=formatNumber(lonminutes,2,0);latminutes=formatNumber(latminutes,2,0);lonseconds=formatNumber(lonseconds,2,3);latseconds=formatNumber(latseconds,2,3);return{longitude:{degrees:lonwhole,minutes:lonminutes,seconds:lonseconds},latitude:{degrees:latwhole,minutes:latminutes,seconds:latseconds}};}
userSmarts.Map.LayerControl=function(properties){properties=setdefault(properties,{id:'map-layer-window',name:" Layers ",timeout:3000,modcount:0,waitOnRefresh:false,autoRefresh:true,maxNameSize:30});userSmarts.wt.widgets.Control.call(this,properties);this.contextListener=connect(this,'context',this,'onContextChange');this.adapterListener=connect(this,"adapter",this,this.onAdapterChange);this.connectListeners={types:['visible','active','mouseout','mouseover','selection'],visible:[],active:[],mouseout:[],mouseover:[],selection:[]};this.updateCheck=bind(this.checkIfUpdated,this);if(this.autoRefresh){if(userSmarts.Map.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};userSmarts.Map.LayerControl.inheritsFrom(userSmarts.wt.widgets.Control);userSmarts.Map.LayerControl.prototype.getNode=function(){return this.paint();};userSmarts.Map.LayerControl.prototype.update=function(){return this.repaint();};userSmarts.Map.LayerControl.prototype.paint=function(){if(!this.layerContent){this.layerContent=this.buildLayers();}
return this.layerContent;};userSmarts.Map.LayerControl.prototype.repaint=function(){if(this.content){this.clearConnectListeners();var temp=this.createLayerEntries();replaceChildNodes(this.content,temp);}};userSmarts.Map.LayerControl.prototype.buildHeader=function(){if(!this.header){this.editorLink=SPAN({'class':'button',title:"Open/Close Layer Editor"},"Edit");this.editorListener=connect(this.editorLink,'onclick',this,this.toggleEditor);this.refresher=SPAN({'title':'Refresh Map','class':'button'},'Refresh');this.manualRefreshListener=connect(this.refresher,'onclick',this,"forceRefresh");this.autoRefresher=SPAN({title:'Enable Automatic Refresh','class':'buttondown'},'Auto Ref.');this.autoRefreshListener=connect(this.autoRefresher,'onclick',this,"toggleAutoRefresh");this.shiftUpper=SPAN({'class':'button'},IMG({title:'Shift Selected Layer Up',src:this.imagedir+'up.gif',width:'16',height:'8'}));this.shiftUpListener=connect(this.shiftUpper,'onclick',bind(this.moveLayer,this,-1,false));this.shiftDowner=SPAN({'class':'button'},IMG({title:'Shift Selected Layer Down',src:this.imagedir+'down.gif',width:'16',height:'8'}));this.shiftDownListener=connect(this.shiftDowner,'onclick',bind(this.moveLayer,this,1,false));this.shiftToTop=SPAN({'class':'button'},IMG({title:'Shift Selected Layer to Top',src:this.imagedir+'top_boundary.gif',width:'16',height:'8'}));this.shiftToTopListener=connect(this.shiftToTop,'onclick',bind(this.moveLayer,this,-1,true));this.shiftToBottom=SPAN({'class':'button'},IMG({title:'Shift Selected Layer to Bottom',src:this.imagedir+'bottom_boundary.gif',width:'16',height:'8'}));this.shiftToBottomListener=connect(this.shiftToBottom,'onclick',bind(this.moveLayer,this,1,true));this.header=TD({'class':'map-layer-bar-subheader',width:'100%','align':'right'},this.refresher,this.autoRefresher,this.shiftToTop,this.shiftToBottom,this.shiftUpper,this.shiftDowner,this.editorLink);}
return this.header;};userSmarts.Map.LayerControl.prototype.buildLayers=function(){var thead=THEAD({},TR({'class':'table-row'},[TD({'class':'table-column-subheader',width:'20','title':'visible?'},IMG({src:this.imagedir+'eye.gif'})),TD({'class':'table-column-subheader',width:'20','title':'query?'},IMG({src:this.imagedir+'tools/describe.gif'})),TD({'class':'table-column-subheader'},'name')]));var tfoot=TFOOT();this.content=TBODY({},this.createLayerEntries());var layerContent=DIV({id:'map-layer-table','class':'map-layer-table'},TABLE({'class':'table',border:'0',width:'100%','cellpadding':'1','cellspacing':'0'},[thead,tfoot,this.content]));return layerContent;};userSmarts.Map.LayerControl.prototype.createLayerEntries=function(){var rows=[];if(this.adapter){var context=this.adapter.getProperty("context");if(context&&context.layers){var l;for(var i=context.layers.length-1;i>=0;i--){l=this.createLayer(context.layers[i],context);if(l.length){for(var j=0;j<l.length;j++){rows.push(l[j]);}}else{rows.push(l);}}}}
return rows;};userSmarts.Map.LayerControl.prototype.createLayer=function(layer,context){var layerId=layer.getServer()+'.'+layer.getLayerId();var row=TR({'class':'table-row layer-entry'});row.layer=layer;if(layer.selected){addElementClass(row,'selected');this.setProperty("selected",row);}
var visibleCheckBox=INPUT({'name':layer.getLayerId(),'type':'checkbox','title':'Check box to make '+layer.getLayerName()+' visible','value':layer.getLayerId()});visibleCheckBox.checked=visibleCheckBox.defaultChecked=layer.visible;var visLis=connect(visibleCheckBox,'onclick',bind(function(input,context,layer){var ch=input.checked;if(this.autoRefresh){if(ch){layer.show();}else{layer.hide();}}else{if(ch){layer.visible=true;}else{layer.visible=false;}
this.updatesPending=true;}},this,visibleCheckBox,context,layer));this.connectListeners.visible[layer]=visLis;var activeCheckBox=INPUT({'name':layer.getLayerId(),'type':'checkbox','title':'Check box to make '+layer.getLayerName()+' active','value':layer.getLayerId()});activeCheckBox.checked=activeCheckBox.defaultChecked=layer.active;if(!layer.queryable)activeCheckBox.disabled=true;var actLis=connect(activeCheckBox,'onclick',bind(function(layer){if(this.checked){layer.activate();}
else{layer.deactivate();}},activeCheckBox,layer));this.connectListeners.active[layer]=actLis;var layerName=layer.getLayerName();if(this.maxNameSize>0){if(layerName.length>this.maxNameSize){layerName=layerName.substring(0,this.maxNameSize)+"...";}}
var layerLabel=SPAN({'class':'layer-name','name':layer.getLayerId(),'title':layer.getLayerName()},layerName+"  ");var overLis=connect(layerLabel,'onmouseover',function(){layerLabel.style.cursor='pointer';});var outLis=connect(layerLabel,'onmouseout',function(){layerLabel.style.cursor='default';});this.connectListeners.mouseover[layer]=overLis;this.connectListeners.mouseout[layer]=outLis;var labelCell=TD({'class':'table-cell'},layerLabel);var labelLis=connect(labelCell,'onclick',bind(function(r){if(!r.layer.selected){var prevSel=this.selected;if(prevSel){removeElementClass(prevSel,'selected');prevSel.layer.selected=false;}
r.layer.selected=true;this.setProperty("selected",r);addElementClass(r,'selected');}else{r.layer.selected=false;this.setProperty("selected",null);removeElementClass(r,'selected');}},this,row));this.connectListeners.selection[layer]=labelLis;row.appendChild(TD({'class':'table-cell','align':'center',width:'5%'},visibleCheckBox));row.appendChild(TD({'class':'table-cell','align':'center',width:'5%'},activeCheckBox));row.appendChild(labelCell);var editRow=TR({'class':'table-row',width:'100%'});var editCell=TD({'class':'table-cell',colSpan:'3'});editRow.appendChild(editCell);var editor=userSmarts.Map.Layer.EditorFactory.getEditor(layer);if(editor){row.editor=editor;editCell.appendChild(editor.paint());if(layer.selected&&layer.visibleEditor){this.toggleEditor();}}
return[row,editRow];};userSmarts.Map.LayerControl.prototype.toggleEditor=function(){if(!this.selected){alert("You must select a layer first!");return;}
var editor=this.selected.editor;if(editor){editor.toggle();this.selected.layer.visibleEditor=editor.isVisible();}};userSmarts.Map.LayerControl.prototype.forceRefresh=function(){if(this.autoRefresh){if(this.timeoutFunc){clearTimeout(this.timeoutFunc);}
this.updatesPending=true;this.checkIfUpdated();}else{this.updatesPending=false;var context=this.adapter.getProperty("context");if(context){context.touch();}}};userSmarts.Map.LayerControl.prototype.toggleAutoRefresh=function(){this.autoRefresh=!this.autoRefresh;if(this.autoRefresh){if(this.autoRefresher){this.autoRefresher.className='buttondown';}
if(userSmarts.Map.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
this.checkIfUpdated();}else{if(this.autoRefresher){this.autoRefresher.className='button';}
if(this.timeoutFunc){clearTimeout(this.timeoutFunc);}
if(userSmarts.Map.DEBUG_FLAG){logDebug("LayerBar auto-refresh disabled");}}};userSmarts.Map.LayerControl.prototype.checkIfUpdated=function(){if(this.updatesPending){var context=this.adapter.getProperty("context");if(context){context.touch();}
this.updatesPending=false;}
if(this.autoRefresh){var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};userSmarts.Map.LayerControl.prototype.onAdapterChange=function(event){var adapter=event.newValue;var context=adapter.getProperty('context');if(context){this.setProperty('context',context);}};userSmarts.Map.LayerControl.prototype.onContextChange=function(event){var context=event.newValue;if(this.layerAddedListener){disconnect(this.layerAddedListener);}
if(this.layerRemovedListener){disconnect(this.layerRemovedListener);}
if(this.layerChangedListener){disconnect(this.layerChangedListener);}
if(context){this.layerAddedListener=connect(context,userSmarts.Map.ViewContext.LAYER_ADDED_EVENT_PROPERTY,this,this.update);this.layerRemovedListener=connect(context,userSmarts.Map.ViewContext.LAYER_REMOVED_EVENT_PROPERTY,this,this.update);this.layerChangedListener=connect(context,userSmarts.Map.ViewContext.LAYER_CHANGED_EVENT_PROPERTY,this,this.update);}
this.repaint();};userSmarts.Map.LayerControl.prototype.onLayerChange=function(event){var found=false;var layer=event.source;for(var i=0;i<this.content.childNodes.length;i++){if(layer==this.content.childNodes[i].layer){found=true;break;}}
if(found){var entry=this.content.childNodes[i];var editor=this.content.childNodes[i+1];var context=this.adapter.getProperty("context");disconnect(this.connectListeners.visible[layer]);disconnect(this.connectListeners.active[layer]);disconnect(this.connectListeners.mouseover[layer]);disconnect(this.connectListeners.mouseout[layer]);disconnect(this.connectListeners.selection[layer]);var newEntries=this.createLayer(layer,context);this.content.replaceChild(newEntries[0],entry);this.content.replaceChild(newEntries[1],editor);}};userSmarts.Map.LayerControl.prototype.ready=function(){this.waitOnRefresh=false;};userSmarts.Map.LayerControl.prototype.touch=function(time){this.update();};userSmarts.Map.LayerControl.prototype.getSelectedLayer=function(){return this.selected.layer;};userSmarts.Map.LayerControl.prototype.moveLayer=function(direction,allTheWay){if(!this.adapter){return;}
var context=this.adapter.getProperty("context");if(!this.context){return;}
var layer=this.getSelectedLayer();if(!layer){return;}
this.moveLayerEntry(direction,allTheWay);if(allTheWay){if(direction<0){context.shiftTo(layer,context.layers.length-1,false);}else if(direction>0){context.shiftTo(layer,0,false);}}else{if(direction<0){context.shiftUp(layer,false);}else if(direction>0){context.shiftDown(layer,false);}}
this.updatesPending=true;};userSmarts.Map.LayerControl.prototype.moveLayerEntry=function(direction,allTheWay){var node=this.selected;var editor=node.nextSibling;var parent=node.parentNode;var targetNode=null;var justAppend=false;if(allTheWay){if(direction<0){targetNode=parent.childNodes[0];}
else if(direction>0){justAppend=true;}}else{if(direction<0){if(node.previousSibling){targetNode=node.previousSibling.previousSibling;}}else if(direction>0){if(editor.nextSibling){targetNode=editor.nextSibling.nextSibling;if(targetNode.nextSibling){targetNode=targetNode.nextSibling;}
else{justAppend=true;targetNode=null;}}}}
if(targetNode){parent.removeChild(node);parent.removeChild(editor);parent.insertBefore(node,targetNode);parent.insertBefore(editor,targetNode);}
if(justAppend===true){parent.removeChild(node);parent.removeChild(editor);parent.appendChild(node);parent.appendChild(editor);}};userSmarts.Map.LayerControl.prototype.clearConnectListeners=function(){var type;for(var i=0;i<this.connectListeners.types.length;i++){type=this.connectListeners.types[i];for(var lis in this.connectListeners[type]){try{disconnect(this.connectListeners[type][lis]);}catch(e){}}}};userSmarts.Map.LayerControl.prototype.dispose=function(){if(this.isDisposed){return;}
this.clearConnectListeners();this.connectListeners=null;disconnect(this.contextListener);this.contextListener=null;disconnect(this.adapterListener);this.adapterListener=null;this.autoRefresh=false;this.selected=null;if(this.header){disconnect(this.editorListener);this.editorListener=null;disconnect(this.manualRefreshListener);this.manualRefreshListener=null;disconnect(this.autoRefreshListener);this.autoRefreshListener=null;disconnect(this.shiftUpListener);this.shiftUpListener=null;disconnect(this.shiftDownListener);this.shiftDownListener=null;disconnect(this.shiftToTopListener);this.shiftToTopListener=null;disconnect(this.shiftToBottomListener);this.shiftToBottomListener=null;replaceChildNodes(this.refresher,null);this.refresher=null;replaceChildNodes(this.autoRefresher,null);this.autoRefresher=null;disposeImage(this.shiftUpper.childNodes[0]);replaceChildNodes(this.shiftUpper,null);this.shiftUpper=null;disposeImage(this.shiftDowner.childNodes[0]);replaceChildNodes(this.shiftDowner,null);this.shiftDowner=null;disposeImage(this.shiftToTop.childNodes[0]);replaceChildNodes(this.shiftToTop,null);this.shiftToTop=null;disposeImage(this.shiftToBottom.childNodes[0]);replaceChildNodes(this.shiftToBottom,null);this.shiftToBottom=null;replaceChildNodes(this.header,null);this.header=null;}
if(this.content){replaceChildNodes(this.content,null);this.content=null;}
this.isDisposed=true;if(this.widget){this.widget.dispose();this.widget=null;}};userSmarts.Map.LayerControlWidget=function(properties){properties=setdefault(properties,{id:'map-layer-widget',imagedir:'images/'});Bean.call(this,properties);};userSmarts.Map.LayerControlWidget.inheritsFrom(Bean);userSmarts.Map.LayerControlWidget.prototype.paint=function(context){if(!this.layout){this.layout=DIV({id:this.id,'class':this.className||'map-layer-bar'});this.currentControl=0;this.layout.appendChild(this.buildHeader());if(this.controls&&this.controls.length>0){this.paintedControls=[];for(var i=0;i<this.controls.length;i++){this.paintedControls.push(this.controls[i].paint());}
this.layout.appendChild(this.paintedControls[this.currentControl]);}
this.widget=this;}
return this.layout;};userSmarts.Map.LayerControlWidget.prototype.repaint=function(context){if(this.controls&&this.controls.length>0){var parent=this.controlHeader.parentNode;replaceChildNodes(parent,this.renderControlHeader());this.controls[this.currentControl].repaint();}};userSmarts.Map.LayerControlWidget.prototype.buildHeader=function(){var header=SPAN();var tabBar=this.buildTabs();var controlHeader=this.renderControlHeader();header.appendChild(TABLE({width:'100%',cellspacing:'0',cellpadding:'0',border:'0'},[THEAD({}),TBODY({},[TR({'class':'table-row','height':'20',width:'100%'},tabBar),TR({'class':'table-row','height':'20',width:'100%'},controlHeader)])]));return header;};userSmarts.Map.LayerControlWidget.prototype.renderControlHeader=function(){if(this.controlHeader){this.controlHeader=null;}
var result;if(this.controls[this.currentControl]&&typeof(this.controls[this.currentControl].buildHeader)=='function'){result=this.controls[this.currentControl].buildHeader();}else{result=TD({'class':'map-layer-bar-subheader',width:'100%','align':'right'});}
this.controlHeader=result;return result;};userSmarts.Map.LayerControlWidget.prototype.buildTabs=function(){if(!this.tabBar){this.tabBar=TD({'class':'table-row map-layer-bar-header',width:'100%'});}
if(this.controlTabListeners){var len=this.controlTabListeners.length;for(var i=0;i<len;i++){disconnect(this.controlTabListeners.shift());}}else{this.controlTabListeners=[];}
var results;if(this.controls&&this.controls.length>0){results=[];var tab;var tabName;for(var i=0;i<this.controls.length;i++){tabName=(this.controls[i].name||this.controls[i].id);tab=SPAN({'class':'button'},B({},tabName));if(this.currentControl==i){tab.className='buttondown';}
this.controlTabListeners.push(connect(tab,'onclick',bind(this.showControl,this,i)));results.push(tab);}}else{results="";}
replaceChildNodes(this.tabBar,results);return this.tabBar;};userSmarts.Map.LayerControlWidget.prototype.showControl=function(arg){var index=null;if(typeof(arg)=='number'){index=arg;}else if(typeof(arg)!='undefined'){for(var i=0;i<this.controls.length;i++){if(this.controls[i]===arg){index=i;break;}}}
if(index==null)return;var old=this.currentControl;this.currentControl=index;this.layout.replaceChild(this.paintedControls[this.currentControl],this.paintedControls[old]);var parent=this.controlHeader.parentNode;this.controlHeader=this.renderControlHeader();replaceChildNodes(parent,this.controlHeader);this.buildTabs();};userSmarts.Map.LayerControlWidget.prototype.toggleVisibility=function(){if(this.layout){if(this.layout.style.display!='none'){this.layout.style.display='none';}
else{this.layout.style.display='block';}}};userSmarts.Map.LayerControlWidget.prototype.dispose=function(){if(this.controlTabListeners){var len=this.controlTabListeners.length;for(var i=0;i<len;i++){disconnect(this.controlTabListeners.shift());}}
if(this.controlHeader){replaceChildNodes(this.controlHeader,null);this.controlHeader=null;}
if(this.tabBar){replaceChildNodes(this.tabBar,null);this.tabBar=null;}
if(this.layout){replaceChildNodes(this.layout,null);this.layout=null;}
var control;var len=this.controls.length;for(var i=0;i<len;i++){control=this.controls.shift();try{control.dispose();}catch(e){}
control=null;}
this.controls=null;};userSmarts.Map.ToolBar=function(properties){properties=setdefault(properties,{id:'mapToolBar_'+Math.random()});Bean.call(this,properties);this.modelListener=bind(this.repaint,this);this.addChangeListener(bind(function(event){this.onModelChange(event);},this),'model');};userSmarts.Map.ToolBar.inheritsFrom(Bean);userSmarts.Map.ToolBar.prototype.paint=function(context){if(!this.layout){this.layout=DIV({'class':'map-toolbar',id:this.id});}
this.repaint();return this.layout;};userSmarts.Map.ToolBar.prototype.repaint=function(context){if(!this.model){return;}
var arr=[];var tools=this.model.getTools();var out;for(var i=0;i<tools.length;i++){out=tools[i].paint();if(out.length){for(var j=0;j<out.length;j++){arr.push(out[j]);}}else{arr.push(out);}}
replaceChildNodes(this.layout,arr);};userSmarts.Map.ToolBar.prototype.onModelChange=function(event){var oldModel=event.oldValue;oldModel.removeChangeListener(this.modelListener,'modified');var newModel=event.newValue;newModel.addChangeListener(this.modelListener,'modified');};userSmarts.Map.ToolBar.prototype.findTool=function(toolId){return this.model.getTool(toolId);};userSmarts.Map.ToolBar.prototype.getModel=function(){return this.model;};ToolIconFactory=function(imagedir){this.imagedir=imagedir;};ToolIconFactory.prototype.create=function(classNameDefault,classNameHover,title){var img=IMG({src:this.imagedir+'spacer.gif','class':classNameDefault});img.onmouseover=function(){img.className=classNameHover;};img.onmouseout=function(){img.className=classNameDefault;};img.title=title;return img;};userSmarts.Map.ToolBarModel=function(properties){properties=setdefault(properties,{toolIds:[],tools:[],overrideHelp:false});Bean.call(this,properties);this.toolListener=bind(function(){this.setProperty('modified',true);},this);this.toolOffListener=bind(function(event){this.onToolDisabled(event);},this);this.readiedToolListener=bind(this.onToolReady,this);connect(this,'adapter',this,this.onAdapterChange);if(!this.overrideHelp){this.addTool(new userSmarts.Map.HelpTool({model:this,factory:this.factory}));}};userSmarts.Map.ToolBarModel.inheritsFrom(Bean);userSmarts.Map.ToolBarModel.prototype.onAdapterChange=function(event){for(var i=0;i<this.tools.length;++i){this.tools[i].setProperty("adapter",event.newValue);}};userSmarts.Map.ToolBarModel.prototype.onToolReady=function(event){this.nextEnabledTool=event.source;this.disableAllTools(event.source.getToolId());};userSmarts.Map.ToolBarModel.prototype.disableAllTools=function(toolId){if(userSmarts.Map.DEBUG_FLAG){var msg="Turning off remaining tools"+
(toolId!=null?" for "+toolId+" tool":"");logDebug(msg);}
this.numDisabledTools=(toolId!=null)?1:0;var tool;for(var i=0;i<this.tools.length;i++){tool=this.tools[i];if(!toolId||tool.id!=toolId){tool.disable();}}};userSmarts.Map.ToolBarModel.prototype.onToolDisabled=function(event){if(!this.tools)return;++this.numDisabledTools;if(this.numDisabledTools==this.tools.length){if(this.nextEnabledTool){this.nextEnabledTool.enable();this.nextEnabledTool=null;}}};userSmarts.Map.ToolBarModel.prototype.addTool=function(tool){if(this.debug){logDebug("ToolBar.Model : adding "+tool.getToolId());}
if(tool.addChangeListener){tool.addChangeListener(this.toolListener,'modified');tool.addChangeListener(this.readiedToolListener,'ready',function(event){return(event.newValue===true&&event.oldValue!==true);});tool.addChangeListener(this.toolOffListener,'disabled',function(event){return(event.newValue===true);});}
this.toolIds[tool.getToolId()]=tool;this.tools.push(tool);if(this.adapter){tool.setProperty('adapter',this.adapter);}};userSmarts.Map.ToolBarModel.prototype.removeTool=function(tool){if(tool.addChangeListener){tool.removeChangeListener(this.toolListener,'modified');tool.removeChangeListener(this.readiedToolListener,'ready');}
if(this.toolIds[tool.getToolId()]){this.toolIds[tool.getToolId()]=null;var index=-1;for(var i=0;i<this.tools.length;++i){if(this.tools[i].id=tool.id){index=i;break;}}
if(index>=0){this.tools.splice(index,1);}}
if(tool.adapter){tool.adapter=null;}};userSmarts.Map.ToolBarModel.prototype.getTools=function(){return this.tools;};userSmarts.Map.ToolBarModel.prototype.getTool=function(arg){var tool;if(typeof(arg)=='string'){tool=this.toolIds[arg];}
return tool;};userSmarts.Map.ToolBarModel.prototype.dispose=function(){this.factory=null;var tool;var len=this.tools.length;for(var i=0;i<len;i++){tool=this.tools[i];tool.setProperty("ready",false);tool.dispose();tool=null;}
this.tools=null;};userSmarts.Map.Tool=function(properties){if(isPrototype(arguments))return false;var props=setdefault(properties,{id:"",ready:false,enabled:false,disabled:true,debug:false});Bean.call(this,properties);this.init();};userSmarts.Map.Tool.inheritsFrom(Bean);userSmarts.Map.Tool.prototype.init=function(){this.enabledListener=connect(this,"enabled",this,this.onEnabledStateChange);this.readyListener=connect(this,"ready",this,this.onReadyStateChange);};userSmarts.Map.Tool.prototype.onReadyStateChange=function(event){if(event.newValue===false){this.disable();}};userSmarts.Map.Tool.prototype.onEnabledStateChange=function(event){};userSmarts.Map.Tool.prototype.enable=function(){if(this.enabled||this.onToolEnable()){this.disabled=false;this.setProperty("enabled",true);}else{logError("Unable to enable "+this.getToolId()+" tool");}};userSmarts.Map.Tool.prototype.disable=function(){if(this.disabled||this.onToolDisable()){this.enabled=false;this.setProperty("disabled",true);}else{logError("Unable to disable "+this.getToolId()+" tool");}};userSmarts.Map.Tool.prototype.onToolEnable=function(){return true;};userSmarts.Map.Tool.prototype.onToolDisable=function(){return true;};userSmarts.Map.Tool.prototype.getToolId=function(){return this.id;};userSmarts.Map.Tool.prototype.getNode=function(){return this.paint();};userSmarts.Map.Tool.prototype.paint=function(){return DIV();};userSmarts.Map.Tool.prototype.update=function(){this.repaint();};userSmarts.Map.Tool.prototype.repaint=function(){};userSmarts.Map.Tool.prototype.enableHover=function(icon,selectedClassName,className){if(!icon){if(!this.icon)return;else icon=this.icon;}
icon.onmouseover=function(){icon.className=selectedClassName;};icon.onmouseout=function(){icon.className=className;};};userSmarts.Map.Tool.prototype.disableHover=function(icon){if(!icon){if(!this.icon)return;else icon=this.icon;}
icon.onmouseover=null;icon.onmouseout=null;};userSmarts.Map.Tool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Abstract Tool : ');var text=document.createTextNode('Tool Description');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.Tool.prototype.dispose=function(){disconnect(this.enabledListener);this.enabledListener=null;disconnect(this.readyListener);this.readyListener=null;};userSmarts.Map.HelpTool=function(properties){properties=setdefault(properties,{id:'help'});userSmarts.Map.Tool.call(this,properties);};userSmarts.Map.HelpTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.HelpTool.prototype.paint=function(){var icon=this.factory.create('helptool','helptool-selected','Show Help');connect(icon,'onclick',this,this.showHelp);this.icon=icon;return this.icon;};userSmarts.Map.HelpTool.prototype.showHelp=function(){var holder;if(this.model){var output=[];var tools=this.model.getTools();var len=tools.length;for(var i=0;i<len;i++){if(tools[i]!=this){var toolinfo=tools[i].about();if(toolinfo){output.push(toolinfo);}}}
holder=DIV(null,output);top.consoleRef=window.open('','helpwindow','width=500,height=500,menubar=0,toolbar=0'+',status=0,scrollbars=1,resizable=1');top.consoleRef.document.writeln('<html>\n'+' <head>\n'+'  <title>userSmarts-GX Maps</title>\n'+'   <style type="text/css">\n'+'   .map-tool-title {\n'+'    font:bold 12px Helvetica;\n'+'   }\n'+'   .map-tool-about {\n'+'    background-color:#eeeeee;\n'+'    border: 1px solid #e0e0e0;\n'+'    font: 12px Helvetica;\n'+'    margin: 2px;\n'+'    padding: 2px;\n'+'   }\n'+'   .map-help-section {\n'+'    background-color:#eeeeee;\n'+'    border: 1px solid #e0e0e0;\n'+'    font: 12px Helvetica;\n'+'   }\n'+'   </style>\n'+' </head>\n'+' <body bgcolor="white" onLoad="self.focus()">\n'+'  <center>Map Help</center>\n'+'  <hr>\n'+'  <center>Tools</center>\n'+
holder.innerHTML+' </body>\n'+'</html>');top.consoleRef.document.close();}};userSmarts.Map.HelpTool.prototype.dispose=function(){disposeImage(this.icon);userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.BookmarkTool=function(properties){var props=setdefault(properties,{id:'bookmark'});userSmarts.Map.Tool.call(this,props);};userSmarts.Map.BookmarkTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.BookmarkTool.prototype.paint=function(){var newIcon=this.factory.create('bookmarktool','bookmarktool-selected','Bookmark Map');connect(newIcon,'onclick',this,this.activate);this.newIcon=newIcon;var backIcon=this.factory.create('bookmarktool-back','bookmarktool-back-selected','Previous Bookmark');connect(backIcon,'onclick',this,this.previous);this.backIcon=backIcon;var fwdIcon=this.factory.create('bookmarktool-forward','bookmarktool-forward-selected','Next Bookmark');connect(fwdIcon,'onclick',this,this.next);this.fwdIcon=fwdIcon;return[newIcon,backIcon,fwdIcon];};userSmarts.Map.BookmarkTool.prototype.activate=function(){if(this.adapter&&this.manager){var context=this.adapter.getProperty("context");var count=this.manager.getNumberOfSavedContexts();var recommendation='BM #'+(count+1);var name=prompt('Enter a name for this bookmark:',recommendation);if(!name)return;var index=this.manager.save(context.clone(),name);if(index<0){alert("Exceeded maximum bookmarks, please remove existing bookmarks first!");}}};userSmarts.Map.BookmarkTool.prototype.next=function(){if(this.manager){this.manager.next();}else{logWarning("Map.Tools.Bookmark : No Context Manager defined for maintaining context bookmarks!");}};userSmarts.Map.BookmarkTool.prototype.previous=function(){if(this.manager){this.manager.previous();}else{logWarning("Map.Tools.Bookmark : No Context Manager defined for maintaining context bookmarks!");}};userSmarts.Map.BookmarkTool.prototype.about=function(){var holder=DIV({'class':'map-tool-about'});holder.appendChild(SPAN({'class':'map-tool-title'},"Bookmark Tool : "));var text=document.createTextNode('When the bookmark tool icon is clicked, '+'the current state of the map (including visible layers and bounding region) is saved for later retrieval.  '+'When a state is saved, a bookmark is placed over the map on the left-hand side of the screen with a '+'user-assigned name or numeric identifier (1-10) if no name is provided.  Clicking the bookmark name '+'will restore the saved state associated that bookmark, and clicking the \'X\' will delete the '+'bookmark and its associated state.');holder.appendChild(text);holder.appendChild(BR());holder.appendChild(I({}," - Select Previous Bookmark : "));text=document.createTextNode('After creating a series of bookmarks, users can cycle backwards '+'through those bookmarks using this tool.  Clicking this tool icon will refresh the map with '+'the bookmark previous to the currently selected one and set the selected bookmark as the current.');holder.appendChild(text);holder.appendChild(BR());holder.appendChild(I({}," - Select Next Bookmark : "));text=document.createTextNode('After creating a series of bookmarks, users can cycle forwards '+'through those bookmarks using this tool.  Clicking this tool will refresh the map with the next '+'bookmark after the currently selected one and set the selected bookmark as the current.');holder.appendChild(text);return holder;};userSmarts.Map.BookmarkTool.prototype.dispose=function(){disposeImage(this.newIcon);this.newIcon=null;disposeImage(this.backIcon);this.backIcon=null;disposeImage(this.fwdIcon);this.fwdIcon=null;this.adapter=null;this.manager.dispose();userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.DescribeTool=function(properties){var props=setdefault(properties,{id:'describe'});userSmarts.Map.Tool.call(this,props);this.featureListener=connect(this,userSmarts.Map.DescribeTool.FEATURES,this,'logFeatures');this.addChangeListener(function(event){logError(event.newValue);},"error");};userSmarts.Map.DescribeTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.DescribeTool.FEATURES='features';userSmarts.Map.DescribeTool.prototype.paint=function(){var icon=this.factory.create('describetool','describetool-selected','Describe Feature');connect(icon,'onclick',this,this.toggleReady);this.icon=icon;return this.icon;};userSmarts.Map.DescribeTool.prototype.toggleReady=function(event){this.setProperty("ready",!this.ready);};userSmarts.Map.DescribeTool.prototype.onToolEnable=function(){if(!this.adapter)return false;this.icon.className="describetool-selected";this.disableHover(this.icon);var canvas=this.adapter.getProperty("canvas");this.canvasMouseListener=connect(canvas.content,'onmousedown',this,"capturePoint");return true;};userSmarts.Map.DescribeTool.prototype.onToolDisable=function(){if(this.canvasMouseListener){disconnect(this.canvasMouseListener);}
this.icon.className="describetool";this.enableHover(this.icon,'describetool-selected','describetool');return true;};userSmarts.Map.DescribeTool.prototype.capturePoint=function(e){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var point=canvas.getPointOnCanvas({x:e.mouse().client.x,y:e.mouse().client.y});this.describe(point);}};userSmarts.Map.DescribeTool.prototype.describe=function(point){var requests=this.buildRequests(point);var counter=0;var handler=this;var meta={callback:function(response){counter++;var features=response;var existingFeatures=handler[userSmarts.Map.DescribeTool.FEATURES];if(!existingFeatures){existingFeatures=[];}
for(var i=0;i<features.length;i++){existingFeatures.push(features[i]);}
if(this.debug){logDebug("Tool.Describe : Retrieved feature info from "+counter+" out of "+requests.length+" sources.");}
if(counter==requests.length){handler.setProperty(userSmarts.Map.DescribeTool.FEATURES,existingFeatures);}},errorHandler:function(error){logError("Tool.Describe :: Error querying wms - "+error);handler.setProperty('error',error);}};for(var i=0;i<requests.length;i++){WmsRemote.doGetFeatureInfo(requests[i],meta);}};userSmarts.Map.DescribeTool.prototype.buildRequests=function(point){var requests=[];if(this.adapter){var canvas=this.adapter.getProperty("canvas");var context=this.adapter.getProperty("context");var layers=context.getActiveLayers();var service="WMS";var version="1.1.1";var request="GetFeatureInfo";var srs=context.boundingBox.srs;var format="text/xml";var count=10;var width=parseInt(canvas.width);var height=parseInt(canvas.height);var x=point.x*1;var y=point.y*1;var box=context.boundingBox.getQueryString();var ex_format="text/xml";var usedIndices=[];for(var i=0;i<layers.length;++i){if(usedIndices[i]===true){continue;}
var ids=[];for(var j=i;j<layers.length;++j){if(layers[j].queryable){if(!layers[j].visible){logWarning("Layer '"+layers[j].getLayerName()+"' is not visible, but will be queried.");}
if((j==i)||(layers[i].server.url==layers[j].server.url)){usedIndices[j]=true;ids.push(layers[j].getLayerId());}}else{logWarning("Layer '"+layers[i].getLayerName()+"' is not queryable, ignoring...");}}
if(ids){requests.push({server:layers[i].server.url,version:version,request:request,srs:srs,format:format,count:count,width:width,height:height,x:x,y:y,exception:ex_format,bbox:box,layers:ids});}}}
return requests;};userSmarts.Map.DescribeTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Describe Tool : ');var text=document.createTextNode('To use the Describe Tool, activate any number of '+'visible layers using the Layer Bar.  After at least one layer is activated, clicking anywhere on the map '+'will generate a WMS GetFeatureInfo request for that specific point on the map and issue the request to '+'a WMS proxy service which relays requests and combines responses into feature responses.  The Describe Tool '+'relies upon externally-defined feature handlers to display results to the user, but a default \'alert\' handler '+'is provided.');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.DescribeTool.prototype.setFeatureHandler=function(listener){if(this.featureListener){disconnect(this.featureListener);}
this.featureListener=connect(this,userSmarts.Map.DescribeTool.FEATURES,listener);};userSmarts.Map.DescribeTool.prototype.logFeatures=function(event){var features=event.newValue;for(var i=0;i<features.length;i++){var feature=features[i];logDebug('FEATURE [LAYER='+feature.layer+']:');for(var k in feature.fields){logDebug(' --> '+k+' = '+feature.fields[k]);}}};userSmarts.Map.DescribeTool.prototype.dispose=function(){this.disable();disconnectAll(this);this.canvasMouseListener=null;disposeImage(this.icon);this.icon=null;this.adapter=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.DragTool=function(properties){var props=setdefault(properties,{id:'drag',canReset:true,draggable:null,dragHandler:new DragHandler()});userSmarts.Map.Tool.call(this,props);this.sTop=0;this.sLeft=0;};userSmarts.Map.DragTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.DragTool.prototype.paint=function(){var icon=this.factory.create('pantool','pantool-selected','Advanced Panning Tool');this.mouseListener=connect(icon,'onclick',this,"toggleReady");this.icon=icon;return this.icon;};userSmarts.Map.DragTool.prototype.toggleReady=function(){this.setProperty("ready",!this.ready);};userSmarts.Map.DragTool.prototype.onToolEnable=function(){if(this.enabled)return true;if(!this.adapter){logError("No adapter for tool");return false;}
if(this.icon){this.icon.className="pantool-selected";this.disableHover(this.icon);}
var canvas=this.adapter.getProperty("canvas");if(!this.canvasListener){this.canvasListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,'reset');}
this.sLeft=parseInt(canvas.layout.style.left);this.sTop=parseInt(canvas.layout.style.top);this.dragHandler.init(canvas.content,canvas.layout);this.dragHandler.startHandler=bind(function(dragger){this.canReset=false;},this);this.dragHandler.endHandler=bind(function(dragger){this.onDragEnd(dragger);},this);return true;};userSmarts.Map.DragTool.prototype.disable=function(){if(this.disabled){this.enabled=false;this.setProperty("disabled",true);return;}
if(!this.canReset){this.timeoutCheck=setTimeout(bind(function(){this.disable();},this),750);}else{if(this.icon){this.icon.className="pantool";this.enableHover(this.icon,'pantool-selected','pantool');}
disconnect(this.canvasListener);this.canvasListener=null;if(this.dragHandler){this.dragHandler.disable();}
this.timeoutCheck=null;this.ready=false;this.enabled=false;this.setProperty("disabled",true);}};userSmarts.Map.DragTool.prototype.onDragEnd=function(dragger){var px=dragger.clipLeft/parseInt(dragger.obj.style.width);var py=dragger.clipTop/parseInt(dragger.obj.style.height);if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(px,-py);this.dragHandler.block();}};userSmarts.Map.DragTool.prototype.reset=function(){if(!this.enabled)return;if(!this.adapter){logError("DragTool is unable to reset due to lack of adapter");}
var canvas=this.adapter.getProperty("canvas");var theImage=canvas.context;var theCanvas=canvas.layout;var imgWidth=parseInt(theCanvas.style.width);var imgHeight=parseInt(theCanvas.style.height);theCanvas.style.left=this.sLeft+"px";theCanvas.style.top=this.sTop+"px";if(theCanvas.clip){theCanvas.clip.left=0;theCanvas.clip.top=0;theCanvas.clip.right=imgWidth;theCanvas.clip.bottom=imgHeight;}else{theCanvas.style.clip="rect(0px, "+imgWidth+"px, "+imgHeight+"px, 0px)";}
this.dragHandler.resume();if(this.debug){logDebug("Tool.Drag : resetting to ("+theCanvas.style.left+","+theCanvas.style.top+") and "+theCanvas.style.clip);}
this.canReset=true;};userSmarts.Map.DragTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Pan-by-Dragging Tool : ');var text=document.createTextNode('Once the tool has been selected, '+'click and hold the left mouse button on the map.  While holding, drag the mouse in any '+'direction to move the map.  To stop dragging, release the left mouse button and the map '+'will automatically refresh with the new location data.');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.DragTool.prototype.dispose=function(){this.dragHandler.disable();if(this.mouseListener){disconnect(this.mouseListener);}
if(this.canvasListener){disconnect(this.canvasListener);}
this.mouseListener=null;disposeImage(this.icon);this.icon=null;this.adapter=null;this.dragHandler=null;if(this.timeoutCheck){clearTimeout(this.timeoutCheck);}
userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.PresetCircleTool=function(properties){var props=setdefault(properties,{id:'preset-circle'});if(isPrototype(arguments)){return;}
userSmarts.Map.Tool.call(this,props);};userSmarts.Map.PresetCircleTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.PresetCircleTool.prototype.paint=function(){icon=this.factory.create('presetcircletool','presetcircletool-selected','Preset Circle Selection Tool');connect(icon,'onclick',this,this.onIconClick);this.icon=icon;return icon;};userSmarts.Map.PresetCircleTool.prototype.onIconClick=function(evt){this.setProperty("ready",!this.ready);};userSmarts.Map.PresetCircleTool.prototype.onToolEnable=function(){if(!this.adapter)return false;if(this.icon){this.icon.className="presetcircletool-selected";this.disableHover(this.icon);}
var canvas=this.adapter.getProperty("canvas");this.bounds={minX:0,minY:0,maxX:0+parseInt(canvas.width),maxY:0+parseInt(canvas.height)};this.captureListener=connect(canvas.layout,'onclick',this,this.capturePoint);return true;};userSmarts.Map.PresetCircleTool.prototype.onToolDisable=function(){if(this.icon){this.icon.className="presetcircletool";this.enableHover(this.icon,"presetcircletool-selected","presetcircletool");}
if(this.captureListener){disconnect(this.captureListener);this.captureListener=null;}
return true;};userSmarts.Map.PresetCircleTool.prototype.about=function(){var holder=DIV({'class':'map-tool-about'});holder.appendChild(SPAN({'class':'map-tool-title'},'Preset Circle Selection Tool : '));var text=document.createTextNode('Once the tool has been selected, '+'Click on the map to place the circle\'s center point.  While holding down the left mouse button, '+'drag the mouse in any direction to specify the radius.  After the mouse button is released, the circle '+'will be drawn according to the selected center point and specified radius value.');holder.appendChild(text);return holder;};userSmarts.Map.PresetCircleTool.prototype.capturePoint=function(evt){var e=evt.event();e=fixE(e);if(this.adapter){var canvas=this.adapter.getProperty("canvas");point=canvas.getPointOnCanvas({x:e.clientX,y:e.clientY});var dialog=new userSmarts.Map.RadiusDialog();dialog.setPosition(e.clientX,e.clientY);var def=dialog.open();def.addCallback(bind(function(okPressed){if(okPressed){var radius=dialog.getRadius();this.buildCircle(point,radius);}},this));}else{logError("No adapter registered for PresetCircleTool, unable to create circle");}};userSmarts.Map.PresetCircleTool.prototype.buildCircle=function(point,radius){if(this.adapter){var canvas=this.adapter.getProperty('canvas');var context=this.adapter.getProperty('context');var overlays=this.adapter.getProperty('overlays');var renderer=this.adapter.getProperty('renderer');var circle=new Geometry("Circle");var centerWSPoint=canvas.projectPoint(point);var centerLLPoint=context.unproject(centerWSPoint.x,centerWSPoint.y);var lon=centerLLPoint[0]*1.0;var lat=centerLLPoint[1]*1.0;var radiusInDegrees=distanceToDegrees(radius);var llWSPoint=context.project(lon-radiusInDegrees,lat-radiusInDegrees);var llPoint=canvas.unprojectPoint({x:llWSPoint[0],y:llWSPoint[1]});var dx=Math.abs(point.x-llPoint.x);var dy=Math.abs(point.y-llPoint.y);var dz=Math.floor(Math.sqrt((dx*dx)+(dy*dy)));var offsetY=Math.min(point.y-this.bounds.minY,this.bounds.maxY-point.y);var offsetMaxX=Math.min(this.bounds.maxX-point.x,offsetY);var offsetMinX=Math.min(point.x-this.bounds.minX,offsetMaxX);dz=Math.min(dz,offsetMinX);var endPoint=new Point(point.x+dz,point.y-dz);point.x-=dz;point.y+=dz;circle.addPoint(point);circle.addPoint(endPoint);var min=canvas.projectPoint(point);var max=canvas.projectPoint(endPoint);var x1=min.x;var x2=max.x;var y1=min.y;var y2=max.y;if(context&&context.unproject){min=context.unproject(x1,y1);max=context.unproject(x2,y2);x1=min[0];y1=min[1];x2=max[0];y2=max[1];}
var diameter=getDistance(x1,y1,x2,y2);var geom=new Geometry("Circle");geom.addPoint(canvas.projectPoint(point));geom.addPoint(canvas.projectPoint(endPoint));var re=renderer.render(circle);if(re){circle.overlay=new userSmarts.Map.WSOverlay({wsgeometry:geom,ssgeometry:circle});var button=re.lastChild;button.title=(diameter/2).toFixed(2)+" miles.  Click to close.";circle.overlay.setContent(re);overlays.add(circle.overlay);}
this.setProperty('geometry',geom);}
return false;};userSmarts.Map.PresetCircleTool.prototype.dispose=function(){this.disable();disconnectAll(this);disposeImage(this.icon);this.icon=null;this.adapter=null;this.bounds=null;if(this.overlay){replaceChildNodes(this.overlay,null);this.overlay=null;}
userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.RadiusDialog=function(properties){properties=properties||{};setdefault(properties,{title:"Specify Radius",modal:false,width:200,height:75,radius:1});userSmarts.wt.dialogs.Dialog.call(this,properties);};userSmarts.Map.RadiusDialog.inheritsFrom(userSmarts.wt.dialogs.Dialog);userSmarts.Map.RadiusDialog.prototype.createDialogArea=function(parent){this.datatype={uri:{prefix:'map',namespaceURI:'http://www.usersmarts.com/map',localPart:"radiusType"},facets:{enumeration:[{value:1,label:"1"},{value:5,label:"5"},{value:10,label:"10"}]}};parent.appendChild(document.createTextNode("NOTE: Rendered circle may be clipped by viewable area."));parent.appendChild(BR());parent.appendChild(BR());parent.appendChild(document.createTextNode("Radius (in miles): "));var props={name:"RADIUS_FIELD",title:"Radius Value",value:this.radius,size:10,optionModel:new userSmarts.wt.forms.DefaultOptionModel({datatype:this.datatype}),parent:this,binding:new BeanPropertyBinding(this,'radius')};var select=new userSmarts.wt.forms.Field(props);parent.appendChild(select.paint());};userSmarts.Map.RadiusDialog.prototype.getRadius=function(){return this.radius*1;};userSmarts.Map.RadiusDialog.prototype.validate=function(){if(!this.radius||isNaN(this.radius)){this.invalidate();return;}
try{this.radius*=1;if(this.radius<0){this.invalidate();}}catch(e){this.invalidate();return;}
var okBtn=this.getOKButton();okBtn.disabled=false;};userSmarts.Map.RadiusDialog.prototype.invalidate=function(){this.radius=1;var okBtn=this.getOKButton();okBtn.disabled=true;};userSmarts.Map.GeometryTool=function(properties){var props=setdefault(properties,{id:'geometry',dragHandler:new DragHandler(),x1:null,y1:null,currentPolygon:null,threshold:20,currentEllipse:null});if(isPrototype(arguments)){return;}
userSmarts.Map.Tool.call(this,props);};userSmarts.Map.GeometryTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.GeometryTool.prototype.paint=function(){var icons=[];var bboxIcon=this.factory.create('boxtool','boxtool-selected','Bounding Box Selection Tool');this.bboxMouseListener=connect(bboxIcon,'onclick',this,this.toggleBboxReady);this.bboxIcon=bboxIcon;icons.push(bboxIcon);var polygonIcon=this.factory.create('polygontool','polygontool-selected','Polygon Selection Tool');this.polyMouseListener=connect(polygonIcon,'onclick',this,this.togglePolygonReady);this.polygonIcon=polygonIcon;icons.push(polygonIcon);var ellipseIcon=this.factory.create('ellipsetool','ellipsetool-selected','Ellipse Selection Tool');this.ellipseMouseListener=connect(ellipseIcon,'onclick',this,this.toggleEllipseReady);this.ellipseIcon=ellipseIcon;icons.push(ellipseIcon);return icons;};userSmarts.Map.GeometryTool.prototype.onToolEnable=function(){var result=false;if(this.boundingBoxEnabled){result=this.enableBoundingBox();}else if(this.polygonEnabled){result=this.enablePolygon();}else if(this.ellipseEnabled){result=this.enableEllipse();}
return result;};userSmarts.Map.GeometryTool.prototype.onToolDisable=function(){var result=false;if(this.boundingBoxEnabled){result=this.disableBoundingBox();}else if(this.polygonEnabled){result=this.disablePolygon();}else if(this.ellipseEnabled){result=this.disableEllipse();}
return result;};userSmarts.Map.GeometryTool.prototype.about=function(){var bbi=DIV({'class':'map-tool-about'});bbi.appendChild(SPAN({'class':'map-tool-title'},"Bounding Box Selection Tool : "));bbi.appendChild(document.createTextNode("Once this tool is active, "+"click and hold the left mouse button while over the map and drag a bounding box "+"around any region of the map.  Finally, release the left mouse button to select the region. "));var pi=DIV({'class':'map-tool-about'});pi.appendChild(SPAN({'class':'map-tool-title'},"Polygon Selection Tool : "));pi.appendChild(document.createTextNode("Once the tool has been selected, "+"Click on the map to place any number of points.  Lines are drawn between successive points.  "+"If any point is within a certain threshold distance from the first point, the polygon is closed "+"using the starting point and a new polygon is started."));var ci=DIV({'class':'map-tool-about'});ci.appendChild(SPAN({'class':'map-tool-title'},"Circle Selection Tool : "));ci.appendChild(document.createTextNode("Once the tool has been selected, "+"Click on the map to place the circle\'s center point.  While holding down the left mouse button, "+"drag the mouse in any direction to specify the radius.  After the mouse button is released, the circle "+"will be drawn according to the selected center point and specified radius value."));return DIV({},bbi,pi,ci);};userSmarts.Map.GeometryTool.prototype.capturePoint=function(e){e=fixE(e);var point={x:e.clientX,y:e.clientY};if(this.adapter){var canvas=this.adapter.getProperty("canvas");var point=canvas.getPointOnCanvas({x:e.clientX,y:e.clientY});}
return point;};userSmarts.Map.GeometryTool.prototype.toggleBboxReady=function(){if(!this.boundingBoxEnabled){if(this.polygonEnabled){this.disablePolygon();this.boundingBoxEnabled=true;this.enableBoundingBox();return;}else if(this.ellipseEnabled){this.disableEllipse();this.boundingBoxEnabled=true;this.enableBoundingBox();return;}else{this.boundingBoxEnabled=true;this.setProperty("ready",true);}}else{this.setProperty("ready",false);}};userSmarts.Map.GeometryTool.prototype.togglePolygonReady=function(){if(!this.polygonEnabled){if(this.boundingBoxEnabled){this.disableBoundingBox();this.polygonEnabled=true;this.enablePolygon();return;}else if(this.ellipseEnabled){this.disableEllipse();this.polygonEnabled=true;this.enablePolygon();return;}else{this.polygonEnabled=true;this.setProperty("ready",true);}}else{this.setProperty("ready",false);}};userSmarts.Map.GeometryTool.prototype.toggleEllipseReady=function(){if(!this.ellipseEnabled){if(this.polygonEnabled){this.disablePolygon();this.ellipseEnabled=true;this.enableEllipse();return;}else if(this.boundingBoxEnabled){this.disableBoundingBox();this.ellipseEnabled=true;this.enableEllipse();return;}else{this.ellipseEnabled=true;this.setProperty("ready",true);}}else{this.setProperty("ready",false);}};userSmarts.Map.GeometryTool.prototype.enableBoundingBox=function(){if(!this.adapter){return false;}
if(this.bboxIcon){this.bboxIcon.className="boxtool-selected";this.disableHover(this.bboxIcon);}
var canvas=this.adapter.getProperty("canvas");this.dragHandler.init(canvas.content,canvas.layout);this.dragHandler.startHandler=bind(function(e,dragger){this.onBoundingBoxDragStart(e,dragger);},this);this.dragHandler.dragHandler=bind(function(e,dragger){this.onBoundingBoxDrag(e,dragger);},this);this.dragHandler.endHandler=bind(function(dragger){this.onBoundingBoxDragEnd(dragger);},this);this.box=null;var layout=this.adapter.getProperty("layout");for(var i=0;i<layout.childNodes.length;++i){if(layout.childNodes[i].className=='bounding-box'){this.box=layout.childNodes[i];}}
if(!this.box){this.box=DIV({'class':'bounding-box'});this.box.style.position='absolute';this.box.style.top='0px';this.box.style.left='0px';this.box.style.width='0px';this.box.style.height='0px';this.box.style.border='2px dashed black';this.box.style.visibility='hidden';layout.appendChild(this.box);}
return true;};userSmarts.Map.GeometryTool.prototype.disableBoundingBox=function(){this.boundingBoxEnabled=false;if(this.bboxIcon){this.bboxIcon.className="boxtool";}
this.enableHover(this.bboxIcon,"boxtool-selected","boxtool");if(this.dragHandler){this.dragHandler.disable();}
if(this.box){this.box.style.visibility='hidden';}
return true;};userSmarts.Map.GeometryTool.prototype.onBoundingBoxDragStart=function(e){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var pos=elementPosition(canvas.layout);var point={x:e.clientX-pos.x+parseInt(document.body.scrollLeft),y:e.clientY-pos.y+parseInt(document.body.scrollTop)};this.box.x1=point.x-parseInt(this.box.style.borderLeftWidth);this.box.y1=point.y-parseInt(this.box.style.borderLeftWidth);this.bounds={minX:0,minY:0,maxX:0+parseInt(canvas.width),maxY:0+parseInt(canvas.height)};}};userSmarts.Map.GeometryTool.prototype.onBoundingBoxDrag=function(e){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var pos=elementPosition(canvas.layout);var point={x:e.clientX-pos.x+parseInt(document.body.scrollLeft),y:e.clientY-pos.y+parseInt(document.body.scrollTop)};if(point.x<this.bounds.minX){point.x=this.bounds.minX+1;}else if(point.x>this.bounds.maxX){point.x=(window.event)?this.bounds.maxX+1:this.bounds.maxX-1;}
if(point.y<this.bounds.minY){point.y=this.bounds.minY+1;}else if(point.y>this.bounds.maxY){point.y=(window.event)?this.bounds.maxY+2:this.bounds.maxY-1;}
var width=point.x-this.box.x1-parseInt(this.box.style.borderLeftWidth);var height=point.y-this.box.y1-parseInt(this.box.style.borderTopWidth);this.box.style.visibility="visible";if(width<0){this.box.style.left=point.x+"px";this.box.style.width=-width+"px";}else{this.box.style.left=this.box.x1+"px";this.box.style.width=width+"px";}
if(height<0){this.box.style.top=point.y+"px";this.box.style.height=-height+"px";}else{this.box.style.top=this.box.y1+"px";this.box.style.height=height+"px";}}};userSmarts.Map.GeometryTool.prototype.onBoundingBoxDragEnd=function(dragger){var bw=parseInt(this.box.style.width);var bh=parseInt(this.box.style.height);if((bw>-5&&bw<5)&&(bh>-5&&bh<5)){this.disable();return;}
if(this.adapter){var canvas=this.adapter.getProperty("canvas");var renderer=this.adapter.getProperty("renderer");var overlays=this.adapter.getProperty("overlays");var boxleft=parseInt(this.box.style.left);var boxtop=parseInt(this.box.style.top);var boxwidth=parseInt(this.box.style.width);var boxheight=parseInt(this.box.style.height);var unprojectedGeometry=new Geometry("Box");unprojectedGeometry.addPoint({x:boxleft,y:boxtop+boxheight});unprojectedGeometry.addPoint({x:boxleft+boxwidth,y:boxtop});var renderedGeometry=renderer.render(unprojectedGeometry);this.box.style.visibility='hidden';var context=this.adapter.getProperty("context");if(context&&typeof(context.unproject)=='function'&&renderedGeometry){var ll=canvas.projectPoint({x:boxleft,y:boxtop+boxheight});var lr=canvas.projectPoint({x:boxleft+boxwidth,y:boxtop+boxheight});var ur=canvas.projectPoint({x:boxleft+boxwidth,y:boxtop});ll=context.unproject(ll.x,ll.y);lr=context.unproject(lr.x,lr.y);ur=context.unproject(ur.x,ur.y);var w=getDistance(ll[0],ll[1],lr[0],lr[1]);var h=getDistance(lr[0],lr[1],ur[0],ur[1]);var area=w*h;if(renderedGeometry){var button=renderedGeometry.lastChild;button.title=area.toFixed(2)+" sq mi.  Click to close.";}}
var geom=new Geometry("Box");var min=canvas.projectPoint({x:boxleft,y:boxtop+boxheight});geom.addPoint(min);var max=canvas.projectPoint({x:boxleft+boxwidth,y:boxtop});geom.addPoint(max);if(renderedGeometry&&geom){var overlay=new userSmarts.Map.WSOverlay({id:'box_'+Math.random(),className:'geometry-overlay',wsgeometry:geom,ssgeometry:unprojectedGeometry});overlay.setContent(renderedGeometry);overlays.add(overlay);}
this.setProperty("geometry",geom);}};userSmarts.Map.GeometryTool.prototype.enablePolygon=function(){if(!this.adapter)return false;this.polygonIcon.className="polygontool-selected";this.disableHover(this.polygonIcon);var canvas=this.adapter.getProperty("canvas");canvas.content.onmousedown=bind(this.buildPolygon,this);return true;};userSmarts.Map.GeometryTool.prototype.disablePolygon=function(){if(this.currentPolygon){this.currentPolygon.addPoint(this.currentPolygon.points[0]);this.closePolygon();}
if(this.adapter){var canvas=this.adapter.getProperty("canvas");if(canvas&&canvas.content){canvas.content.onmousedown=null;}}
this.polygonEnabled=false;this.polygonIcon.className="polygontool";this.enableHover(this.polygonIcon,'polygontool-selected','polygontool');return true;};userSmarts.Map.GeometryTool.prototype.buildPolygon=function(e){var point=this.capturePoint(e);if(this.adapter){var renderer=this.adapter.getProperty('renderer');var canvas=this.adapter.getProperty('canvas');var overlays=this.adapter.getProperty('overlays');var closed=false;var overlay;if(!this.currentPolygon){this.currentPolygon=new Geometry("Polygon");overlay=new userSmarts.Map.WSOverlay({id:'polygon-'+Math.random(),className:'geometry-overlay',wsgeometry:null,ssgeometry:this.currentPolygon});this.currentPolygon.overlay=overlay;overlays.add(this.currentPolygon.overlay);}
var points=this.currentPolygon.getPoints();if(points.length>0){var dx=Math.abs(points[0].x-point.x);var dy=Math.abs(points[0].y-point.y);var dz=dx*dx+dy*dy;if(dz<(this.threshold*this.threshold)){point=points[0];closed=true;}}
this.currentPolygon.addPoint(point);var rp=renderer.renderPoint({x:point.x-1,y:point.y-1,width:3,height:3});if(rp){this.currentPolygon.overlay.addContent(rp);}
if(points.length>1){var point1=points[points.length-2];var point2=points[points.length-1];var rp=renderer.renderLine(point1,point2,2,true);if(rp){this.currentPolygon.overlay.addContent(rp);}}
if(closed){this.closePolygon();}}};userSmarts.Map.GeometryTool.prototype.closePolygon=function(){if(this.adapter){var renderer=this.adapter.getProperty("renderer");var canvas=this.adapter.getProperty("canvas");var rp=renderer.render(this.currentPolygon);if(rp){this.currentPolygon.overlay.setContent(rp);}
var geom=new Geometry('Polygon');var points=this.currentPolygon.getPoints();for(var ci=0;ci<points.length;ci++){var p=points[ci];geom.addPoint(canvas.projectPoint(p));}
this.currentPolygon.overlay.setWSGeometry(geom);delete this.currentPolygon.overlay;this.setProperty('geometry',geom);}
this.currentPolygon=null;};userSmarts.Map.GeometryTool.prototype.enableEllipse=function(){if(!this.adapter)return true;this.ellipseIcon.className="ellipsetool-selected";this.disableHover(this.ellipseIcon);var canvas=this.adapter.getProperty("canvas");this.bounds={minX:0,minY:0,maxX:0+parseInt(canvas.width),maxY:0+parseInt(canvas.height)};this.dragHandler.init(canvas.content,canvas.layout);this.dragHandler.startHandler=bind(function(e,dragger){this.onEllipseDragStart(e,dragger);},this);this.dragHandler.dragHandler=bind(function(e,dragger){this.onEllipseDrag(e,dragger);},this);this.dragHandler.endHandler=bind(function(dragger){this.onEllipseDragEnd(dragger);},this);return true;};userSmarts.Map.GeometryTool.prototype.disableEllipse=function(){this.ellipseEnabled=false;this.ellipseIcon.className="ellipsetool";this.enableHover(this.ellipseIcon,"ellipsetool-selected","ellipsetool");if(this.adapter){var canvas=this.adapter.getProperty("canvas");if(canvas&&canvas.content){canvas.content.onmousedown=null;}}
if(this.dragHandler){this.dragHandler.disable();}
return true;};userSmarts.Map.GeometryTool.prototype.onEllipseDragStart=function(e,dragger){var point=this.capturePoint(e);this.buildEllipse(point);};userSmarts.Map.GeometryTool.prototype.onEllipseDrag=function(e,dragger){var x=e.clientX;var y=e.clientY;if(!this.endPoint){this.endPoint={x:x,y:y};}else{this.endPoint.x=x;this.endPoint.y=y;}};userSmarts.Map.GeometryTool.prototype.onEllipseDragEnd=function(dragger){if(this.endPoint){var point=this.capturePoint({clientX:this.endPoint.x,clientY:this.endPoint.y});this.buildEllipse(point);}};userSmarts.Map.GeometryTool.prototype.buildEllipse=function(point){if(this.adapter){var canvas=this.adapter.getProperty('canvas');var overlays=this.adapter.getProperty('overlays');var renderer=this.adapter.getProperty('renderer');var overlay;if(!this.currentEllipse){this.currentEllipse=new Geometry("Circle");overlay=new userSmarts.Map.WSOverlay({id:"circle-"+Math.random(),className:'geometry-overlay',wsgeometry:null,ssgeometry:this.currentEllipse});this.currentEllipse.overlay=overlay;overlays.add(overlay);}
var points=this.currentEllipse.getPoints();if(points.length<1){this.currentEllipse.addPoint(point);var re=renderer.renderPoint({x:point.x-1,y:point.y-1,width:3,height:3});if(re){this.currentEllipse.overlay.addContent(re);}
return false;}
var dx=Math.abs(point.x-points[0].x);var dy=Math.abs(point.y-points[0].y);var dz=Math.floor(Math.sqrt((dx*dx)+(dy*dy)));var offsetY=Math.min(points[0].y-this.bounds.minY,this.bounds.maxY-points[0].y);var offsetMaxX=Math.min(this.bounds.maxX-points[0].x,offsetY);var offsetMinX=Math.min(points[0].x-this.bounds.minX,offsetMaxX);dz=Math.min(dz,offsetMinX);var endPoint=new Point(points[0].x+dz,points[0].y-dz);points[0].x-=dz;points[0].y+=dz;this.currentEllipse.addPoint(endPoint);var re=renderer.render(this.currentEllipse);if(re){this.currentEllipse.overlay.setContent(re);}
var context=this.adapter.getProperty("context");if(context&&typeof(context.unproject)=='function'&&re){var min=canvas.projectPoint(points[0]);var max=canvas.projectPoint(points[1]);min=context.unproject(min.x,min.y);max=context.unproject(max.x,max.y);var diameter=getDistance(min[0],min[1],max[0],max[1]);if(re){var button=re.lastChild;button.title=(diameter/2).toFixed(2)+" miles.  Click to close.";}}
var geom=new Geometry("Circle");for(var ci=0;ci<points.length;ci++){geom.addPoint(canvas.projectPoint(points[ci]));}
this.currentEllipse.overlay.setWSGeometry(geom);delete this.currentEllipse.overlay;this.setProperty('geometry',geom);this.currentEllipse=null;}
return false;};userSmarts.Map.GeometryTool.prototype.createEllipse=function(){this.currentEllipse=new Geometry("Circle");this.currentEllipse.div=DIV();this.div.appendChild(this.currentEllipse.div);return this.currentEllipse;};userSmarts.Map.GeometryTool.prototype.dispose=function(){this.disable();if(this.bboxMouseListener){disconnect(this.bboxMouseListener);this.bboxMouseListener=null;}
if(this.polyMouseListener){disconnect(this.polyMouseListener);this.polyMouseListener=null;}
if(this.ellipseMouseListener){disconnect(this.ellipseMouseListener);this.ellipseMouseListener=null;}
disconnectAll(this);disposeImage(this.bboxIcon);this.bboxIcon=null;disposeImage(this.polygonIcon);this.polygonIcon=null;disposeImage(this.ellipseIcon);this.ellipseIcon=null;this.adapter=null;this.dragHandler=null;this.box=null;this.points=null;this.bounds=null;if(this.overlay){replaceChildNodes(this.overlay,null);this.overlay=null;}
this.currentPolygon=null;this.currentEllipse=null;this.endPoint=null;this.points=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.MeasureTool=function(properties){var props=setdefault(properties,{id:'measure',units:'mi',points:[],totalDistance:0});userSmarts.Map.Tool.call(this,props);};userSmarts.Map.MeasureTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.MeasureTool.prototype.paint=function(context){var icon=this.factory.create('measuretool','measuretool-selected','Measure Tool');connect(icon,'onclick',this,this.toggleReady);this.icon=icon;return this.icon;};userSmarts.Map.MeasureTool.prototype.toggleReady=function(event){this.setProperty("ready",!this.ready);};userSmarts.Map.MeasureTool.prototype.onToolEnable=function(){if(!this.adapter)return false;var canvas=this.adapter.getProperty("canvas");this.canvasMouseListener=connect(canvas.content,'onmousedown',this,this.capturePoint);this.icon.className='measuretool-selected';this.disableHover(this.icon);this.canvasReloadListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,this.disable);return true;};userSmarts.Map.MeasureTool.prototype.onToolDisable=function(){if(this.canvasMouseListener){disconnect(this.canvasMouseListener);this.canvasMouseListener=null;}
if(this.canvasReloadListener){disconnect(this.canvasReloadListener);this.canvasReloadListener=null;}
if(this.icon){this.icon.className='measuretool';this.enableHover(this.icon,'measuretool-selected','measuretool');}
this.reset();this.ready=false;return true;};userSmarts.Map.MeasureTool.prototype.setUnits=function(units){this.units=units;};userSmarts.Map.MeasureTool.prototype.capturePoint=function(m_e){var m=m_e.mouse();var mouseX=m.client.x;var mouseY=m.client.y;if(this.adapter){var canvas=this.adapter.getProperty("canvas");var pos=elementPosition(canvas.layout);var scrollOffset=(parseInt(canvas.layout.scrollOffset)||0);var point={x:mouseX-pos.x+document.body.scrollLeft,y:(mouseY-scrollOffset)-pos.y+parseInt(document.body.scrollTop)};if(!this.overlay){var overlays=this.adapter.getProperty('overlays');this.overlay=new userSmarts.Map.Overlay();overlays.add(this.overlay);}
var renderer=this.adapter.getProperty("renderer");var rp=renderer.renderPoint({x:point.x-2,y:point.y-2,width:4,height:4});if(rp){this.overlay.addContent(rp);}
this.points.push(point);if(this.points.length>1){var sp=this.points[this.points.length-2];var ep=this.points[this.points.length-1];var rl=renderer.renderLine({x:sp.x,y:sp.y},{x:ep.x,y:ep.y},2,true);if(rl){this.overlay.addContent(rl);}
var min=canvas.projectPoint(ep);var max=canvas.projectPoint(sp);var x1=min.x;var x2=max.x;var y1=min.y;var y2=max.y;var context=this.adapter.getProperty('context');if(context&&context.unproject){var min=context.unproject(x1,y1);var max=context.unproject(x2,y2);x1=min[0];y1=min[1];x2=max[0];y2=max[1];}
var mx=(ep.x>sp.x)?Math.floor((ep.x-sp.x)/2)+sp.x:Math.floor((sp.x-ep.x)/2)+ep.x;var my=(ep.y>sp.y)?Math.floor((ep.y-sp.y)/2)+sp.y:Math.floor((sp.y-ep.y)/2)+ep.y;var dist=getDistance(x1,y1,x2,y2);this.totalDistance+=dist;var localDistance=convertUnits(dist,'mi',this.units)*1;if(typeof(localDistance)=='number'){localDistance=localDistance.toFixed(2);}
var globalDistance=convertUnits(this.totalDistance,'mi',this.units)*1;if(typeof(globalDistance)=='number'){globalDistance=globalDistance.toFixed(2);}
var labelValue=localDistance+' '+this.units+' ('+globalDistance+' total)';var label=makeLabel(mx,my,120,null,labelValue);if(label){this.overlay.addContent(label);}}}};userSmarts.Map.MeasureTool.prototype.reset=function(){if(this.overlay){this.overlay.setContent(SPAN());this.totalDistance=0;this.points=[];}};userSmarts.Map.MeasureTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Measure Tool : ');var text=document.createTextNode('This tool allows users to measure distances on the map.  '+'Activate the Measure Tool and click on the map to place markers.  Between each pair of markers, the distance '+'from the first marker to the second is shown in user-configurable units.  After this value, the total '+'distance from the first marker to the most recent is shown in parenthesis ');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.MeasureTool.prototype.dispose=function(){this.disable();disposeImage(this.icon);this.icon=null;this.adapter=null;if(this.overlay){this.overlay.dispose();this.overlay=null;}
this.points=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.PanTool=function(properties){var props=setdefault(properties,{id:'pan',factor:0.25});userSmarts.Map.Tool.call(this,props);};userSmarts.Map.PanTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.PanTool.prototype.paint=function(){var leftIcon=this.factory.create('panleft','panleft-selected','Pan Left');connect(leftIcon,'onclick',bind(this.panLeft,this));this.leftIcon=leftIcon;var rightIcon=this.factory.create('panright','panright-selected','Pan Right');connect(rightIcon,'onclick',bind(this.panRight,this));this.rightIcon=rightIcon;var upIcon=this.factory.create('panup','panup-selected','Pan Up');connect(upIcon,'onclick',bind(this.panUp,this));this.upIcon=upIcon;var downIcon=this.factory.create('pandown','pandown-selected','Pan Down');connect(downIcon,'onclick',bind(this.panDown,this));this.downIcon=downIcon;return[leftIcon,rightIcon,upIcon,downIcon];};userSmarts.Map.PanTool.prototype.setPanFactor=function(factor){this.factor=factor;};userSmarts.Map.PanTool.prototype.panLeft=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(-this.factor,0.0);}};userSmarts.Map.PanTool.prototype.panRight=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(this.factor,0.0);}};userSmarts.Map.PanTool.prototype.panUp=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(0.0,this.factor);}};userSmarts.Map.PanTool.prototype.panDown=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(0.0,-this.factor);}};userSmarts.Map.PanTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Pan Tool : ');var text=document.createTextNode('Clicking any of the four '+'arrow icons will invoke a manual panning of the map in the given direction.');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.PanTool.prototype.dispose=function(){disposeImage(this.leftIcon);this.leftIcon=null;disposeImage(this.rightIcon);this.rightIcon=null;disposeImage(this.upIcon);this.upIcon=null;disposeImage(this.downIcon);this.downIcon=null;this.adapter=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.ZoomToBoxTool=function(properties){if(isPrototype(arguments)){return;}
var props=setdefault(properties,{id:'zoombox',canReset:true,dragHandler:new DragHandler()});userSmarts.Map.Tool.call(this,props);};userSmarts.Map.ZoomToBoxTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.ZoomToBoxTool.prototype.paint=function(){var icon=this.factory.create('zoomboxtool','zoomboxtool-selected','Zoom to Box');this.mouseListener=connect(icon,'onclick',this,"toggleReady");this.icon=icon;return this.icon;};userSmarts.Map.ZoomToBoxTool.prototype.toggleReady=function(){this.setProperty("ready",!this.ready);};userSmarts.Map.ZoomToBoxTool.prototype.onToolEnable=function(){if(this.enabled)return true;if(!this.adapter)return false;if(this.icon){this.icon.className='zoomboxtool-selected';this.disableHover(this.icon);}
var canvas=this.adapter.getProperty("canvas");this.canvasListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,'reset');var theImage=canvas.content;var theCanvas=canvas.layout;this.dragHandler=new DragHandler();this.dragHandler.init(theImage,theCanvas);this.dragHandler.startHandler=bind(this.onDragStart,this);this.dragHandler.dragHandler=bind(function(e,dragger){this.onDrag(e,dragger);},this);this.dragHandler.endHandler=bind(function(dragger){this.onDragEnd(dragger);},this);this.box=null;var layout=this.adapter.getProperty("layout");forEach(layout.childNodes,bind(function(child){if(child.className=='bounding-box'){this.box=child;}},this));if(!this.box){this.box=DIV({'class':'bounding-box'});this.box.style.position='absolute';this.box.style.top='0px';this.box.style.left='0px';this.box.style.width='0px';this.box.style.height='0px';this.box.style.border='2px dashed black';this.box.style.visibility='hidden';layout.appendChild(this.box);}
return true;};userSmarts.Map.ZoomToBoxTool.prototype.disable=function(){if(this.disabled){this.enabled=false;this.setProperty("disabled",true);return;}
if(!this.canReset){this.timeoutCheck=setTimeout(bind(function(){this.disable();},this),750);}else{if(this.icon){this.icon.className='zoomboxtool';this.enableHover(this.icon,'zoomboxtool-selected','zoomboxtool');}
disconnect(this.canvasListener);this.canvasListener=null;if(this.dragHandler){this.dragHandler.disable();}
this.timeoutCheck=null;this.ready=false;this.enabled=false;this.setProperty("disabled",true);}};userSmarts.Map.ZoomToBoxTool.prototype.zoom=function(){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var context=this.adapter.getProperty("context");var boxleft=parseInt(this.box.style.left);var boxtop=parseInt(this.box.style.top);var boxwidth=parseInt(this.box.style.width);var boxheight=parseInt(this.box.style.height);var min=canvas.projectPoint({x:boxleft,y:boxtop+boxheight});var max=canvas.projectPoint({x:boxleft+boxwidth,y:boxtop});var coord=context.unproject(min.x,min.y);min.x=coord[0];min.y=coord[1];coord=context.unproject(max.x,max.y);max.x=coord[0];max.y=coord[1];var box=new Geometry("Box");box.addPoint(min);box.addPoint(max);context.setView(box);}};userSmarts.Map.ZoomToBoxTool.prototype.onDragStart=function(e){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var pos=elementPosition(canvas.layout);var point={x:e.clientX-pos.x+parseInt(getViewportScrollX()),y:e.clientY-pos.y+parseInt(getViewportScrollY())};this.box.x1=point.x-parseInt(this.box.style.borderLeftWidth);this.box.y1=point.y-parseInt(this.box.style.borderLeftWidth);this.bounds={minX:0,minY:0,maxX:0+parseInt(canvas.width),maxY:0+parseInt(canvas.height)};this.canReset=false;}};userSmarts.Map.ZoomToBoxTool.prototype.onDrag=function(e){if(this.adapter){var canvas=this.adapter.getProperty("canvas");var pos=elementPosition(canvas.layout);var point={x:e.clientX-pos.x+parseInt(getViewportScrollX()),y:e.clientY-pos.y+parseInt(getViewportScrollY())};if(point.x<this.bounds.minX){point.x=this.bounds.minX+1;}else if(point.x>this.bounds.maxX){point.x=(window.event)?this.bounds.maxX+1:this.bounds.maxX-1;}
if(point.y<this.bounds.minY){point.y=this.bounds.minY+1;}else if(point.y>this.bounds.maxY){point.y=(window.event)?this.bounds.maxY+2:this.bounds.maxY-1;}
var width=point.x-this.box.x1-parseInt(this.box.style.borderLeftWidth);var height=point.y-this.box.y1-parseInt(this.box.style.borderTopWidth);this.box.style.visibility="visible";if(width<0){this.box.style.left=point.x+"px";this.box.style.width=-width+"px";}else{this.box.style.left=this.box.x1+"px";this.box.style.width=width+"px";}
if(height<0){this.box.style.top=point.y+"px";this.box.style.height=-height+"px";}else{this.box.style.top=this.box.y1+"px";this.box.style.height=height+"px";}}};userSmarts.Map.ZoomToBoxTool.prototype.onDragEnd=function(dragger){var bw=parseInt(this.box.style.width);var bh=parseInt(this.box.style.height);if((bw>-5&&bw<5)&&(bh>-5&&bh<5)){this.disable();return;}
this.dragHandler.block();this.zoom();};userSmarts.Map.ZoomToBoxTool.prototype.reset=function(){if(this.enabled){this.box.style.visibility="hidden";this.box.style.width="0px";this.box.style.height="0px";this.canReset=true;this.dragHandler.resume();}};userSmarts.Map.ZoomToBoxTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Zoom-to-Box Tool : ');var text=document.createTextNode('Once the tool has been selected, '+'select a bounding box in the same manner as the Bounding Box tool.  After a region is '+'is selected, the map will zoom into that region.');return DIV({'class':'map-tool-about'},title,text);};userSmarts.Map.ZoomToBoxTool.prototype.dispose=function(){this.dragHandler.disable();disconnect(this.mouseListener);this.mouseListener=null;disposeImage(this.icon);this.icon=null;this.adapter=null;this.dragHandler=null;this.box=null;this.bounds=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.ZoomTool=function(properties){var props=setdefault(properties,{id:'zoom',infactor:0.5,outfactor:2.0});userSmarts.Map.Tool.call(this,props);};userSmarts.Map.ZoomTool.inheritsFrom(userSmarts.Map.Tool);userSmarts.Map.ZoomTool.prototype.paint=function(){var inIcon=this.factory.create('zoomintool','zoomintool-selected','Zoom In');connect(inIcon,'onclick',this,this.zoomIn);this.inIcon=inIcon;var outIcon=this.factory.create('zoomouttool','zoomouttool-selected','Zoom Out');connect(outIcon,'onclick',this,this.zoomOut);this.outIcon=outIcon;return[inIcon,outIcon];};userSmarts.Map.ZoomTool.prototype.setZoomInFactor=function(factor){if((factor>0.0)&&(factor<1.0)){this.infactor=factor;}};userSmarts.Map.ZoomTool.prototype.setZoomOutFactor=function(factor){if(factor>1.0){this.outfactor=factor;}};userSmarts.Map.ZoomTool.prototype.zoomIn=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.zoom(this.infactor);}};userSmarts.Map.ZoomTool.prototype.zoomOut=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.zoom(this.outfactor);}};userSmarts.Map.ZoomTool.prototype.about=function(){var title=SPAN({'class':'map-tool-title'},'Zoom In & Out Tools : ');var text=document.createTextNode('Selecting either of these tools will cause '+'the map to manually zoom in or out by a pre-defined amount.');var holder=DIV({'class':'map-tool-about'},title,text);return holder;};userSmarts.Map.ZoomTool.prototype.dispose=function(){disposeImage(this.inIcon);this.inIcon=null;disposeImage(this.outIcon);this.outIcon=null;this.adapter=null;userSmarts.Map.Tool.prototype.dispose.call(this);};userSmarts.Map.Layer=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{server:null,name:'unknown layer',title:'unknown layer',srs:'EPSG:4326',visible:false,queryable:false,active:false,selected:false,opacity:1.0,status:userSmarts.Map.Layer.STATUS_NOT_LOADED,refreshProperties:[],transience:false,isAcetate:false});superClass.call(this,properties);this.dirtyListener=bind(this.markAsDirty,this);this.addChangeListener(this.dirtyListener,'*',bind(this.changeTest,this));};userSmarts.Map.Layer.STATUS_LOADING=2;userSmarts.Map.Layer.STATUS_LOADED=1;userSmarts.Map.Layer.STATUS_NOT_LOADED=0;userSmarts.Map.Layer.STATUS_ERROR=-1;$prototype.activate=function(){this.active=true;};$prototype.deactivate=function(){this.active=false;};$prototype.markAsDirty=function(){this.dirty=true;};$prototype.select=function(){this.selected=true;};$prototype.deselect=function(){this.selected=false;};$prototype.show=function(){this.setProperty("visible",true);};$prototype.hide=function(){this.setProperty("visible",false);};$prototype.getLayerId=function(){return this.name;};$prototype.getLayerName=function(){return this.title;};$prototype.getServer=function(){return this.server.getName();};$prototype.getSRS=function(){return this.srs;};$prototype.getStatus=function(){return this.status;};$prototype.isTransient=function(){return this.transience;};$prototype.clone=function(){var l=new userSmarts.Map.Layer({server:this.server.clone(),name:this.name,title:this.title,srs:this.srs,visible:this.visible,queryable:this.queryable,selected:this.selected,active:this.active,opacity:this.opacity,status:this.status,transience:this.transience,isAcetate:this.isAcetate,refreshProperties:this.refreshProperties});return l;};$prototype.equals=function(layer){if(!(layer instanceof userSmarts.Map.Layer))return false;var result=((this.getLayerId()==layer.getLayerId())&&(this.server.equals(layer.server)));return result;};$prototype.getProperties=function(){var arr=[];var bp3=new BeanPropertyBinding(this,'opacity');bp3.datatype={uri:{prefix:'usd',namespaceURI:'http://www.usersmarts.com/datatype#',localPart:"opacity"},isRange:true,facets:{minInclusive:0.0,maxInclusive:1.0,increment:0.25},base:datatypes.getType("xsd:float"),format:new FloatFormat()};bp3.label="Opacity";arr.push(bp3);return arr;};$prototype.shouldCoalesceWith=function(layer){var result=this.server.equals(layer.server);result=result&&(this.opacity==layer.opacity);return result;};$prototype.shouldRefreshFor=function(propertyName){var result=(propertyName=='visible'||(this.visible&&(propertyName=='opacity'))||this.refreshProperties[propertyName]);return result;};$prototype.changeTest=function(event){var result=(event.propertyName!='dirty');result=result&&(event.propertyName!='visible');result=result&&(event.propertyName!='active');result=result&&(event.propertyName!='status');result=result&&!(this.visible===true);return result;};$prototype.toXml=function(d){if(this.isTransient()){return null;}
var doc;if(!d||d.nodeType!=9){doc=createXMLDocument('ViewContext','http://www.opengis.net/context',null);}else{doc=d;}
var layer=createElementNS('http://www.opengis.net/context','Layer',doc);layer.setAttribute("queryable",(this.queryable?'1':'0'));layer.setAttribute("hidden",(this.visible?'0':'1'));layer.setAttribute("opacity",this.opacity);layer.appendChild(this.server.toXml(doc));var name=createElementNS('http://www.opengis.net/context','Name',doc);name.appendChild(doc.createTextNode(this.name));layer.appendChild(name);var title=createElementNS('http://www.opengis.net/context','Title',doc);title.appendChild(doc.createTextNode(this.title));layer.appendChild(title);var srs=createElementNS('http://www.opengis.net/context','SRS',doc);srs.appendChild(doc.createTextNode(this.srs));layer.appendChild(srs);if(this.metadataURL){var murl=createElementNS('http://www.opengis.net/context','MetadataURL',doc);murl.appendChild(doc.createTextNode(this.metadataURL));layer.appendChild(murl);}
return layer;};$prototype.isGroup=function(){return false;};userSmarts.Map.Server=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{url:'',title:'unknown server',service:'WMS',version:'1.1.1',format:"image/gif"});Bean.call(this,properties);};userSmarts.Map.Server.inheritsFrom(Bean);userSmarts.Map.Server.prototype.getName=function(){return this.title;};userSmarts.Map.Server.prototype.equals=function(server){return(this.url==server.url)&&(this.service==server.service)&&(this.format==server.format);};userSmarts.Map.Server.prototype.clone=function(){return new userSmarts.Map.Server({url:this.url,title:this.title,service:this.service,version:this.version});};userSmarts.Map.Server.prototype.render=function(pkg,context){var result;try{var url=this.getURL(pkg,context);if(userSmarts.Map.DEBUG_FLAG||this.debug){log("[ Map Request ]");var parts=url.split("?");log("Server: "+parts[0]);log("Params: "+parts[1]);log("[ End Request ]");}
var opacity=pkg.getDefaultPropertyValue('opacity')||1.0;result=loadImage({url:url,width:context.width,height:context.height,opacity:opacity});result.deferred.addCallback(bind(this.loadLegendImages,this,pkg));}catch(e){result={deferred:new Deferred(),image:null};result.deferred.errback(e);}
return result;};userSmarts.Map.Server.prototype.getURL=function(pkg,context){var width=context.width;var height=context.height;var bbox=context.boundingBox;var srs=bbox.srs;var host=this.url;if(host.indexOf('?')<0){host+='?';}else if(host.indexOf('?')!=(host.length-1)){host+='&';}
var url=host+"REQUEST=GetMap&SERVICE="+this.service+"&VERSION="+this.version;url+="&BBOX="+bbox.getQueryString()+"&WIDTH="+width+"&HEIGHT="+height;url+="&SRS="+srs+"&Transparent=TRUE"+"&FORMAT="+this.format+"&STYLES=";var layerIds=this.determineLayerIds(pkg);url+="&layers="+layerIds;return url;};userSmarts.Map.Server.prototype.determineLayerIds=function(pkg){var layers=pkg.getVisibleLayers();if(layers.length<1){throw new Exception("No visible layers in package");}
var style;var legendURL;var legendImg;var legendImgs=[];var layerIdsStr='';for(var i=0;i<layers.length;i++){if(i>0){layerIdsStr+=',';}
layerIdsStr+=layers[i].getLayerId();if(layers[i]&&layers[i].styles){style=layers[i].styles.current;if(style>=0){legendURL=layers[i].styles[style].legendURL;if(legendURL){legendImg=loadImage({url:legendURL,opacity:layers[i].opacity,position:'relative'}).image;legendImgs.unshift(legendImg);}}}}
if(legendImgs.length>0){pkg.setLegend(legendImgs);}
return layerIdsStr;};userSmarts.Map.Server.prototype.loadLegendImages=function(pkg){};userSmarts.Map.Server.prototype.refreshLayerPackage=function(pkg,event){var complete=false;var layer=event.source;var property=event.propertyName;var value=event.newValue;if(layer.dirty){if(userSmarts.Map.DEBUG_FLAG){logDebug("Layer "+layer.getLayerName()+" was previously marked as dirty, re-rendering package...");}
layer.dirty=false;return complete;}
switch(property){case'active':case'selected':complete=true;break;case'visible':var layers=pkg.getVisibleLayers();if((layers.length===1&&value===true)||(layers.length===0&&value===false)){var img=pkg.getImage();if(img&&pkg.isImageCurrent()){img.style.visibility=layer.visible?'visible':'hidden';complete=true;var legendImgs=pkg.getLegend();if(legendImgs){for(var i=0;i<legendImgs.length;i++){legendImgs[i].style.display=layer.visible?'inline':'none';}}}}
break;case'opacity':var layers=pkg.getVisibleLayers();if(layers.length<=1){var img=pkg.getImage();if(img){img.style.filter='alpha(opacity='+(layer.opacity*100)+')';img.style.opacity=(layer.opacity*1.0);complete=true;var legendImgs=pkg.getLegend();if(legendImgs){for(var i=0;i<legendImgs.length;i++){legendImgs[i].style.filter='alpha(opacity='+(layer.opacity*100)+')';legendImgs[i].style.opacity=(layer.opacity*1.0);}}}}
break;default:break;}
return complete;};userSmarts.Map.Server.prototype.toXml=function(d){var doc;if(!d||d.nodeType!=9){doc=createXMLDocument('ViewContext','http://www.opengis.net/context',null);}else{doc=d;}
var server=createElementNS('http://www.opengis.net/context','Server',doc);server.setAttribute("service",this.service);server.setAttribute("version",this.version);server.setAttribute("title",this.title);var or=createElementNS('http://www.opengis.net/context','OnlineResource',doc);or.setAttribute("xlink:type",'simple');or.setAttribute("xlink:href",this.url);server.appendChild(or);return server;};userSmarts.Map.BoundingBox=function(srs){this.srs=srs;this.projection=userSmarts.Map.ProjectionFactory.instance(srs);this.bounds=this.projection.bounds;this.boundsCheck=this.projection.boundsCheck;};userSmarts.Map.BoundingBox.prototype.setBoundingBox=function(x1,y1,x2,y2){if(this.boundsCheck){this.minX=(x1>=this.bounds.minX)?x1:this.bounds.minX;this.maxX=(x2<=this.bounds.maxX)?x2:this.bounds.maxX;this.minY=(y1>=this.bounds.minY)?y1:this.bounds.minY;this.maxY=(y2<=this.bounds.maxY)?y2:this.bounds.maxY;}else{this.minX=x1;this.minY=y1;this.maxX=x2;this.maxY=y2;}};userSmarts.Map.BoundingBox.prototype.pan=function(dx,dy){if(this.boundsCheck){if((this.minX+dx)>=this.bounds.minX&&(this.maxX+dx)<=this.bounds.maxX){this.minX+=dx;this.maxX+=dx;}else if((this.minX+dx)<this.bounds.minX){dx=-1*(this.minX-this.bounds.minX);this.minX+=dx;this.maxX+=dx;}else if((this.maxX+dx)>this.bounds.maxX){dx=(this.bounds.maxX-this.maxX);this.minX+=dx;this.maxX+=dx;}
if((this.minY+dy)>=this.bounds.minY&&(this.maxY+dy)<=this.bounds.maxY){this.minY+=dy;this.maxY+=dy;}else if((this.minY+dy)<this.bounds.minY){dy=-1*(this.minY-this.bounds.minY);this.minY+=dy;this.maxY+=dy;}else if((this.maxY+dy)>this.bounds.maxY){dy=this.bounds.maxY-this.maxY;this.minY+=dy;this.maxY+=dy;}
if(this.minY<this.bounds.minY){var wy=(this.maxY-this.minY);var dy1=this.bounds.minY-this.minY;var fy1=(dy1*2+wy)/wy;this.zoom(fy1);}else if(this.maxY>this.bounds.maxY){var dy2=this.maxY-this.bounds.maxY;var fy2=(dy2*2+wy)/wy;this.zoom(fy2);}}else{this.minX+=dx;this.maxX+=dx;this.minY+=dy;this.maxY+=dy;}};userSmarts.Map.BoundingBox.prototype.scaledPan=function(px,py){this.ensureNumberValues();this.pan((this.maxX-this.minX)*px,(this.maxY-this.minY)*py);};userSmarts.Map.BoundingBox.prototype.ensureNumberValues=function(){this.minX=1*this.minX;this.maxX=1*this.maxX;this.minY=1*this.minY;this.maxY=1*this.maxY;};userSmarts.Map.BoundingBox.prototype.zoom=function(factor){this.ensureNumberValues();var dx=this.maxX-this.minX;var dy=this.maxY-this.minY;var addx=((dx*factor)-dx)/2.0;var addy=((dy*factor)-dy)/2.0;if(this.boundsCheck){if((this.minX-addx)>=this.bounds.minX&&(this.maxX+addx)<=this.bounds.maxX&&(this.minY-addy)>=this.bounds.minY&&(this.maxY+addy)<=this.bounds.maxY){this.minX-=addx;this.maxX+=addx;this.minY-=addy;this.maxY+=addy;}else{var dx1=this.minX-this.bounds.minX;var fx1=(dx1*2+dx)/dx;var dx2=this.bounds.maxX-this.maxX;var fx2=(dx2*2+dx)/dx;var dy1=this.minY-this.bounds.minY;var fy1=(dy1*2+dy)/dy;var dy2=this.bounds.maxY-this.maxY;var fy2=(dy2*2+dy)/dy;var newFactor=Math.min(fx1,Math.min(fx2,Math.min(fy1,fy2)));addx=((dx*newFactor)-dx)/2.0;addy=((dy*newFactor)-dy)/2.0;this.minX-=addx;this.maxX+=addx;this.minY-=addy;this.maxY+=addy;}}else{this.minX-=addx;this.maxX+=addx;this.minY-=addy;this.maxY+=addy;}};userSmarts.Map.BoundingBox.prototype.getCoordinateX=function(px){this.ensureNumberValues();return this.minX+((this.maxX-this.minX)*px);};userSmarts.Map.BoundingBox.prototype.getCoordinatePx=function(x){this.ensureNumberValues();return(x-this.minX)/(this.maxX-this.minX);};userSmarts.Map.BoundingBox.prototype.getCoordinateY=function(py){this.ensureNumberValues();return this.minY+((this.maxY-this.minY)*py);};userSmarts.Map.BoundingBox.prototype.getCoordinatePy=function(y){this.ensureNumberValues();return(y-this.minY)/(this.maxY-this.minY);};userSmarts.Map.BoundingBox.prototype.getCoordinate=function(px,py){return new Point(this.getCoordinateX(px),this.getCoordinateY(py));};userSmarts.Map.BoundingBox.prototype.getCoordinatePercentage=function(x,y){return new Point(this.getCoordinatePx(x),this.getCoordinatePy(y));};userSmarts.Map.BoundingBox.prototype.getQueryString=function(){return this.minX.toFixed(3)+","+this.minY.toFixed(3)+","+this.maxX.toFixed(3)+","+this.maxY.toFixed(3);};userSmarts.Map.BoundingBox.prototype.clone=function(){var newBox=new userSmarts.Map.BoundingBox(this.srs);newBox.minX=this.minX;newBox.maxX=this.maxX;newBox.minY=this.minY;newBox.maxY=this.maxY;return newBox;};userSmarts.Map.BoundingBox.prototype.toXml=function(d){var doc;if(!d||d.nodeType!=9){doc=createXMLDocument('ViewContext','http://www.opengis.net/context',null);}else{doc=d;}
var bbox=createElementNS('http://www.opengis.net/context','BoundingBox',doc);bbox.setAttribute("SRS",this.srs);bbox.setAttribute("minx",this.minX);bbox.setAttribute("maxx",this.maxX);bbox.setAttribute("miny",this.minY);bbox.setAttribute("maxy",this.maxY);return bbox;};userSmarts.Map.ViewContext=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{id:'',layers:[],width:0,height:0,boundingBox:new userSmarts.Map.BoundingBox('EPSG:4326')});Bean.call(this,properties);this.lastModified=new Date().getTime();this.layerListener=bind(this.onLayerChange,this);for(var i=0;i<this.layers.length;i++){this.layers[i].addChangeListener(this.layerListener,"*");}};userSmarts.Map.ViewContext.inheritsFrom(Bean);userSmarts.Map.ViewContext.LAYER_CHANGED_EVENT_PROPERTY='layeChanged';userSmarts.Map.ViewContext.LAYER_ADDED_EVENT_PROPERTY='layerAdded';userSmarts.Map.ViewContext.LAYER_REMOVED_EVENT_PROPERTY='layerRemoved';userSmarts.Map.ViewContext.CHANGE_EVENT_PROPERTY='lastModified';userSmarts.Map.ViewContext.VIEW_CHANGE_EVENT_PROPERTY="viewChanged";userSmarts.Map.ViewContext.prototype.touch=function(){if(this.controller){var def=this.controller.onChangeEvent(this);def.addCallback(bind(function(p,v){this.setProperty(p,v);},this,userSmarts.Map.ViewContext.CHANGE_EVENT_PROPERTY,new Date().getTime()));}else{this.setProperty(userSmarts.Map.ViewContext.CHANGE_EVENT_PROPERTY,new Date().getTime());}};userSmarts.Map.ViewContext.prototype.setController=function(controller){this.controller=controller;};userSmarts.Map.ViewContext.prototype.pan=function(dx,dy){this.boundingBox.pan(dx,dy);this.setProperty(userSmarts.Map.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};userSmarts.Map.ViewContext.prototype.scaledPan=function(dx,dy){this.boundingBox.scaledPan(dx,dy);this.setProperty(userSmarts.Map.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};userSmarts.Map.ViewContext.prototype.zoom=function(factor){this.boundingBox.zoom(factor);this.setProperty(userSmarts.Map.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};userSmarts.Map.ViewContext.prototype.getView=function(){var geom=new Geometry("Box");var min=this.unproject(this.boundingBox.minX,this.boundingBox.minY);var max=this.unproject(this.boundingBox.maxX,this.boundingBox.maxY);if(!min||!max){min=[this.boundingBox.minX,this.boundingBox.minY];max=[this.boundingBox.maxX,this.boundingBox.maxY];}
geom.addPoint(new Point(min[0],min[1]));geom.addPoint(new Point(max[0],max[1]));return geom;};userSmarts.Map.ViewContext.prototype.setView=function(geom){if(geom&&geom.getEnvelope){var envelope=geom.getEnvelope();var points=envelope.getPoints();if(points.length==2){var min=this.project(points[0].x,points[0].y);var max=this.project(points[1].x,points[1].y);if(!min||!max){return;}
this.boundingBox.setBoundingBox(min[0],min[1],max[0],max[1]);this.correctAspectRatio();this.setProperty(userSmarts.Map.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();}}};userSmarts.Map.ViewContext.prototype.unproject=function(x,y){return this.boundingBox.projection.unproject(x,y);};userSmarts.Map.ViewContext.prototype.project=function(x,y){return this.boundingBox.projection.project(x,y);};userSmarts.Map.ViewContext.prototype.onLayerChange=function(event){var newEvent=new PropertyChangeEvent(event.source,event.propertyName,event.oldValue,event.newValue);this.setProperty(userSmarts.Map.ViewContext.LAYER_CHANGED_EVENT_PROPERTY,newEvent);};userSmarts.Map.ViewContext.prototype.getLayerPosition=function(layer){for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){return i;}}
return-1;};userSmarts.Map.ViewContext.prototype.shiftDown=function(layer,refresh){var index=this.getLayerPosition(layer);if(index>0){this.layers.swap(index,index-1);if(typeof(refresh)=='undefined'||refresh===true){this.touch();}}};userSmarts.Map.ViewContext.prototype.shiftUp=function(layer,refresh){var index=this.getLayerPosition(layer);if(index>=0&&index<(this.layers.length-1)){this.layers.swap(index,index+1);if(typeof(refresh)=='undefined'||refresh===true){this.touch();}}};userSmarts.Map.ViewContext.prototype.shiftTo=function(layer,toIndex,refresh){if(layer.isAcetate){return;}
if(typeof(toIndex)=='number'&&toIndex<this.layers.length&&toIndex>=0){var index=this.getLayerPosition(layer);if(index>=0&&index!=toIndex){this.layers.splice(index,1);this.layers.splice(toIndex,0,layer);if(typeof(refresh)=='undefined'||refresh===true){this.touch();}}}};userSmarts.Map.ViewContext.prototype.showLayer=function(layer){layer.show();};userSmarts.Map.ViewContext.prototype.hideLayer=function(layer){layer.hide();};userSmarts.Map.ViewContext.prototype.activateLayer=function(layer){layer.active=true;};userSmarts.Map.ViewContext.prototype.deactivateLayer=function(layer){layer.active=false;};userSmarts.Map.ViewContext.prototype.getSelectedLayer=function(){for(var i=0;i<this.layers.length;i++){if(this.layers[i].selected){return this.layers[i];}}
return null;};userSmarts.Map.ViewContext.prototype.getActiveLayers=function(){var l=[];for(var i=0;i<this.layers.length;i++){if(this.layers[i].active){l.push(this.layers[i]);}}
return l;};userSmarts.Map.ViewContext.prototype.getNumberOfVisibleLayers=function(){var count=0;for(var i=0;i<this.layers.length;i++){if(this.layers[i].visible){count++;}}
return count;};userSmarts.Map.ViewContext.prototype.addLayer=function(layer){var added=this.includeLayer(layer);if(added){this.touch();}
return added;};userSmarts.Map.ViewContext.prototype.addLayers=function(layers){var layersAdded=false;if(typeof(layers.length)=='number'){var layer;for(var j=0;j<layers.length;j++){layer=layers[j];layersAdded=layersAdded||this.includeLayer(layer);}
if(layersAdded){this.touch();}}
return layersAdded;};userSmarts.Map.ViewContext.prototype.removeLayer=function(layer){for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){layer.removeChangeListener(this.layerListener,'*');this.layers.splice(i,1);this.setProperty(userSmarts.Map.ViewContext.LAYER_REMOVED_EVENT_PROPERTY,layer);this.touch();return layer;}}};userSmarts.Map.ViewContext.prototype.includeLayer=function(layer){for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){return false;}}
layer.addChangeListener(this.layerListener,'*');this.layers.push(layer);this.setProperty(userSmarts.Map.ViewContext.LAYER_ADDED_EVENT_PROPERTY,layer);return true;}
userSmarts.Map.ViewContext.prototype.correctAspectRatio=function(){var aspectRatio=this.width/this.height;if(!this.boundingBox.minX){return aspectRatio;}
var left=this.boundingBox.minX;var right=this.boundingBox.maxX;var top=this.boundingBox.maxY;var bottom=this.boundingBox.minY;var width=right-left;var height=top-bottom;var px=width/this.width;var py=height/this.height;var cy=(height/2)+bottom;var cx=(width/2)+left;if(px>py){if(aspectRatio>0.0){height=(width/aspectRatio);}else if(aspectRatio<0.0){height=(width*aspectRatio);}else{height=width;}
top=cy+(height/2);bottom=cy-(height/2);}else{if(aspectRatio>0.0){width=(height*aspectRatio);}else if(aspectRatio<0.0){width=(height/aspectRatio);}else{width=height;}
left=cx-(width/2);right=cx+(width/2);}
this.boundingBox.minX=left;this.boundingBox.minY=bottom;this.boundingBox.maxX=right;this.boundingBox.maxY=top;return aspectRatio;};userSmarts.Map.ViewContext.prototype.clone=function(){var context=new userSmarts.Map.ViewContext({id:this.id,width:this.width,height:this.height});context.loadLayers(this);context.loadBoundingBox(this);context.listeners=[];if(this.listeners){forEach(this.listeners,function(listener){context.listeners.push(listener);});}
return context;};userSmarts.Map.ViewContext.prototype.load=function(context,refresh){this.id=context.id;this.loadLayers(context);this.loadBoundingBox(context);this.correctAspectRatio();if(!!refresh){this.touch();}};userSmarts.Map.ViewContext.prototype.loadLayers=function(context){var layer;var i;for(i=this.layers.length;i>=0;i--){layer=this.removeLayer(this.layers[i]);layer=null;}
for(i=0;i<context.layers.length;i++){this.addLayer(context.layers[i].clone());}};userSmarts.Map.ViewContext.prototype.loadBoundingBox=function(context){this.boundingBox=context.boundingBox.clone();};userSmarts.Map.ViewContext.prototype.within=function(x1,y1,x2,y2){if(this.boundingBox.minX>=x1&&this.boundingBox.maxX<=x2&&this.boundingBox.minY>=y1&&this.boundingBox.maxY<=y2){return true;}};userSmarts.Map.ViewContext.prototype.removeListeners=function(){this.pcs.properties.clear();};userSmarts.Map.ViewContext.prototype.toXml=function(d){var doc;if(!d||d.nodeType!=9){doc=createXMLDocument('ViewContext','http://www.opengis.net/context',null);}else{doc=d;}
var vc=createElementNS('http://www.opengis.net/context','ViewContext',doc);vc.setAttribute('version','1.1.1');vc.setAttribute('id',this.id);vc.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");vc.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");vc.setAttribute("xsi:schemaLocation","http://www.opengis.net/context http://schemas.opengis.net/context/1.0.0/context.xsd");var general=createElementNS('http://www.opengis.net/context','General',doc);vc.appendChild(general);var win=createElementNS('http://www.opengis.net/context','Window',doc);win.setAttribute("width",this.width);win.setAttribute("height",this.height);general.appendChild(win);general.appendChild(this.boundingBox.toXml(doc));var titleElement=createElementNS('http://www.opengis.net/context','Title',doc);if(this.title){titleElement.appendChild(doc.createTextNode(this.title));}
general.appendChild(titleElement);if(this.abstr){var abstrElement=createElementNS("http://www.opengis.net/context","Abstract",doc);abstrElement.appendChild(doc.createTextNode(this.abstr));general.appendChild(abstrElement);}
if(this.contactInformation){general.appendChild(this.contactInformation.toXml(doc));}
var layerlist=createElementNS('http://www.opengis.net/context','LayerList',doc);vc.appendChild(layerlist);for(var i=0;i<this.layers.length;i++){var layerNode=this.layers[i].toXml(doc);if(layerNode){layerlist.appendChild(layerNode);}}
return vc;};userSmarts.Map.ViewContextParser=Class.create(Bean);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);connect(this,"xml",this,this.onXmlChange);connect(this,"url",this,this.onURLChange);};$prototype.onURLChange=function(event){var d=parseXML(event.newValue);d.addCallback(bind(this.onXmlChange,this));};$prototype.onXmlChange=function(xml){if(typeof xml=="undefined"){return;}
var context=this.fromXML(xml);context.id=this.url;this.setProperty("viewContext",context);};$prototype.fromXML=function(xml){var layerObjs=[];var root=xml;if(xml.nodeType==9){root=xml.documentElement;}
var id=getNodeAttribute(root,"id");var nl=root.getElementsByTagName('General');var generalElement=DOMUtils.getChild(root,"General");var windowElement=DOMUtils.getChild(generalElement,"Window");var boundingBoxElement=DOMUtils.getChild(generalElement,"BoundingBox");var title=DOMUtils.getChildText(generalElement,"Title","");var abstr=DOMUtils.getChildText(generalElement,"Abstract","");var width=Coerce.toInteger(getNodeAttribute(windowElement,'width'),0);var height=Coerce.toInteger(getNodeAttribute(windowElement,'height'),0);var bbox=this.parseBoundingBox(boundingBoxElement);var layerlist=DOMUtils.getChild(root,"LayerList");var layers=DOMUtils.getChildren(layerlist,"Layer");for(var i=0;i<layers.length;i++){var layer=this.readLayerInformation(layers[i]);if(layer.srs!=bbox.srs){logWarning('Layer-specific SRS('+layer.srs+') does not match global SRS ('+bbox.srs+') !  Using global...');layer.srs=bbox.srs;}
layerObjs.push(layer);}
var context=new userSmarts.Map.ViewContext({id:id,title:title,abstr:abstr,layers:layerObjs,boundingBox:bbox,width:width,height:height});return context;};$prototype.parseBoundingBox=function(boundingBoxElement){var minX=Coerce.toDouble(getNodeAttribute(boundingBoxElement,'minx'),-125.0);var minY=Coerce.toDouble(getNodeAttribute(boundingBoxElement,'miny'),20.0);var maxX=Coerce.toDouble(getNodeAttribute(boundingBoxElement,'maxx'),-66.0);var maxY=Coerce.toDouble(getNodeAttribute(boundingBoxElement,'maxy'),60.0);var srs=getNodeAttribute(boundingBoxElement,'SRS');if(!srs){srs='EPSG:4326';logWarning("No SRS was specified in the context document!  Defaulting to 'EPSG:4326'");}
var bbox=new userSmarts.Map.BoundingBox(srs);bbox.setBoundingBox(minX,minY,maxX,maxY);return bbox;};$prototype.readLayerInformation=function(element){var serverElement=DOMUtils.getChild(element,"Server");var serviceType=getNodeAttribute(serverElement,"service")||"WMS";return userSmarts.Map.LayerParserRegistry.parse(serviceType,element);};userSmarts.Map.LayerParserRegistry={parsers:[]};userSmarts.Map.LayerParserRegistry.register=function(service,parser){var reg=userSmarts.Map.LayerParserRegistry;service=service.toLowerCase();if(!reg.parsers[service]){reg.parsers[service]=[];}
reg.parsers[service].push(parser);};userSmarts.Map.LayerParserRegistry.parse=function(service,element){var reg=userSmarts.Map.LayerParserRegistry;service=service.toLowerCase();var result=null;if(reg.parsers[service]){var parsers=reg.parsers[service];for(var i=0;i<parsers.length;i++){result=parsers[i].parse(element);if(result!==null){break;}}}
return result;};userSmarts.Map.ViewContextLayerParser=function(){if(isPrototype(this,arguments)){return;}};userSmarts.Map.ViewContextLayerParser.prototype.parse=function(obj){var name=obj.localName||obj.tagName;name=name.toLowerCase();if("layer"==name){return this.parseLayer(obj);}else if('server'==name){return this.parseServer(obj);}};userSmarts.Map.ViewContextLayerParser.prototype.parseLayer=function(element){try{if(!element){return null;}
var serverElement=DOMUtils.getChild(element,"Server");var serverObj=this.parseServer(serverElement);var queryable=Coerce.toBoolean(getNodeAttribute(element,'queryable'),false);var visible=!Coerce.toBoolean(getNodeAttribute(element,'hidden'),true);var hidden=!visible;var opacity=Coerce.toDouble(getNodeAttribute(element,"opacity"),1.0);opacity=Math.max(opacity,0.0);opacity=Math.min(opacity,1.0);var name=DOMUtils.getChildText(element,"Name","");var title=DOMUtils.getChildText(element,"Title","");var srs=DOMUtils.getChildText(element,"SRS","EPSG:4326");var metadataURL=DOMUtils.getChildText(element,"MetadataURL",null);var styles;var styleListElements=element.getElementsByTagName("StyleList");if(styleListElements.length>0){styles=this.parseStyles(styleListElements[0]);}else{styles=[];styles.current=-1;}
return new userSmarts.Map.Layer({server:serverObj,opacity:opacity,name:name,title:title,srs:srs,queryable:queryable,visible:visible,metadataURL:metadataURL,styles:styles});}catch(e){logError("Error parsing layer - "+e);return null;}};userSmarts.Map.ViewContextLayerParser.prototype.parseStyles=function(styleListElement){var layerStyles=[];var styleElements=styleListElement.getElementsByTagName('Style');var styleElement;var legendElement;var orElement;var legendURL;var name;var nameElement;var title;var titleElement;for(var i=0;i<styleElements.length;i++){styleElement=styleElements[i];nameElement=styleElement.getElementsByTagName("Name")[0];if(!nameElement){continue;}
name=scrapeText(nameElement);titleElement=styleElement.getElementsByTagName("Title")[0];if(!titleElement){continue;}
title=scrapeText(titleElement);legendElement=styleElement.getElementsByTagName("LegendURL")[0];if(!legendElement){continue;}
orElement=legendElement.getElementsByTagName("OnlineResource")[0];if(!orElement){continue;}
legendURL=getNodeAttribute(orElement,"xlink:href");layerStyles.push({name:name,title:title,legendURL:legendURL});if(getNodeAttribute(styleElement,'current')=='1'){layerStyles.current=i;}}
return layerStyles;};userSmarts.Map.ViewContextLayerParser.prototype.parseServer=function(serverElement){if(!serverElement){return null;}
var serverService=getNodeAttribute(serverElement,'service')||"WMS";var serverVersion=getNodeAttribute(serverElement,'version')||"1.1.1";var serverTitle=getNodeAttribute(serverElement,'title')||"";var serverURL;var serverURLElement=DOMUtils.getChild(serverElement,"OnlineResource");serverURL=getNodeAttribute(serverURLElement,"xlink:href");return new userSmarts.Map.Server({url:serverURL,title:serverTitle,service:serverService,version:serverVersion});};if(typeof(userSmarts.Map.LayerParserRegistry)!='undefined'){userSmarts.Map.LayerParserRegistry.register("wms",new userSmarts.Map.ViewContextLayerParser());userSmarts.Map.LayerParserRegistry.register("kml",new userSmarts.Map.ViewContextLayerParser());userSmarts.Map.LayerParserRegistry.register("shp",new userSmarts.Map.ViewContextLayerParser());userSmarts.Map.LayerParserRegistry.register("georss",new userSmarts.Map.ViewContextLayerParser());userSmarts.Map.LayerParserRegistry.register("feed",new userSmarts.Map.ViewContextLayerParser());}
function ProgressBar(properties){properties=setdefault(properties,{id:'mapProgressBar'+Math.random(),workTotal:0,workDone:0});Bean.call(this,properties);var div=DIV({'class':'progress-bar-frame'});div.style.position='relative';div.style.top='0px';div.style.left='0px';div.style.width='128px';div.style.height='32px';div.style.display='none';this.div=div;var bar=DIV({'class':'progress-bar'});bar.style.width='100%';bar.style.height='100%';this.div.appendChild(bar);if(this.adapter){this.overlay=new userSmarts.Map.Overlay({id:this.id});this.overlay.setContent(this.div);var overlays=this.adapter.getProperty("overlays");overlays.add(this.overlay);}
this.hide();}
ProgressBar.inheritsFrom(Bean);ProgressBar.prototype.paint=function(context){this.repaint(context);return this.div;};ProgressBar.prototype.repaint=function(context){var done=this.workDone;var total=this.workTotal;var percDone=(this.workDone/this.workTotal);var width=parseInt(this.div.style.width);var barWidth=(done>=total)?width:Math.floor(percDone*width);};ProgressBar.prototype.setPosition=function(x,y){if(this.overlay){this.overlay.setPosition({x:x,y:y});}else{this.div.style.top=y+"px";this.div.style.left=x+"px";}};ProgressBar.prototype.setSize=function(width,height){this.div.style.width=width+"px";this.div.style.height=height+"px";};ProgressBar.prototype.setWorkTotal=function(work){this.workTotal=work;};ProgressBar.prototype.worked=function(){this.workDone++;this.repaint();};ProgressBar.prototype.reset=function(){this.bar.style.width='0px';this.workDone=0;this.hide();};ProgressBar.prototype.show=function(){if(this.div){this.div.style.display='block';}};ProgressBar.prototype.hide=function(){if(this.div){this.div.style.display='none';}};ProgressBar.prototype.dispose=function(){if(this.overlay){var overlays=this.adapter.getProperty("overlays");overlays.remove(this.overlay);this.overlay.setContent(null);this.overlay=null;}
this.div=null;this.isDisposed=true;};userSmarts.Map.OverlayManager=function(properties){Bean.call(this,properties);this.layout=DIV({'class':'map-overlay-manager'});this.addChangeListener(bind(this.onAdapterChange,this),"adapter");this.overlays=[];};userSmarts.Map.OverlayManager.inheritsFrom(Bean);userSmarts.Map.OverlayManager.prototype.onAdapterChange=function(event){var adapter=event.newValue;var layout=adapter.getProperty('layout');if(layout){layout.appendChild(this.layout);}
var canvas=adapter.getProperty('canvas');if(this.canvasListener){disconnect(this.canvasListener);}
this.canvasListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};userSmarts.Map.OverlayManager.prototype.paint=function(){return this.layout;};userSmarts.Map.OverlayManager.prototype.repaint=function(){var overlay;for(var k in this.overlays){overlay=this.overlays[k];if(overlay instanceof userSmarts.Map.WSOverlay){this.updateOverlay(overlay);}}};userSmarts.Map.OverlayManager.prototype.getWSOverlays=function(){var overlays=[];var overlay;for(var k in this.overlays){overlay=this.overlays[k];if(overlay instanceof userSmarts.Map.WSOverlay){overlays.push(overlay);}}
return overlays;};userSmarts.Map.OverlayManager.prototype.updateOverlay=function(overlay){if(!overlay)return;var geometry=overlay.getWSGeometry();if(!geometry){this.remove(overlay);return;}
var points=geometry.getPoints();var canvas=this.adapter.getProperty("canvas");if(canvas){var ng=new Geometry(geometry.type);var np;for(var i=0;i<points.length;i++){np=canvas.unprojectPoint(points[i]);ng.addPoint(np);};var env=ng.getEnvelope();if(env.points[0].x<0||env.points[1].x>canvas.width||env.points[0].y<0||env.points[1].y>canvas.height){overlay.hide();return;}else if(!overlay.isVisible()){overlay.show();}
var renderer=this.adapter.getProperty('renderer');if(renderer){overlay.update(ng);var div=renderer.render(ng);overlay.setContent(div);}}};userSmarts.Map.OverlayManager.prototype.add=function(overlay){this.overlays[overlay.id]=overlay;var content=overlay.paint();if(content){this.layout.appendChild(content);}
if(overlay instanceof userSmarts.Map.WSOverlay){overlay.mgrconnect=connect(overlay,"deleted",this,this.remove);}};userSmarts.Map.OverlayManager.prototype.remove=function(overlay,event){if(this.disposed){return;}
var content=overlay.paint();if(content&&this.layout){this.layout.removeChild(content);}
if(event){overlay.close(event);}
this.overlays[overlay.id]=null;if(overlay instanceof userSmarts.Map.WSOverlay){disconnect(overlay.mgrconnect);overlay.mgrconnect=null;overlay.mgrlistener=null;}};userSmarts.Map.OverlayManager.prototype.dispose=function(){this.disposed=true;if(this.overlays){var overlay;for(var k in this.overlays){overlay=this.overlays[k];if(overlay instanceof userSmarts.Map.Overlay){overlay.dispose();overlay=null;}
this.overlays[k]=null;}
this.overlays=null;}
this.content=null;this.layout=null;this.adapter=null;};userSmarts.Map.Overlay=function(properties){if(isPrototype(arguments)){return;}
setdefault(properties,{id:Math.random(),className:'map-overlay'});setdefault(this,properties);this.content=DIV({'class':this.className});this.content.style.position='relative';};userSmarts.Map.Overlay.prototype.paint=function(){return this.content;};userSmarts.Map.Overlay.prototype.setContent=function(content){replaceChildNodes(this.content,((typeof(content)=='array')?content:[content]));};userSmarts.Map.Overlay.prototype.addContent=function(content,className){if(typeof(content)=='array'){for(var i=0;i<content.length;++i){this.content.appendChild(content[i]);}}else{this.content.appendChild(content);}};userSmarts.Map.Overlay.prototype.setPosition=function(point){this.content.style.position='absolute';if(point.x){this.content.style.left=point.x+"px";}
if(point.y){this.content.style.top=point.y+"px";}};userSmarts.Map.Overlay.prototype.getPosition=function(){return{x:parseInt(this.content.style.left),y:parseInt(this.content.style.top)};};userSmarts.Map.Overlay.prototype.setSize=function(width,height){this.content.style.width=width+"px";this.content.style.height=height+"px";};userSmarts.Map.Overlay.prototype.getSize=function(){return{x:parseInt(this.content.style.width),y:parseInt(this.content.style.height)};};userSmarts.Map.Overlay.prototype.show=function(){if(this.content&&this.content.style){this.content.style.display='block';}};userSmarts.Map.Overlay.prototype.hide=function(){if(this.content&&this.content.style){this.content.style.display='none';}};userSmarts.Map.Overlay.prototype.isVisible=function(){if(this.content&&this.content.style){return(this.content.style.display!='none');}
return false;};userSmarts.Map.Overlay.prototype.close=function(event){if(event){var geometry=event.newValue;geometry.removeChangeListener(this.listener,Geometry.DELETED);}
this.listener=null;};userSmarts.Map.Overlay.prototype.dispose=function(){var child;for(var i=this.content.childNodes.length-1;i>=0;i--){child=this.content.childNodes[i];this.content.removeChild(child);child=null;}};userSmarts.Map.WSOverlay=function(properties){userSmarts.Map.Overlay.call(this,properties);this.init();};userSmarts.Map.WSOverlay.inheritsFrom(userSmarts.Map.Overlay);userSmarts.Map.WSOverlay.prototype.init=function(){if(this.ssgeometry&&this.ssgeometry instanceof Geometry){this.listener=connect(this.ssgeometry,Geometry.DELETED,this,this.onSSGeometryRemoved);}};userSmarts.Map.WSOverlay.prototype.update=function(geometry){if(this.listener){disconnect(this.listener);}
if(geometry&&geometry instanceof Geometry){if(this.ssgeometry){this.ssgeometry.dispose();}
this.ssgeometry=geometry;this.listener=connect(this.ssgeometry,Geometry.DELETED,this,this.onSSGeometryRemoved);}};userSmarts.Map.WSOverlay.prototype.getWSGeometry=function(){return this.wsgeometry;};userSmarts.Map.WSOverlay.prototype.setWSGeometry=function(wsgeometry){this.wsgeometry=wsgeometry;};userSmarts.Map.WSOverlay.prototype.getSSGeometry=function(){return this.ssgeometry;};userSmarts.Map.WSOverlay.prototype.onSSGeometryRemoved=function(){signal(this,"deleted",this,{newValue:this.ssgeometry});if(this.wsgeometry){this.wsgeometry.remove();}};userSmarts.Map.WSOverlay.prototype.dispose=function(){var child;for(var i=this.content.childNodes.length-1;i>=0;i--){child=this.content.childNodes[i];this.content.removeChild(child);child=null;}
if(this.listener){disconnect(this.listener);}
if(this.wsgeometry){this.wsgeometry.dispose();}
if(this.ssgeometry){this.ssgeometry.dispose();}};userSmarts.Map.ContextManager=function(properties){properties=setdefault(properties,{contexts:[],current:-1});if(isPrototype(arguments)){return;}
Bean.call(this,properties);this.overlay=new userSmarts.Map.ContextTab({manager:this});connect(this,'adapter',this,this.onAdapterChange);this.counterId=0;};userSmarts.Map.ContextManager.inheritsFrom(Bean);userSmarts.Map.ContextManager.MAX_CONTEXTS=10;userSmarts.Map.ContextManager.CONTEXT_RESTORED='contextRestored';userSmarts.Map.ContextManager.CONTEXT_SAVED='contextSaved';userSmarts.Map.ContextManager.CONTEXT_REMOVED='contextRemoved';userSmarts.Map.ContextManager.prototype.onAdapterChange=function(event){var adapter=event.newValue;var overlays=adapter.getProperty("overlays");if(this.overlay){overlays.add(this.overlay);}};userSmarts.Map.ContextManager.prototype.save=function(context,name){var index=-1;if(this.contexts.length<userSmarts.Map.ContextManager.MAX_CONTEXTS){this.contexts.push({label:name,value:context,selected:false});index=this.contexts.length-1;this.setProperty(userSmarts.Map.ContextManager.CONTEXT_SAVED,context);this.select(index);if(this.overlay){this.overlay.update();}}
return index;};userSmarts.Map.ContextManager.prototype.restore=function(index){if(index>=0&&index<this.contexts.length){if(this.adapter){var widget=this.adapter.getProperty("widget");var ctx=this.contexts[index].value.clone();widget.setContext(ctx);this.select(index);if(this.overlay){this.overlay.update();}}
this.setProperty(userSmarts.Map.ContextManager.CONTEXT_RESTORED,this.contexts[index].value.clone());}};userSmarts.Map.ContextManager.prototype.select=function(index){if(index<0||index>=this.contexts.length){return;}
if(this.current!=undefined&&this.current>=0){this.contexts[this.current].selected=false;}
this.current=index;this.contexts[this.current].selected=true;};userSmarts.Map.ContextManager.prototype.getContext=function(){return this.contextRestored;};userSmarts.Map.ContextManager.prototype.getNumberOfSavedContexts=function(){return this.contexts.length;};userSmarts.Map.ContextManager.prototype.remove=function(index){if(index>=0&&index<this.contexts.length){var context=this.contexts.splice(index,1);this.setProperty(userSmarts.Map.ContextManager.CONTEXT_REMOVED,context.value);}};userSmarts.Map.ContextManager.prototype.next=function(){var next=0;if(this.current>=0){if(this.current<(this.contexts.length-1)){next=this.current+1;}}
this.restore(next);};userSmarts.Map.ContextManager.prototype.previous=function(){var prev=this.contexts.length-1;if(this.current>=0){if(this.current>0){prev=this.current-1;}}
this.restore(prev);};userSmarts.Map.ContextManager.prototype.dispose=function(){disconnectAll(this);var len=this.contexts.length;for(var i=0;i<len;i++){this.contexts.shift();}
this.current=null;if(this.overlay){replaceChildNodes(this.overlay,null);this.overlay=null;}};userSmarts.Map.ContextTab=function(properties){properties=setdefault(properties,{id:'mapContextTab',overlay:new userSmarts.Map.Overlay()});if(isPrototype(arguments)){return;}
Bean.call(this,properties);if(this.overlays){this.overlays.add(this.overlay);}};userSmarts.Map.ContextTab.inheritsFrom(Bean);userSmarts.Map.ContextTab.prototype.paint=function(context){return this.overlay.content;};userSmarts.Map.ContextTab.prototype.build=function(index,name,selectedFlag){var top=(index*20)+10;var left=0;var tab=DIV({'id':this.id+'_'+index,'class':'map-bookmark-tab'});tab.style.position='absolute';tab.style.top=top+'px';tab.style.left=left+'px';tab.contextIndex=index;var label=(name)?name:(index+1);if(label.length>7){label=label.substring(0,7)+"...";}
var num=SPAN({'class':'map-bookmark-label'},label);if(selectedFlag){addElementClass(num,'map-bookmark-selected');}
num.contextIndex=index;connect(num,'onclick',bind(function(i){this.manager.restore(i);},this,index));num.title=(name)?name:(index+1);tab.appendChild(num);var closer=SPAN({'class':'map-bookmark-close'},'X');closer.onmouseover=function(){closer.style.cursor='pointer';};closer.onmouseout=function(){closer.style.cursor='default';};connect(closer,'onclick',bind(function(i){this.manager.remove(i);this.update();},this,index));tab.appendChild(closer);return tab;};userSmarts.Map.ContextTab.prototype.update=function(){var tabs=[];var tab=null;if(this.manager){for(var i=0;i<this.manager.contexts.length;i++){tab=this.build(i,this.manager.contexts[i].label,this.manager.contexts[i].selected);if(tab){tabs.push(tab);}}}
this.overlay.setContent(tabs);};userSmarts.Map.ContextTab.prototype.dispose=function(){replaceChildNodes(this.overlay,null);this.overlay=null;this.overlays=null;this.manager=null;};function DragHandler(){this.obj=null;}
DragHandler.prototype.init=function(o,oRoot,minX,maxX,minY,maxY,bSwapHorzRef,bSwapVertRef,fXMapper,fYMapper){this.obj=o;if(o.childNodes){for(var i=0;i<o.childNodes.length;i++){o.childNodes[i].onmousedown=function(e){return false;};o.childNodes[i].ondrag=function(e){return false;};}}
this.obj.root=oRoot;this.oDownListener=connect(this.obj,'onmousedown',this,this.start);o.hmode=bSwapHorzRef?false:true;o.vmode=bSwapVertRef?false:true;o.root=oRoot&&oRoot!==null?oRoot:o;if(o.hmode&&isNaN(parseInt(o.root.style.left))){o.root.style.left="0px";}
if(o.vmode&&isNaN(parseInt(o.root.style.top))){o.root.style.top="0px";}
if(!o.hmode&&isNaN(parseInt(o.root.style.right))){o.root.style.right="0px";}
if(!o.vmode&&isNaN(parseInt(o.root.style.bottom))){o.root.style.bottom="0px";}
o.minX=typeof minX!='undefined'?minX:null;o.minY=typeof minY!='undefined'?minY:null;o.maxX=typeof maxX!='undefined'?maxX:null;o.maxY=typeof maxY!='undefined'?maxY:null;o.xMapper=fXMapper?fXMapper:null;o.yMapper=fYMapper?fYMapper:null;o.root.onDragStart=function(){};o.root.onDragEnd=function(){};o.root.onDrag=function(){};this.clipTop=0;this.clipLeft=0;this.clipBottom=0;this.clipRight=0;};DragHandler.prototype.start=function(evt){if(this.blocking){return;}
var o=this.obj;var e=evt.event();e=fixE(e);var y=parseInt(o.vmode?o.root.style.top:o.root.style.bottom);var x=parseInt(o.hmode?o.root.style.left:o.root.style.right);o.root.onDragStart(x,y);o.lastMouseX=e.clientX;o.lastMouseY=e.clientY;if(o.hmode){if(o.minX!==null){o.minMouseX=e.clientX-x+o.minX;}
if(o.maxX!==null){o.maxMouseX=o.minMouseX+o.maxX-o.minX;}}else{if(o.minX!==null){o.maxMouseX=-o.minX+e.clientX+x;}
if(o.maxX!==null){o.minMouseX=-o.maxX+e.clientX+x;}}
if(o.vmode){if(o.minY!==null){o.minMouseY=e.clientY-y+o.minY;}
if(o.maxY!==null){o.maxMouseY=o.minMouseY+o.maxY-o.minY;}}else{if(o.minY!==null){o.maxMouseY=-o.minY+e.clientY+y;}
if(o.maxY!==null){o.minMouseY=-o.maxY+e.clientY+y;}}
this.docMoveListener=connect(document,'onmousemove',this,this.drag);this.docUpListener=connect(document,'onmouseup',this,this.end);disconnect(this.oDownListener);this.clipRight=parseInt(o.style.width);this.clipBottom=parseInt(o.style.height);if(this.startHandler){this.startHandler(e,this);}
return false;};DragHandler.prototype.drag=function(evt){var e=evt.event();e=fixE(e);var o=this.obj;if(this.dragHandler){this.dragHandler(e,this);}else{var ey=e.clientY;var ex=e.clientX;var y=parseInt(o.vmode?o.root.style.top:o.root.style.bottom);var x=parseInt(o.hmode?o.root.style.left:o.root.style.right);var nx,ny;if(o.minX!==null){ex=o.hmode?Math.max(ex,o.minMouseX):Math.min(ex,o.maxMouseX);}
if(o.maxX!==null){ex=o.hmode?Math.min(ex,o.maxMouseX):Math.max(ex,o.minMouseX);}
if(o.minY!==null){ey=o.vmode?Math.max(ey,o.minMouseY):Math.min(ey,o.maxMouseY);}
if(o.maxY!==null){ey=o.vmode?Math.min(ey,o.maxMouseY):Math.max(ey,o.minMouseY);}
dx=((ex-o.lastMouseX)*(o.hmode?1:-1));dy=((ey-o.lastMouseY)*(o.vmode?1:-1));nx=x+dx;ny=y+dy;if(o.xMapper){nx=o.xMapper(y);}else if(o.yMapper){ny=o.yMapper(x);}
o.root.style[o.hmode?"left":"right"]=nx+"px";o.root.style[o.vmode?"top":"bottom"]=ny+"px";o.lastMouseX=ex;o.lastMouseY=ey;this.clipLeft-=dx;this.clipRight-=dx;this.clipTop-=dy;this.clipBottom-=dy;if(o.clip){o.root.clip.left=this.clipLeft+"px";o.root.clip.right=this.clipRight+"px";o.root.clip.top=this.clipTop+"px";o.root.clip.bottom=this.clipBottom+"px";}else{o.root.style.clip="rect("+this.clipTop+"px "+this.clipRight+"px "+this.clipBottom+"px "+this.clipLeft+"px)";}
o.root.style.overflow="hidden";o.root.onDrag(nx,ny);}
return false;};DragHandler.prototype.end=function(){disconnect(this.docMoveListener);this.docMoveListener=null;disconnect(this.docUpListener);this.docUpListener=null;this.oDownListener=connect(this.obj,'onmousedown',this,this.start);this.obj.root.onDragEnd(parseInt(this.obj.root.style[this.obj.hmode?"left":"right"]),parseInt(this.obj.root.style[this.obj.vmode?"top":"bottom"]));if(this.endHandler){this.endHandler(this);}
this.clipLeft=0;this.clipBottom=parseInt(this.obj.style.width);this.clipTop=0;this.clipRight=parseInt(this.obj.style.height);};DragHandler.prototype.block=function(){if(!this.blocking){this.blocking=true;}};DragHandler.prototype.resume=function(){if(this.blocking){this.blocking=false;}};DragHandler.prototype.isBlocking=function(){return(this.blocking==true);};DragHandler.prototype.disable=function(){if(this.isBlocking()){this.resume();}
if(this.obj){if(this.obj.root){this.obj.root.onDragStart=null;this.obj.root.onDrag=null;this.obj.root.onDragEnd=null;this.obj.root=null;}
disconnect(this.oDownListener);this.oDownListener=null;this.obj.lastMouseX=null;this.obj.lastMouseY=null;this.obj=null;}
this.startHandler=null;this.dragHandler=null;this.endHandler=null;if(this.docMoveListener){disconnect(this.docMoveListener);this.docMoveListener=null;}
if(this.docUpListener){disconnect(this.docUpListener);this.docUpListener=null;}};userSmarts.util.DragHandler=function(){this.clipTop=0;this.clipBottom=0;this.clipLeft=0;this.clipRight=0;};userSmarts.util.DragHandler.prototype.init=function(element){try{this._down=connect(element,'onmousedown',bind(this.start,this));logDebug("This.down is "+this._down);}catch(e){logError("userSmarts.util.DragHandler.init() - error connecting to 'onmousedown' for element '"+element+"' : "+e.message);}};userSmarts.util.DragHandler.prototype.disable=function(element){try{disconnect(this._down);}catch(e){logError("userSmarts.util.DragHandler.disable() - error disconnecting to 'onmousedown' : "+e.message);}};userSmarts.util.DragHandler.prototype.start=function(e){try{e.stop();this.target=e.target();this.clipBottom=parseInt(this.target.style.height);this.clipRight=parseInt(this.target.style.width);this.position=elementPosition(this.target);this.offset=this.diff(e.mouse().page,this.position);this._move=connect(document,'onmousemove',bind(this.dragWithClipping,this));this._up=connect(document,'onmouseup',bind(this.stop,this));if(this.startHandler){this.startHandler(e);}}catch(e){logError("userSmarts.util.DragHandler.start() - error handling 'start' : "+e.message);}};userSmarts.util.DragHandler.prototype.drag=function(e){try{if(this.dragHandler){this.dragHandler(e);}else{e.stop();setElementPosition(this.target,this.diff(e.mouse().page,this.offset));}}catch(e){logError("userSmarts.util.DragHandler.drag() - error handling 'drag' : "+e.message);}};userSmarts.util.DragHandler.prototype.dragWithClipping=function(e){if(this.dragHandler){this.dragHandler(e);}else{e.stop();var delta=this.diff(e.mouse().page,this.offset);this.clipLeft-=delta.x;this.clipRight-=delta.x;this.clipTop-=delta.y;this.clipBottom-=delta.y;if(this.target.clip){this.target.clip.left=this.clipLeft;this.target.clip.right=this.clipRight;this.target.clip.top=this.clipTop;this.target.clip.bottom=this.clipBottom;}else{this.target.style.clip="rect("+this.clipTop+"px "+this.clipRight+"px "+this.clipBottom+"px "+this.clipLeft+"px)";}
this.target.style.overflow="hidden";setElementPosition(this.target,delta);}};userSmarts.util.DragHandler.prototype.stop=function(e){disconnect(this._move);disconnect(this._up);if(this.stopHandler){this.stopHandler(e);}};userSmarts.util.DragHandler.prototype.diff=function(lhs,rhs){return new MochiKit.DOM.Coordinates(lhs.x-rhs.x,lhs.y-rhs.y);};userSmarts.util.DragHandler.prototype.getMoveDistance=function(){return this.diff(this.position,elementPosition(this.target));};userSmarts.Map.Manager=function(map){this.map=map;};userSmarts.Map.Manager.findMap=function(id){var widget;if(!id){return null;}
if(id instanceof userSmarts.Map.Widget){widget=id;}else if(typeof(id)=='string'){var map=$(id);if(!map||!map.widget){logError("Unable to find map element with id specified - "+id);return null;}
widget=map.widget;}
return widget;};userSmarts.Map.Manager.prototype.loadContext=function(url){var parser=new userSmarts.Map.ViewContextParser();var listener=bind(function(event){this.setContext(event.newValue);},this.map);parser.addChangeListener(listener,"viewContext");parser.setProperty("url",url);};userSmarts.Map.Manager.loadContext=function(id,url){var map=userSmarts.Map.Manager.findMap(id);if(map){var parser=new userSmarts.Map.ViewContextParser();var listener=bind(function(event){this.setContext(event.newValue);},map);parser.addChangeListener(listener,"viewContext");parser.setProperty("url",url);}};userSmarts.Map.Manager.prototype.setContext=function(context){if(!context||!(context instanceof userSmarts.Map.ViewContext)){logError("Specified object is not a valid ViewContext object");alert("Specified object is not a valid ViewContext object, unable to change map!");return;}
this.map.setContext(context);};userSmarts.Map.Manager.setContext=function(id,context){if(!context||!(context instanceof userSmarts.Map.ViewContext)){logError("Specified object is not a valid ViewContext object");alert("Specified object is not a valid ViewContext object, unable to change map!");return;}
var map=userSmarts.Map.Manager.findMap(id);if(map){map.setContext(context);}};userSmarts.Map.Manager.prototype.setView=function(geom){var context=this.map.getProperty('context');if(!context||!(context instanceof userSmarts.Map.ViewContext)){logError("Specified map does not have a valid view context");alert("Specified map does not have a valid view context, unable to change view!");return;}
context.setView(geom);};userSmarts.Map.Manager.setView=function(id,geom){var map=userSmarts.Map.Manager.findMap(id);if(map){var context=map.getProperty('context');if(!context||!(context instanceof userSmarts.Map.ViewContext)){logError("Specified map does not have a valid view context");alert("Specified map does not have a valid view context, unable to change view!");return;}
context.setView(geom);}};userSmarts.Map.Manager.prototype.getProgressBar=function(){var result=this.map.getProperty("progressBar");return result;};userSmarts.Map.Manager.getProgressBar=function(id){var result;var map=userSmarts.Map.Manager.findMap(id);if(map){result=map.getManager().getProgressBar();}
return result;};userSmarts.Map.Manager.getGeometryRenderer=function(id){var result=null;var map=userSmarts.Map.Manager.findMap(id);if(map){result=map.getGeometryRenderer();}
return result;};userSmarts.Map.Manager.getOverlayManager=function(id){var result=null;var map=userSmarts.Map.Manager.findMap(id);if(map){result=map.getOverlayManager();}
return result;};userSmarts.Map.Manager.prototype.registerGeometryListener=function(func){var tbmodel=this.map.locate('toolbar-model');if(!tbmodel){logError("Specified map does not have a toolbar model registered with it");return;}
var geometryTool=tbmodel.getTool('geometry');if(!geometryTool){logError("Specified map does not have a geometry tool");return;}
connect(geometryTool,"geometry",func);alert("Successfully registered geometry listener!");};userSmarts.Map.Manager.registerGeometryListener=function(id,func){if(typeof(func)!='function'){logError("Geometry listener must be of type 'function'");return;}
var map=userSmarts.Map.Manager.findMap(id);if(map){var tbmodel=map.locate('toolbar-model');if(!tbmodel){logError("Specified map does not have a toolbar model registered with it");return;}
var geometryTool=tbmodel.getTool('geometry');if(!geometryTool){logError("Specified map does not have a geometry tool");return;}
geometryTool.addChangeListener(func,'geometry');alert("Successfully registered geometry listener!");}};userSmarts.Map.Manager.prototype.unregisterGeometryListener=function(func){var tbmodel=this.map.locate('toolbar-model');if(!tbmodel){logError("Specified map does not have a toolbar model registered with it");return;}
var geometryTool=tbmodel.getTool('geometry');if(!geometryTool){logError("Specified map does not have a geometry tool");return;}
geometryTool.removeChangeListener(func,'geometry');alert("Successfully un-registered geometry listener!");};userSmarts.Map.Manager.unregisterGeometryListener=function(id,func){if(typeof(func)!='function'){logError("Geometry listener must be of type 'function'");return;}
var map=userSmarts.Map.Manager.findMap(id);if(map){var tbmodel=map.locate('toolbar-model');if(!tbmodel){logError("Specified map does not have a toolbar model registered with it");return;}
var geometryTool=tbmodel.getTool('geometry');if(!geometryTool){logError("Specified map does not have a geometry tool");return;}
geometryTool.removeChangeListener(func,'geometry');alert("Successfully un-registered geometry listener!");}};userSmarts.Map.Manager.correctAspectRatio=function(id,points){var map=userSmarts.Map.Manager.findMap(id);if(map){return map.getManager().correctAspectRatio(points);}};userSmarts.Map.Manager.prototype.correctAspectRatio=function(points){var aspectRatio=this.map.aspectRatio;if(!points||!points.minX||!points.minY||!points.maxX||!points.maxY){return points;}
var left=points.minX;var right=points.maxX;var top=points.maxY;var bottom=points.minY;var width=right-left;var height=top-bottom;var px=width/this.width;var py=height/this.height;var cy=(height/2)+bottom;var cx=(width/2)+left;if(px>py){if(aspectRatio>0.0){height=(width/aspectRatio);}else if(aspectRatio<0.0){height=(width*aspectRatio);}else{height=width;}
top=cy+(height/2);bottom=cy-(height/2);}else{if(aspectRatio>0.0){width=(height*aspectRatio);}else if(aspectRatio<0.0){width=(height/aspectRatio);}else{width=height;}
left=cx-(width/2);right=cx+(width/2);}
points.minX=left;points.minY=bottom;points.maxX=right;points.maxY=top;return points;};userSmarts.Map.Manager.createMap=function(properties,parent){if(!properties){properties={};}
properties=setdefault(properties,{id:"map-"+Math.random(),width:500,height:500,timeout:3000,imagedir:'images/',debug:false,showScale:false});userSmarts.Map.DEBUG_FLAG=properties.debug;var canvas=new userSmarts.Map.Canvas({id:properties.id+'-canvas',width:properties.width-(window.ActiveXObject?2:0),height:properties.height-(window.ActiveXObject?2:0),timeout:properties.timeout,debug:properties.debug});var renderer=(window.ActiveXObject)?new VMLGeometryRenderer({imagedir:properties.imagedir}):new GeometryRenderer({imagedir:properties.imagedir});var widget=new userSmarts.Map.Widget({id:properties.id,width:properties.width,height:properties.height,canvas:canvas,renderer:renderer,debug:properties.debug});var layerRenderer=new userSmarts.Map.LayerRenderer({timeout:properties.timeout,debug:properties.debug});widget.register('layer-renderer',layerRenderer);if(parent&&parent.appendChild){parent.appendChild(widget.paint());}
if(properties.showScale){var scaleLegend=new userSmarts.Map.ScaleLegend({id:properties.id+'-scale'});widget.register('scale-legend',scaleLegend);scaleLegend.paint();}
return widget;};function Point(x,y){this.x=x;this.y=y;}
Geometry=function(type){if(isPrototype(arguments)){return;}
Bean.call(this,{type:(type||'Geometry'),points:[]});};Geometry.inheritsFrom(Bean);Geometry.DELETED='deleted';Geometry.UPDATED='updated';Geometry.prototype.remove=function(){this.setProperty(Geometry.DELETED,this);};Geometry.prototype.update=function(){this.setProperty(Geometry.UPDATED,this);};Geometry.prototype.getType=function(){return this.type;};Geometry.prototype.addPoint=function(p){p.x*=1.0;p.y*=1.0;this.points.push(p);};Geometry.prototype.getPoint=function(i){if(i<this.points.length&&i>=0){return this.points[i];}else{return null;}};Geometry.prototype.getPoints=function(){return this.points;};Geometry.prototype.getEnvelope=function(){var env=new Geometry("Box");var minx=null,maxx=null,miny=null,maxy=null;for(var i=0;i<this.points.length;i++){if(minx===null||this.points[i].x<minx){minx=this.points[i].x;}
if(miny===null||this.points[i].y<miny){miny=this.points[i].y;}
if(maxx===null||this.points[i].x>maxx){maxx=this.points[i].x;}
if(maxy===null||this.points[i].y>maxy){maxy=this.points[i].y;}}
env.addPoint(new Point(minx,miny));env.addPoint(new Point(maxx,maxy));return env;};Geometry.prototype.getCenter=function(){var env=this.getEnvelope();var cx=(env.points[1].x-env.points[0].x)/2+env.points[0].x;var cy=(env.points[1].y-env.points[0].y)/2+env.points[0].y;return new Point(cx,cy);};Geometry.prototype.getWidth=function(){var env=this.getEnvelope();return(env.points[1].x-env.points[0].x);};Geometry.prototype.getHeight=function(){var env=this.getEnvelope();return(env.points[1].y-env.points[0].y);};Geometry.prototype.getDescription=function(){return"";};Geometry.prototype.within=function(geometry){var thisEnv=this.getEnvelope();var thatEnv=geometry.getEnvelope();var thisMinX=thisEnv.points[0].x;var thisMinY=thisEnv.points[0].y;var thisMaxX=thisEnv.points[1].x;var thisMaxY=thisEnv.points[1].y;var thatMinX=thatEnv.points[0].x;var thatMinY=thatEnv.points[0].y;var thatMaxX=thatEnv.points[1].x;var thatMaxY=thatEnv.points[1].y;if(thatMinX>thisMinX)return false;if(thatMaxX<thisMaxX)return false;if(thatMinY>thisMinY)return false;if(thatMaxY<thisMaxY)return false;return true;};Geometry.prototype.toString=function(){var str=((this.type)?this.type:"Geometry")+"{";for(var i=0;i<this.points.length;i++){str=str+((i>0)?',':'')+'('+this.points[i].x+","+this.points[i].y+')';}
return str+"}";};Geometry.valueOf=function(str){var startIndex=str.indexOf("{");var x="}";if(startIndex<0){return null;}
var type=str.substring(0,startIndex);var geom=new Geometry(type);var pointStr=str.substring(startIndex+2,str.length-2);if(pointStr===''){return geom;}
var points=pointStr.split('),(');for(var i=0;i<points.length;i++){var xy=points[i].trim().split(',');geom.addPoint(new Point(xy[0].trim()*1.0,xy[1].trim()*1.0));}
return geom;};Geometry.parseGeometry=function(str){var startIndex=str.indexOf('(');if(startIndex<0){return null;}
var type=str.substring(0,startIndex);var geom=new Geometry(type);var pointStr=str.substring(startIndex+1,str.length-1);if(pointStr===''){return geom;}
var points=pointStr.split(',');if((points.length%2)!==0){return geom;}
for(var i=0;i<points.length;i+=2){var x=points[i].trim();var y=points[i+1].trim();geom.addPoint(new Point(x,y));}
return geom;};function createGeometryCloseButton(geometry,location){var button=DIV({'class':'map-label'},'info');button.title=geometry.toString()+".  Click to close.";button.style.position='absolute';button.style.top=(location.y+1)+'px';button.style.left=location.x+'px';connect(button,'onclick',geometry,"remove");connect(button,'onmouseover',function(){button.style.cursor="pointer";});connect(button,'onmouseout',function(){button.style.cursor="default";});return button;}
GeometryFormat=function(){};GeometryFormat.inheritsFrom(Format);GeometryFormat.prototype.parseObject=function(lexical){return Geometry.valueOf(lexical);};GeometryFormat.prototype.format=function(geometry){return(!geometry)?null:geometry.toString();};datatypes.addType({uri:{prefix:'geo',namespaceURI:"geo",localPart:"geometry"},facets:{enumeration:['true','false']},isAtomic:true,isList:true,format:new GeometryFormat()});GeometryRenderer=function(properties){if(isPrototype(arguments)){return;}
this.imagedir=properties.imagedir||"images/";};GeometryRenderer.prototype.render=function(geometry){if(!geometry.type){return null;}
switch(geometry.type){case'Ellipse':case'Circle':return this.renderEllipse(geometry);case'Line':var points=geometry.getPoints();return this.renderLine(points[0],points[1]);case'Point':return this.renderPoint(geometry);case'Box':return this.renderBox(geometry);default:return this.renderPolygon(geometry);}};GeometryRenderer.prototype.renderPoint=function(point){var width=point.width||3;var height=point.height||3;var div=document.createElement('div');div.className="point";div.style.position="absolute";div.style.left=(point.x-(width/2))+'px';div.style.top=(point.y-(height/2))+'px';div.style.width=width+'px';div.style.height=height+'px';var img=document.createElement("img");img.setAttribute('src',this.imagedir+'spacer.gif');img.setAttribute('width','1');img.setAttribute('height','1');div.appendChild(img);return div;};GeometryRenderer.prototype.renderBox=function(box){var p0=box.points[0];var p2=box.points[1];var p1={x:p2.x,y:p0.y};var p3={x:p0.x,y:p2.y};var div=DIV({'class':"Polygon"});div.appendChild(this.renderPoint({x:p0.x-1,y:p0.y-1,width:3,height:3}));div.appendChild(this.renderLine(p0,p1,1,true));div.appendChild(this.renderPoint({x:p1.x-1,y:p1.y-1,width:3,height:3}));div.appendChild(this.renderLine(p1,p2,1,true));div.appendChild(this.renderPoint({x:p2.x-1,y:p2.y-1,width:3,height:3}));div.appendChild(this.renderLine(p2,p3,1,true));div.appendChild(this.renderPoint({x:p3.x-1,y:p3.y-1,width:3,height:3}));div.appendChild(this.renderLine(p3,p0,1,true));div.appendChild(createGeometryCloseButton(box,p3));return div;};GeometryRenderer.prototype.renderLine=function(point1,point2,size,flag){var div=DIV({'class':'line'});var flag=!!flag;var dim=5;var x1=point1.x;var x2=point2.x;var y1=point1.y;var y2=point2.y;if(x1>x2){var _x2=x2;var _y2=y2;x2=x1;y2=y1;x1=_x2;y1=_y2;}
var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,yIncr=(y1>y2)?-1:1,drw=true,counter=0;if(dx>=dy){var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx;while((dx--)>0){if(flag){if(drw){div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}
if((++counter)==dim){drw=!drw;counter=0;}}else{div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}
if(p>0){y+=yIncr;p+=pru;}
else{p+=pr;}
++x;}
if(flag){if(drw){div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}}else{div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}}else{var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy;while((dy--)>0){if(flag){if(drw){div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}
if((++counter)==dim){drw=!drw;counter=0;}}else{div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}
y+=yIncr;if(p>0){++x;p+=pru;}else{p+=pr;}}
if(flag){if(drw){div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}}else{div.appendChild(this.renderPoint({x:x,y:y,width:size,height:size}));}}
return div;};GeometryRenderer.prototype.renderPolygon=function(geometry){var div=DIV({'class':geometry.type});var points=geometry.getPoints();for(var i=0;i<points.length;i++){var point=points[i];div.appendChild(this.renderPoint({x:point.x-1,y:point.y-1,width:3,height:3}));if(i>0){var point1=points[i-1];div.appendChild(this.renderLine(point1,point,1,true));}}
if(points.length>0){div.appendChild(createGeometryCloseButton(geometry,points[0]));}
return div;};GeometryRenderer.prototype.renderEllipse=function(geometry){var div=DIV({'class':geometry.type});var bounds=geometry.getEnvelope();var left=bounds.points[0].x;var top=bounds.points[0].y;var width=bounds.points[1].x-bounds.points[0].x;var height=bounds.points[1].y-bounds.points[0].y;var dim=5;var counter=0;var a=width>>1,b=height>>1,wod=width&1,hod=height&1,cx=left+a,cy=top+b,x=0,y=b,aa2=(a*a)<<1,aa4=aa2<<1,bb=(b*b)<<1,st=(aa2>>1)*(1-(b<<1))+bb,tt=(bb>>1)-aa2*((b<<1)-1),drw=true;while(y>0){if(st<0){st+=bb*((x<<1)+3);tt+=(bb<<1)*(++x);}else if(tt<0){st+=bb*((x<<1)+3)-aa4*(y-1);tt+=(bb<<1)*(++x)-aa2*(((y--)<<1)-3);}else{tt-=aa2*((y<<1)-3);st-=aa4*(--y);}
if(drw){var arr=this.mkOvQds(cx,cy,-x,x+wod,-y,y+hod);for(var q=0;q<arr.length;q++){div.appendChild(arr[q]);}}
if((++counter)==dim){drw=!drw;counter=0;}}
div.appendChild(createGeometryCloseButton(geometry,{x:left+((width/2)-10),y:top}));return div;};GeometryRenderer.prototype.mkOvQds=function(cx,cy,xl,xr,yt,yb){return[this.renderPoint({x:xr+cx,y:yt+cy,width:1,height:1}),this.renderPoint({x:xr+cx,y:yb+cy,width:1,height:1}),this.renderPoint({x:xl+cx,y:yb+cy,width:1,height:1}),this.renderPoint({x:xl+cx,y:yt+cy,width:1,height:1})];};VMLGeometryRenderer=function(){};VMLGeometryRenderer.prototype.render=function(geometry){if(!geometry.type){return null;}
switch(geometry.type){case'Ellipse':case'Circle':return this.renderEllipse(geometry);case'Line':var points=geometry.getPoints();return this.renderLine(points[0],points[1]);case'Point':return this.renderPoint(geometry);case'Box':return this.renderBox(geometry);default:return this.renderPolygon(geometry);}};VMLGeometryRenderer.prototype.renderPoint=function(point){var width=point.width||3;var height=point.height||3;var div=DIV();div.className='point';div.style.position='absolute';div.style.top=(point.y-(height/2))+'px';div.style.left=(point.x-(width/2))+'px';div.style.width=width+'px';div.style.height=height+'px';div.innerHTML='<v:oval style="width:'+width+'px; height:'+height+'px;" fillcolor="black" />';return div;};VMLGeometryRenderer.prototype.renderBox=function(box){var p0=box.points[0];var p1=box.points[1];var width=Math.abs(p1.x-p0.x);var height=Math.abs(p1.y-p0.y);var left=Math.min(p0.x,p1.x);var top=Math.min(p0.y,p1.y);var div=DIV({'class':'polygon'});var str='<DIV><v:polyline strokecolor="black" strokeweight="1px" filled="false" fillcolor="transparent" points="';str+=left+"px,"+(top+height)+'px,';str+=(left+width)+"px,"+(top+height)+"px,";str+=(left+width)+"px,"+top+"px,";str+=left+"px,"+top+"px,";str+=left+"px,"+(top+height)+'px';str+='">'+'<v:stroke dashstyle="dash" />'+'</v:polyline></DIV>';div.innerHTML=str;div.appendChild(createGeometryCloseButton(box,{x:left,y:top}));logDebug("Drew box onto "+div.outerHTML);return div;};VMLGeometryRenderer.prototype.renderLine=function(point1,point2,size,flag){var div=DIV({'class':'line'});div.style.position='absolute';div.style.top=Math.min(point1.y,point2.y)+'px';div.style.left=Math.min(point1.x,point2.x)+'px';div.style.width=Math.abs(point1.x-point2.x)+'px';div.style.height=Math.abs(point1.y-point2.y)+'px';var p1={x:point1.x,y:point1.y};var p2={x:point2.x,y:point2.y};if(p1.x<p2.x){p2.x-=p1.x;p1.x=0;}else{p1.x-=p2.x;p2.x=0;}
if(p1.y<p2.y){p2.y-=p1.y;p1.y=0;}else{p1.y-=p2.y;p2.y=0;}
var str='<v:line '+'from="'+p1.x+','+p1.y+'" '+'to="'+p2.x+','+p2.y+'" '+'strokecolor="#000000" strokeweight="'+size+'px">';if(flag){str+='<v:stroke dashstyle="dash" />';}
str+='</v:line>';div.innerHTML=str;return div;};VMLGeometryRenderer.prototype.renderPolygon=function(geometry){var div=DIV({'class':geometry.type});var str='<v:polyline strokecolor="black" strokeweight="1px" filled="false" fillcolor="transparent" points="';var points=geometry.getPoints();for(var i=0;i<points.length;i++){var point=points[i];str+=((i>0)?',':'')+point.x+'px,'+point.y+'px';}
str+='">'+'<v:stroke dashstyle="dash" />'+'</v:polyline>';div.innerHTML="<DIV>"+str+"</DIV>";if(points.length>0){div.appendChild(createGeometryCloseButton(geometry,points[0]));}
logDebug("Drew polygon onto "+div.outerHTML);return div;};VMLGeometryRenderer.prototype.renderEllipse=function(geometry){var bounds=geometry.getEnvelope();var left=bounds.points[0].x;var top=bounds.points[0].y;var width=bounds.points[1].x-bounds.points[0].x;var height=bounds.points[1].y-bounds.points[0].y;var div=DIV({'class':geometry.type});div.style.position='absolute';div.style.top=top+'px';div.style.left=left+'px';div.style.width=width+'px';div.style.height=width+'px';div.innerHTML='<v:oval style="width:'+width+'px; height:'+width+'px;" filled="false" fillcolor="transparent" strokeweight="1px">'+'<v:stroke dashstyle="dash" />'+'</v:oval>';div.appendChild(createGeometryCloseButton(geometry,{x:0,y:(height/2)}));return div;};function GeometryOverlay(mgr){if(this.isPrototype(arguments)){return;}
this.id='geometry-overlay';this.div=DIV({id:this.id});this.renderer=new GeometryRenderer();var overlay=new Overlay({id:this.id});overlay.setContent(this.div);overlay.setPosition({x:0,y:0});mgr.add(overlay);}
GeometryOverlay.prototype.registerListenerTo=function(producer){if(producer.addChangeListener){producer.addChangeListener(bind(function(event){this.update(event.newValue);},this),'updated');}};GeometryOverlay.prototype.update=function(geometry){var div=this.renderer.render(geometry);if(!div){logWarning('Warning! Geometry could not be rendered!');return;}
var container=DIV({'class':'geo-container'},div);geometry.addChangeListener(bind(function(div,event){logDebug('GOM - updating geometry: '+event.newValue+' on '+div.className);var geometry=event.newValue;var oldDiv=div.childNodes[0];var points=geometry.getPoints();var lastPoint=points[points.length-1];var newPoint=makePointDiv(lastPoint.x-1,lastPoint.y-1,3,3);oldDiv.appendChild(newPoint);if(points.length>1){var temp=DIV();var prevPoint=points[points.length-2];drawDottedLine(prevPoint.x,prevPoint.y,lastPoint.x,lastPoint.y,5,temp);oldDiv.appendChild(temp);}
if(div.childNodes.length<2){var closer=makeLabel(geometry.getPoints()[0].x+20,geometry.getPoints()[0].y-3,15,null,"X");connect(closer,'onclick',bind(function(child,event){this.div.removeChild(child);},this,div));div.appendChild(closer);}},this,container),'updated');this.div.appendChild(container);};userSmarts.Map.Layer.Editor=function(layer){if(isPrototype(arguments)){return;}
this.layer=layer;this.controls=[];this.isPainted=false;};userSmarts.Map.Layer.Editor.prototype.show=function(){if(this.layout){if(!this.isPainted){this.repaint();this.isPainted=true;}
this.layout.style.display="block";}};userSmarts.Map.Layer.Editor.prototype.hide=function(){if(this.layout){this.layout.style.display="none";}};userSmarts.Map.Layer.Editor.prototype.isVisible=function(){return(this.layout.style.display!="none");};userSmarts.Map.Layer.Editor.prototype.toggle=function(evt){if(this.layout&&this.layout.style.display=="none"){this.show();}else{this.hide();}
if(evt&&evt.stopPropagation){evt.stopPropagation();}};userSmarts.Map.Layer.Editor.prototype.dispose=function(){this.show();this.layer=null;if(this.briefListener){disconnect(this.briefListener);}
if(this.summListener){disconnect(this.summListener);}
if(this.fullListener){disconnect(this.fullListener);}
var control;var len=this.controls.length;for(var i=0;i<len;i++){control=this.controls.shift();try{control.dispose();}catch(e){}
control=null;}
if(this.layout){replaceChildNodes(this.layout,null);this.layout=null;}};userSmarts.Map.Layer.EditorFF=function(layer){userSmarts.Map.Layer.Editor.apply(this,[layer]);};userSmarts.Map.Layer.EditorFF.inheritsFrom(userSmarts.Map.Layer.Editor);userSmarts.Map.Layer.EditorFF.prototype.paint=function(){if(!this.layout){this.layout=TABLE({'class':'editor',border:'0',cellpadding:'0',cellspacing:'0',width:'100%',height:'100%'});}
this.hide();return this.layout;};userSmarts.Map.Layer.EditorFF.prototype.repaint=function(){if(!this.layer){return;}
if(this.layer.metadataURL){var metadataURL=this.layer.metadataURL;briefMDLink=SPAN({'class':'layer-editor-toggle'},'[brief]');this.briefListener=connect(briefMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=brief","BriefMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});summMDLink=SPAN({'class':'layer-editor-toggle'},'[summary]');this.summListener=connect(summMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=summary","SummaryMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});fullMDLink=SPAN({'class':'layer-editor-toggle'},'[full]');this.fullListener=connect(fullMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=full","FullMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});this.layout.appendChild(THEAD(null,TR(null,TD({width:'100%',colspan:'2'},"view metadata: ",briefMDLink,summMDLink,fullMDLink))));}
var tbody=TBODY();this.layout.appendChild(tbody);var properties=this.layer.getProperties();if(properties&&properties.length){for(var i=0;i<properties.length;i++){tbody.appendChild(this.createControl(properties[i]));}}else{tbody.appendChild(document.createTextNode("No properties"));}};userSmarts.Map.Layer.EditorFF.prototype.createControl=function(property){var dt=property.datatype;var pLabel=property.label;var row=TR();var label=TD({'class':'editor-label'},document.createTextNode(pLabel+": "));row.appendChild(label);var control=TD({'class':'editor-control'});row.appendChild(control);var ctrl;if(dt.isRange&&dt.isRange===true){ctrl=createSliderWidget(property);}else if(dt.isList&&dt.isList===true){ctrl=createSelectWidget(property);}else{ctrl=createTextBox(property);}
control.appendChild(ctrl.paint());this.controls.push(ctrl);return row;};userSmarts.Map.Layer.EditorIE=function(layer){userSmarts.Map.Layer.Editor.apply(this,[layer]);};userSmarts.Map.Layer.EditorIE.inheritsFrom(userSmarts.Map.Layer.Editor);userSmarts.Map.Layer.EditorIE.prototype.paint=function(){if(!this.layout){this.layout=SPAN({'class':'editor'});}
this.hide();return this.layout;};userSmarts.Map.Layer.EditorIE.prototype.repaint=function(){if(!this.layer){return;}
if(this.layer.metadataURL){var metadataURL=this.layer.metadataURL;briefMDLink=SPAN({'class':'layer-editor-toggle'},'[brief]');this.briefListener=connect(briefMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=brief","BriefMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});summMDLink=SPAN({'class':'layer-editor-toggle'},'[summary]');this.summListener=connect(summMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=summary","SummaryMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});fullMDLink=SPAN({'class':'layer-editor-toggle'},'[full]');this.fullListener=connect(fullMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=full","FullMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});this.layout.appendChild(document.createTextNode("view metadata: "));this.layout.appendChild(briefMDLink);this.layout.appendChild(summMDLink);this.layout.appendChild(fullMDLink);this.layout.appendChild(BR());}
var properties=this.layer.getProperties();if(properties&&properties.length){for(var i=0;i<properties.length;i++){this.createControl(properties[i]);}}else{this.layout.appendChild(document.createTextNode("No properties"));}};userSmarts.Map.Layer.EditorIE.prototype.createControl=function(property){var dt=property.datatype;var pLabel=property.label;var label=SPAN({'class':'editor-label'});label.appendChild(document.createTextNode(pLabel+": "));this.layout.appendChild(label);var control=SPAN({'class':'editor-control'});this.layout.appendChild(control);var ctrl;if(dt.isRange&&dt.isRange===true){ctrl=createSliderWidget(property);}else if(dt.isList&&dt.isList===true){ctrl=createSelectWidget(property);}else{ctrl=createTextBox(property);}
control.appendChild(ctrl.paint());this.controls.push(ctrl);this.layout.appendChild(BR());};userSmarts.Map.Layer.EditorFactory=function(){};userSmarts.Map.Layer.EditorFactory.getEditor=function(layer){var editor;if(window.ActiveXObject){editor=new userSmarts.Map.Layer.EditorIE(layer);}else{editor=new userSmarts.Map.Layer.EditorFF(layer);}
return editor;};function createSliderWidget(property){var dt=property.datatype;var min=(typeof(dt.facets.minInclusive)=='number')?dt.facets.minInclusive:(typeof(dt.facets.minExclusive)=='number')?dt.facets.minExclusive:0;var max=(typeof(dt.facets.maxInclusive)=='number')?dt.facets.maxInclusive:(typeof(dt.facets.maxExclusive)=='number')?dt.facets.maxExclusive:0;var widget=new userSmarts.wt.widgets.SliderWidget({min:min,max:max,increment:dt.facets.increment,value:property.getValue()});connect(widget,'onchange',function(){property.setValue(dt.format.parseObject(widget.selected));});return widget;}
function createSelectWidget(property){var dt=property.datatype;var label=property.label;var pValue=property.getValue();var values=dt.facets.enumeration;var om=new userSmarts.wt.forms.DefaultOptionModel({options:values});var input=new userSmarts.wt.forms.SelectWidget({name:label+"_SELECT",size:1,length:30,value:pValue,optionModel:om,binding:property});return input;}
function createTextBox(property){var dt=property.datatype;var label=property.label;var pValue=property.getValue();var input=INPUT({type:'text',size:30,value:pValue});connect(input,'onchange',function(){property.setValue(dt.format.parseObject(input.value));});var obj={input:input,paint:function(){return this.input;},dispose:function(){disconnectAll(this.input);this.input=null;}};return obj;}
userSmarts.Map.LayerLegend=function(properties){userSmarts.wt.widgets.Control.call(this,properties);this.name=" Legend ";this.adapterListener=connect(this,'adapter',this,this.onAdapterChange);};userSmarts.Map.LayerLegend.inheritsFrom(userSmarts.wt.widgets.Control);userSmarts.Map.LayerLegend.prototype.onAdapterChange=function(evt){var canvas=this.adapter.getProperty("canvas");if(this.canvasListener){disconnect(this.canvasListener);}
this.canvasListener=connect(canvas,userSmarts.Map.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};userSmarts.Map.LayerLegend.prototype.getNode=function(){return this.paint();};userSmarts.Map.LayerLegend.prototype.paint=function(){if(!this.layout){this.layout=DIV({'class':'map-layer-legend-content'});}
this.repaint();return this.layout;};userSmarts.Map.LayerLegend.prototype.update=function(){this.repaint();};userSmarts.Map.LayerLegend.prototype.repaint=function(){if(this.adapter){var renderer=this.adapter.getProperty("layer-renderer");if(renderer){var legends=[];var legendImgs;var packages=renderer.getPackages();for(var i=0;i<packages.length;i++){legendImgs=packages[i].getLegend();if(legendImgs&&legendImgs.length>0){legends.unshift(DIV({'class':'legend-icon'},legendImgs));}}
this.disposeLayerImages();if(this.layout){replaceChildNodes(this.layout,legends);}}else{logWarning("userSmarts.Map.LayerLegend could not get reference to layer renderer!  "+"Unable to display rendered package legend images...");}}};userSmarts.Map.LayerLegend.prototype.buildHeader=function(){if(!this.header){this.header=TD({'class':'map-layer-bar-subheader',width:'100%','align':'right'},"");}
return this.header;};userSmarts.Map.LayerLegend.prototype.dispose=function(){disconnect(this.canvasListener);disconnect(this.adapterListener);if(this.layout){this.disposeLayerImages();replaceChildNodes(this.layout,null);this.layout=null;}
if(this.adapter){this.adapter=null;}};userSmarts.Map.LayerLegend.prototype.disposeLayerImages=function(){if(!this.layout)return;var child;var len=this.layout.childNodes.length;for(var i=len-1;i>=0;i--){child=this.layout.childNodes[i];this.layout.removeChild(child);for(var j=child.childNodes.length-1;j>=0;j--){try{disposeImage(child.removeChild(child.childNodes[j]));}catch(e){}}}};userSmarts.Map.LayerLegendWidget=function(properties){properties=setdefault(properties,{id:'map-legend-widget'});Bean.call(this,properties);};userSmarts.Map.LayerLegendWidget.inheritsFrom(Bean);userSmarts.Map.LayerLegendWidget.prototype.paint=function(context){if(!this.layout){this.layout=DIV({'class':'map-layer-legend'});this.layout.appendChild(DIV({'class':'map-layer-legend-header'},"Legend"));if(this.control){this.layout.appendChild(this.control.paint());}}
return this.layout;};userSmarts.Map.LayerLegendWidget.prototype.repaint=function(context){if(this.control){this.control.repaint();}};userSmarts.Map.LayerLegendWidget.prototype.dispose=function(){if(this.control){this.control.dispose();}
if(this.layout){replaceChildNodes(this.layout,null);this.layout=null;}};$namespace.SuggestedLayerControl=Class.create(userSmarts.wt.widgets.List);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'map-layer-window',name:"Suggested Layers",timeout:3000,modcount:0,waitOnRefresh:false,showFooter:false,layoutData:{width:"100%",height:"100%"}});superClass.call(this,properties);this.model=new userSmarts.wt.widgets.TableModel({columns:[new userSmarts.wt.widgets.TableColumn({name:"name",index:0}),new userSmarts.wt.widgets.TableColumn({label:"SRS",name:"srs",index:1})],buffer:[]});};$prototype.paint=function(){return this.getNode();};$prototype.repaint=function(){this.update();};$prototype.setLayers=function(layerArr){if(typeof(layerArr.length)=='number'){this.model.buffer=layerArr;this.update();}};$prototype.buildHeader=function(){if(!this.header){this.includeButton=SPAN({title:"Add to current layers",'class':'button'},"Add");this.includeButtonListener=connect(this.includeButton,'onclick',this,this.onIncludeLayer);this.wmsHarvestButton=SPAN({title:"Harvest layers from WMS",'class':'button'},"WMS Harvest");this.wmsHarvestButtonListener=connect(this.wmsHarvestButton,'onclick',this,this.performWMSHarvest);this.cswHarvestButton=SPAN({title:"Harvest layers from CSW",'class':'button'},"CSW Harvest");this.cswHarvestButtonListener=connect(this.cswHarvestButton,'onclick',this,this.performCSWHarvest);this.clearButton=SPAN({'title':'Clear Suggested Layers','class':'button'},'Clear');this.clearButtonListener=connect(this.clearButton,'onclick',this,this.clear);this.header=TD({'class':'map-layer-bar-subheader',width:'100%','align':'right'},this.includeButton,this.wmsHarvestButton,this.cswHarvestButton,this.clearButton);}
return this.header;};$prototype.onIncludeLayer=function(){if(!this.selected){alert("Must select a layer to add first!");return;}
var layer=this.selected;if(layer.included)return;if(this.adapter){var context=this.adapter.getProperty("context");if(layer.srs==context.boundingBox.srs){context.addLayer(layer);layer.included=true;}else{alert("Cannot import selected layer - "+"Coordinate Reference System must match "+"one in use by current Web Map Context!");}}else{logWarning("userSmarts.Map.SuggestedLayerControl : "+"control was not properly registered with the map widget, "+"unable to include layer in current view context");}};$prototype.performWMSHarvest=function(){if(this.harvester){if(typeof(this.harvester.harvestWMSLayers)!="undefined"){this.harvester.harvestWMSLayers();}else{alert("Registered harvester provides no "+"'harvestWMSLayers' method! Unable to "+"harvest layers from WMS...");}}else{alert("No harvester registered to perform harvest! "+"Unable to harvest layers from WMS...");}};$prototype.performCSWHarvest=function(){if(this.harvester){if(typeof(this.harvester.harvestCSWLayers)!='undefined'){this.harvester.harvestCSWLayers();}else{alert("Registered harvester provides no "+"'harvestCSWLayers' method! Unable to "+"harvest layers from CSW...");}}else{alert("No harvester registered to perform harvest! "+"Unable to harvest layers from CSW...");}};$prototype.clear=function(){this.setLayers([]);};$prototype.dispose=function(){if(this.header){disconnect(this.includeButton);this.includeButton=null;disconnect(this.wmsHarvestButton);this.wmsHarvestButton=null;disconnect(this.cswHarvestButton);this.cswHarvestButton=null;disconnect(this.clearButtonListener);this.clearButtonListener=null;replaceChildNodes(this.header,null);this.header=null;}
if(this.adapter){this.adapter=null;}};$namespace.LayerPackage=Class.create();$prototype.initialize=function(server){this.server=server;this.layers=[];};$prototype.getServer=function(){return this.server;};$prototype.setServer=function(server){this.server=server;};$prototype.addLayer=function(layer){this.layers.push(layer);};$prototype.getLayers=function(){return this.layers;};$prototype.getVisibleLayers=function(){return this.layers.filter(function(item){return item.visible;},null);};$prototype.setLoadingStatus=function(status){var layers=this.getVisibleLayers();for(var i=0;i<layers.length;i++){layers[i].setProperty("status",status);}};$prototype.getDefaultPropertyValue=function(propertyName){var result=null;for(var i=0;i<this.layers.length;i++){if(this.layers[i].visible){result=this.layers[i][propertyName];break;}}
return result;};$prototype.size=function(){return this.layers.length;};$prototype.indexOf=function(layer){var result=-1;for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){result=i;break;}}
return result;};$prototype.contains=function(layer){return(this.indexOf(layer)>=0);};$prototype.setImage=function(image){this.imageToken=this.calculateImageToken();this.image=image;};$prototype.getImage=function(){return this.image;};$prototype.isImageCurrent=function(){var result=true;if(this.image&&this.getVisibleLayers().length>0){result=(this.imageToken==this.calculateImageToken());}
return result;};$prototype.setLegend=function(arg){if(typeof(arg)=='array'||arg.length){this.legendImages=arg;}else{this.legendImages=[arg];}};$prototype.getLegend=function(){return this.legendImages;};$prototype.repr=function(){return this.toString();};$prototype.toString=function(){var str='{ ';str+='Server: ['+((this.server)?this.server.getName():'NoServer')+']\n';str+='Layers: [';for(var i=0;i<this.layers.length;i++){if(i>0){str+=', ';}
str+=this.layers[i].getLayerName();}
str+='] }';return str;};$prototype.calculateImageToken=function(){var token='';var layers=this.getVisibleLayers();for(var i=0;i<layers.length;i++){token+=(i>0?',':'')+layers[i].name;}
return token;};$prototype.clear=function(){this.server=null;this.layers=[];this.image=null;this.imageToken=null;this.legendImages=[];};$prototype.load=function(context){var deferred=new Deferred();if(this.server){var result=this.server.render(this,context);if(result.image){this.setImage(result.image);delete result.image;result.image=null;}
result.deferred.addCallback(function(img){if(img){deferred.callback(img);}else{deferred.errback("image was null");}});result.deferred.addErrback(bind(function(e){deferred.errback(e);},this));}
return deferred;};$prototype.dispose=function(){if(this.image){disposeImage(this.image);}
this.clear();};$prototype.equals=function(pkg){var result=false;if(pkg&&pkg instanceof userSmarts.Map.LayerPackage){result=pkg.repr()==this.repr();}
return result;};userSmarts.Map.PackageFactory={packages:[],MAX_PKGS:50};userSmarts.Map.PackageFactory.getPackage=function(){if(userSmarts.Map.PackageFactory.packages.length===0){return new userSmarts.Map.LayerPackage(null);}else{return userSmarts.Map.PackageFactory.packages.shift();}};userSmarts.Map.PackageFactory.releasePackage=function(pkg){if(pkg instanceof userSmarts.Map.LayerPackage){pkg.dispose();if(userSmarts.Map.PackageFactory.packages.length<userSmarts.Map.PackageFactory.MAX_PKGS){userSmarts.Map.PackageFactory.packages.push(pkg);}}};$namespace.PackageManager=Class.create();$prototype.initialize=function(){this.total=0;this.packages=[];};$prototype.loadPackageSync=function(index,packages,context){if(index>=packages.length){this.onComplete();return;}
if(packages[index].getVisibleLayers().length===0){this.packages.push(packages[index]);this.loadPackageSync(index+1,packages,context);}else{this.packages.push(packages[index]);def=packages[index].load(context);def.addCallback(bind(function(i){this.loadPackageSync(i,packages,context);},this,index+1));def.addErrback(bind(function(i,e){this.loadPackageSync(i,packages,context);},this,index+1));}};$prototype.loadPackageAsync=function(packages,context){this.total=packages.length;for(var index=0;index<packages.length;index++){this.packages.push(packages[index]);if(packages[index].getVisibleLayers().length===0){this.onLoad(null);}else{def=packages[index].load(context);def.addCallback(bind(this.onLoad,this));def.addErrback(bind(this.onError,this));}}};$prototype.load=function(packages,context){this.result=new Deferred();if(typeof(packages.length)=='undefined'){if(userSmarts.Map.DEBUG_FLAG){logWarning("Package array was not valid, loading skipped");}
this.result.callback([]);return this.result;}
this.oldPackages=this.packages;this.packages=[];this.total=packages.length;this.loadPackageAsync(packages,context);return this.result;};$prototype.onLoad=function(image){--this.total;if(this.total===0){this.onComplete();}};$prototype.onError=function(error){--this.total;if(this.total===0){this.onComplete();}};$prototype.onComplete=function(){if(this.oldPackages){var len=this.oldPackages.length;for(var i=0;i<len;i++){userSmarts.Map.PackageFactory.releasePackage(this.oldPackages.shift());}}
this.result.callback(null);};$prototype.getImages=function(){var images=[];var image;for(var i=0;i<this.packages.length;i++){image=this.packages[i].getImage();if(image){images.push(image);}}
return images;};$prototype.findPackage=function(layer){for(var i=0;i<this.packages.length;i++){if(this.packages[i].contains(layer)){return this.packages[i];}}
return null;};$prototype.replacePackage=function(pkg,context,newPackages){if(this.result){this.result.results[0]=this.result.results[1]=null;this.result=null;}
if(pkg){this.result=new Deferred();if(newPackages!==null&&newPackages!==undefined){var length=0;if(typeof(newPackages.length)!='undefined'){length=newPackages.length;this.packages=spliceArray(this.packages,pkg.index,1,newPackages);for(var i=pkg.index;i<this.packages.length;i++){this.packages[i].index=i;}}else{length=1;this.packages=spliceArray(this.packages,pkg.index,1,[newPackages]);this.packages[pkg.index].index=pkg.index;}
this.total=length;var def;for(var i=pkg.index;i<(pkg.index+length);i++){if(this.packages[i].getVisibleLayers().length>0){def=this.packages[i].load(context);def.addCallback(bind(this.onLoad,this));def.addErrback(bind(this.onError,this));}else{this.onLoad(null);}}}else{this.packages=spliceArray(this.packages,pkgIndex,1,[]);this.total=1;this.onLoad(null);}
this.oldPackages=[pkg];}
return this.result;};$prototype.dispose=function(){for(var i=0;i<this.packages.length;++i){this.packages[i].dispose();this.packages[i]=null;}
this.packages=null;};$namespace.LayerRenderer=Class.create(Bean);$prototype.initialize=function(properties){Bean.call(this,properties);this.callbacks=[];connect(this,"context",this,this.onContextChange);this.cb=bind(this.fireCallback,this);};$prototype.render=function(){if(this.adapter){var pbar=this.adapter.getProperty("progressBar");if(pbar){pbar.show();}
var context=this.adapter.getProperty("context");if(!context){return;}
var layers=context.layers;if(!layers){return;}
var packages=this.packageLayers(layers);if(!this.manager){this.manager=new userSmarts.Map.PackageManager();}
var result=this.manager.load(packages,context);result.addCallback(this.cb);}
return null;};$prototype.fireCallback=function(){this.callback(this.manager.getImages());};$prototype.packageLayers=function(layers){var packages=[];var layer;var pkg;var pkgIndex=0;for(var i=0;i<layers.length;i++){layer=layers[i];pkg=userSmarts.Map.PackageFactory.getPackage();pkg.setServer(layer.server);pkg.addLayer(layer);pkg.index=pkgIndex;pkgIndex++;packages.push(pkg);if(i<(layers.length-1)){var j=i+1;var go=true;while(go&&j<layers.length){var nextLayer=layers[j];go=nextLayer.shouldCoalesceWith(layer)&&layer.shouldCoalesceWith(nextLayer);if(go){pkg.addLayer(nextLayer);j++;}}
i=(j<layers.length)?j-1:layers.length;}}
return packages;};$prototype.onContextChange=function(event){if(this.layerChangedListener){disconnect(this.layerChangedListener);}
ctx=event.newValue;if(ctx){this.layerChangedListener=connect(ctx,userSmarts.Map.ViewContext.LAYER_CHANGED_EVENT_PROPERTY,this,'onContextFiredLayerChange');}};$prototype.addCallback=function(func){this.callbacks.push(func);};$prototype.callback=function(arg){for(var i=0;i<this.callbacks.length;i++){this.callbacks[i](arg);}
var pbar=this.adapter.getProperty("progressBar");if(pbar){pbar.hide();}};$prototype.onContextFiredLayerChange=function(event){var layerEvent=event.newValue;this.onLayerChange(layerEvent);};$prototype.onLayerChange=function(event){var layer=event.source;var property=event.propertyName;var value=event.newValue;if(!layer.shouldRefreshFor(property)){return;}
if(!this.manager){return;}
var pkg=this.manager.findPackage(layer);if(!pkg){logWarning("Warning! Unable to find the package for the changed layer!");return;}
if(this.adapter){var pbar=this.adapter.getProperty("progressBar");if(pbar){pbar.show();}}
if(!pkg.server.refreshLayerPackage(pkg,event)){if(this.adapter){var newPkgs=this.packageLayers(pkg.layers);var result=this.manager.replacePackage(pkg,this.adapter.getProperty("context"),newPkgs);if(result){result.addCallback(this.cb);}}}else{if(this.adapter){var pbar=this.adapter.getProperty("progressBar");if(pbar){pbar.hide();}}}};$prototype.getPackages=function(){var result;if(this.manager){result=this.manager.packages;}
else{result=[];}
return result;};$prototype.dispose=function(){disconnectAll(this);if(this.layerChagedListener){disconnect(this.layerChangedListener);}
if(this.manager){this.manager.dispose();this.manager=null;}};namespace('OGC');namespace("userSmarts.ogc.filter");OGC.NAMESPACE_URI="http://www.opengis.net/ogc";OGC.NAMESPACE_PREFIX="ogc";OGC.FilterOperation={OR:"Or",AND:"And",NOT:"Not",PROPERTYISEQUALTO:"PropertyIsEqualTo",PROPERTYISLESSTHAN:"PropertyIsLessThan",PROPERTYISLESSTHANOREQUALTO:"PropertyIsLessThanOrEqualTo",PROPERTYISGREATERTHAN:"PropertyIsGreaterThan",PROPERTYISGREATERTHANOREQUALTO:"PropertyIsGreaterThanOrEqualTo",PROPERTYISBETWEEN:"PropertyIsBetween",PROPERTYISLIKE:"PropertyIsLike",PROPERTYISNULL:"PropertyIsNull",BBOX:"BBOX",INTERSECTS:"Intersects",DISJOINT:"Disjoint",WITHIN:"Within",OVERLAPS:"Overlaps",isLogicalOperation:function(operation){var opName;if(operation instanceof userSmarts.ogc.filter.Node){opName=operation.name;}else if(typeof operation=='string'){opName=operation;}
var result=false;if(opName){result=(opName==OGC.FilterOperation.OR)||(opName==OGC.FilterOperation.AND)||(opName==OGC.FilterOperation.NOT);}
return result;},isComparisonOperation:function(operation){var opName;if(operation instanceof userSmarts.ogc.filter.Node){opName=operation.name;}else if(typeof operation=='string'){opName=operation;}
var result=false;if(opName){result=(opName==OGC.FilterOperation.PROPERTYISBETWEEN)||(opName==OGC.FilterOperation.PROPERTYISEQUALTO)||(opName==OGC.FilterOperation.PROPERTYISGREATERTHAN)||(opName==OGC.FilterOperation.PROPERTYISGREATERTHANOREQUALTO)||(opName==OGC.FilterOperation.PROPERTYISLESSTHAN)||(opName==OGC.FilterOperation.PROPERTYISLESSTHANOREQUALTO)||(opName==OGC.FilterOperation.PROPERTYISLIKE)||(opName==OGC.FilterOperation.PROPERTYISNULL);}
return result;},isSpatialOperation:function(operation){var opName;if(operation instanceof userSmarts.ogc.filter.Node){opName=operation.name;}else if(typeof operation=='string'){opName=operation;}
var result=false;if(opName){result=(opName==OGC.FilterOperation.BBOX)||(opName==OGC.FilterOperation.INTERSECTS)||(opName==OGC.FilterOperation.DISJOINT)||(opName==OGC.FilterOperation.WITHIN)||(opName==OGC.FilterOperation.OVERLAPS);}
return result;}};userSmarts.ogc.filter.Node=function(properties){if(isPrototype(arguments)){return;}
setdefault(this,properties);};userSmarts.ogc.filter.Node.prototype.getName=function(){return this.name;};userSmarts.ogc.filter.Filter=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{name:'Filter'});this.root=new userSmarts.ogc.filter.LogicalOperation({name:OGC.FilterOperation.OR});userSmarts.ogc.filter.Node.call(this,properties);};userSmarts.ogc.filter.Filter.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.Filter.prototype.setRoot=function(node){if(node instanceof userSmarts.ogc.filter.Node){this.root=node;}};userSmarts.ogc.filter.Filter.prototype.getRoot=function(){return this.root;};userSmarts.ogc.filter.Filter.prototype.toString=function(){var str='<'+OGC.NAMESPACE_PREFIX+':Filter xmlns:'+OGC.NAMESPACE_PREFIX+'="'+OGC.NAMESPACE_URI+'">';str+=this.root.toString();str+="</"+OGC.NAMESPACE_PREFIX+":Filter>";return str;};userSmarts.ogc.filter.Filter.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,"Filter",document,OGC.NAMESPACE_PREFIX);element.appendChild(this.root.toXml(document));return element;};userSmarts.ogc.filter.PropertyName=function(name){if(isPrototype(arguments)){return;}
userSmarts.ogc.filter.Node.call(this,{name:name});};userSmarts.ogc.filter.PropertyName.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.PropertyName.prototype.setName=function(name){this.name=name;};userSmarts.ogc.filter.PropertyName.prototype.toString=function(){return'<'+OGC.NAMESPACE_PREFIX+':PropertyName>'+this.name+'</'+OGC.NAMESPACE_PREFIX+':PropertyName>';};userSmarts.ogc.filter.PropertyName.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,"PropertyName",document,OGC.NAMESPACE_PREFIX);element.appendChild(document.createTextNode(this.name));return element;};userSmarts.ogc.filter.Literal=function(value){if(isPrototype(arguments)){return;}
userSmarts.ogc.filter.Node.call(this,{value:value});};userSmarts.ogc.filter.Literal.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.Literal.prototype.setValue=function(value){this.value=value;};userSmarts.ogc.filter.Literal.prototype.getValue=function(){return this.value;};userSmarts.ogc.filter.Literal.prototype.toString=function(){var val=this.value;if(this.value===null){val='null';}
return'<'+OGC.NAMESPACE_PREFIX+':Literal>'+val+'</'+OGC.NAMESPACE_PREFIX+':Literal>';};userSmarts.ogc.filter.Literal.prototype.toXml=function(document){var val=this.value;if(this.value===null){val='null';}
var element=createElementNS(OGC.NAMESPACE_URI,"Literal",document,OGC.NAMESPACE_PREFIX);element.appendChild(document.createTextNode(val));return element;};userSmarts.ogc.filter.ComparisonOperation=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{name:OGC.FilterOperation.PROPERTYISEQUALTO,propertyName:new userSmarts.ogc.filter.PropertyName("Any"),literal:new userSmarts.ogc.filter.Literal("*")});userSmarts.ogc.filter.Node.call(this,properties);};userSmarts.ogc.filter.ComparisonOperation.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.ComparisonOperation.prototype.setPropertyName=function(propertyName){if(propertyName instanceof userSmarts.ogc.filter.PropertyName){this.propertyName=propertyName;}};userSmarts.ogc.filter.ComparisonOperation.prototype.getPropertyName=function(){return this.propertyName;};userSmarts.ogc.filter.ComparisonOperation.prototype.setLiteral=function(literal){if(literal instanceof userSmarts.ogc.filter.Literal){this.literal=literal;}};userSmarts.ogc.filter.ComparisonOperation.prototype.getLiteral=function(){return this.literal;};userSmarts.ogc.filter.ComparisonOperation.prototype.toString=function(){var str='<'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';str+=this.propertyName.toString();str+=this.literal.toString();str+='</'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';return str;};userSmarts.ogc.filter.ComparisonOperation.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,this.name,document,OGC.NAMESPACE_PREFIX);element.appendChild(this.propertyName.toXml(document));element.appendChild(this.literal.toXml(document));return element;};userSmarts.ogc.filter.BetweenComparison=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{name:OGC.FilterOperation.PROPERTYISBETWEEN,lower:new userSmarts.ogc.filter.Literal("*"),upper:new userSmarts.ogc.filter.Literal("*")});userSmarts.ogc.filter.ComparisonOperation.call(this,properties);};userSmarts.ogc.filter.BetweenComparison.inheritsFrom(userSmarts.ogc.filter.ComparisonOperation);userSmarts.ogc.filter.BetweenComparison.prototype.setLowerBounds=function(literal){if(literal instanceof userSmarts.ogc.filter.Literal){this.lower=literal;}};userSmarts.ogc.filter.BetweenComparison.prototype.getLowerBounds=function(){return this.lower;};userSmarts.ogc.filter.BetweenComparison.prototype.setUpperBounds=function(literal){if(literal instanceof userSmarts.ogc.filter.Literal){this.upper=literal;}};userSmarts.ogc.filter.BetweenComparison.prototype.getUpperBounds=function(){return this.upper;};userSmarts.ogc.filter.BetweenComparison.prototype.toString=function(){var str='<'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';str+=this.propertyName.toString();str+='<'+OGC.NAMESPACE_PREFIX+':LowerBoundary>';str+=this.lower.toString();str+='</'+OGC.NAMESPACE_PREFIX+':LowerBoundary>';str+='<'+OGC.NAMESPACE_PREFIX+':UpperBoundary>';str+=this.upper.toString();str+='</'+OGC.NAMESPACE_PREFIX+':UpperBoundary>';str+='</'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';return str;};userSmarts.ogc.filter.BetweenComparison.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,this.name,document,OGC.NAMESPACE_PREFIX);element.appendChild(this.propertyName.toXml(document));var lowerElement=createElementNS(OGC.NAMESPACE_URI,'LowerBoundary',document,OGC.NAMESPACE_PREFIX);element.appendChild(lowerElement);lowerElement.appendChild(this.lower.toXml(document));var upperElement=createElementNS(OGC.NAMESPACE_URI,'UpperBoundary',document,OGC.NAMESPACE_PREFIX);element.appendChild(upperElement);upperElement.appendChild(this.upper.toXml(document));return element;};userSmarts.ogc.filter.LogicalOperation=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{name:OGC.OR,nodes:[]});userSmarts.ogc.filter.Node.call(this,properties);};userSmarts.ogc.filter.LogicalOperation.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.LogicalOperation.prototype.addOperation=function(node){this.nodes.push(node);};userSmarts.ogc.filter.LogicalOperation.prototype.getOperations=function(){return this.nodes;};userSmarts.ogc.filter.LogicalOperation.prototype.toString=function(){var str="<"+OGC.NAMESPACE_PREFIX+":"+this.name+">";for(var i=0;i<this.nodes.length;i++){str+=this.nodes[i].toString();}
str+="</"+OGC.NAMESPACE_PREFIX+":"+this.name+">";return str;};userSmarts.ogc.filter.LogicalOperation.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,this.name,document,OGC.NAMESPACE_PREFIX);for(var i=0;i<this.nodes.length;i++){element.appendChild(this.nodes[i].toXml(document));}
return element;};userSmarts.ogc.filter.SpatialOperation=function(properties){if(isPrototype(arguments)){return;}
properties=setdefault(properties,{name:OGC.FilterOperation.BBOX,propertyName:new userSmarts.ogc.filter.PropertyName("Any"),geometry:Geometry.valueOf('Box{(-180.0,-90.0),(180.0,90.0)}')});userSmarts.ogc.filter.Node.call(this,properties);};userSmarts.ogc.filter.SpatialOperation.inheritsFrom(userSmarts.ogc.filter.Node);userSmarts.ogc.filter.SpatialOperation.prototype.setPropertyName=function(propertyName){if(propertyName instanceof userSmarts.ogc.filter.PropertyName){this.propertyName=propertyName;}};userSmarts.ogc.filter.SpatialOperation.prototype.getPropertyName=function(){return this.propertyName;};userSmarts.ogc.filter.SpatialOperation.prototype.setGeometry=function(geometry){if(geometry instanceof Geometry){this.geometry=geometry;}};userSmarts.ogc.filter.SpatialOperation.prototype.getGeometry=function(){return this.geometry;};userSmarts.ogc.filter.SpatialOperation.prototype.toString=function(){var str='<'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';str+=this.propertyName.toString();str+=this.geometry.toGmlString();str+='</'+OGC.NAMESPACE_PREFIX+':'+this.name+'>';return str;};userSmarts.ogc.filter.SpatialOperation.prototype.toXml=function(document){var element=createElementNS(OGC.NAMESPACE_URI,this.name,document);element.appendChild(this.propertyName.toXml(document));element.appendChild(document.createTextNode(this.geometry.toGml(document)));return element;};Geometry.prototype.toGmlString=function(){var type=this.getType();var points=this.getPoints();var pointStr='';for(var i=0;i<points.length;i++){if(i>0&&type!="Box"){pointStr+=',';}
else if(type=="Box"){pointStr+=' ';}
pointStr+=points[i].x+","+points[i].y;}
var str='<gml:'+type+' xmlns:gml="http://www.opengis.net/gml">';str+='<gml:coordinates>'+pointStr+'</gml:coordinates>';str+='</gml:'+type+'>';return str;};Geometry.prototype.toGml=function(document){var type=this.getType();var points=this.getPoints();var pointStr='';for(var i=0;i<points.length;i++){if(i>0){pointStr+=',';}
pointStr+=points[i].x+","+points[i].y;}
var element=createElementNS("http://www.opengis.net/gml",type,document,"gml");var coords=createElementNS("http://www.opengis.net/gml","coordinates",document,"gml");coords.appendChild(document.createTextNode(pointStr));element.appendChild(coords);return element;};userSmarts.ogc.filter.FilterParser=function(properties){setdefault(this,properties);};userSmarts.ogc.filter.FilterParser.prototype.parse=function(node){var root;if(node.nodeType==1){root=node;}else if(node.nodeType==9){root=node.documentElement;}else{return null;}
return this.parseFilterNode(root);};userSmarts.ogc.filter.FilterParser.prototype.parseFilterNode=function(node){try{if(node.nodeType!=1){logDebug("Ignoring non-Element node");return null;}
var nodeName=node.localName||node.tagName;logDebug("Node is named '"+nodeName+"'");var out;if(nodeName=='Filter'){logDebug("Parsing Filter");out=new userSmarts.ogc.filter.Filter();var op=this.parseFilterNode(node.childNodes[0]);if(op){out.setRoot(op);}else{logError("Error!");}}else if(OGC.FilterOperation.isLogicalOperation(nodeName)){logDebug("Parsing LogicalOperation");out=this.parseLogicalOperation(node);}else if(OGC.FilterOperation.isComparisonOperation(nodeName)){logDebug("Parsing ComparisonOperation");out=this.parseComparisonOperation(node);}else if(OGC.FilterOperation.isSpatialOperation(nodeName)){logDebug("Parsing SpatialOperation");out=this.parseSpatialOperation(node);}else{logError("Unknown Filter node '"+nodeName+"'");}
return out;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parseFilterNode : Error - "+e);}};userSmarts.ogc.filter.FilterParser.prototype.parsePropertyName=function(node){try{if(!node){logError("userSmarts.ogc.filter.FilterParser.parsePropertyName() : ERROR - unable to parse PropertyName, node was null");return null;}
var name=scrapeText(node);var propertyName=new userSmarts.ogc.filter.PropertyName(name);return propertyName;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parsePropertyName : Error - "+e);}};userSmarts.ogc.filter.FilterParser.prototype.parseLiteral=function(node){try{if(!node){logError("userSmarts.ogc.filter.FilterParser.parseLiteral() : ERROR - unable to parse Literal, node was null");return null;}
var value=scrapeText(node);var literal=new userSmarts.ogc.filter.Literal(value);return literal;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parseLiteral : Error - "+e);}};userSmarts.ogc.filter.FilterParser.prototype.parseLogicalOperation=function(node){try{var nodeName=node.localName||node.tagName;var out=new userSmarts.ogc.filter.LogicalOperation({name:nodeName});var child;logDebug("Or has "+node.childNodes.length+" children");for(var i=0;i<node.childNodes.length;i++){child=this.parseFilterNode(node.childNodes[i]);if(child){out.addOperation(child);}
else{}}
return out;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parseLogicalOperation : Error - "+e);}};userSmarts.ogc.filter.FilterParser.prototype.parseComparisonOperation=function(node){try{var nodeName=node.localName||node.tagName;var propertyNameNode=node.getElementsByTagNameNS(OGC.NAMESPACE_URI,"PropertyName")[0];var propertyName=this.parsePropertyName(propertyNameNode);if(!propertyName){return null;}
var out;if(nodeName==OGC.FilterOperation.PROPERTYISBETWEEN){var lowerBoundaryNode=node.getElementsByTagNameNS(OGC.NAMESPACE_URI,"LowerBoundary")[0];var lowerBoundaryLiteralNode=lowerBoundaryNode.getElementsByTagNameNS(OGC.NAMESPACE_URI,"Literal")[0];var lowerBoundaryLiteral=this.parseLiteral(lowerBoundaryLiteralNode);if(!lowerBoundaryLiteral){return null;}
var upperBoundaryNode=node.getElementsByTagNameNS(OGC.NAMESPACE_URI,"UpperBoundary")[0];var upperBoundaryLiteralNode=upperBoundaryNode.getElementsByTagNameNS(OGC.NAMESPACE_URI,"Literal")[0];var upperBoundaryLiteral=this.parseLiteral(upperBoundaryLiteralNode);if(!upperBoundaryLiteral){return null;}
out=new userSmarts.ogc.filter.BetweenComparison({name:nodeName});out.setPropertyName(propertyName);out.setLowerBounds(lowerBoundaryLiteral);out.setUpperBounds(upperBoundaryLiteral);}else{var literalNode=node.getElementsByTagNameNS(OGC.NAMESPACE_URI,"Literal")[0];var literal=this.parseLiteral(literalNode);if(!literal){return null;}
out=new userSmarts.ogc.filter.ComparisonOperation({name:nodeName});out.setPropertyName(propertyName);out.setLiteral(literal);}
return out;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parseComparisonOperation : Error - "+e);}};userSmarts.ogc.filter.FilterParser.prototype.parseSpatialOperation=function(node){try{var nodeName=node.localName||node.tagName;var propertyNameNode=node.getElementsByTagNameNS(OGC.NAMESPACE_URI,"PropertyName")[0];var propertyName=this.parsePropertyName(propertyNameNode);if(!propertyName){return null;}
var boxNode=node.getElementsByTagNameNS("http://www.opengis.net/gml","Box")[0];var coordNode=node.getElementsByTagNameNS("http://www.opengis.net/gml","coordinates")[0];var coordinates=scrapeText(coordNode);var coordArray=coordinates.split(',');forEach(coordArray,function(coord){coord.trim();});var coordStr='';for(var i=0;i<coordArray.length;i+=2){if(i>0){coordStr+=',';}
coordStr+='('+coordArray[i]+','+coordArray[i+1]+')';}
var geometry=Geometry.valueOf('Box{'+coordStr+'}');var out=new userSmarts.ogc.filter.SpatialOperation({name:nodeName,propertyName:propertyName,geometry:geometry});return out;}catch(e){logError("userSmarts.ogc.filter.FilterParser.parseSpatialOperation : Error - "+e);}};namespace("userSmarts.map.ui");userSmarts.map.ui.MapToolContribution=function(properties){userSmarts.wt.action.ContributionItem.call(this,properties);};userSmarts.map.ui.MapToolContribution.inheritsFrom(userSmarts.wt.action.ContributionItem);userSmarts.map.ui.MapToolContribution.prototype.getId=function(){if(this.tool){return this.tool.id;}
return"";};userSmarts.map.ui.MapToolContribution.prototype.execute=function(){};userSmarts.map.ui.MapToolContribution.prototype.getNode=function(){if(!this.node){this.node=this.tool.paint();}
return this.node;};userSmarts.map.ui.ResizableControl=function(properties){if(isPrototype(arguments)){return;}
userSmarts.wt.widgets.Control.call(this,properties);};userSmarts.map.ui.ResizableControl.inheritsFrom(userSmarts.wt.widgets.Control);userSmarts.map.ui.ResizableControl.prototype.setSize=function(width,height){width=Math.floor(width);height=Math.floor(height);if(!this.size){this.size={};}
var modified=!(this.size.width==width&&this.size.height==height);if(modified){this.size.width=width||0;this.size.height=height||0;var node=this.getNode();node.style.width=this.size.width+"px";node.style.height=this.size.height+"px";if(this.adapter){this.adapter.resize(this.size.width,this.size.height);}}
return modified;};userSmarts.map.ui.MapControl=function(properties){if(isPrototype(arguments)){return;}
userSmarts.wt.widgets.Control.call(this,properties);};userSmarts.map.ui.MapControl.inheritsFrom(userSmarts.wt.widgets.Control);userSmarts.map.ui.MapControl.prototype.setSize=function(width,height){width=Math.floor(width);height=Math.floor(height);if(!this.size){this.size={};}
var modified=!(this.size.width==width&&this.size.height==height);if(modified){this.size.width=width||0;this.size.height=height||0;var node=this.getNode();node.style.width=this.size.width+"px";node.style.height=this.size.height+"px";var width=this.size.width-2;var height=this.size.height-2;var area=width*height;if(area>=1000000){var scale=1000000.0/area;width=Math.floor(width*scale);height=Math.floor(height*scale);}
if(this.adapter){this.adapter.resizeMap(width,height);}}
return modified;};userSmarts.map.ui.MapView=function(desc){if(isPrototype(arguments)){return;}
userSmarts.ui.ViewPart.call(this,desc);this.width=600;this.height=400;this.showToolbar=true;this.showLocation=true;};userSmarts.map.ui.MapView.inheritsFrom(userSmarts.ui.ViewPart);userSmarts.map.ui.MapView.prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};userSmarts.map.ui.MapView.prototype.createPartControl=function(){if(!this.layout){var layout=DIV({'class':'map-view'});layout.style.overflow="hidden";this.layout=layout;var map=this.buildMap();this.map=map;this.contributeToActionBars();}
this.control=new userSmarts.map.ui.ResizableControl({adapter:this,node:this.layout});return this.control;};userSmarts.map.ui.MapView.prototype.contributeToActionBars=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var map=this.map;if(this.showToolbar){var toolFactory=new ToolIconFactory(userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/map/'));var toolbarModel=new userSmarts.Map.ToolBarModel({factory:toolFactory,overrideHelp:true});map.register('toolbar-model',toolbarModel);var contextManager=map.locate("context-mgr");if(!contextManager){contextManager=new userSmarts.Map.ContextManager();map.register('context-mgr',contextManager);}
this.addTools(toolbarModel,toolFactory);var tools=toolbarModel.getTools();forEach(tools,function(tool){tbmgr.add(new userSmarts.map.ui.MapToolContribution({tool:tool}));});}
if(this.showLocation){this.location=new userSmarts.Map.LocationBar();map.register('location-bar',this.location);this.location.paint();this.location.hide();}
var slmgr=actionbars.getStatusLineManager();connect(this.location,'location',this,this.onLocationChange);};userSmarts.map.ui.MapView.prototype.addTools=function(toolbarModel,toolFactory){toolbarModel.addTool(new userSmarts.Map.HelpTool({factory:toolFactory,model:toolbarModel}));toolbarModel.addTool(new userSmarts.Map.PanTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.DragTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.ZoomTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.ZoomToBoxTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.BookmarkTool({factory:toolFactory,manager:contextManager}));toolbarModel.addTool(new userSmarts.Map.MeasureTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.GeometryTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.PresetCircleTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.Map.DescribeTool({factory:toolFactory}));};userSmarts.map.ui.MapView.prototype.onLocationChange=function(event){var actionbars=this.getSite().getActionBars();var slmgr=actionbars.getStatusLineManager();var value=event.newValue;value=value.replace("longitude:",'lon:');value=value.replace("latitude:",'lat:');slmgr.setMessage(value);};userSmarts.map.ui.MapView.prototype.resize=function(width,height){width=Math.min(900,width-3);height=Math.min(900,height-3);var map=this.map;if(!map){return;}
var context=map.getProperty("context");if(context){context.removeListeners();}
var ctxmgr=map.locate('context-mgr');if(ctxmgr){map.unregister('context-mgr');}
var tbmodel=map.locate('toolbar-model');if(tbmodel){map.unregister('toolbar-model');}
if(this.location){map.unregister('location-bar');}
var layerbar=map.locate('layer-control');if(layerbar){map.unregister('layer-control');}
map.dispose();map=null;map=this.buildMap(width,height);this.map=map;if(tbmodel){map.register('toolbar-model',tbmodel);}
if(ctxmgr){map.register('context-mgr',ctxmgr);}
if(this.location){map.register('location-bar',this.location);}
if(layerbar){map.register('layer-control',layerbar);}
if(context){map.setContext(context);}};userSmarts.map.ui.MapView.prototype.buildMap=function(width,height){if(width){this.width=width;}
if(height){this.height=height;}
var map=userSmarts.Map.Manager.createMap({id:"map",width:this.width,height:this.height,imagedir:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/map/'),showScale:true,debug:false});replaceChildNodes(this.layout,map.paint());return map;};userSmarts.map.ui.LayerControlView=function(desc){if(isPrototype(arguments)){return;}
userSmarts.ui.ViewPart.call(this,desc);};userSmarts.map.ui.LayerControlView.inheritsFrom(userSmarts.ui.ViewPart);userSmarts.map.ui.LayerControlView.prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};userSmarts.map.ui.LayerControlView.prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var slmgr=bars.getStatusLineManager();var tbmgr=bars.getToolbarManager();tbmgr.add(new userSmarts.wt.action.Action({id:'refreshAction',text:'Refresh',toolTipText:'Refresh the map',run:bind(function(){this.layerControl.context.touch();},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/refresh.png')}));tbmgr.add(new userSmarts.wt.action.StatefulAction({id:'autoRefreshAction',text:'Auto Ref',toolTipText:'Automatically Refresh Map',checked:true,run:bind(function(){this.layerControl.toggleAutoRefresh();},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/refresh.png')}));tbmgr.add(new userSmarts.wt.action.Action({id:'topAction',text:'Shift Top',toolTipText:'Shift selected layer to top',run:bind(function(){this.layerControl.moveLayer(-1,true);},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/layer_top.png')}));tbmgr.add(new userSmarts.wt.action.Action({id:'botAction',text:'Shift Bot',toolTipText:'Shift selected layer to bottom',run:bind(function(){this.layerControl.moveLayer(1,true);},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/layer_bottom.png')}));tbmgr.add(new userSmarts.wt.action.Action({id:'upAction',text:'Shift Up',toolTipText:'Shift selected layer up',run:bind(function(){this.layerControl.moveLayer(-1,false);},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/layer_up.png')}));tbmgr.add(new userSmarts.wt.action.Action({id:'downAction',text:'Shift Down',toolTipText:'Shift selected layer down',run:bind(function(){this.layerControl.moveLayer(1,false);},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/layer_down.png')}));tbmgr.add(new userSmarts.wt.action.Action({id:'editAction',text:'Edit',toolTipText:'Edit selected layer',run:bind(function(){this.layerControl.toggleEditor();},this),image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/actions/layer_edit.png')}));};userSmarts.map.ui.LayerControlView.prototype.createPartControl=function(){if(!this.control){var layerControl=new userSmarts.Map.LayerControl({imagedir:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/map/'),timeout:3000,maxNameSize:-1});layerControl.widget=this;this.layerControl=layerControl;this.contributeToActionBars();this.control=new userSmarts.imat.ui.ResizableControl({adapter:this,node:this.layerControl.getNode()});}
return this.control;};userSmarts.map.ui.LayerControlView.prototype.registerOnMap=function(map){map.register('layer-control',layerControl);};userSmarts.map.ui.LayerControlView.prototype.resize=function(width,height){this.control.node.style.width=width+"px";this.control.node.style.height=height+"px";};userSmarts.map.ui.LegendView=function(desc){if(isPrototype(arguments)){return;}
userSmarts.ui.ViewPart.call(this,desc);};userSmarts.map.ui.LegendView.inheritsFrom(userSmarts.ui.ViewPart);userSmarts.map.ui.LegendView.prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};userSmarts.map.ui.LegendView.prototype.createPartControl=function(){if(!this.layout){var legendControl=new userSmarts.Map.LayerLegend();legendControl.widget=this;this.content=legendControl.paint();layout=DIV({'class':'legend-view'},this.content);this.layout=layout;}
this.control=new userSmarts.map.ui.ResizableControl({adapter:this,node:this.layout});return this.control;};userSmarts.map.ui.LegendView.prototype.resize=function(width,height){this.content.style.width=width+"px";this.content.style.height=height+"px";};userSmarts.map.ui.LegendView.prototype.registerOnMap=function(map){map.register('layer-legend',legendControl);};userSmarts.map.ui.SuggestedLayerControlView=function(desc){if(isPrototype(arguments)){return;}
userSmarts.ui.ViewPart.call(this,desc);};userSmarts.map.ui.SuggestedLayerControlView.inheritsFrom(userSmarts.ui.ViewPart);userSmarts.map.ui.SuggestedLayerControlView.prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};userSmarts.map.ui.SuggestedLayerControlView.prototype.createPartControl=function(){if(!this.layout){var suggestedControl=new userSmarts.map.SuggestedLayerControl();this.suggestedControl=suggestedControl;this.content=suggestedControl.paint();layout=DIV({'class':'suggested-layers-view'},this.content);this.layout=layout;this.contributeToActionBars();}
this.control=new userSmarts.map.ui.ResizableControl({adapter:this,node:this.layout});return this.control;};userSmarts.map.ui.SuggestedLayerControlView.prototype.resize=function(width,height){this.content.style.width=width+"px";this.content.style.height=height+"px";};userSmarts.map.ui.SuggestedLayerControlView.prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var slmgr=bars.getStatusLineManager();var tbmgr=bars.getToolbarManager();var harvestWMSAction=bind(function(){slmgr.setMessage('Harvesting from WMS');this.suggestedControl.performWMSHarvest();},this);var harvestCSWAction=bind(function(){slmgr.setMessage('Harvesting from CSW');this.suggestedControl.performCSWHarvest();},this);var clearAction=bind(function(){this.suggestedControl.clear();},this);var wmsAction=new userSmarts.wt.action.Action({id:'wmsAction',toolTipText:'Harvest from WMS',run:harvestWMSAction,image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/refresh.png')});tbmgr.add(wmsAction);var cswAction=new userSmarts.wt.action.Action({id:'cswAction',toolTipText:'Harvest from CSW',run:harvestCSWAction,image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/up.gif')});tbmgr.add(cswAction);var clrAction=new userSmarts.wt.action.Action({id:'clrAction',toolTipText:'Clear Suggested Layers',run:clearAction,image:userSmarts.runtime.Platform.find('com.usersmarts.rcp.rcp-geo-plugin','images/down.gif')});tbmgr.add(clrAction);};userSmarts.map.ui.SuggestedLayerControlView.prototype.registerOnMap=function(map){map.register("suggested-layers",suggestedControl);};userSmarts.map.ui.ViewContextTableModel=function(properties){if(isPrototype(arguments))return;userSmarts.wt.widgets.TableModel.call(this,properties);this.columns=[new userSmarts.map.ui.LayerTableColumn({label:'Viz',name:'visible','class':'layer-control-checkbox-column',width:25}),new userSmarts.map.ui.LayerTableColumn({label:'Qry',name:'queryable','class':'layer-control-checkbox-column',width:25}),new userSmarts.map.ui.LayerTableColumn({label:'Layer',name:'title','class':'layer-control-text-column'})];connect(this,"context",this,this.onContextChange);this.touch("context");};userSmarts.map.ui.ViewContextTableModel.inheritsFrom(userSmarts.wt.widgets.TableModel);userSmarts.map.ui.ViewContextTableModel.prototype.onContextChange=function(event){var context=event.oldValue;if(context&&this.contextEventListener){disconnect(this.contextEventListener);}
if(this.context instanceof userSmarts.Map.ViewContext){this.contextEventListener=connect(this.context,userSmarts.Map.ViewContext.CHANGE_EVENT_PROPERTY,this,this.populate);}
this.populate(0);};userSmarts.map.ui.ViewContextTableModel.prototype.getLabel=function(column,row){return column.getLabel(row);};userSmarts.map.ui.ViewContextTableModel.prototype.getClassName=function(column,row){return column.getClassName(row);};userSmarts.map.ui.ViewContextTableModel.prototype.getColumnLabel=function(column,row){return column.getColumnLabel();};userSmarts.map.ui.ViewContextTableModel.prototype.getColumnClassName=function(column,row){return"layer-control-column-header";};userSmarts.map.ui.ViewContextTableModel.prototype.populate=function(position){if(position.newValue)position=0;if(position!==undefined&&position!==null){position=position*1;if(position>=0&&position<this.size()){this.currentRow=position;}}
this.buffer=[];if(this.context&&this.context.layers){var layers=this.context.layers;this.matches=layers.length;var layer;for(var i=layers.length-1;i>=0;--i){layer=layers[i];this.buffer.push(layer);}}
this.setProperty("modified",true);};userSmarts.map.ui.LayerTableColumn=function(properties){if(isPrototype(arguments))return;userSmarts.wt.widgets.TableColumn.call(this,properties);};userSmarts.map.ui.LayerTableColumn.inheritsFrom(userSmarts.wt.widgets.TableColumn);userSmarts.map.ui.LayerTableColumn.prototype.getColumnLabel=function(){if(!this.label)this.label="Column";return this.label;};userSmarts.map.ui.LayerTableColumn.prototype.getLabel=function(row){var label="";var result=row[this.name];if(result==="true")result=true;if(result==="false")result=false;if(result===true||result===false){var id=row.getLayerId();label=INPUT({'name':id,'type':'checkbox','title':'Check box to make '+row.getLayerName()+' '+this.name,'value':id});var usingQueryable=(this.name=="queryable");if(usingQueryable){if(!result){label.disabled=true;label.title=row.getLayerName()+' is not queryable';}
label.checked=label.defaultChecked=row.active;}else{label.checked=label.defaultChecked=result;}
connect(label,'onclick',bind(function(layer,property){if(this.checked)layer.setProperty(property,true);else layer.setProperty(property,false);this.defaultChecked=this.checked;},label,row,(usingQueryable?"active":this.name)));}else{label=result;}
return label;};userSmarts.map.ui.LayerTableColumn.prototype.getClassName=function(row){if(!this['class'])this['class']='layer-control-column';return this['class'];};userSmarts.map.ui.PagedViewContextTableModel=function(properties){if(isPrototype(arguments))return;setdefault(properties,{currentRow:0,pageSize:5});userSmarts.map.ui.ViewContextTableModel.call(this,properties);};userSmarts.map.ui.PagedViewContextTableModel.inheritsFrom(userSmarts.map.ui.ViewContextTableModel);userSmarts.map.ui.PagedViewContextTableModel.prototype.size=function(){var result=0;if(this.context){result=this.context.layers.length;}
return result;};userSmarts.map.ui.PagedViewContextTableModel.prototype.populate=function(position){if(position.newValue)position=0;if(position!==undefined&&position!==null){position=position*1;if(position>=0&&position<this.size()){this.currentRow=position;}}
this.buffer=[];if(this.context){var layers=this.context.layers;this.matches=layers.length;var start=this.matches-1-this.currentRow;var end=Math.max(0,start-this.pageSize+1);var layer;for(var i=start;i>=end;--i){layer=layers[i];this.buffer.push(layer);}}
this.setProperty("modified",true);};$namespace.LayerEditorComposite=Class.create(userSmarts.wt.widgets.Composite);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.listeners=[];};userSmarts.map.ui.LayerEditorComposite.prototype.update=function(){replaceChildNodes(this.node,[]);if(this.listeners){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);this.listeners[i]=null;}}
this.listeners=[];if(!this.layerProvider)return;var layer=this.layerProvider.layer;if(!layer){this.node.appendChild(SPAN({},"No Layer Selected"));return;}
var heading=DIV({'class':'layer-editor-property'},B({},"Layer: "),layer.getLayerName());heading.style.width=Math.max((this.size.width-4),25)+"px";this.node.appendChild(heading);heading=DIV({'class':'layer-editor-property'},B({},"Server: "),layer.server.getName());heading.style.width=Math.max((this.size.width-4),25)+"px";this.node.appendChild(heading);var properties=layer.getProperties();if(properties&&properties.length){for(var i=0;i<properties.length;i++){this.createControl(properties[i]);}}
if(layer.metadataURL){var metadataURL=layer.metadataURL;heading=DIV({'class':'layer-editor-property'},B({},"View Metadata: "));heading.style.width=Math.max((this.size.width-4),25)+"px";heading.style.overflow="auto";this.node.appendChild(heading);briefMDLink=SPAN({'class':'layer-editor-toggle'},'[brief]');var listener=connect(briefMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=brief","BriefMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});this.listeners.push(listener);heading.appendChild(briefMDLink);summMDLink=SPAN({'class':'layer-editor-toggle'},'[summary]');listener=connect(summMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=summary","SummaryMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});this.listeners.push(listener);heading.appendChild(summMDLink);fullMDLink=SPAN({'class':'layer-editor-toggle'},'[full]');listener=connect(fullMDLink,'onclick',function(e){window.open(metadataURL+"&ELEMENTSETNAME=full","FullMetadataView","width=800,height=600,resizable=yes,scrollbars=yes");});this.listeners.push(listener);heading.appendChild(fullMDLink);this.node.appendChild(heading);}};userSmarts.map.ui.LayerEditorComposite.prototype.createControl=function(property){var dt=property.datatype;var pLabel=property.label;var ctrl;if(dt.isRange&&dt.isRange===true){ctrl=this.createSliderWidget(property);}else if(dt.isList&&dt.isList===true){ctrl=createSelectWidget(property);}else{ctrl=createTextBox(property);}
var label=DIV({'class':'layer-editor-property'},B({},pLabel+": "),ctrl.paint());label.style.width=Math.max((this.size.width-4),25)+"px";this.node.appendChild(label);};userSmarts.map.ui.LayerEditorComposite.prototype.createSliderWidget=function(property){var dt=property.datatype;var min=(typeof(dt.facets.minInclusive)=='number')?dt.facets.minInclusive:(typeof(dt.facets.minExclusive)=='number')?dt.facets.minExclusive:0;var max=(typeof(dt.facets.maxInclusive)=='number')?dt.facets.maxInclusive:(typeof(dt.facets.maxExclusive)=='number')?dt.facets.maxExclusive:0;var widget=new userSmarts.wt.widgets.SliderWidget({min:min,max:max,increment:dt.facets.increment,value:property.getValue(),width:Math.max((this.size.width-80),15)});var listener=connect(widget,'onchange',function(){property.setValue(dt.format.parseObject(widget.selected));});this.listeners.push(listener);return widget;};userSmarts.map.ui.LayerEditorComposite.prototype.dispose=function(){userSmarts.wt.widgets.Composite.prototype.dispose.call(this);if(this.listeners){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);this.listeners[i]=null;}
this.listeners=null;}
if(this.node){replaceChildNodes(this.node,[]);this.node=null;}};namespace("userSmarts.geo");$namespace.GeoOpenSearchTableModel=function(properties){if(isPrototype(arguments))return;properties=setdefault(properties,{bbox:null});userSmarts.wt.widgets.OpenSearchTableModel.call(this,properties);};$namespace.GeoOpenSearchTableModel.inheritsFrom(userSmarts.wt.widgets.OpenSearchTableModel);$prototype.populate=function(position){if(this.resource){this.resource.params.bbox="";if(this.aoi){var points=this.aoi.getPoints();this.resource.params.bbox=points[0].x+","+points[0].y+","+points[1].x+","+points[1].y;}}
userSmarts.wt.widgets.OpenSearchTableModel.prototype.populate.call(this,position);};$prototype.parseRows=function(root){var buffer=userSmarts.wt.widgets.OpenSearchTableModel.prototype.parseRows.call(this,root);this.setProperty("bbox",this.getFeedBoundingBox(root));return buffer;};$prototype.getFeedBoundingBox=function(root){var bbox=null;var boxNodes=root.getElementsByTagName("box");if(boxNodes.length>1){var boxNode=boxNodes[0];if(boxNode){var boxStr=scrapeText(boxNode);if(boxStr){var coords=boxStr.split(" ");if(coords.length==4){bbox=new Geometry("Box");bbox.addPoint(new Point(coords[0],coords[1]));bbox.addPoint(new Point(coords[2],coords[3]));}}}}
return bbox;};$prototype.getBoundingBox=function(){return this.bbox;};$prototype.setAOI=function(aoi){if(aoi instanceof Geometry){if(aoi.getPoints().length>2){aoi=aoi.getEnvelope();}
this.aoi=aoi;this.populate(0);}};$namespace.GeorssEntry=Class.create(userSmarts.pub.Entry);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{extensionElements:[]});superClass.call(this,properties);};$namespace.GeorssEntry.NAMESPACE_URI="http://www.georss.org/georss";$prototype.getBox=function(){if(!this.box){if(this.node){var boxStr=this.getValue("boxStr","box",null);if(boxStr){var coords=boxStr.split(" ");if(coords.length==4){this.box=new Geometry("Box");this.box.addPoint(new Point(coords[0]*1.0,coords[1]*1.0));this.box.addPoint(new Point(coords[2]*1.0,coords[3]*1.0));}}}
if(!this.box){var where=this.getWhere();if(where){this.box=where.getEnvelope();}}}
return this.box;};$prototype.setBox=function(box){if(box instanceof Geometry){this.box=box;}}
$prototype.getWhere=function(){if(!this.where&&this.node){var whereStr=this.getValue("coordinates","coordinates",null);if(whereStr){var coords=whereStr.split(" ");this.where=new Geometry((coords.length>1)?"Polygon":"Point");for(var i=0;i<coords.length;++i){var xy=coords.split(",");this.where.addPoint(new Point(xy[0]*1.0,xy[1]*1.0));}}}
return this.where;};$prototype.checkExtension=function(ns,tagName){if(ns==userSmarts.geo.GeorssEntry.NAMESPACE_URI&&tagName=="box"){this.setBox(value);return false;}else{return userSmarts.pub.Entry.prototype.checkExtension.call(this,ns,tagName);}};$prototype.toXml=function(doc){var ns=userSmarts.geo.GeorssEntry.NAMESPACE_URI;var entry=userSmarts.pub.Entry.prototype.toXml.call(this,doc);if(entry){var box=this.getBox();if(box){var points=box.getPoints();var pointStr=points[0].x+" "+points[0].y+" "+points[1].x+" "+points[1].y;this.appendElementWithText(entry,ns,"box",pointStr);}}
return entry;};namespace("userSmarts.Map.grid");userSmarts.Map.grid.GriddedServer=function(properties){if(isPrototype(arguments)){return;}
userSmarts.Map.Server.call(this,properties);this.numTiles=16;};userSmarts.Map.grid.GriddedServer.inheritsFrom(userSmarts.Map.Server);userSmarts.Map.grid.GriddedServer.prototype.clone=function(){return new userSmarts.Map.grid.GriddedServer({url:this.url,title:this.title,service:this.service,version:this.version});};userSmarts.Map.grid.GriddedServer.prototype.render=function(pkg,context){var result={deferred:new Deferred(),image:null};try{var opacity=pkg.getDefaultPropertyValue('opacity')||1.0;var tileWidth=context.width/Math.sqrt(this.numTiles);var tileHeight=context.height/Math.sqrt(this.numTiles);result.numTiles=this.numTiles;result.image=DIV();var dim=Math.sqrt(this.numTiles);var row;var col;var imgTop;var imgLeft;var img;var res;var urls=new Array(this.numTiles);for(var i=0;i<this.numTiles;i++){urls[i]=this.getURL(pkg,context,i);if(userSmarts.Map.DEBUG_FLAG){log("[ Tile Request #"+(i+1)+" out of "+this.numTiles+"]");var parts=urls[i].split("?");log("Server: "+parts[0]);log("Params: "+parts[1]);log("[ End Request ]");}
res=loadImage({url:urls[i],width:tileWidth,height:tileHeight,opacity:opacity});img=res.image;img.style.position="absolute";col=i%dim;imgLeft=col*tileWidth;img.style.left=imgLeft+"px";row=Math.floor(i/dim);imgTop=(Math.floor(this.numTiles/dim)-row-1)*tileHeight;img.style.top=imgTop+"px";img.style.width=tileWidth+"px";img.style.height=tileHeight+"px";img.style.visibility="visible";result.image.appendChild(img);result.numTiles--;if(result.numTiles==0){result.deferred.callback(result.image);}}}catch(e){result={deferred:new Deferred(),image:null};result.deferred.errback(e);}
return result;};userSmarts.Map.grid.GriddedServer.prototype.getURL=function(pkg,context,tile){var width=context.width;var height=context.height;var bbox=context.boundingBox;var srs=bbox.srs;var host=this.url;if(host.indexOf('?')<0){host+='?';}else if(host.indexOf('?')!=(host.length-1)){host+='&';}
var format='image/png';var bboxMin={x:bbox.minX,y:bbox.minY};var bboxMax={x:bbox.maxX,y:bbox.maxY};var dim=Math.sqrt(this.numTiles);var row=Math.floor(tile/dim);var col=tile%dim;var minLon;if(col==0){minLon=bboxMin.x;}else{minLon=(((bboxMax.x-bboxMin.x)/dim)*col)+bboxMin.x;}
var minLat;if(row==0){minLat=bboxMin.y;}else{minLat=(((bboxMax.y-bboxMin.y)/dim)*row)+bboxMin.y;}
var maxLon;if(col==dim){maxLon=bboxMax.x;}else{maxLon=(((bboxMax.x-bboxMin.x)/dim)*(col+1))+bboxMin.x;}
var maxLat;if(row==dim){maxLat=bboxMax.y;}else{maxLat=(((bboxMax.y-bboxMin.y)/dim)*(row+1))+bboxMin.y;}
width=Math.floor(width/dim);height=Math.floor(height/dim);var url=host+"REQUEST=GetMap&SERVICE="+this.service+"&VERSION="+this.version;url+="&BBOX="+minLon+","+minLat+","+maxLon+","+maxLat+"&WIDTH="+width+"&HEIGHT="+height;url+="&SRS="+srs+"&Transparent=TRUE"+"&FORMAT="+format+"&STYLES=";var layerIds=this.determineLayerIds(pkg);url+="&layers="+layerIds;url+="&tileIndex="+tile;return url;};userSmarts.Map.grid.GriddedServer.prototype.loadLegendImages=function(pkg){};userSmarts.runtime.Platform.registerPluginJSON({"id":"com.usersmarts.rcp.rcp-geo-plugin","prerequisites":["com.usersmarts.rcp.rcp-wt-plugin","com.usersmarts.rcp.rcp-ui-plugin"],"pluginClass":"","providerName":"","extensionPoints":{},"name":"Geo Plugin","installURL":"${installURL}","label":"Geo Plugin","version":"0.1"});
