/*
 * 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.annotations.views");namespace("userSmarts.annotations.views");namespace("userSmarts.annotations.views");$namespace.AnnotationsView=Class.create(userSmarts.ui.views.ListView);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);this.newAnnotationAction=new userSmarts.annotations.actions.NewAnnotationAction();var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("editor","initialized",this,this.onEditorChange);var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();connect(page,"activeEditor",this,this.onEditorChange);this.onEditorChange({newValue:page.getActiveEditor()});this.defaultModel=new userSmarts.annotations.models.EmptyTableModel();};$prototype.contributeToActionBars=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();if(userSmarts.sx.Plugin!=undefined){if(userSmarts.sx.Plugin.isUserInRole("CREATE_ANNOTATION")){tbmgr.add(this.newAnnotationAction);mbmgr.add(this.newAnnotationAction);}
if(userSmarts.sx.Plugin.isUserInRole("EDIT_ANNOTATION")){var action=new userSmarts.annotations.actions.EditAnnotationAction();tbmgr.add(action);mbmgr.add(action);}
if(userSmarts.sx.Plugin.isUserInRole("DELETE_ANNOTATION")){var action=new userSmarts.annotations.actions.DeleteAnnotationAction();tbmgr.add(action);mbmgr.add(action);}}
mbmgr.add(new userSmarts.annotations.actions.HelpAction());mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());userSmarts.ui.views.ListView.prototype.contributeToActionBars.call(this);};$prototype.displayQueryMessage=function(){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage("Please wait...");};$prototype.displayFinishedMessage=function(success){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage(success?"":"Error retrieving annotations");};$prototype.onSelectionChange=function(event){var id=null;var url=null;var title=null;var selection=event.newValue;if(selection){id=selection.getId();url=selection.getLink();title=selection.getTitle();}
var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("annotations","selected",{id:id,url:url,label:title});};$prototype.onEditorChange=function(event){var editor=event.newValue;if(editor&&typeof(editor.getAnnotationModel)=="function"){var def=editor.getAnnotationModel();def.addCallback(bind(this.setAnnotationModel,this));def.addErrback(bind(this.setAnnotationModel,this,null));}else{this.setAnnotationModel(null);}};$prototype.setAnnotationModel=function(model){if(model&&model!=this.list.model){this.newAnnotationAction.setChecked(false);this.newAnnotationAction.setEnabled(true);this.newAnnotationAction.setModel(model);this.list.setProperty("model",model);}else if(!model){this.newAnnotationAction.setChecked(false);this.newAnnotationAction.setEnabled(false);this.newAnnotationAction.setModel(this.defaultModel);if(this.list.model!=this.defaultModel){this.list.setProperty("model",this.defaultModel);}}};namespace("userSmarts.annotations.models");namespace("userSmarts.annotations.models");namespace("userSmarts.annotations.models");$namespace.AnnotationsModel=Class.create(userSmarts.pub.atom.FeedModel);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{pageSize:50});superClass.call(this,properties);this.addColumn(new userSmarts.pub.atom.EntryColumn({label:"Title",name:"title",order:true}));this.addColumn(new userSmarts.pub.atom.EntryColumn({label:"Summary",name:"summary",order:true}));var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("annotations","*",this,this.onAnnotationsChange);if(this.adapter){this.setSource(new userSmarts.pub.atom.GeoCollection({url:"pub/"+this.adapter.getCollectionId()+"/annotations.atom",factory:new userSmarts.pub.atom.DefaultEntryFactory({entryClass:"userSmarts.annotations.pub.Annotation"})}));}};$prototype.getImage=function(){userSmarts.runtime.Platform.getTheme().getImage("image.annotation");};$prototype.getAdapter=function(){return this.adapter;};$prototype.onAnnotationsChange=function(event){var property=event.propertyName;if(property=="created"||property=="deleted"||property=="updated"){this.populate(this.getOffset());}};$prototype.onLoaded=function(coll){var layer=this.getLayer();layer.setProperty("annotationsChanged",true);userSmarts.pub.atom.FeedModel.prototype.onLoaded.call(this,coll);};$prototype.getLayer=function(){if(!this.layer){var server=new userSmarts.maps.context.Server({baseURL:"pub/wms?",title:"Annotation Server",modcount:0,url:"pub/wms?modcount=0&collectionId="+this.adapter.getCollectionId()});var styles=[];styles['current']=-1;this.layer=new userSmarts.maps.context.Layer({server:server,name:"annotations",title:'Annotations',srs:'EPSG:4326',visible:true,queryable:false,transience:true,opacity:0.6,styles:styles,refreshProperties:{'annotationsChanged':true}});if(this.adapter){var context=this.adapter.getViewContext();context.addLayer(this.layer);}}else{var url=this.layer.server.url;var start=url.indexOf("modcount")+9;var end=start+(this.layer.server.modcount+"").length;url=url.substring(0,start)+(++this.layer.server.modcount)+url.substring(end,url.length);this.layer.server.url=url;}
return this.layer;};namespace("userSmarts.annotations.models");$namespace.EmptyTableModel=Class.create(userSmarts.wt.widgets.TableModel);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.columns=[];};$prototype.getAdapter=function(){return this;};$prototype.getCollectionId=function(){return null;};$prototype.getViewContext=function(){return null;};$prototype.getMap=function(){return null;};$prototype.size=function(){return 0;};$prototype.populate=function(){this.buffer=[];this.setProperty("modified",true);};namespace("userSmarts.annotations.actions");namespace("userSmarts.annotations.actions");namespace("userSmarts.annotations.actions");$namespace.NewAnnotationAction=Class.create(userSmarts.wt.action.StatefulAction);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:"newAnnAction",text:"New",toolTipText:"Create New Annotation",image:"image.annotation.new"});superClass.call(this,properties);var wb=userSmarts.ui.PlatformUI.getWorkbench();var page=wb.getActiveWorkbenchWindow().getActivePage();connect(page,"activeEditor",this,this.onEditorChange);this.dialogCallback=bind(this.onDialogClosed,this);this.createdCallback=bind(this.onAnnotationCreated,this);this.errback=handleResponseError;};$prototype.run=function(){if(this.isChecked()){if(this.model){this.collectionId=this.model.getAdapter().getCollectionId();var map=this.model.getAdapter().getMap();if(map){var tbm=map.locate("toolbar-model");if(tbm){var tool=tbm.getTool("annotation");if(tool){tool.enable();this.tool=tool;this.toolListener=connect(this.tool,"created",this,this.onAnnotationDrawn);}}
return;}}}
if(this.editorListener){disconnect(this.editorListener);}
if(this.tool){this.tool.disable();}
if(this.toolListener){disconnect(this.toolListener);this.toolListener=null;}};$prototype.onAnnotationDrawn=function(event){var geometry=event.newValue;var annotation=new userSmarts.annotations.pub.Annotation();annotation.setTitle("New Annotation");annotation.setSummary("");annotation.setColor(userSmarts.util.Colors.RED);annotation.setCollectionId(this.collectionId);annotation.setBufferSize("5280.0");annotation.setWhere(geometry);var dialog=new userSmarts.annotations.dialogs.EditAnnotationDialog({annotation:annotation});var def=dialog.open();def.addCallback(this.dialogCallback);};$prototype.onDialogClosed=function(annotation){if(annotation){var url="pub/"+this.collectionId+"/annotations.atom";var collection=new userSmarts.pub.atom.Collection();collection.setURL(url);var def=collection.add(annotation);def.addCallback(this.createdCallback);def.addErrback(this.errback);}};$prototype.onAnnotationCreated=function(annotation){var id=annotation.getId();annotation.getCollection().dispose();var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("annotations","created",id);};$prototype.onEditorChange=function(event){if(this.isChecked()){if(this.tool){this.tool.reset();this.tool=null;}}
if(this.toolListener){disconnect(this.toolListener);this.toolListener=null;}};$prototype.setModel=function(model){this.model=model;};namespace("userSmarts.annotations.actions");$namespace.EditAnnotationAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:"userSmarts.annotations.actions.editannotation",text:"Edit",toolTipText:"Edit Selected Annotation",image:"image.annotation.edit"});superClass.call(this,properties);this.dialogCallback=bind(this.onDialogClosed,this);this.updatedCallback=bind(this.onAnnotationUpdated,this);this.callback=bind(this.onAnnotationRetrieved,this);this.errback=bind(function(arg){handleResponseError(arg);var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("annotations","deleted",null);},this)};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("annotations","selected");if(selection&&selection.url){var annotation=new userSmarts.annotations.pub.Annotation();annotation.setURL(selection.url);var def=annotation.get();def.addCallback(this.callback);def.addErrback(this.errback);}else{alert("Please select an annotation first!");}};$prototype.onAnnotationRetrieved=function(annotation){var dialog=new userSmarts.annotations.dialogs.EditAnnotationDialog({annotation:annotation});var def=dialog.open();def.addCallback(this.dialogCallback);};$prototype.onDialogClosed=function(annotation){if(annotation){var def=annotation.put();def.addCallback(this.updatedCallback);def.addErrback(this.errback);}};$prototype.onAnnotationUpdated=function(annotation){var id=annotation.getId();annotation.dispose();var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("annotations","updated",id);};namespace("userSmarts.annotations.actions");$namespace.DeleteAnnotationAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:"userSmarts.annotations.actions.deleteannotation",text:"Delete",toolTipText:"Delete Selected Annotation",image:"image.annotation.delete"});superClass.call(this,properties);this.callback=bind(this.onAnnotationDeleted,this);this.errback=handleResponseError;};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("annotations","selected");if(selection&&selection.url){var label=selection.label||selection.id;if(userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Item","Are you sure you want to delete '"+label+"'?")){var annotation=new userSmarts.annotations.pub.Annotation();annotation.setURL(selection.url);var def=annotation.del();def.addCallback(this.callback);def.addErrback(this.errback);}}else{alert("Please select an annotation first!");}};$prototype.onAnnotationDeleted=function(){var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("annotations","deleted",null);ps.setProperty("annotations","selected",null);};namespace("userSmarts.annotations.actions");$namespace.HelpAction=Class.create(userSmarts.wt.action.StatefulAction);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:"annHelpAction",text:"Help",toolTipText:"Annotation Help",image:"image.help"});superClass.call(this,properties);this.run=this.runMethod;this.dialog=new userSmarts.annotations.dialogs.HelpDialog();this.dialogCloseCallback=bind(this.onDialogClose,this);};$prototype.runMethod=function(){if(this.isChecked()){var def=this.dialog.open();def.addCallback(this.dialogCloseCallback);}else{this.dialog.close();}};$prototype.onDialogClose=function(okPressed){this.setChecked(false);};namespace("userSmarts.annotations.dialogs");namespace("userSmarts.annotations.dialogs");namespace("userSmarts.annotations.dialogs");$namespace.EditAnnotationDialog=Class.create(userSmarts.wt.dialogs.CDialog);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{modal:false,title:"Annotation Details",description:"Specify Annotation Details",width:300,height:300,image:"image.annotation",enableDrag:true,enableResize:true,showClose:true});superClass.call(this,properties);};$prototype.createDialogArea=function(composite){var annotation=this.annotation;if(!annotation){alert("No Annotation provided for dialog to populate");this.cancelPressed();return;}
composite.setLayout(new userSmarts.wt.layout.RowLayout({type:"vertical"}));new userSmarts.wt.forms.Text({parent:composite,value:this.description,layoutData:{width:"100%",height:30},margin:{top:5,left:0,right:0,bottom:2}});if(!annotation.getTitle()){this.getOKButton().disabled=true;}
this.titleField=new userSmarts.wt.forms.FieldComposite({parent:composite,layoutData:{width:"100%",height:30},showLabel:true,title:"Title",labelWidth:80,binding:new BeanPropertyBinding(annotation,"title"),validator:this,validationFunc:"validate"});new userSmarts.wt.forms.TextAreaComposite({parent:composite,layoutData:{width:"100%",height:100},showLabelOnTop:true,title:"Description",labelWidth:80,binding:new BeanPropertyBinding(annotation,"summary")});var selectedOption=-1;var color=annotation.getColor();var colorType=this.getColorOptions();var colors=colorType.facets.enumeration;for(var i=0;i<colors.length;++i){if(colors[i].value.equals(color)){colors[i].selected=true;selectedOption=i;}else{colors[i].selected=false;}}
if(selectedOption<0){colorType.facets.enumeration[0].selected=true;annotation.setColor(colorType.facets.enumeration[0].value);}
new userSmarts.wt.forms.SelectComposite({parent:composite,layoutData:{width:"100%",height:30},showLabel:true,title:"Color",labelWidth:80,binding:new BeanPropertyBinding(annotation,"color"),datatype:colorType});annotation.setBuffered(true);selectedOption=-1;var buffer=annotation.getBufferSize()+"";var sizeType=this.getSizeOptions();var sizes=sizeType.facets.enumeration;for(var i=0;i<sizes.length;++i){if(sizes[i].value==buffer){sizes[i].selected=true;selectedOption=i;}else{sizes[i].selected=false;}}
if(selectedOption<0){sizeType.facets.enumeration[1].selected=true;annotation.setBufferSize(sizeType.facets.enumeration[1].value);}
new userSmarts.wt.forms.SelectComposite({parent:composite,layoutData:{width:"100%",height:30},showLabel:true,title:"Buffer Size",labelWidth:80,binding:new BeanPropertyBinding(annotation,"bufferSize"),datatype:sizeType});};$prototype.focus=function(){this.titleField.focus();};$prototype.onBufferChange=function(event){var cb=event.src();this.annotation.setBuffered(cb.checked);};$prototype.validate=function(){var okButton=this.getOKButton();if(!this.titleField.getValue()){okButton.disabled=true;}else{okButton.disabled=false;}};$prototype.okPressed=function(){if(this.deferred){this.deferred.callback(this.annotation);this.deferred=null;}};$prototype.getColorOptions=function(){return{uri:{namespaceURI:"http://www.usersmarts.com/sx/annotations/color",prefix:"annColor",localPart:"colors"},facets:{enumeration:[{label:"Red",value:userSmarts.util.Colors.RED,selected:true},{label:"Green",value:userSmarts.util.Colors.GREEN},{label:"Blue",value:userSmarts.util.Colors.BLUE},{label:"Yellow",value:userSmarts.util.Colors.YELLOW},{label:"Cyan",value:userSmarts.util.Colors.CYAN},{label:"Magenta",value:userSmarts.util.Colors.MAGENTA},{label:"White",value:userSmarts.util.Colors.WHITE}]}};};$prototype.getSizeOptions=function(){return{uri:{namespaceURI:"http://www.usersmarts.com/sx/annotations/buffer",prefix:"annBuffer",localPart:"size"},facets:{enumeration:[{label:"2 miles",value:"10560.0"},{label:"1 mile",value:"5280.0",selected:true},{label:"1/2 mile",value:"2640.0"},{label:"1/4 mile",value:"1320.0"},{label:"1/8 mile",value:"660.0"},{label:"1/16 mile",value:"330.0"},{label:"160 ft",value:"160.0"},{label:"100 ft",value:"100.0"},{label:"50 ft",value:"50.0"}]}};};namespace("userSmarts.annotations.dialogs");$namespace.HelpDialog=Class.create(userSmarts.wt.dialogs.Dialog);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{modal:false,title:"Annotation Help",description:"How to use annotations",width:400,height:400});superClass.call(this,properties);};$prototype.createDialogArea=function(parent){parent.appendChild(DIV({},this.description));parent.appendChild(P({},"Annotations only appear in list below "+"when a report containing annotations is "+"being viewed in an editor.  To show annotations "+"either open a report with annotations using "+"the Reports tab's View Report button or select "+"an already opened report's tab at the top of "+"the editor area to the left."));parent.appendChild(B({},"Creating annotations"));parent.appendChild(P({},"Select the Annotation Tool from the toolbar.  "+"Once the tool is active (icon is depressed), "+"begin placing points on the map in the opened "+"report to the left. When you are done, deselect "+"the tool's button and enter metadata about the "+"annotation in the new window that appears.  "+"Click 'OK' to save the annotation or 'Cancel' to "+"discard.  You must have permissions to create "+"annotations to see the Annotation tool button."));parent.appendChild(B({},"Editing annotations"));parent.appendChild(P({},"Select an annotation from the list below and "+"click the Edit Annotation icon in the toolbar.  "+"Modify the annotation's information and click "+"'OK' to save the changes or 'Cancel' to discard.  "+"You must have permission to edit annotations to "+"see the Edit Annotation button."));parent.appendChild(B({},"Deleting annotations"));parent.appendChild(P({},"Select an annotation from the list below and "+"click the Delete Annotation icon in the toolbar.  "+"At the prompt, click 'OK' to remove the annotation "+"or 'Cancel' to leave the annotation.  You must "+"have permissions to delete annotations to see "+"the Delete Annotation button."));replaceChildNodes(this.getButtonBar(),this.getOKButton());};namespace("userSmarts.annotations.pub");namespace("userSmarts.annotations.pub");namespace("userSmarts.annotations.pub");$namespace.Annotation=Class.create(userSmarts.pub.atom.GeoEntry);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);};$prototype.getColor=function(){var tnNode=this.getExtension("color");if(tnNode&&tnNode.value){return userSmarts.util.Color.valueOf(tnNode.value);}
return null;};$prototype.setColor=function(carr){var color=userSmarts.util.Color.valueOf(carr);this.setExtension("color",color.toString(),null);};$prototype.isBuffered=function(){return true;};$prototype.setBuffered=function(buffered){this.buffered=(buffered==true);};$prototype.getBufferSize=function(){var tnNode=this.getExtension("buffer");if(tnNode&&tnNode.value){return tnNode.value;}
return null;};$prototype.setBufferSize=function(size){this.setExtension("buffer",size,null);};$prototype.getCollectionId=function(){var tnNode=this.getExtension("collectionId");if(tnNode&&tnNode.value){return tnNode.value;}
return null;};$prototype.setCollectionId=function(id){this.setExtension("collectionId",id,null);};$prototype.toXml=function(doc){var entry=userSmarts.pub.atom.Entry2.prototype.toXml.call(this,doc);if(entry){var geometry=this.getWhere();if(geometry){var whereStr="";var points=geometry.getPoints();for(var i=0;i<points.length;++i){whereStr+=((i>0)?" ":"")+points[i].x+","+points[i].y;}
this.appendElement(entry,this.getWhereType().toLowerCase(),whereStr,"http://www.georss.org/georss");}}
return entry;};namespace("userSmarts.maps.context");namespace("userSmarts.maps.context");namespace("userSmarts.maps.context");$namespace.BoundingBox=Class.create();$prototype.initialize=function(superClass,srs){superClass.call(this,{});this.srs=srs;this.projection=userSmarts.geo.proj.ProjectionFactory.instance(srs);this.bounds=this.projection.bounds;this.boundsCheck=this.projection.boundsCheck;};$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;}};$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;}};$prototype.scaledPan=function(px,py){this.ensureNumberValues();this.pan((this.maxX-this.minX)*px,(this.maxY-this.minY)*py);};$prototype.ensureNumberValues=function(){this.minX=1*this.minX;this.maxX=1*this.maxX;this.minY=1*this.minY;this.maxY=1*this.maxY;};$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;}};$prototype.getCoordinateX=function(px){this.ensureNumberValues();return this.minX+((this.maxX-this.minX)*px);};$prototype.getCoordinatePx=function(x){this.ensureNumberValues();return(x-this.minX)/(this.maxX-this.minX);};$prototype.getCoordinateY=function(py){this.ensureNumberValues();return this.minY+((this.maxY-this.minY)*py);};$prototype.getCoordinatePy=function(y){this.ensureNumberValues();return(y-this.minY)/(this.maxY-this.minY);};$prototype.getCoordinate=function(px,py){return new Point(this.getCoordinateX(px),this.getCoordinateY(py));};$prototype.getCoordinatePercentage=function(x,y){return new Point(this.getCoordinatePx(x),this.getCoordinatePy(y));};$prototype.getQueryString=function(){return this.minX.toFixed(3)+","+this.minY.toFixed(3)+","+this.maxX.toFixed(3)+","+this.maxY.toFixed(3);};$prototype.clone=function(){var newBox=new userSmarts.maps.context.BoundingBox(this.srs);newBox.minX=this.minX;newBox.maxX=this.maxX;newBox.minY=this.minY;newBox.maxY=this.maxY;return newBox;};$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;};namespace("userSmarts.maps.context");$namespace.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,cacheable:true,refreshMode:"onChange",refreshInterval:4,status:userSmarts.maps.context.Layer.STATUS_NOT_LOADED,refreshProperties:{modified:1},transience:false,isAcetate:false});superClass.call(this,properties);this.dirtyListener=bind(this.markAsDirty,this);this.addChangeListener(this.dirtyListener,'*',bind(this.changeTest,this));if(this.refreshMode=="onInterval"&&typeof(this.refreshInterval)=="number"){this.ping=bind(this.refreshAutomatically,this);setTimeout(this.ping,this.refreshInterval*1000);}};$namespace.Layer.STATUS_LOADING=2;$namespace.Layer.STATUS_LOADED=1;$namespace.Layer.STATUS_NOT_LOADED=0;$namespace.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);if(this.ping){this.refreshAutomatically();}};$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.maps.context.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,cacheable:this.cacheable,refreshMode:this.refreshMode,refreshInterval:this.refreshInterval,status:this.status,transience:this.transience,isAcetate:this.isAcetate,refreshProperties:this.refreshProperties});return l;};$prototype.equals=function(layer){if(!(layer instanceof userSmarts.maps.context.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.setAttribute("cacheable",this.cacheable+"");if(this.refreshMode&&this.refreshInterval){layer.setAttribute("refreshMode",this.refreshMode);layer.setAttribute("refreshInterval",this.refreshInterval+"");}
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;};$prototype.refreshAutomatically=function(){if(this.visible){this.setProperty("modified",true);setTimeout(this.ping,this.refreshInterval*1000);}};$prototype.dispose=function(){this.server.dispose();this.server=this.name=this.title=this.src=null;this.visible=this.queryable=this.active=this.selected=null;this.opacity=this.cacheable=this.refreshMode=this.refreshInterval=null;this.status=this.refreshProperties=this.transience=this.isAcetate=null;this.removeChangeListener(this.dirtyListener);this.dirtyListener=null;if(this.ping){this.ping=null;}};namespace("userSmarts.maps.context");$namespace.Server=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{url:'',title:'unknown server',service:'WMS',version:'1.1.1',format:"image/gif"});superClass.call(this,properties);};$prototype.getName=function(){return this.title;};$prototype.equals=function(server){return(this.url==server.url)&&(this.service==server.service)&&(this.format==server.format);};$prototype.clone=function(){return new userSmarts.maps.context.Server({url:this.url,title:this.title,service:this.service,version:this.version});};$prototype.render=function(pkg,context){var result;try{var url=this.getURL(pkg,context);if(userSmarts.maps.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;};$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;var layers=pkg.getVisibleLayers();for(var i=0;i<layers.length;i++){if(!layers[i].cacheable){url+="&requestId="+Math.random();break;}}
return url;};$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;};$prototype.loadLegendImages=function(pkg){};$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.maps.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;};$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;};$prototype.dispose=function(){this.url=this.title=this.service=this.version=this.format=null;};namespace("userSmarts.maps.context");$namespace.GriddedServer=Class.create($namespace.Server);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.numTiles=16;};$prototype.clone=function(){return new userSmarts.maps.context.GriddedServer({url:this.url,title:this.title,service:this.service,version:this.version});};$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.maps.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;};$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;};$prototype.loadLegendImages=function(pkg){};namespace("userSmarts.maps.context");$namespace.ViewContext=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'',layers:[],width:0,height:0,boundingBox:new userSmarts.maps.context.BoundingBox('EPSG:4326')});superClass.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,"*");}};$namespace.ViewContext.LAYER_CHANGED_EVENT_PROPERTY='layeChanged';$namespace.ViewContext.LAYER_ADDED_EVENT_PROPERTY='layerAdded';$namespace.ViewContext.LAYER_REMOVED_EVENT_PROPERTY='layerRemoved';$namespace.ViewContext.CHANGE_EVENT_PROPERTY='lastModified';$namespace.ViewContext.VIEW_CHANGE_EVENT_PROPERTY="viewChanged";$prototype.touch=function(){if(this.controller){var def=this.controller.onChangeEvent(this);def.addCallback(bind(function(p,v){this.setProperty(p,v);},this,userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,new Date().getTime()));}else{this.setProperty(userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,new Date().getTime());}};$prototype.setController=function(controller){this.controller=controller;};$prototype.pan=function(dx,dy){this.boundingBox.pan(dx,dy);this.setProperty(userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};$prototype.scaledPan=function(dx,dy){this.boundingBox.scaledPan(dx,dy);this.setProperty(userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};$prototype.zoom=function(factor){this.boundingBox.zoom(factor);this.setProperty(userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();};$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;};$prototype.setView=function(geom,correctAspect){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]);if(correctAspect||typeof(correctAspect)=="undefined"){this.correctAspectRatio();}
this.setProperty(userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this.getView());this.touch();}}};$prototype.unproject=function(x,y){return this.boundingBox.projection.unproject(x,y);};$prototype.project=function(x,y){return this.boundingBox.projection.project(x,y);};$prototype.onLayerChange=function(event){var newEvent=new PropertyChangeEvent(event.source,event.propertyName,event.oldValue,event.newValue);this.setProperty(userSmarts.maps.context.ViewContext.LAYER_CHANGED_EVENT_PROPERTY,newEvent);};$prototype.getLayerPosition=function(layer){for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){return i;}}
return-1;};$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();}}};$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();}}};$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();}}}};$prototype.showLayer=function(layer){layer.show();};$prototype.hideLayer=function(layer){layer.hide();};$prototype.activateLayer=function(layer){layer.active=true;};$prototype.deactivateLayer=function(layer){layer.active=false;};$prototype.getSelectedLayer=function(){for(var i=0;i<this.layers.length;i++){if(this.layers[i].selected){return this.layers[i];}}
return null;};$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;};$prototype.getNumberOfVisibleLayers=function(){var count=0;for(var i=0;i<this.layers.length;i++){if(this.layers[i].visible){count++;}}
return count;};$prototype.addLayer=function(layer,position){var added=this.includeLayer(layer,position);if(added){this.touch();}
return added;};$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;};$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.maps.context.ViewContext.LAYER_REMOVED_EVENT_PROPERTY,layer);this.touch();return layer;}}};$prototype.includeLayer=function(layer,position){for(var i=0;i<this.layers.length;i++){if(this.layers[i].equals(layer)){return false;}}
layer.addChangeListener(this.layerListener,'*');if(typeof(position)=="number"&&position>=0&&position<this.layers.length){this.layers.splice(position,0,layer);}else{this.layers.push(layer);}
this.setProperty(userSmarts.maps.context.ViewContext.LAYER_ADDED_EVENT_PROPERTY,layer);return true;};$prototype.getLayers=function(){return this.layers;};$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;};$prototype.clone=function(){var context=new userSmarts.maps.context.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;};$prototype.load=function(context,refresh){this.id=context.id;this.loadLayers(context);this.loadBoundingBox(context);this.correctAspectRatio();if(!!refresh){this.touch();}};$prototype.loadLayers=function(srcCtx){var layer;var i;for(i=this.layers.length;i>=0;i--){layer=this.removeLayer(this.layers[i]);layer=null;}
for(i=0;i<srcCtx.layers.length;i++){this.addLayer(srcCtx.layers[i].clone());}};$prototype.loadBoundingBox=function(srcCtx){this.boundingBox=srcCtx.boundingBox.clone();};$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;}};$prototype.removeListeners=function(){this.pcs.properties.clear();};$prototype.toXml=function(d){var vc;var doc;if(!d||d.nodeType!=9){doc=createXMLDocument('ViewContext','http://www.opengis.net/context',null);vc=doc.documentElement;}else{doc=d;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;};namespace("userSmarts.maps.context");$namespace.LayerParserRegistry={parsers:[]};$namespace.LayerParserRegistry.register=function(service,parser){var reg=userSmarts.maps.context.LayerParserRegistry;service=service.toLowerCase();if(!reg.parsers[service]){reg.parsers[service]=[];}
reg.parsers[service].push(parser);};$namespace.LayerParserRegistry.parse=function(service,element){var reg=userSmarts.maps.context.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;};namespace("userSmarts.maps.context");$namespace.ViewContextParser=Class.create(Bean);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.xmlListener=connect(this,"xml",this,this.onXmlChange);this.urlListener=connect(this,"url",this,this.onURLChange);this.callback=bind(this.onXmlChange,this);};$prototype.onURLChange=function(event){var d=parseXML(event.newValue);d.addCallback(this.callback);d.addErrback(handleResponseError);};$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.maps.context.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.maps.context.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.maps.context.LayerParserRegistry.parse(serviceType,element);};namespace("userSmarts.maps.context");$namespace.LayerParser=Class.create();$prototype.initialize=function(){};$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);}};$prototype.parseLayer=function(element){if(!element)return null;try{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 cacheable=Coerce.toBoolean(getNodeAttribute(element,'cacheable'),true);var refreshMode=Coerce.toString(getNodeAttribute(element,"refreshMode"),"onChange");var refreshInterval=Coerce.toInteger(getNodeAttribute(element,"refreshInterval"),4);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.maps.context.Layer({server:serverObj,opacity:opacity,cacheable:cacheable,refreshMode:refreshMode,refreshInterval:refreshInterval,name:name,title:title,srs:srs,queryable:queryable,visible:visible,metadataURL:metadataURL,styles:styles});}catch(e){logError("Error parsing layer - "+e);return null;}};$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;};$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.maps.context.Server({url:serverURL,title:serverTitle,service:serverService,version:serverVersion});};if(typeof(userSmarts.maps.context.LayerParserRegistry)!='undefined'){userSmarts.maps.context.LayerParserRegistry.register("wms",new userSmarts.maps.context.LayerParser());userSmarts.maps.context.LayerParserRegistry.register("kml",new userSmarts.maps.context.LayerParser());userSmarts.maps.context.LayerParserRegistry.register("shp",new userSmarts.maps.context.LayerParser());userSmarts.maps.context.LayerParserRegistry.register("georss",new userSmarts.maps.context.LayerParser());userSmarts.maps.context.LayerParserRegistry.register("feed",new userSmarts.maps.context.LayerParser());}
namespace("userSmarts.maps.tools");namespace("userSmarts.maps.tools");namespace("userSmarts.maps.tools");$namespace.Tool=Class.create(Bean);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:"",ready:false,enabled:false,disabled:true,debug:false});superClass.call(this,properties);this.init();};$prototype.init=function(){this.enabledListener=connect(this,"enabled",this,this.onEnabledStateChange);this.readyListener=connect(this,"ready",this,this.onReadyStateChange);};$prototype.onReadyStateChange=function(event){if(event.newValue===false){this.disable();}};$prototype.onEnabledStateChange=function(event){};$prototype.enable=function(){if(this.enabled||this.onToolEnable()){this.disabled=false;this.setProperty("enabled",true);}else{logError("Unable to enable "+this.getToolId()+" tool");}};$prototype.disable=function(){if(this.disabled||this.onToolDisable()){this.enabled=false;this.setProperty("disabled",true);}else{logError("Unable to disable "+this.getToolId()+" tool");}};$prototype.onToolEnable=function(){return true;};$prototype.onToolDisable=function(){return true;};$prototype.getToolId=function(){return this.id;};$prototype.getNode=function(){return this.paint();};$prototype.paint=function(){return DIV();};$prototype.update=function(){this.repaint();};$prototype.repaint=function(){};$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;};};$prototype.disableHover=function(icon){if(!icon){if(!this.icon)return;else icon=this.icon;}
icon.onmouseover=null;icon.onmouseout=null;};$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;};$prototype.dispose=function(){disconnect(this.enabledListener);this.enabledListener=null;disconnect(this.readyListener);this.readyListener=null;Bean.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.BookmarkTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'bookmark'});superClass.call(this,props);};$prototype.paint=function(){var newIcon=this.factory.create('bookmarktool','bookmarktool-selected','Bookmark Map',"image.map.tool.bookmark.new");connect(newIcon,'onclick',this,this.activate);this.newIcon=newIcon;var backIcon=this.factory.create('bookmarktool-back','bookmarktool-back-selected','Previous Bookmark',"image.map.tool.bookmark.previous");connect(backIcon,'onclick',this,this.previous);this.backIcon=backIcon;var fwdIcon=this.factory.create('bookmarktool-forward','bookmarktool-forward-selected','Next Bookmark',"image.map.tool.bookmark.next");connect(fwdIcon,'onclick',this,this.next);this.fwdIcon=fwdIcon;return[newIcon,backIcon,fwdIcon];};$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!");}}};$prototype.next=function(){if(this.manager){this.manager.next();}else{logWarning("Map.Tools.Bookmark : No Context Manager defined for maintaining context bookmarks!");}};$prototype.previous=function(){if(this.manager){this.manager.previous();}else{logWarning("Map.Tools.Bookmark : No Context Manager defined for maintaining context bookmarks!");}};$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;};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.DescribeTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'describe'});superClass.call(this,props);this.featureListener=connect(this,userSmarts.maps.tools.DescribeTool.FEATURES,this,'logFeatures');this.connect("error",function(event){getLogger().logError(event.newValue);});};$namespace.DescribeTool.FEATURES='features';$prototype.paint=function(){var icon=this.factory.create('describetool','describetool-selected','Describe Feature',"image.map.tool.describe");connect(icon,'onclick',this,this.toggleReady);this.icon=icon;return this.icon;};$prototype.toggleReady=function(event){this.setProperty("ready",!this.ready);};$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;};$prototype.onToolDisable=function(){if(this.canvasMouseListener){disconnect(this.canvasMouseListener);}
this.icon.className="describetool";this.enableHover(this.icon,'describetool-selected','describetool');return true;};$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);}};$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.maps.tools.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.maps.tools.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);}};$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;};$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;};$prototype.setFeatureHandler=function(listener){if(this.featureListener){this.disconnect(this.featureListener);}
this.featureListener=this.connect(userSmarts.maps.tools.DescribeTool.FEATURES,listener);};$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]);}}};$prototype.dispose=function(){this.disable();disconnectAll(this);this.canvasMouseListener=null;disposeImage(this.icon);this.icon=null;this.adapter=null;userSmarts.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.DragTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'drag',canReset:true,draggable:null,dragHandler:new DragHandler()});superClass.call(this,props);this.sTop=0;this.sLeft=0;};$prototype.paint=function(){var icon=this.factory.create('pantool','pantool-selected','Advanced Panning Tool',"image.map.tool.pan.drag");this.mouseListener=connect(icon,'onclick',this,"toggleReady");this.icon=icon;return this.icon;};$prototype.toggleReady=function(){this.setProperty("ready",!this.ready);};$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.maps.widget.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;};$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);}};$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();}};$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;};$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;};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.GeometryTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'geometry',dragHandler:new DragHandler(),x1:null,y1:null,currentPolygon:null,threshold:20,currentEllipse:null,enableBBOXHandler:true,enablePolygonHandler:true,enableCircleHandler:true});superClass.call(this,props);};$prototype.paint=function(){var icons=[];if(this.enableBBOXHandler){var bboxIcon=this.factory.create('boxtool','boxtool-selected','Bounding Box Selection Tool',"image.map.tool.box");this.bboxMouseListener=connect(bboxIcon,'onclick',this,this.toggleBboxReady);this.bboxIcon=bboxIcon;icons.push(bboxIcon);}
if(this.enablePolygonHandler){var polygonIcon=this.factory.create('polygontool','polygontool-selected','Polygon Selection Tool',"image.map.tool.polygon");this.polyMouseListener=connect(polygonIcon,'onclick',this,this.togglePolygonReady);this.polygonIcon=polygonIcon;icons.push(polygonIcon);}
if(this.enableCircleHandler){var ellipseIcon=this.factory.create('ellipsetool','ellipsetool-selected','Ellipse Selection Tool',"image.map.tool.circle");this.ellipseMouseListener=connect(ellipseIcon,'onclick',this,this.toggleEllipseReady);this.ellipseIcon=ellipseIcon;icons.push(ellipseIcon);}
return icons;};$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;};$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;};$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);};$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;};$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);}};$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);}};$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);}};$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;};$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;};$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)};}};$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";}}};$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.maps.widget.WSOverlay({id:'box_'+Math.random(),className:'geometry-overlay',wsgeometry:geom,ssgeometry:unprojectedGeometry});overlay.setContent(renderedGeometry);overlays.add(overlay);}
this.setProperty("geometry",geom);}};$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;};$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;};$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.maps.widget.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();}}};$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;};$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;};$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;};$prototype.onEllipseDragStart=function(e,dragger){var point=this.capturePoint(e);this.buildEllipse(point);};$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;}};$prototype.onEllipseDragEnd=function(dragger){if(this.endPoint){var point=this.capturePoint({clientX:this.endPoint.x,clientY:this.endPoint.y});this.buildEllipse(point);}};$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.maps.widget.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;};$prototype.createEllipse=function(){this.currentEllipse=new Geometry("Circle");this.currentEllipse.div=DIV();this.div.appendChild(this.currentEllipse.div);return this.currentEllipse;};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.HelpTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'help'});superClass.call(this,properties);};$prototype.paint=function(){var icon=this.factory.create('helptool','helptool-selected','Show Help',"image.map.tool.help");connect(icon,'onclick',this,this.showHelp);this.icon=icon;return this.icon;};$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();}};$prototype.dispose=function(){disposeImage(this.icon);userSmarts.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.MeasureTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'measure',units:'mi',points:[],totalDistance:0});superClass.call(this,props);};$prototype.paint=function(context){var icon=this.factory.create('measuretool','measuretool-selected','Measure Tool',"image.map.tool.measure");connect(icon,'onclick',this,this.toggleReady);this.icon=icon;return this.icon;};$prototype.toggleReady=function(event){this.setProperty("ready",!this.ready);};$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.maps.widget.Canvas.ONLOAD_COMPLETE_EVENT,this,this.disable);return true;};$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;};$prototype.setUnits=function(units){this.units=units;};$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.maps.widget.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);}}}};$prototype.reset=function(){if(this.overlay){this.overlay.setContent(SPAN());this.totalDistance=0;this.points=[];}};$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;};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.PanTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'pan',factor:0.25});superClass.call(this,props);};$prototype.paint=function(){var leftIcon=this.factory.create('panleft','panleft-selected','Pan Left',"image.map.tool.pan.left");connect(leftIcon,'onclick',bind(this.panLeft,this));this.leftIcon=leftIcon;var rightIcon=this.factory.create('panright','panright-selected','Pan Right',"image.map.tool.pan.right");connect(rightIcon,'onclick',bind(this.panRight,this));this.rightIcon=rightIcon;var upIcon=this.factory.create('panup','panup-selected','Pan Up',"image.map.tool.pan.up");connect(upIcon,'onclick',bind(this.panUp,this));this.upIcon=upIcon;var downIcon=this.factory.create('pandown','pandown-selected','Pan Down',"image.map.tool.pan.down");connect(downIcon,'onclick',bind(this.panDown,this));this.downIcon=downIcon;return[leftIcon,rightIcon,upIcon,downIcon];};$prototype.setPanFactor=function(factor){this.factor=factor;};$prototype.panLeft=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(-this.factor,0.0);}};$prototype.panRight=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(this.factor,0.0);}};$prototype.panUp=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(0.0,this.factor);}};$prototype.panDown=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.scaledPan(0.0,-this.factor);}};$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;};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.PresetCircleTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'preset-circle'});superClass.call(this,props);};$prototype.paint=function(){icon=this.factory.create('presetcircletool','presetcircletool-selected','Preset Circle Selection Tool',"image.map.tool.circle.preset");connect(icon,'onclick',this,this.onIconClick);this.icon=icon;return icon;};$prototype.onIconClick=function(evt){this.setProperty("ready",!this.ready);};$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;};$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;};$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;};$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.maps.tools.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");}};$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.maps.widget.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;};$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.maps.tools.Tool.prototype.dispose.call(this);};$namespace.RadiusDialog=Class.create(userSmarts.wt.dialogs.Dialog);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{title:"Specify Radius",modal:false,width:200,height:75,radius:1});superClass.call(this,properties);};$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());};$prototype.getRadius=function(){return this.radius*1;};$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;};$prototype.invalidate=function(){this.radius=1;var okBtn=this.getOKButton();okBtn.disabled=true;};namespace("userSmarts.maps.tools");$namespace.ZoomToBoxTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'zoombox',canReset:true,dragHandler:new DragHandler()});superClass.call(this,props);};$prototype.paint=function(){var icon=this.factory.create('zoomboxtool','zoomboxtool-selected','Zoom to Box',"image.map.tool.zoom.box");this.mouseListener=connect(icon,'onclick',this,"toggleReady");this.icon=icon;return this.icon;};$prototype.toggleReady=function(){this.setProperty("ready",!this.ready);};$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.maps.widget.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;};$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);}};$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);}};$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;}};$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";}}};$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();};$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();}};$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);};$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.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.tools");$namespace.ZoomTool=Class.create($namespace.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'zoom',infactor:0.5,outfactor:2.0});superClass.call(this,props);};$prototype.paint=function(){var inIcon=this.factory.create('zoomintool','zoomintool-selected','Zoom In',"image.map.tool.zoom.in");connect(inIcon,'onclick',this,this.zoomIn);this.inIcon=inIcon;var outIcon=this.factory.create('zoomouttool','zoomouttool-selected','Zoom Out',"image.map.tool.zoom.out");connect(outIcon,'onclick',this,this.zoomOut);this.outIcon=outIcon;return[inIcon,outIcon];};$prototype.setZoomInFactor=function(factor){if((factor>0.0)&&(factor<1.0)){this.infactor=factor;}};$prototype.setZoomOutFactor=function(factor){if(factor>1.0){this.outfactor=factor;}};$prototype.zoomIn=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.zoom(this.infactor);}};$prototype.zoomOut=function(){if(this.adapter){var context=this.adapter.getProperty("context");context.zoom(this.outfactor);}};$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;};$prototype.dispose=function(){disposeImage(this.inIcon);this.inIcon=null;disposeImage(this.outIcon);this.outIcon=null;this.adapter=null;userSmarts.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.annotations");namespace("userSmarts.annotations");namespace("userSmarts.annotations");$namespace.AnnotationTool=Class.create(userSmarts.maps.tools.Tool);$prototype.initialize=function(superClass,properties){var props=setdefault(properties,{id:'annotation',threshold:20,currentAnnotation:null});superClass.call(this,props);};$prototype.paint=function(){return DIV();};$prototype.onToolEnable=function(){if(!this.adapter)return false;var canvas=this.adapter.getProperty("canvas");this.canvasMouseListener=connect(canvas.content,'onmousedown',this,this.capturePoint);if(this.icon){this.icon.className='annotationtool-selected';this.disableHover(this.icon);}
return true;};$prototype.onToolDisable=function(){if(this.canvasMouseListener){disconnect(this.canvasMouseListener);this.canvasMouseListener=null;}
if(this.icon){this.icon.className='annotationtool';this.enableHover(this.icon,'annotationtool-selected','annotationtool');}
this.finalizeAnnotation();this.ready=false;return true;};$prototype.about=function(){var holder=DIV({'class':'map-tool-about'});holder.appendChild(SPAN({'class':'map-tool-title'},"Annotation Tool : "));holder.appendChild(document.createTextNode(""));return holder;};$prototype.capturePoint=function(evt){var e=evt.event();e=fixE(e);if(this.adapter){var canvas=this.adapter.getProperty("canvas");var point=canvas.getPointOnCanvas({x:e.clientX,y:e.clientY});}
this.addPointToCurrentAnnotation(point);};$prototype.addPointToCurrentAnnotation=function(point){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.currentAnnotation){this.currentAnnotation=new Geometry();overlay=new userSmarts.maps.widget.WSOverlay({id:'annotation-'+Math.random(),className:'geometry-overlay',wsgeometry:null,ssgeometry:this.currentAnnotation});this.currentAnnotation.overlay=overlay;overlays.add(overlay);}else{overlay=this.currentAnnotation.overlay;}
this.currentAnnotation.addPoint(point);var rp=renderer.renderPoint({x:point.x-1,y:point.y-1,width:3,height:3});if(rp){overlay.addContent(rp);}
var points=this.currentAnnotation.getPoints();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){overlay.addContent(rp);}}}};$prototype.finalizeAnnotation=function(){if(this.currentAnnotation){var points=this.currentAnnotation.getPoints();if(points.length>2){var lastPoint=points[points.length-1];var firstPoint=points[0];var dx=Math.abs(firstPoint.x-lastPoint.x);var dy=Math.abs(firstPoint.y-lastPoint.y);var dz=dx*dx+dy*dy;if(dz<(this.threshold*this.threshold)){this.currentAnnotation.addPoint(firstPoint);this.currentAnnotation.type="Polygon";}else{this.currentAnnotation.type="Line";}}else if(points.length>1){this.currentAnnotation.type="Line";}else if(points.length>0){this.currentAnnotation.type="Point";}
if(this.adapter){var overlays=this.adapter.getProperty('overlays');overlays.remove(this.currentAnnotation.overlay);delete this.currentAnnotation.overlay;var canvas=this.adapter.getProperty("canvas");var geom=new Geometry(this.currentAnnotation.type);var points=this.currentAnnotation.getPoints();for(var ci=0;ci<points.length;ci++){var p=points[ci];geom.addPoint(canvas.projectPoint(p));}
this.setProperty('created',geom);}
this.currentAnnotation=null;}};$prototype.reset=function(){if(this.currentAnnotation){if(this.currentAnnotation.overlay){if(this.adapter){var overlays=this.adapter.getProperty('overlays');overlays.remove(this.currentAnnotation.overlay);}
this.currentAnnotation.overlay=null;delete this.currentAnnotation.overlay;}
this.currentAnnotation=null;}
this.disable();};$prototype.dispose=function(){this.disable();disconnectAll(this);this.adapter=null;this.currentAnnotation=null;userSmarts.maps.tools.Tool.prototype.dispose.call(this);};namespace("userSmarts.maps.widget");namespace("userSmarts.maps.widget");namespace("userSmarts.maps.widget");$namespace.Canvas=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapCanvas_'+Math.random(),width:500,height:400,timeout:5000,debug:false,recenterEnabled:true});superClass.call(this,properties);connect(this,'context',this,'onContextChange');};$namespace.Canvas.ONLOAD_COMPLETE_EVENT='loadingComplete';$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;};$prototype.repaint=function(context){this.renderLayers();};$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...");}};$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.maps.widget.Canvas.ONLOAD_COMPLETE_EVENT,new Date().getTime());};$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.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,this,'repaint');}
this.repaint();};$onWidgetChange=function(event){this.repaint();};$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);};$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;};$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;};$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;};$prototype.setMouseMoveListener=function(func){if(this.layout){this.layout.onmousemove=func;}else{this.mouseMoveListener=func;}};$prototype.enableRecenter=function(){if(this.layout){this.recenterListener=connect(this.layout,"ondblclick",this,this.recenter);this.recenterEnabled=true;}};$prototype.disableRecenter=function(){if(this.recenterListener){disconnect(this.recenterListener);this.recenterListener=null;}
this.recenterEnabled=false;};$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;}};$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;}}};namespace("userSmarts.maps.widget");$namespace.ComponentAdapter=Class.create(Bean);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);if(this.component.onWidgetChange){this.connect("modified",this.component,this.component.onWidgetChange);this.widget.connect("modified",bind(function(){this.setProperty('modified',true);},this));}
this.applyProperty("adapter",this);};$prototype.applyProperty=function(propertyName,value){if(typeof(this.component.setProperty)=='function'){this.component.setProperty(propertyName,value);}else{this.component[propertyName]=value;}};$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;}};namespace("userSmarts.maps.widget");$namespace.ContextManager=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{contexts:[],current:-1});superClass.call(this,properties);this.overlay=new userSmarts.maps.widget.ContextTab({manager:this});connect(this,'adapter',this,this.onAdapterChange);this.counterId=0;};userSmarts.maps.widget.ContextManager.MAX_CONTEXTS=10;userSmarts.maps.widget.ContextManager.CONTEXT_RESTORED='contextRestored';userSmarts.maps.widget.ContextManager.CONTEXT_SAVED='contextSaved';userSmarts.maps.widget.ContextManager.CONTEXT_REMOVED='contextRemoved';$prototype.onAdapterChange=function(event){var adapter=event.newValue;var overlays=adapter.getProperty("overlays");if(this.overlay){overlays.add(this.overlay);}};$prototype.save=function(context,name){var index=-1;if(this.contexts.length<userSmarts.maps.widget.ContextManager.MAX_CONTEXTS){this.contexts.push({label:name,value:context,selected:false});index=this.contexts.length-1;this.setProperty(userSmarts.maps.widget.ContextManager.CONTEXT_SAVED,context);this.select(index);if(this.overlay){this.overlay.update();}}
return index;};$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.maps.widget.ContextManager.CONTEXT_RESTORED,this.contexts[index].value.clone());}};$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;};$prototype.getContext=function(){return this.contextRestored;};$prototype.getNumberOfSavedContexts=function(){return this.contexts.length;};$prototype.remove=function(index){if(index>=0&&index<this.contexts.length){var context=this.contexts.splice(index,1);this.setProperty(userSmarts.maps.widget.ContextManager.CONTEXT_REMOVED,context.value);}};$prototype.next=function(){var next=0;if(this.current>=0){if(this.current<(this.contexts.length-1)){next=this.current+1;}}
this.restore(next);};$prototype.previous=function(){var prev=this.contexts.length-1;if(this.current>=0){if(this.current>0){prev=this.current-1;}}
this.restore(prev);};$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;}};$namespace.ContextTab=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapContextTab',overlay:new userSmarts.maps.widget.Overlay()});superClass.call(this,properties);if(this.overlays){this.overlays.add(this.overlay);}};$prototype.paint=function(context){return this.overlay.content;};$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;};$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);};$prototype.dispose=function(){replaceChildNodes(this.overlay,null);this.overlay=null;this.overlays=null;this.manager=null;};namespace("userSmarts.maps.widget");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;}};namespace("userSmarts.maps.widget");$namespace.ImageLoader=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{timeout:3000,numImagesToLoad:0,loadedImages:[],images:[],debug:false});superClass.call(this,properties);};$prototype.load=function(urlArray){this.numImagesToLoad=urlArray.length;this.finished=false;var loader=this;this.images.clear();this.loadedImages.clear();var uid=new Date().getTime()+Math.random();this.groupId=uid;if(this.progressBar){this.progressBar.reset();this.progressBar.setWorkTotal(this.numImagesToLoad);}
for(var i=0;i<this.numImagesToLoad;i++){var url=urlArray.shift();var image=this.createImage(url,uid+'_'+(i+1),uid);this.images.push(image);if(this.debug){logDebug('----------------- request [ '+i+' ] -------------------');var urlParts=url.split('request=');var host=urlParts[0];var params=urlParts[1].split('&');params[0]='request='+params[0];logDebug('   '+host);for(var p=0;p<params.length;p++){logDebug('   '+params[p]);}
logDebug('------------- request of url[ '+i+' ] ---------------');}}
setTimeout(function(){if(!loader.finished){loader.progressBar.show();}},500);if(this.timeout&&this.timeout>0){setTimeout(function(){if(loader.numImagesLeftToLoad>0){logWarning('ImageLoader - timeout loading images, returning prematurely');}
loader.finishedLoading(uid);},loader.timeout);}};$prototype.createImage=function(url,id,groupId){var image=IMG();image.style.position='absolute';image.style.top='0px';image.style.left='0px';image.style.visibility='visible';image.onmousedown=function(e){return false;};image.ondrag=function(e){return false;};image.id=id;image.groupId=groupId;var loader=this;image.onload=bind(function(img){loader.onLoad(img);},null,image);image.src=url;return image;};$prototype.onLoad=function(image){if(this.groupId==image.groupId){if(this.loadedImages.contains(image.id)){return;}
this.loadedImages.push(image.id);this.numImagesToLoad--;if(this.progressBar){this.progressBar.worked();}
if(this.numImagesToLoad===0){this.finishedLoading(image.groupId);}}};$prototype.finishedLoading=function(uid){if(this.finished){return;}else if(this.groupId==uid){if(this.progressBar){this.progressBar.hide();}
this.callback(this.images);this.finished=true;}else{logWarning('wrong group id was specified, ignoring this image');}};$prototype.setProgressBar=function(pbar){this.progressBar=pbar;};$prototype.getProgressBar=function(){return this.progressBar;};namespace("userSmarts.maps.widget");$namespace.LayerControl=Class.create(userSmarts.wt.widgets.Control);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'map-layer-window',name:" Layers ",timeout:3000,modcount:0,waitOnRefresh:false,autoRefresh:true,maxNameSize:30});superClass.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.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.getNode=function(){return this.paint();};$prototype.update=function(){return this.repaint();};$prototype.paint=function(){if(!this.layerContent){this.layerContent=this.buildLayers();}
return this.layerContent;};$prototype.repaint=function(){if(this.content){this.clearConnectListeners();var temp=this.createLayerEntries();replaceChildNodes(this.content,temp);}};$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");var theme=userSmarts.runtime.Platform.getTheme();this.shiftUpper=SPAN({'class':'button'},IMG({title:'Shift Selected Layer Up',src:theme.get("image.map.tool.pan.up"),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:theme.get("image.map.tool.pan.down"),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:'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:'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;};$prototype.buildLayers=function(){var theme=userSmarts.runtime.Platform.getTheme();var thead=THEAD({},TR({'class':'table-row'},[TD({'class':'table-column-subheader',width:'20','title':'visible?'},IMG({src:theme.get("image.watch")})),TD({'class':'table-column-subheader',width:'20','title':'query?'},IMG({src:theme.get("image.map.tool.pan.describe")})),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;};$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;};$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.maps.context.Layer.EditorFactory.getEditor(layer);if(editor){row.editor=editor;editCell.appendChild(editor.paint());if(layer.selected&&layer.visibleEditor){this.toggleEditor();}}
return[row,editRow];};$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();}};$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();}}};$prototype.toggleAutoRefresh=function(){this.autoRefresh=!this.autoRefresh;if(this.autoRefresh){if(this.autoRefresher){this.autoRefresher.className='buttondown';}
if(userSmarts.maps.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.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh disabled");}}};$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);}};$prototype.onAdapterChange=function(event){var adapter=event.newValue;var context=adapter.getProperty('context');if(context){this.setProperty('context',context);}};$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.maps.context.ViewContext.LAYER_ADDED_EVENT_PROPERTY,this,this.update);this.layerRemovedListener=connect(context,userSmarts.maps.context.ViewContext.LAYER_REMOVED_EVENT_PROPERTY,this,this.update);this.layerChangedListener=connect(context,userSmarts.maps.context.ViewContext.LAYER_CHANGED_EVENT_PROPERTY,this,this.update);}
this.repaint();};$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);}};$prototype.ready=function(){this.waitOnRefresh=false;};$prototype.touch=function(time){this.update();};$prototype.getSelectedLayer=function(){return this.selected.layer;};$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;};$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);}};$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){}}}};$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;}};namespace("userSmarts.maps.widget");$namespace.LayerControlWidget=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'map-layer-widget'});superClass.call(this,properties);};$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;};$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();}};$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;};$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;};$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;};$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();};$prototype.toggleVisibility=function(){if(this.layout){if(this.layout.style.display!='none'){this.layout.style.display='none';}
else{this.layout.style.display='block';}}};$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;};namespace("userSmarts.maps.widget");userSmarts.maps.widget.LayerEditor=function(layer){if(isPrototype(arguments)){return;}
this.layer=layer;this.controls=[];this.isPainted=false;};userSmarts.maps.widget.LayerEditor.prototype.show=function(){if(this.layout){if(!this.isPainted){this.repaint();this.isPainted=true;}
this.layout.style.display="block";}};userSmarts.maps.widget.LayerEditor.prototype.hide=function(){if(this.layout){this.layout.style.display="none";}};userSmarts.maps.widget.LayerEditor.prototype.isVisible=function(){return(this.layout.style.display!="none");};userSmarts.maps.widget.LayerEditor.prototype.toggle=function(evt){if(this.layout&&this.layout.style.display=="none"){this.show();}else{this.hide();}
if(evt&&evt.stopPropagation){evt.stopPropagation();}};userSmarts.maps.widget.LayerEditor.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.maps.widget.LayerEditorFF=Class.create(userSmarts.maps.widget.LayerEditor);$prototype.initialize=function(superClass,layer){superClass.call(this,layer);};userSmarts.maps.widget.LayerEditorFF.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.maps.widget.LayerEditorFF.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.maps.widget.LayerEditorFF.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.maps.widget.LayerEditorIE=Class.create(userSmarts.maps.widget.LayerEditor);$prototype.initialize=function(superClass,layer){superClass.call(this,layer);};userSmarts.maps.widget.LayerEditorIE.prototype.paint=function(){if(!this.layout){this.layout=SPAN({'class':'editor'});}
this.hide();return this.layout;};userSmarts.maps.widget.LayerEditorIE.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.maps.widget.LayerEditorIE.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.maps.widget.LayerEditorFactory=function(){};userSmarts.maps.widget.LayerEditorFactory.getEditor=function(layer){var editor;if(window.ActiveXObject){editor=new userSmarts.maps.widget.LayerEditorIE(layer);}else{editor=new userSmarts.maps.widget.LayerEditorFF(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.Slider({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.Select({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;}
namespace("userSmarts.maps.widget");$namespace.LayerLegend=Class.create(userSmarts.wt.widgets.Control);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.name=" Legend ";this.adapterListener=connect(this,'adapter',this,this.onAdapterChange);};$prototype.onAdapterChange=function(evt){var canvas=this.adapter.getProperty("canvas");if(this.canvasListener){disconnect(this.canvasListener);}
this.canvasListener=connect(canvas,userSmarts.maps.widget.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};$prototype.getNode=function(){return this.paint();};$prototype.paint=function(){if(!this.layout){this.layout=DIV({'class':'map-layer-legend-content'});}
this.repaint();return this.layout;};$prototype.update=function(){this.repaint();};$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.maps.context.LayerLegend could not get reference to layer renderer!  "+"Unable to display rendered package legend images...");}}};$prototype.buildHeader=function(){if(!this.header){this.header=TD({'class':'map-layer-bar-subheader',width:'100%','align':'right'},"");}
return this.header;};$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;}};$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){}}}};$namespace.LayerLegendWidget=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'map-legend-widget'});superClass.call(this,properties);};$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;};$prototype.repaint=function(context){if(this.control){this.control.repaint();}};$prototype.dispose=function(){if(this.control){this.control.dispose();}
if(this.layout){replaceChildNodes(this.layout,null);this.layout=null;}};namespace("userSmarts.maps.widget");$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.maps.context.LayerPackage){result=pkg.repr()==this.repr();}
return result;};userSmarts.maps.widget.PackageFactory={packages:[],MAX_PKGS:50};userSmarts.maps.widget.PackageFactory.getPackage=function(){if(userSmarts.maps.widget.PackageFactory.packages.length===0){return new userSmarts.maps.widget.LayerPackage(null);}else{return userSmarts.maps.widget.PackageFactory.packages.shift();}};userSmarts.maps.widget.PackageFactory.releasePackage=function(pkg){if(pkg instanceof userSmarts.maps.widget.LayerPackage){pkg.dispose();if(userSmarts.maps.widget.PackageFactory.packages.length<userSmarts.maps.widget.PackageFactory.MAX_PKGS){userSmarts.maps.widget.PackageFactory.packages.push(pkg);}}};namespace("userSmarts.maps.widget");$namespace.LayerRenderer=Class.create(Bean);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.callbacks=[];this.connect("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.maps.widget.PackageManager();}
var result=this.manager.load(packages,context);result.addCallback(this.cb);}
return null;};$prototype.fireCallback=function(){if(this.manager){this.callback(this.manager.getImages());}else{this.callback([]);}};$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.maps.widget.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.maps.context.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("userSmarts.maps.widget");$namespace.LocationBar=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapLocationBar',height:15,units:userSmarts.maps.widget.LocationBar.DECIMAL_DEGREES});superClass.call(this,properties);this.canvasListener=bind(this.update,this);this.adapterListener=connect(this,'adapter',this,this.onAdapterChange);};$namespace.LocationBar.DECIMAL_DEGREES="decimal degrees";$namespace.LocationBar.DEG_MIN_SEC="degrees_minutes_seconds";$namespace.LocationBar.DEFAULT='default';$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;};$prototype.repaint=function(context){};$prototype.show=function(){if(this.layout.style.display=='none'){this.layout.style.display='block';}};$prototype.hide=function(){if(this.layout.style.display!='none'){this.layout.style.display='none';}};$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.maps.widget.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.maps.widget.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;};$prototype.setUnits=function(units){if(units==userSmarts.maps.widget.LocationBar.DECIMAL_DEGREES||units==userSmarts.maps.widget.LocationBar.DEG_MIN_SEC||units==userSmarts.maps.widget.LocationBar.DEFAULT){this.units=units;}};$prototype.toggleVisibility=function(){this.layout.style.display=(this.layout.style.display=='none')?'block':'none';};$prototype.toggleUnits=function(){if(this.units==userSmarts.maps.widget.LocationBar.DECIMAL_DEGREES){this.setUnits(userSmarts.maps.widget.LocationBar.DEG_MIN_SEC);}else if(this.units==userSmarts.maps.widget.LocationBar.DEG_MIN_SEC){this.setUnits(userSmarts.maps.widget.LocationBar.DEFAULT);}else{this.setUnits(userSmarts.maps.widget.LocationBar.DECIMAL_DEGREES);}};$prototype.onAdapterChange=function(event){var adapter=event.newValue;var canvas=adapter.getProperty("canvas");canvas.setMouseMoveListener(this.canvasListener);};$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}};}
namespace("userSmarts.maps.widget");userSmarts.maps.widget.Manager=function(map){this.map=map;};userSmarts.maps.widget.Manager.findMap=function(id){var widget;if(!id){return null;}
if(id instanceof userSmarts.maps.widget.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.maps.widget.Manager.prototype.loadContext=function(url){var parser=new userSmarts.maps.context.ViewContextParser();var listener=bind(function(event){this.setContext(event.newValue);},this.map);parser.connect("viewContext",listener);parser.setProperty("url",url);};userSmarts.maps.widget.Manager.loadContext=function(id,url){var map=userSmarts.maps.widget.Manager.findMap(id);if(map){var parser=new userSmarts.maps.context.ViewContextParser();var listener=bind(function(event){this.setContext(event.newValue);},map);parser.connect("viewContext",listener);parser.setProperty("url",url);}};userSmarts.maps.widget.Manager.prototype.setContext=function(context){if(!context||!(context instanceof userSmarts.maps.context.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.maps.widget.Manager.setContext=function(id,context){if(!context||!(context instanceof userSmarts.maps.context.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.maps.widget.Manager.findMap(id);if(map){map.setContext(context);}};userSmarts.maps.widget.Manager.prototype.setView=function(geom){var context=this.map.getProperty('context');if(!context||!(context instanceof userSmarts.maps.context.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.maps.widget.Manager.setView=function(id,geom){var map=userSmarts.maps.widget.Manager.findMap(id);if(map){var context=map.getProperty('context');if(!context||!(context instanceof userSmarts.maps.context.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.maps.widget.Manager.prototype.getProgressBar=function(){var result=this.map.getProperty("progressBar");return result;};userSmarts.maps.widget.Manager.getProgressBar=function(id){var result;var map=userSmarts.maps.widget.Manager.findMap(id);if(map){result=map.getManager().getProgressBar();}
return result;};userSmarts.maps.widget.Manager.getGeometryRenderer=function(id){var result=null;var map=userSmarts.maps.widget.Manager.findMap(id);if(map){result=map.getGeometryRenderer();}
return result;};userSmarts.maps.widget.Manager.getOverlayManager=function(id){var result=null;var map=userSmarts.maps.widget.Manager.findMap(id);if(map){result=map.getOverlayManager();}
return result;};userSmarts.maps.widget.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;}
geometryTool.addChangeListener(func,'geometry');getLogger().logInfo("Successfully registered geometry listener!");};userSmarts.maps.widget.Manager.registerGeometryListener=function(id,func){if(typeof(func)!='function'){logError("Geometry listener must be of type 'function'");return;}
var map=userSmarts.maps.widget.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');getLogger().logInfo("Successfully registered geometry listener!");}};userSmarts.maps.widget.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.maps.widget.Manager.unregisterGeometryListener=function(id,func){if(typeof(func)!='function'){logError("Geometry listener must be of type 'function'");return;}
var map=userSmarts.maps.widget.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.maps.widget.Manager.correctAspectRatio=function(id,points){var map=userSmarts.maps.widget.Manager.findMap(id);if(map){return map.getManager().correctAspectRatio(points);}};userSmarts.maps.widget.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.maps.widget.Manager.createMap=function(properties,parent){if(!properties){properties={};}
properties=setdefault(properties,{id:"map-"+Math.random(),width:500,height:500,timeout:3000,debug:false,showScale:false});userSmarts.maps.DEBUG_FLAG=properties.debug;var canvas=new userSmarts.maps.widget.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 userSmarts.geo.renderer.VMLGeometryRenderer():new userSmarts.geo.renderer.GeometryRenderer();var widget=new userSmarts.maps.widget.Widget({id:properties.id,width:properties.width,height:properties.height,canvas:canvas,renderer:renderer,debug:properties.debug});var layerRenderer=new userSmarts.maps.widget.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.maps.widget.ScaleLegend({id:properties.id+'-scale'});widget.register('scale-legend',scaleLegend);scaleLegend.paint();}
return widget;};namespace("userSmarts.maps.widget");$namespace.OverlayManager=Class.create(Bean);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.layout=DIV({'class':'map-overlay-manager'});this.layout.style.zIndex="999";this.connect("adapter",this,this.onAdapterChange);this.overlays=[];};$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.maps.widget.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};$prototype.paint=function(){return this.layout;};$prototype.repaint=function(){var overlay;for(var k in this.overlays){overlay=this.overlays[k];if(overlay instanceof userSmarts.maps.widget.WSOverlay){this.updateOverlay(overlay);}}};$prototype.getWSOverlays=function(){var overlays=[];var overlay;for(var k in this.overlays){overlay=this.overlays[k];if(overlay instanceof userSmarts.maps.widget.WSOverlay){overlays.push(overlay);}}
return overlays;};$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);}}};$prototype.add=function(overlay){this.overlays[overlay.id]=overlay;var content=overlay.paint();if(content){this.layout.appendChild(content);}
if(overlay instanceof userSmarts.maps.widget.WSOverlay){overlay.mgrconnect=connect(overlay,"deleted",this,this.remove);}};$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.maps.widget.WSOverlay){disconnect(overlay.mgrconnect);overlay.mgrconnect=null;overlay.mgrlistener=null;}};$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.maps.widget.Overlay){overlay.dispose();overlay=null;}
this.overlays[k]=null;}
this.overlays=null;}
this.content=null;this.layout=null;this.adapter=null;};$namespace.Overlay=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:Math.random(),className:'map-overlay'});superClass.call(this,properties);this.content=DIV({'class':this.className});this.content.style.position='relative';};$prototype.paint=function(){return this.content;};$prototype.setContent=function(content){replaceChildNodes(this.content,((typeof(content)=='array')?content:[content]));};$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);}};$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";}};$prototype.getPosition=function(){return{x:parseInt(this.content.style.left),y:parseInt(this.content.style.top)};};$prototype.setSize=function(width,height){this.content.style.width=width+"px";this.content.style.height=height+"px";};$prototype.getSize=function(){return{x:parseInt(this.content.style.width),y:parseInt(this.content.style.height)};};$prototype.show=function(){if(this.content&&this.content.style){this.content.style.display='block';}};$prototype.hide=function(){if(this.content&&this.content.style){this.content.style.display='none';}};$prototype.isVisible=function(){if(this.content&&this.content.style){return(this.content.style.display!='none');}
return false;};$prototype.close=function(event){if(event){var geometry=event.newValue;geometry.removeChangeListener(this.listener,Geometry.DELETED);}
this.listener=null;};$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;}};$namespace.WSOverlay=Class.create($namespace.Overlay);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.init();};$prototype.init=function(){if(this.ssgeometry&&this.ssgeometry instanceof Geometry){this.listener=connect(this.ssgeometry,Geometry.DELETED,this,this.onSSGeometryRemoved);}};$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);}};$prototype.getWSGeometry=function(){return this.wsgeometry;};$prototype.setWSGeometry=function(wsgeometry){this.wsgeometry=wsgeometry;};$prototype.getSSGeometry=function(){return this.ssgeometry;};$prototype.onSSGeometryRemoved=function(){signal(this,"deleted",this,{newValue:this.ssgeometry});if(this.wsgeometry){this.wsgeometry.remove();}};$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();}};namespace("userSmarts.maps.widget");$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.maps.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.maps.widget.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("userSmarts.maps.widget");$namespace.ProgressBar=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapProgressBar'+Math.random(),workTotal:0,workDone:0});superClass.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.maps.widget.Overlay({id:this.id});this.overlay.setContent(this.div);var overlays=this.adapter.getProperty("overlays");overlays.add(this.overlay);}
this.hide();}
$prototype.paint=function(context){this.repaint(context);return this.div;};$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);};$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";}};$prototype.setSize=function(width,height){this.div.style.width=width+"px";this.div.style.height=height+"px";};$prototype.setWorkTotal=function(work){this.workTotal=work;};$prototype.worked=function(){this.workDone++;this.repaint();};$prototype.reset=function(){this.bar.style.width='0px';this.workDone=0;this.hide();};$prototype.show=function(){if(this.div){this.div.style.display='block';}};$prototype.hide=function(){if(this.div){this.div.style.display='none';}};$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;};namespace("userSmarts.maps.widget");$namespace.ScaleLegend=Class.create(userSmarts.wt.widgets.Control);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapScaleLegend',uom:'mi',distanceScaleFactor:0.0,position:new Point(0,0)});superClass.call(this,properties);connect(this,'adapter',this,this.onAdapterChange);};$prototype.onAdapterChange=function(event){if(this.canvasListener){disconnect(this.canvasListener);}
var adapter=event.newValue;var canvas=adapter.getProperty('canvas');this.canvasListener=connect(canvas,userSmarts.maps.widget.Canvas.ONLOAD_COMPLETE_EVENT,this,this.repaint);};$prototype.paint=function(){return this.getNode();};$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.maps.widget.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;};$prototype.repaint=function(){this.update();};$prototype.update=function(){if(!this.content){return;}
var result=this.determineScale();replaceChildNodes(this.content,result);};$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;};$prototype.setCanvasSize=function(width,height){if(width<100){width=100;}
this.unitPercentage=100/width;};$prototype.setPosition=function(x,y){this.position.x=x;this.position.y=y;if(this.overlay){this.overlay.setPosition(this.position);}};$prototype.setUnits=function(uom){this.uom=uom;};$prototype.toggleVisibility=function(){};$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;}};namespace("userSmarts.maps.widget");$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.maps.widget.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("userSmarts.maps.widget");$namespace.ToolBar=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'mapToolBar_'+Math.random()});superClass.call(this,properties);this.modelChangeListener=this.connect("model",this,this.onModelChange);};$prototype.paint=function(context){if(!this.layout){this.layout=DIV({'class':'map-toolbar',id:this.id});}
this.repaint();return this.layout;};$prototype.update=function(){this.repaint();}
$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);};$prototype.onModelChange=function(event){if(this.modelListener){disconnect(this.modelListener);}
var newModel=event.newValue;this.modelListener=newModel.connect("modified",this,this.update);};$prototype.findTool=function(toolId){return this.model.getTool(toolId);};$prototype.getModel=function(){return this.model;};ToolIconFactory=function(){};ToolIconFactory.prototype.create=function(classNameDefault,classNameHover,title,key){classNameDefault+=" action-item";classNameHover+=" action-item";var img=userSmarts.runtime.Platform.getTheme().getImage(key);img.className=classNameDefault;img.onmouseover=function(){img.className=classNameHover;};img.onmouseout=function(){img.className=classNameDefault;};img.title=title;return img;};$namespace.ToolBarModel=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{toolIds:[],tools:[],overrideHelp:false});superClass.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.maps.tools.HelpTool({model:this,factory:this.factory}));}};$prototype.onAdapterChange=function(event){for(var i=0;i<this.tools.length;++i){this.tools[i].setProperty("adapter",event.newValue);}};$prototype.onToolReady=function(event){this.nextEnabledTool=event.source;this.disableAllTools(event.source.getToolId());};$prototype.disableAllTools=function(toolId){if(userSmarts.maps.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();}}};$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;}}};$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);}};$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;}};$prototype.getTools=function(){return this.tools;};$prototype.getTool=function(arg){var tool;if(typeof(arg)=='string'){tool=this.toolIds[arg];}
return tool;};$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;};namespace("userSmarts.maps.widget");$namespace.Widget=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'map-'+Math.random(),width:500,height:400,components:{},componentIds:[]});superClass.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.maps.widget.OverlayManager();this.register('overlays',this.overlays);this.progressBar=new userSmarts.maps.widget.ProgressBar({adapter:this});this.manager=new userSmarts.maps.widget.Manager(this);connect(this,"context",this,function(event){this.setContext(event.newValue);});};$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;};$prototype.repaint=function(context){if(this.canvas){this.canvas.repaint(context);}};$prototype.register=function(id,component){var comp=new userSmarts.maps.widget.ComponentAdapter({id:id,component:component,widget:this});this.components[id]=comp;this.componentIds.push(id);return comp;};$prototype.unregister=function(id){this.components[id]=null;this.componentIds.splice(this.componentIds.indexOf(id),1);};$prototype.locate=function(id){var adapter=this.components[id];if(adapter){return adapter.component;}
else{return null;}};$prototype.applyProperty=function(propertyName,value){if(userSmarts.maps.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);}}}};$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);};$prototype.getManager=function(){return this.manager;};$prototype.getGeometryRenderer=function(){return this.renderer;};$prototype.getOverlayManager=function(){return this.overlays;};$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;};namespace("userSmarts.maps.widget");$namespace.ToolContributionItem=Class.create(userSmarts.wt.action.ContributionItem);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{'class':'action-item',margin:{top:0,left:0,right:0,bottom:0},padding:{top:0,left:0,right:0,bottom:0},border:{style:"solid",top:1,left:1,right:1,bottom:1},layoutData:{width:25,height:"100%"}});superClass.call(this,properties);};$prototype.getId=function(){if(this.tool){return this.tool.id;}
return"";};$prototype.getText=function(){return this.getId();};$prototype.execute=function(){};$prototype.initNode=function(){var node=this.node;node.style.cursor="pointer";node.style.textAlign="center";var icons=this.tool.paint();if(typeof(icons.push)!="undefined"){for(var i=0;i<icons.length;++i){node.appendChild(icons[i]);}
this.layoutData.width=(30*icons.length);}else{node.appendChild(icons);}
this.update();};namespace("userSmarts.maps.widget");$namespace.MapControl=Class.create(userSmarts.wt.widgets.Control);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);};$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.resize(width,height);}}
return modified;};namespace("userSmarts.maps.widget");$namespace.MapController=Class.create();$prototype.initialize=function(superClass){this.ps=userSmarts.runtime.Platform.getPropertyService();this.ps.setProvider("map",this);this.ps.connect("page","activeEditor",this,this.onActiveEditorChange)};$prototype.setProperty=function(property,value){var context=this.getActiveMapContext();if(context){if("aoi"==property){context.setView(value);}else if("layer"==property){context.addLayer(value);}}};$prototype.getProperty=function(property){var result=null;var context=this.getActiveMapContext();if(context){if("aoi"==property){result=context.getView();}else if("context"==property){result=context;}}
return result;};$prototype.getActiveMapContext=function(){var result=null;var activeEditor=this.getActiveMap();if(activeEditor){result=activeEditor.getProperty("context");}
return result;};$prototype.getActiveMap=function(){var result=null;var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var activeEditor=page.getActiveEditor();if(activeEditor){if(activeEditor instanceof userSmarts.maps.editors.MapEditor){result=activeEditor;}}
return result;};$prototype.onActiveEditorChange=function(event){if(this.editorListener){disconnect(this.editorListener);}
var editor=event.newValue;if(editor&&editor instanceof userSmarts.maps.editors.MapEditor){this.editorListener=connect(editor,"*",this,this.onEditorPropertyChange);}};$prototype.onEditorPropertyChange=function(event){var property=event.propertyName;if(property=="aoi"||property=="context"){var oldValue=this[property];this[property]=event.newValue;signalp(this,property,oldValue,event.newValue);}};namespace("userSmarts.maps.widget");$namespace.LayerEditorComposite=Class.create(userSmarts.wt.widgets.Composite);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{updateOnBoundsChange:true,_layout:new userSmarts.wt.layout.RowLayout({type:"vertical"})});superClass.call(this,properties);this.listeners=[];};$prototype.initNode=function(){};$prototype.setLayer=function(layer){var children=this.children;for(var i=children.length-1;i>=0;--i){children[i].dispose();children[i]=null;}
this.children=[];if(this.listeners){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);this.listeners[i]=null;}}
this.listeners=[];if(layer){new userSmarts.wt.forms.Text({parent:this,layoutData:{width:"100%",height:25},showLabel:true,title:"Layer",labelWidth:75,value:layer.getLayerName()});new userSmarts.wt.forms.Text({parent:this,layoutData:{width:"100%",height:25},showLabel:true,title:"Server",labelWidth:75,value:layer.server.getName()});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;var comp=new userSmarts.wt.widgets.Composite({parent:this,layoutData:{width:"100%",height:25},_layout:new userSmarts.wt.layout.RowLayout({type:"horizontal"})});new userSmarts.wt.forms.Label({parent:comp,layoutData:{width:75,height:"100%"},value:"Metadata:"});var ctrl=new userSmarts.wt.widgets.Control({parent:comp,layoutData:{width:"*",height:"100%"}});ctrl.getNode().style.overflow="hidden";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);ctrl.getNode().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);ctrl.getNode().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);ctrl.getNode().appendChild(fullMDLink);}}else{new userSmarts.wt.forms.Text({parent:this,layoutData:{width:"100%",height:"100%"},value:"No Layer Selected"});}
this.layout();this.update();};$prototype.createControl=function(property){var dt=property.datatype;var pLabel=property.label;var pValue=property.getValue();var ctrl;if(dt.isRange&&dt.isRange===true){var comp=new userSmarts.wt.widgets.Composite({parent:this,layoutData:{width:"100%",height:25},_layout:new userSmarts.wt.layout.RowLayout({type:"horizontal"})});new userSmarts.wt.forms.Label({parent:comp,layoutData:{width:75,height:"100%"},value:pLabel+":"});new userSmarts.wt.widgets.CSlider({parent:comp,layoutData:{width:"100%",height:"100%"},value:pValue,type:"horizontal",binding:property});}else if(dt.isList&&dt.isList===true){new userSmarts.wt.forms.SelectComposite({parent:this,layoutData:{width:"100%",height:25},datatype:dt,binding:property,value:pValue,showLabel:true,title:pLabel,labelWidth:75});}else{new userSmarts.wt.forms.FieldControl({parent:this,layoutData:{width:"100%",height:25},binding:property,value:pValue,showLabel:true,title:pLabel,labelWidth:75});}};$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.maps.widget.Slider({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;};$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.maps.widget");$namespace.Slider=Class.create(Bean);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{width:150,value:0});superClass.call(this,properties);connect(this,'onchange',this,"onValueChange");};$prototype.paint=function(){if(!this.content){this.content=DIV();this.content.style.width=this.width+"px";this.sliderValue=DIV({'class':'slider-value'});this.sliderValue.style.width=this.width+"px";this.content.appendChild(this.sliderValue);this.slider=DIV({'class':'slider'});this.slider.style.width=this.width+"px";this.content.appendChild(this.slider);this.sliderMarker=DIV({'class':'slider-marker'});this.sliderMarker.style.width=this.width+"px";this.content.appendChild(this.sliderMarker);}
this.repaint();return this.content;};$prototype.repaint=function(){if(typeof(this.min)=='number'&&typeof(this.max)=='number'&&typeof(this.increment)=='number'){var perc=(this.value*this.width);if(!this.bar){this.bar=DIV({'class':'slider-bar'},IMG({src:'../../images/map/background-bar-red.gif',height:'6',width:'2'}));this.slider.appendChild(this.bar);this.sliderClickListener=connect(this.content,'onclick',this,'onClick');}
this.bar.style.width=perc+'px';this.bar.style.textAlign='right';var marker=SPAN({},'^');marker.style.position='relative';marker.style.left=perc+'px';marker.style.font='8px arial';replaceChildNodes(this.sliderMarker,marker);var val=SPAN({},this.value.toFixed(2));val.style.position='relative';val.style.left=perc+'px';val.style.font='8px arial';replaceChildNodes(this.sliderValue,val);}};$prototype.onClick=function(evt){var event=fixE(evt.event());var pos=elementPosition(this.content);var posRelToSlider={x:event.clientX-pos.x+parseInt(document.body.scrollLeft),y:event.clientY-pos.y+parseInt(document.body.scrollTop)};var wp=posRelToSlider.x/this.width;this.value=this.max*wp;this.value=Math.min(this.value,this.max);this.value=Math.max(this.value,this.min);signal(this,'onchange',this.value);};$prototype.onValueChange=function(value){this.setProperty("selected",value);this.repaint();};$prototype.getValue=function(){return this.value;};$prototype.setValue=function(value){this.value=value;};$prototype.dispose=function(){if(this.sliderClickListener){disconnect(this.sliderClickListener);}
if(this.content){disconnectAll(this.content);replaceChildNodes(this.content,null);this.bar=null;this.sliderValue=null;this.slider=null;this.sliderMarker=null;this.content=null;}};namespace("userSmarts.maps.views");namespace("userSmarts.maps.views");namespace("userSmarts.maps.views");$namespace.LayersView=Class.create(userSmarts.ui.views.ListView);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);this.model=new userSmarts.maps.models.LayersModel();connect(this.model,'modified',this,this.onModelUpdated);};$prototype.contributeToActionBars=function(){connect(this.model,'populating',this,this.displayQueryMessage);connect(this.model,'modified',this,this.displayFinishedMessage);var ps=userSmarts.runtime.Platform.getPropertyService();var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("map","aoi",this,this.onAOIChange);var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();var filled=false;var ANS=userSmarts.maps.actions;var P=userSmarts.sx.Plugin;var action;if(P!=undefined){if(P.isUserInRole("CREATE_LAYER")){action=new ANS.NewLayerAction();tbmgr.add(action);mbmgr.add(action);filled=true;}
if(P.isUserInRole("EDIT_LAYER")){action=new ANS.EditLayerAction();tbmgr.add(action);mbmgr.add(action);filled=true;}
if(P.isUserInRole("DELETE_LAYER")){action=new ANS.DeleteLayerAction();tbmgr.add(action);mbmgr.add(action);filled=true;}}
if(filled){mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());}
action=new ANS.AddLayerAction();if(!filled)tbmgr.add(action);mbmgr.add(action);action=new ANS.ConstrainLayersAction({model:this.model});if(!filled)tbmgr.add(action);mbmgr.add(action);mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());userSmarts.ui.views.ListView.prototype.contributeToActionBars.call(this);};$prototype.displayQueryMessage=function(){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage("Querying layers...");};$prototype.displayFinishedMessage=function(success){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage(success?"Listing layers":"Error listing layers");};$prototype.onSelectionChange=function(event){var id=null;var url=null;var title=null;var selection=event.newValue;if(selection){var wrapper=selection;var node=wrapper.getNode();var idNode=node.getElementsByTagName("id").item(0);id=scrapeText(idNode);var linkNode=node.getElementsByTagName("link").item(0);url=getNodeAttribute(linkNode,"href");var titleNode=node.getElementsByTagName("title").item(0);title=scrapeText(titleNode);}
this.setSelection({id:id,url:url,label:title});};$prototype.setSelection=function(obj){this.setProperty("selected",obj.id);userSmarts.runtime.Platform.getPropertyService().setProperty("layers","selected",obj);};$prototype.onModelUpdated=function(event){this.checkSelected();};$prototype.checkSelected=function(){var present=false;if(this.selected){var rows=this.model.getRows();var wrapper;for(var i=0;i<rows.length;++i){wrapper=rows[i];var node=wrapper.getNode();var idNode=node.getElementsByTagName("id").item(0);var id=scrapeText(idNode);if(this.selected==id){present=true;this.list.select(wrapper);}}}
if(!present){this.selected=null;}};$prototype.onAOIChange=function(event){if(event.source!=this){this.setAOI(event.newValue);}};$prototype.setAOI=function(aoi){if(this.model){this.model.setAOI(aoi);}};namespace("userSmarts.maps.views");$namespace.MapsView=Class.create(userSmarts.ui.views.ListView);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);this.model=new userSmarts.maps.models.MapsModel();connect(this.model,'modified',this,this.onModelUpdated);};$prototype.contributeToActionBars=function(){connect(this.model,'populating',this,this.displayQueryMessage);connect(this.model,'modified',this,this.displayFinishedMessage);var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();if(userSmarts.sx.Plugin!=undefined){var action;if(userSmarts.sx.Plugin.isUserInRole("CREATE_MAP")){action=new userSmarts.maps.actions.NewMapAction();tbmgr.add(action);mbmgr.add(action);}
action=new userSmarts.maps.actions.EditMapAction();tbmgr.add(action);mbmgr.add(action);action=new userSmarts.maps.actions.OpenKmlAction();mbmgr.add(action);if(userSmarts.sx.Plugin.isUserInRole("DELETE_MAP")){action=new userSmarts.maps.actions.DeleteMapAction();tbmgr.add(action);mbmgr.add(action);}}
mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());userSmarts.ui.views.ListView.prototype.contributeToActionBars.call(this);};$prototype.displayQueryMessage=function(){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage("Querying maps...");};$prototype.displayFinishedMessage=function(success){var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage(success?"Listing maps":"Error listing maps");};$prototype.onSelectionChange=function(event){var id=null;var url=null;var title=null;var selection=event.newValue;if(selection){var wrapper=selection;var node=wrapper.getNode();var idNode=node.getElementsByTagName("id").item(0);id=scrapeText(idNode);var linkNode=node.getElementsByTagName("link").item(0);url=getNodeAttribute(linkNode,"href");var titleNode=node.getElementsByTagName("title").item(0);title=scrapeText(titleNode);}
this.setSelection({id:id,url:url,label:title});};$prototype.onModelUpdated=function(event){this.checkSelected();};$prototype.setSelection=function(obj){this.setProperty("selected",obj.id);userSmarts.runtime.Platform.getPropertyService().setProperty("maps","selected",obj);};$prototype.checkSelected=function(){var present=false;if(this.selected){var rows=this.model.getRows();var wrapper;for(var i=0;i<rows.length;++i){wrapper=rows[i];var node=wrapper.getNode();var idNode=node.getElementsByTagName("id").item(0);var id=scrapeText(idNode);if(this.selected==id){present=true;this.list.select(wrapper);}}}
if(!present){this.setSelection({id:null,url:null});this.selectedSituationAOI=null;}};$prototype.setAOI=function(aoi){if(this.model){this.model.setAOI(aoi);}};namespace("userSmarts.maps.views");$namespace.MapView=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{mapId:"map"});superClass.call(this,properties);this.width=600;this.height=400;this.showToolbar=true;this.showLocation=true;};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};$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.maps.widget.MapControl({adapter:this,node:this.layout});return this.control;};$prototype.contributeToActionBars=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var map=this.map;if(this.showToolbar){var toolFactory=new ToolIconFactory("");var toolbarModel=new userSmarts.maps.widget.ToolBarModel({factory:toolFactory,overrideHelp:true});map.register('toolbar-model',toolbarModel);var contextManager=map.locate("context-mgr");if(!contextManager){contextManager=new userSmarts.maps.widget.ContextManager();map.register('context-mgr',contextManager);}
this.addTools(toolbarModel,toolFactory);var tools=toolbarModel.getTools();forEach(tools,function(tool){tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));});}
if(this.showLocation){this.location=new userSmarts.maps.widget.LocationBar();map.register('location-bar',this.location);this.location.paint();this.location.hide();}
var slmgr=actionbars.getStatusLineManager();connect(this.location,'location',this,this.onLocationChange);};$prototype.addTools=function(toolbarModel,toolFactory){toolbarModel.addTool(new userSmarts.maps.tools.HelpTool({factory:toolFactory,model:toolbarModel}));toolbarModel.addTool(new userSmarts.maps.tools.PanTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.DragTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.ZoomTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.ZoomToBoxTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.BookmarkTool({factory:toolFactory,manager:contextManager}));toolbarModel.addTool(new userSmarts.maps.tools.MeasureTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.GeometryTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.PresetCircleTool({factory:toolFactory}));toolbarModel.addTool(new userSmarts.maps.tools.DescribeTool({factory:toolFactory}));};$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);};$prototype.resize=function(width,height){width=Math.min(900,width);height=Math.min(900,height);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);}};$prototype.buildMap=function(width,height){if(width){this.width=width;}
if(height){this.height=height;}
var map=userSmarts.maps.widget.Manager.createMap({id:this.mapId,width:this.width,height:this.height,showScale:true,debug:false});replaceChildNodes(this.layout,map.paint());return map;};namespace("userSmarts.maps.views");$namespace.OverviewMapView=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);setdefault(this,{text:"",width:240,height:140,timeout:3000,imageBase:"",context:userSmarts.runtime.Platform.find('com.usersmarts.rcp.sx.maps',"data/safe.xml"),aoi:Geometry.valueOf("Box{(-125.0,20.0),(-66.0,60.0)}")});};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);var editor=this.getSite().getPage().getActiveEditor();if(editor&&(editor instanceof userSmarts.maps.editors.PrimaryMapEditor)&&editor.context){this.aoi=editor.context.getView();}
this.map=this.buildMap();if(typeof(this.context)=="string"){var d=parseXML(this.context);d.addCallback(bind(function(document){this.parseViewContext(document);},this));}
connect(this,"aoi",this,this.updateOverlayGeometry);this.editorChangeListener=connect(this.getSite().getPage(),"activeEditor",this,this.onActiveEditorChange);var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();};$prototype.parseViewContext=function(xml){var parser=new userSmarts.maps.context.ViewContextParser();var context=parser.fromXML(xml);if(this.map){this.map.setContext(context);}
this.setProperty("context",context);this.updateOverlayGeometry();};$prototype.createPartControl=function(){var div=DIV({'class':'map-holder'});div.style.width='100%';div.appendChild(this.map.paint());this.control=new userSmarts.maps.widget.MapControl({adapter:this,node:div});return this.control;};$prototype.onActiveEditorChange=function(event){if(this.editorContextListener){disconnect(this.editorContextListener);}
if(this.editorViewListener){disconnect(this.editorViewListener);}
var editor=event.newValue;if(editor&&editor instanceof userSmarts.maps.editors.MapEditor){this.editorContextListener=connect(editor,"contextModified",this,this.onEditorContextChange);this.editorViewListener=connect(editor,"viewModified",this,this.updateAOI);if(editor.context&&editor.context instanceof userSmarts.maps.context.ViewContext){this.setProperty("aoi",editor.context.getView());}}};$prototype.onEditorContextChange=function(event){var context=event.newValue;this.setProperty("aoi",context.getView());};$prototype.updateAOI=function(event){var aoi=event.newValue;this.setProperty("aoi",aoi);};$prototype.updateOverlayGeometry=function(){if(this.aoi&&this.aoi instanceof Geometry){if(this.aoi.getPoints().length>2){this.aoi=this.aoi.getEnvelope();}
if(this.context&&(this.context instanceof userSmarts.maps.context.ViewContext)){this.context.setView(this.aoi);this.context.zoom(3.0);}
var min=this.map.canvas.unprojectPoint(this.aoi.points[0]);var max=this.map.canvas.unprojectPoint(this.aoi.points[1]);this.clipPoint(min,this.map.canvas.width-4,this.map.canvas.height-4);this.clipPoint(max,this.map.canvas.width-4,this.map.canvas.height-4);var div=DIV({'class':'Box'});div.style.position='absolute';div.style.top=max.y+"px";div.style.left=min.x+"px";div.style.height=(min.y-max.y)+"px";div.style.width=(max.x-min.x)+"px";div.appendChild(IMG({src:this.imageBase+"/spacer.gif",width:'1',height:'1'}));if(!this.extentOverlay){var olm=this.map.overlays;this.extentOverlay=new userSmarts.maps.widget.Overlay(div);olm.add(this.extentOverlay);}else{this.extentOverlay.setContent(div);}
this.extentOverlay.geometry=this.aoi;}}
$prototype.clipPoint=function(point,width,height){point.x=Math.max(0,point.x);point.y=Math.max(0,point.y);point.x=Math.min(width,point.x);point.y=Math.min(height,point.y);};$prototype.resizeMap=function(width,height){if(!this.map)return;if(this.extentOverlay){var olm=this.map.overlays;olm.remove(this.extentOverlay);}
var context=this.map.getProperty("context");if(context)context.removeListeners();this.map.dispose();this.map=null;this.map=this.buildMap(width,height);if(context)this.map.setContext(context);if(this.extentOverlay){var olm=this.map.overlays;olm.add(this.extentOverlay);this.updateOverlayGeometry();}};$prototype.buildMap=function(width,height){if(width)this.width=width;if(height)this.height=height;var widget=userSmarts.maps.widget.Manager.createMap({id:"overview",showScale:false,debug:false,width:this.width,height:this.height,timeout:this.timeout});if(this.control){replaceChildNodes(this.control.getNode(),widget.paint());}
return widget;};namespace("userSmarts.maps.views");$namespace.ViewContextView=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.composite=new userSmarts.wt.widgets.Composite({'class':'view-context-view',updateOnBoundsChange:true,layoutData:{width:"100%",height:"100%"},_layout:new userSmarts.wt.layout.RowLayout({type:"vertical"})});this.layerTable=new userSmarts.wt.widgets.Table({parent:this.composite,updateOnBoundsChange:true,showFooter:false,layoutData:{width:"100%",height:"80%"}});connect(this.layerTable,"selected",this,this.selectLayer);this.layerViewer=new userSmarts.maps.widget.LayerEditorComposite({'class':'vc-layer-properties',layerProvider:this,parent:this.composite,updateOnBoundsChange:true,layoutData:{width:"100%",height:"20%"},padding:{top:1,left:1,right:1,bottom:1},border:{style:"solid",top:3,left:0,right:0,bottom:0}});this.updateCheck=bind(this.checkIfUpdated,this);if(this.autoRefresh){var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);site.setPropertyProvider(this);var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("page","activeEditor",this,this.onEditorChange);var activeEditor=site.getPage().getActiveEditor();this.setNewEditorContext(activeEditor);this.contributeToActionBars();};$prototype.createPartControl=function(){this.composite.update();return this.composite;};$prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var slmgr=bars.getStatusLineManager();var tbmgr=bars.getToolbarManager();var mbmgr=bars.getMenuBarManager();var removeAction=bind(function(){if(this.selected){var layer=this.selected;var ok=userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Layer?","Are you sure you want to delete the selected layer? ('"+
layer.getLayerName()+"')");if(ok){var context=this.getViewContext();if(context){context.removeLayer(layer);this.selectLayer(null);}}}else{alert("You must select a layer before attempting to delete one!");}},this);var selectAllAction=bind(function(){for(var i=0;i<this.layerTable.model.context.layers.length;i++){this.layerTable.model.context.layers[i].visible=true;}
var context=this.getViewContext();if(context)context.touch();},this);var unSelectAllAction=bind(function(){for(var i=0;i<this.layerTable.model.context.layers.length;i++){this.layerTable.model.context.layers[i].visible=false;}
var context=this.getViewContext();if(context)context.touch();},this);var action=new userSmarts.wt.action.Action({id:'refreshAction',text:'Refresh',toolTipText:'Refresh the map',run:bind(function(){var context=this.getViewContext();if(context)context.touch();},this),image:"image.refresh"});tbmgr.add(action);mbmgr.add(action);action=new userSmarts.wt.action.StatefulAction({id:'autoRefreshAction',text:'Auto Refresh',toolTipText:'Automatically Refresh Map',checked:true,run:bind(function(){this.toggleAutoRefresh();},this),image:"image.refresh.auto"});mbmgr.add(action);mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());action=new userSmarts.wt.action.Action({id:'topAction',text:'Shift Layer to Top',toolTipText:'Shift selected layer to top',run:bind(function(){this.moveLayer(-1,true);},this),image:"image.layer.shift.top"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'botAction',text:'Shift Layer to Bottom',toolTipText:'Shift selected layer to bottom',run:bind(function(){this.moveLayer(1,true);},this),image:"image.layer.shift.bottom"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'upAction',text:'Shift Layer Up',toolTipText:'Shift selected layer up',run:bind(function(){this.moveLayer(-1,false);},this),image:"image.layer.shift.up"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'downAction',text:'Shift Layer Down',toolTipText:'Shift selected layer down',run:bind(function(){this.moveLayer(1,false);},this),image:"image.layer.shift.down"});mbmgr.add(action);mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());var selAllAction=new userSmarts.wt.action.Action({id:'selectAllAction',text:"Show All",toolTipText:'Make all layers visible',run:selectAllAction,image:"image.layer.check"});mbmgr.add(selAllAction);var unSelAllAction=new userSmarts.wt.action.Action({id:'unSelectAllAction',text:"Hide All",toolTipText:'Make all layers hidden',run:unSelectAllAction,image:"image.layer.uncheck"});mbmgr.add(unSelAllAction);var remAction=new userSmarts.wt.action.Action({id:'removeAction',text:"Remove",toolTipText:'Remove selected layer',run:removeAction,image:"image.layer.delete"});mbmgr.add(remAction);};$prototype.selectLayer=function(event){var layer=null;if(event){layer=event.newValue;}
this.setProperty("selected",layer);this.layer=layer;this.layerViewer.setLayer(layer);};$prototype.onAdapterChange=function(event){var adapter=event.newValue;var context=adapter.getProperty('context');if(context){this.setProperty('context',context);}};$prototype.onContextChange=function(event){this.context=event.newValue;this.layerTable.model.setProperty("context",this.context);};$prototype.onEditorChange=function(event){this.setNewEditorContext(event.newValue);};$prototype.setNewEditorContext=function(editor){if(editor&&typeof(editor.getViewContextModel)=="function"){var model=editor.getViewContextModel();if(this.layerTable){this.layerTable.setProperty("model",model);}
if(model){model.populate(0);}}else{if(this.layerTable){this.layerTable.setProperty("model",null);this.layerTable.update();}}
this.selectLayer(null);}
$prototype.moveLayer=function(direction,allTheWay){var context=this.getViewContext();if(!context){return;}
var layer=this.selected;if(!layer){return;}
var slmgr=this.getSite().getActionBars().getStatusLineManager();if(allTheWay){if(direction<0){slmgr.setMessage("Shifting layer to top");context.shiftTo(layer,context.layers.length-1,false);}else if(direction>0){slmgr.setMessage("Shifting layer to bottom");context.shiftTo(layer,0,false);}}else{if(direction<0){slmgr.setMessage("Shifting layer up");context.shiftUp(layer,false);}else if(direction>0){slmgr.setMessage("Shifting layer down");context.shiftDown(layer,false);}}
this.layerTable.model.populate(0);this.updatesPending=true;};$prototype.toggleAutoRefresh=function(){if(typeof(this.autoRefresh)=="undefined")
this.autoRefresh=false;this.autoRefresh=!this.autoRefresh;var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage((this.autoRefresh?"Enabling":"Disabling")+" automatic refresh");if(this.autoRefresh){if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
this.checkIfUpdated();}else{if(this.timeoutFunc){clearTimeout(this.timeoutFunc);}
if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh disabled");}}};$prototype.checkIfUpdated=function(){if(this.updatesPending){var context=this.getViewContext();if(context){context.touch();}
this.updatesPending=false;}
if(this.autoRefresh){var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.getViewContext=function(){var result=null;if(this.layerTable&&this.layerTable.model){result=this.layerTable.model.context;}
return result;};namespace("userSmarts.maps.views");$namespace.ViewContextViewLite=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,desc){if(isPrototype(arguments)){return;}
userSmarts.ui.ViewPart.call(this,desc);setdefault(this,{id:'default',timeout:1000,autoRefresh:true});this.table=new userSmarts.wt.widgets.Table({showFooter:false});connect(this.table,"selected",this,this.selectLayer);this.updateCheck=bind(this.checkIfUpdated,this);if(this.autoRefresh){if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);site.setPropertyProvider(this);var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("page","activeEditor",this,this.onEditorChange);var activeEditor=site.getPage().getActiveEditor();this.setNewEditorContext(activeEditor);this.contributeToActionBars();};$prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var slmgr=bars.getStatusLineManager();var tbmgr=bars.getToolbarManager();var mbmgr=bars.getMenuBarManager();var removeAction=bind(function(){if(this.selected){var layer=this.selected;var ok=userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Layer?","Are you sure you want to delete the selected layer? ('"+
layer.getLayerName()+"')");if(ok){var context=this.getViewContext();if(context){context.removeLayer(layer);this.setProperty("selected",null);}}}else{alert("You must select a layer before attempting to delete one!");}},this);var selectAllAction=bind(function(){for(var i=0;i<this.table.model.context.layers.length;i++){this.table.model.context.layers[i].visible=true;}
var context=this.getViewContext();if(context)context.touch();},this);var unSelectAllAction=bind(function(){for(var i=0;i<this.table.model.context.layers.length;i++){this.table.model.context.layers[i].visible=false;}
var context=this.getViewContext();if(context)context.touch();},this);var action=new userSmarts.wt.action.Action({id:'refreshAction',text:'Refresh',toolTipText:'Refresh the map',run:bind(function(){var context=this.getViewContext();if(context)context.touch();},this),image:"image.refresh"});tbmgr.add(action);mbmgr.add(action);action=new userSmarts.wt.action.StatefulAction({id:'autoRefreshAction',text:'Auto Refresh',toolTipText:'Automatically Refresh Map',checked:true,run:bind(function(){this.toggleAutoRefresh();},this),image:"image.refresh.auto"});mbmgr.add(action);mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());action=new userSmarts.wt.action.Action({id:'topAction',text:'Shift Layer to Top',toolTipText:'Shift selected layer to top',run:bind(function(){this.moveLayer(-1,true);},this),image:"image.layer.shift.top"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'botAction',text:'Shift Layer to Bottom',toolTipText:'Shift selected layer to bottom',run:bind(function(){this.moveLayer(1,true);},this),image:"image.layer.shift.bottom"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'upAction',text:'Shift Layer Up',toolTipText:'Shift selected layer up',run:bind(function(){this.moveLayer(-1,false);},this),image:"image.layer.shift.up"});mbmgr.add(action);action=new userSmarts.wt.action.Action({id:'downAction',text:'Shift Layer Down',toolTipText:'Shift selected layer down',run:bind(function(){this.moveLayer(1,false);},this),image:"image.layer.shift.down"});mbmgr.add(action);mbmgr.add(new userSmarts.wt.action.HorizontalSeparator());var selAllAction=new userSmarts.wt.action.Action({id:'selectAllAction',text:"Show All",toolTipText:'Make all layers visible',run:selectAllAction,image:"image.layer.check"});mbmgr.add(selAllAction);var unSelAllAction=new userSmarts.wt.action.Action({id:'unSelectAllAction',text:"Hide All",toolTipText:'Make all layers hidden',run:unSelectAllAction,image:"image.layer.uncheck"});mbmgr.add(unSelAllAction);};$prototype.createPartControl=function(){return this.table;};$prototype.selectLayer=function(event){this.setProperty("selected",event.newValue);var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("userSmarts.maps.context.Layer","selected",event.newValue);};$prototype.onAdapterChange=function(event){var adapter=event.newValue;var context=adapter.getProperty('context');if(context){this.setProperty('context',context);}};$prototype.onContextChange=function(event){this.context=event.newValue;this.table.model.setProperty("context",this.context);};$prototype.onEditorChange=function(event){this.setNewEditorContext(event.newValue);};$prototype.setNewEditorContext=function(editor){if(editor&&typeof(editor.getViewContextModel)=="function"){var model=editor.getViewContextModel();if(this.table){this.table.setProperty("model",model);}
if(model){model.populate(0);}}else{this.table.setProperty("model",null);this.table.update();}
this.setProperty("selected",null);}
$prototype.moveLayer=function(direction,allTheWay){var context=this.getViewContext();if(!context){return;}
var layer=this.selected;if(!layer){return;}
var slmgr=this.getSite().getActionBars().getStatusLineManager();if(allTheWay){if(direction<0){slmgr.setMessage("Shifting layer to top");context.shiftTo(layer,context.layers.length-1,false);}else if(direction>0){slmgr.setMessage("Shifting layer to bottom");context.shiftTo(layer,0,false);}}else{if(direction<0){slmgr.setMessage("Shifting layer up");context.shiftUp(layer,false);}else if(direction>0){slmgr.setMessage("Shifting layer down");context.shiftDown(layer,false);}}
this.table.model.populate(0);this.updatesPending=true;};$prototype.toggleAutoRefresh=function(){if(typeof(this.autoRefresh)=="undefined")
this.autoRefresh=false;this.autoRefresh=!this.autoRefresh;var slmgr=this.getSite().getActionBars().getStatusLineManager();slmgr.setMessage((this.autoRefresh?"Enabling":"Disabling")+" automatic refresh");if(this.autoRefresh){if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
this.checkIfUpdated();}else{if(this.timeoutFunc){clearTimeout(this.timeoutFunc);}
if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh disabled");}}};$prototype.checkIfUpdated=function(){if(this.updatesPending){var context=this.getViewContext();if(context){context.touch();}
this.updatesPending=false;}
if(this.autoRefresh){var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.getViewContext=function(){var result=null;if(this.table&&this.table.model){result=this.table.model.context;}
return result;};namespace("userSmarts.maps.views");$namespace.LayerPropertiesView=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);setdefault(this,{id:'default',timeout:3000});this.control=new userSmarts.maps.widget.LayerEditorComposite({node:DIV({'class':'layer-editor-view'}),updateOnBoundsChange:true,layerProvider:this});};$prototype.onSelectionChange=function(event){this.layer=event.newValue;this.control.setLayer(this.layer);};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("userSmarts.maps.context.Layer","selected",this,this.onSelectionChange);this.contributeToActionBars();};$prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var slmgr=bars.getStatusLineManager();var tbmgr=bars.getToolbarManager();};$prototype.createPartControl=function(){this.control.update();return this.control;};namespace("userSmarts.maps.views");$namespace.LegendView=Class.create(userSmarts.ui.ViewPart);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);};$prototype.init=function(site){userSmarts.ui.ViewPart.prototype.init.call(this,site);};$prototype.createPartControl=function(){if(!this.layout){var legendControl=new userSmarts.maps.widget.LayerLegend();legendControl.widget=this;this.content=legendControl.paint();layout=DIV({'class':'legend-view'},this.content);this.layout=layout;}
this.control=new userSmarts.wt.widgets.Control();this.control.getNode().appendChild(this.content);return this.control;};$prototype.registerOnMap=function(map){map.register('layer-legend',legendControl);};namespace("userSmarts.maps.views");$namespace.LegendTableView=Class.create(userSmarts.ui.views.TableView);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);this.table=new userSmarts.wt.widgets.Table({model:this.model,'class':'legend-view',showFooter:false,allowSelection:false});};$prototype.init=function(site){userSmarts.ui.views.TableView.prototype.init.call(this,site);var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("page","activeEditor",this,this.onEditorChange);var activeEditor=site.getPage().getActiveEditor();this.setNewModel(activeEditor);};$prototype.contributeToActionBars=function(){var bars=this.getSite().getActionBars();var tbmgr=bars.getToolbarManager();var mbmgr=bars.getMenuBarManager();var action=new userSmarts.wt.action.RefreshTableAction({control:this.table});tbmgr.add(action);mbmgr.add(action);};$prototype.createPartControl=function(){this.table.setProperty(this.model);connect(this.table,'selected',this,this.onTableSelectionChange);return this.table;};$prototype.updateLegend=function(){if(this.table.model){this.table.model.populate(0);}};$prototype.onEditorChange=function(event){this.setNewModel(event.newValue);};$prototype.setNewModel=function(editor){if(editor&&typeof(editor.getLegendModel)=="function"){var model=editor.getLegendModel();if(this.table){this.table.setProperty("model",model);}
if(model){model.populate();}}else{this.table.setProperty("model",null);this.table.update();}}
namespace("userSmarts.maps.models");namespace("userSmarts.maps.models");namespace("userSmarts.maps.models");$namespace.LayerTableColumn=Class.create(userSmarts.wt.widgets.TableColumn);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);};$prototype.getColumnLabel=function(){if(!this.label)this.label="Column";return this.label;};$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;};$prototype.getClassName=function(row){if(!this['class'])this['class']='layer-control-column';return this['class'];};namespace("userSmarts.maps.models");$namespace.LayersModel=Class.create(userSmarts.pub.GeoOpenSearchTableModel);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{pageSize:50,nodeOffset:0,depth:0,nodeNames:["entry"]});superClass.call(this,properties);var icon=userSmarts.runtime.Platform.getTheme().getImage("image.layer");this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Id",name:"id",index:0,order:true,visible:false}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Title",name:"title",index:1,order:true,image:icon}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Server",name:"server",index:2,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Keywords",name:"keywords",index:3,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"SRS",name:"srs",index:4,order:true}));this.sortElement=this.columns[1].name;this.sortOrder=this.columns[1].order;this.setProperty("source","pub/layers.atom");var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("layers","*",this,this.onLayerChanges);};$prototype.onLayerChanges=function(event){var property=event.propertyName;if(property=="created"||property=="updated"||property=="deleted"){this.populate(this.getOffset());}};namespace("userSmarts.maps.models");$namespace.MapsModel=Class.create(userSmarts.pub.OpenSearchTableModel);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{pageSize:50,nodeOffset:0,depth:0,nodeNames:["entry"]});superClass.call(this,properties);var icon=userSmarts.runtime.Platform.getTheme().getImage("image.map");this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Id",name:"id",index:0,order:true,visible:false}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Title",name:"title",index:1,order:true,image:icon}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({name:"summary",index:2,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Number of Layers",name:"numLayers",index:3,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Published",name:"published",index:4,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"Modified",name:"updated",index:5,order:true}));this.addColumn(new userSmarts.wt.widgets.DOMTableColumn({label:"AOI",name:"box",index:6,order:true}));var workspace=userSmarts.runtime.Platform.getWorkspace();this.setProperty("source",workspace.getLink("maps").href);var ps=userSmarts.runtime.Platform.getPropertyService();ps.connect("maps","*",this,this.onMapsChange);};$prototype.onMapsChange=function(event){var property=event.propertyName;if(property=="created"||property=="deleted"||property=="updated"){this.populate(this.getOffset());}};namespace("userSmarts.maps.models");$namespace.LegendModel=Class.create(userSmarts.wt.widgets.TableModel);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{pageSize:50});superClass.call(this,properties);this.columns=[{label:"Layers",index:0},{label:"Icons",index:1}];};$prototype.getLabel=function(column,row){var result="";if(column.index==0){var layers=row.getLayers();for(var l=0;l<layers.length;++l){result+=(l>0?", ":"")+layers[l].getLayerName();}}else{result=row.getLegend();if(result&&typeof(result.push)=="function"){for(var l=0;l<result.length;++l){result[l].style.opacity=1.0;result[l].style.filter='alpha(opacity=100)';result[l].style.display="inline";}}}
return result;};$prototype.getColumnLabel=function(column,row){return column.label;};$prototype.getClassName=function(column,row){return this.getColumnClassName(column,row);};$prototype.getColumnClassName=function(column,row){return"legend-"+column.label.toLowerCase()+"-column";};$prototype.getColumns=function(){return this.columns;};$prototype.hideColumn=function(col){};$prototype.showColumn=function(col){};$prototype.isColumnVisible=function(col){return true;};$prototype.size=function(){return this.buffer.length;};$prototype.populate=function(position){this.setProperty("populating",true);if(!this.adapter){this.buffer=[];return;}
var map=this.adapter.getMap();if(!map){this.buffer=[];return;}
if(!this.mapListener){this.mapListener=connect(map,"context",this,this.onContextChange);}
if(!this.contextListener){var context=map.context;this.contextListener=connect(context,userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,this,this.onContextModified);}
var renderer=map.locate("layer-renderer");if(!renderer){this.buffer=[];return;}
var imgCol=this.columns[1];this.buffer=[];var arr=renderer.getPackages();for(var c=arr.length-1;c>=0;c--){if(this.getLabel(imgCol,arr[c])){this.buffer.push(arr[c]);}}
this.setProperty("modified",true);};$prototype.sort=function(column){};$prototype.onContextChange=function(event){if(this.contextListener){disconnect(this.contextListener);this.contextListener=null;}
var context=event.newValue;if(context){this.contextListener=connect(context,userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,this,this.onContextModified);}
this.populate(0);};$prototype.onContextModified=function(event){this.populate(0);};namespace("userSmarts.maps.models");$namespace.ViewContextTableModel=Class.create(userSmarts.wt.widgets.TableModel);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.columns=[new userSmarts.maps.models.LayerTableColumn({label:'Viz',name:'visible','class':'layer-control-checkbox-column',width:25}),new userSmarts.maps.models.LayerTableColumn({label:'Qry',name:'queryable','class':'layer-control-checkbox-column',width:25}),new userSmarts.maps.models.LayerTableColumn({label:'Layer',name:'title','class':'layer-control-text-column'})];connect(this,"context",this,this.onContextChange);this.touch("context");};$prototype.onContextChange=function(event){var context=event.oldValue;if(context&&this.contextEventListener){disconnect(this.contextEventListener);}
if(this.context instanceof userSmarts.maps.context.ViewContext){this.contextEventListener=connect(this.context,userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,this,this.populate);}
this.populate(0);};$prototype.getLabel=function(column,row){return column.getLabel(row);};$prototype.getClassName=function(column,row){return column.getClassName(row);};$prototype.getColumnLabel=function(column,row){return column.getColumnLabel();};$prototype.getColumnClassName=function(column,row){return"layer-control-column-header";};$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);};namespace("userSmarts.maps.models");$namespace.PagedViewContextTableModel=Class.create(userSmarts.maps.models.ViewContextTableModel);$prototype.initialize=function(superClass,properties){if(isPrototype(arguments))return;setdefault(properties,{currentRow:0,pageSize:5});superClass.call(this,properties);};$prototype.size=function(){var result=0;if(this.context){result=this.context.layers.length;}
return result;};$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("userSmarts.maps.editors");namespace("userSmarts.maps.editors");namespace("userSmarts.maps.editors");$namespace.LayerEditor=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.listeners=[];this.getCallback=bind(this.parseLayerInfo,this);this.putCallback=bind(this.updateEntry,this);this.opacityDT={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()};};$prototype.init=function(site,input){userSmarts.ui.EditorPart.prototype.init.call(this,site,input);var def=input.get();def.addCallback(this.getCallback);def.addErrback(bind(function(arg){handleResponseError(arg);var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();page.closeEditor(this,false);userSmarts.runtime.Platform.getPropertyService().setProperty("layers","deleted",null);},this));};$prototype.findPath=function(path){if(!this.path){this.path=userSmarts.runtime.Platform.find('com.usersmarts.rcp.sx.maps',path);}
return this.path;};$prototype.parseLayerInfo=function(xml){this.entry=new userSmarts.maps.pub.LayerEntry({node:xml.documentElement});this.entry.getLayerName();this.entry.getTitle();this.entry.getQueryable();this.entry.getHidden();this.entry.getOpacity();this.entry.getProxied();this.entry.getSRS();this.entry.getSummary();this.entry.getKeywords();this.entry.getMetadataURL;this.entry.getServerTitle();this.entry.getService();this.entry.getVersion();this.entry.getOnlineResource();if(this.control){this.updateControl();};};$prototype.updateEntry=function(){var def=this.input.get();def.addCallback(bind(this.parseLayerInfo,this));def.addErrback(handleResponseError);};$prototype.createPartControl=function(){if(!this.control){this.control=new userSmarts.wt.widgets.Control({'class':'layer-editor'});var bars=this.getSite().getActionBars();var tbmgr=bars.getToolbarManager();this.saveAction=new userSmarts.wt.action.Action({id:'saveAction',text:'Save',toolTipText:'Save Changes',run:bind(this.doSave,this),image:"image.save"});tbmgr.add(this.saveAction);}
if(this.entry){this.updateControl();}
return this.control;};$prototype.updateControl=function(){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);}
var button;var node=this.control.getNode();replaceChildNodes(node,[]);var col1;var col2;var tbody=TBODY({});var table=TABLE({cellpadding:"3",cellPadding:"3",cellspacing:"0",cellSpacing:"0",border:"0",width:"100%"},tbody);node.appendChild(table);col1=TD({width:"100px",'class':'editor-section-title'},"Layer Details");col2=TD({},"");tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Name: "));var box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'layerName')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"layerName",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Title: "));var box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'title')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"title",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Visible? "));button=BUTTON({},(this.entry.getHidden()?"Hidden":"Visible"));this.listeners.push(connect(button,'onclick',this,this.onVisibleButtonClick));col2.appendChild(button);tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Queryable? "));button=BUTTON({},(this.entry.getQueryable()?"Queryable":"Not Queryable"));this.listeners.push(connect(button,'onclick',this,this.onQueryableButtonClick));col2.appendChild(button);tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Proxy? "));button=BUTTON({},(this.entry.getProxied()?"Proxied":"Not Proxied"));this.listeners.push(connect(button,"onclick",this,this.onProxiedButtonClick));col2.appendChild(button);tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Opacity: "));var min=this.opacityDT.facets.minInclusive;var max=this.opacityDT.facets.maxInclusive;var widget=new userSmarts.wt.widgets.Slider({min:this.opacityDT.facets.minInclusive,max:this.opacityDT.facets.maxInclusive,increment:this.opacityDT.facets.increment,value:Coerce.toDouble(this.entry.getOpacity(),1.0),width:200});this.listeners.push(connect(widget,'onchange',this,this.onOpacityChange));this.opacityWidget=widget;col2.appendChild(widget.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"SRS: "));var box=new userSmarts.wt.forms.Field({size:20,parent:null,binding:new BeanPropertyBinding(this.entry,'srs')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"srs",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Abstract: "));var box=new userSmarts.wt.forms.TextArea({rows:3,cols:37,parent:null,binding:new BeanPropertyBinding(this.entry,'summary')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"summary",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Keywords: "));for(var i=0;i<this.entry.keywords.length;++i){var closer=SUP({}," [x] ");closer.style.cursor="pointer";closer.style.color="#ff0000";closer.title="Remove this keyword";closer.keywordIndex=i;this.listeners.push(connect(closer,"onclick",this,this.removeKeyword));var span=SPAN({'class':'editor-section-text'},(i>0?", ":"")+this.entry.keywords[i],closer);span.style.cursor="pointer";span.title="Edit this keyword";span.keywordIndex=i;this.listeners.push(connect(span,'onclick',this,this.editKeyword));col2.appendChild(span);}
var opener=SUP({},"[+]");opener.style.color="#00ff00";button=SPAN({'class':'editor-section-text'},", New Keyword...",opener);button.style.cursor="pointer";button.style.fontStyle="italic";button.title="Add new keyword";this.listeners.push(connect(button,'onclick',this,this.addKeyword));col2.appendChild(button);tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px",'class':'editor-section-title'},"Server Details");col2=TD({},"");tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Title: "));var box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'serverTitle')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"serverTitle",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Service: "));var box=new userSmarts.wt.forms.Field({size:15,parent:null,binding:new BeanPropertyBinding(this.entry,'service')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"service",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));col1=TD({width:"100px"});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"URL: "));var box=new userSmarts.wt.forms.Field({size:100,parent:null,binding:new BeanPropertyBinding(this.entry,'onlineResource')});col2.appendChild(box.paint());this.listeners.push(connect(this.entry,"onlineResource",this,this.onInputChange));tbody.appendChild(TR({},col1,col2));};$prototype.onInputChange=function(event){this.dirty=true;this.setMessage(" ");}
$prototype.doSave=function(){var def=this.getEditorInput().put(this.entry.toXml());def.addCallback(bind(function(){this.dirty=false;this.setMessage("Layer info updated.");userSmarts.runtime.Platform.getPropertyService().setProperty("layers","updated",this.entry.getId());},this));def.addErrback(bind(function(arg){handleResponseError(arg);var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();page.closeEditor(this,false);userSmarts.runtime.Platform.getPropertyService().setProperty("layers","deleted",null);},this));};$prototype.setMessage=function(message){var actionbars=this.getSite().getActionBars();var slmgr=actionbars.getStatusLineManager();slmgr.setMessage(message);};$prototype.onVisibleButtonClick=function(event){this.entry.setHidden(!this.entry.getHidden());var button=event.src();var buttonLabel=(this.entry.getHidden()?"Hidden":"Visible");replaceChildNodes(button,buttonLabel);};$prototype.onQueryableButtonClick=function(event){this.entry.setQueryable(!this.entry.getQueryable());var button=event.src();var buttonLabel=(this.entry.getQueryable()?"Queryable":"Not Queryable");replaceChildNodes(button,buttonLabel);};$prototype.onProxiedButtonClick=function(event){this.entry.setProxied(!this.entry.getProxied());var button=event.src();var buttonLabel=(this.entry.getProxied()?"Proxied":"Not Proxied");replaceChildNodes(button,buttonLabel);};$prototype.removeKeyword=function(event){var button=event.src();var keyword=button.keywordIndex;this.entry.keywords.splice(keyword,1);this.updateControl();};$prototype.editKeyword=function(event){var input=event.src();var keyword=input.keywordIndex;var value=prompt("Enter the new value:",this.entry.keywords[keyword]);if(value){this.entry.keywords[keyword]=value;}
this.updateControl();}
$prototype.addKeyword=function(event){var keyword=prompt("Enter the new keyword:","");if(keyword){this.entry.keywords.push(keyword);this.updateControl();}};$prototype.validateOpacity=function(event){var input=event.src();var value=input.value;if(!isNaN(value)){this.entry.setOpacity(value*1);}else{input.value=this.entry.getOpacity();}};$prototype.onOpacityChange=function(){var opacity=this.opacityDT.format.parseObject(this.opacityWidget.selected);this.entry.setOpacity(opacity);};namespace("userSmarts.maps.editors");$namespace.LayerEditorInput=Class.create(userSmarts.ui.EditorInput);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.resource=new userSmarts.maps.pub.LayerResource({id:this.id,params:{format:"text/xml",mode:'edit'}});}
$prototype.equals=function(other){return this.id==other.id;};$prototype.get=function(){return this.resource.get();};$prototype.put=function(content){return this.resource.put(content);};$prototype.del=function(){this.resource.del();};namespace("userSmarts.maps.editors");$namespace.MultiPageLayerEditor=Class.create(userSmarts.ui.MultiPageEditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);};$prototype.init=function(site,input){userSmarts.ui.MultiPageEditorPart.prototype.init.call(this,site,input);connect(input,"loaded",this,this.onInputLoaded);input.load();};$prototype.createPages=function(){if(!this.hasPages()){var page=new userSmarts.maps.editors.LayerPageOne();this.addPage(page);page=new userSmarts.maps.editors.LayerPageTwo();this.addPage(page);page=new userSmarts.maps.editors.LayerPageThree();this.addPage(page);}};$prototype.doSave=function(){this.input.save();};$prototype.onInputLoaded=function(event){var success=event.newValue;if(success){if(!this.outer){this.createPartControl();}
this.createPages();this.outer.update();userSmarts.runtime.Platform.getPropertyService().setProperty("editor","initialized",this);}else{var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();page.closeEditor(this,false);userSmarts.runtime.Platform.getPropertyService().setProperty("users","deleted",null);}};$prototype.createPartControl=function(parent){if(!this.outer){this.outer=new userSmarts.wt.widgets.Composite({'class':'multi-editor',updateOnBoundsChange:true,layoutData:{width:'100%',height:'100%'}});this.outer.setLayout(new userSmarts.wt.layout.RowLayout({type:"vertical"}));this.createPageContainer();this.tabControl=new userSmarts.wt.widgets.Composite({parent:this.outer,"class":"btabs",layoutData:{width:"100%",height:'25px'}});}
return this.outer;};namespace("userSmarts.maps.editors");$namespace.MultiPageLayerEditorInput=Class.create(userSmarts.ui.EditorInput);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.resource=new userSmarts.maps.pub.LayerResource({id:this.id,params:{format:"text/xml",mode:'edit'}});this.errback=bind(function(arg){handleResponseError(arg);this.setProperty("loaded",false);},this);}
$prototype.equals=function(other){return this.url==other.url;};$prototype.get=function(){return this.resource.get();};$prototype.put=function(content){return this.resource.put(content);};$prototype.del=function(content){return this.resource.del(content);};$prototype.load=function(){var def=this.get();def.addCallback(bind(this.onInputLoaded,this));def.addErrback(this.errback);};$prototype.onInputLoaded=function(xml){this.entry=new userSmarts.maps.pub.LayerEntry({node:xml.documentElement});this.entry.getLayerName();this.entry.getTitle();this.entry.getQueryable();this.entry.getHidden();this.entry.getOpacity();this.entry.getProxied();this.entry.getSRS();this.entry.getSummary();this.entry.getKeywords();this.entry.getMetadataURL;this.entry.getServerTitle();this.entry.getService();this.entry.getVersion();this.entry.getOnlineResource();this.setProperty("loaded",true);};$prototype.doSave=function(){var def=this.put(this.entry.toXml());def.addCallback(bind(function(){this.dirty=false;alert("Layer saved!");},this));def.addErrback(bind(function(arg){handleResponseError(arg);userSmarts.runtime.Platform.getPropertyService().setProperty("layers","deleted",null);},this));};$prototype.getEntry=function(){return this.entry;};namespace("userSmarts.maps.editors");$namespace.LayerPageOne=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Details";this.listeners=[];this.opacityDT={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()};};$prototype.createPartControl=function(){if(!this.control){this.control=new userSmarts.wt.widgets.Control({'class':'user-editor'});this.entry=this.input.getEntry();}
if(this.entry)this.updateControl();return this.control;};$prototype.findPath=function(path){return userSmarts.runtime.Platform.find('com.usersmarts.rcp.sx.maps',path);};$prototype.updateControl=function(){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);}
if(!this.entry)return;this.changeListener=connect(this.entry,"*",this,this.onInputChange);var button;var node=this.control.getNode();replaceChildNodes(node,[]);var col1;var col2;var tbody=TBODY({});var table=TABLE({cellpadding:"3",cellPadding:"3",cellspacing:"0",cellSpacing:"0",border:"0",width:"100%"},tbody);node.appendChild(table);col1=TD({width:'75px','class':'editor-section-title'},"Details");col2=TD();tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Name: "));box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'layerName')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Title: "));box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'title')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Opacity: "));var min=this.opacityDT.facets.minInclusive;var max=this.opacityDT.facets.maxInclusive;var widget=new userSmarts.wt.widgets.Slider({min:this.opacityDT.facets.minInclusive,max:this.opacityDT.facets.maxInclusive,increment:this.opacityDT.facets.increment,value:Coerce.toDouble(this.entry.getOpacity(),1.0)});this.listeners.push(connect(widget,'onchange',this,this.onOpacityChange));this.opacityWidget=widget;col2.appendChild(widget.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"SRS: "));box=new userSmarts.wt.forms.Field({size:15,parent:null,binding:new BeanPropertyBinding(this.entry,'srs')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Abstract: "));box=new userSmarts.wt.forms.TextArea({rows:3,cols:30,parent:null,binding:new BeanPropertyBinding(this.entry,'summary')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({colSpan:'2',colspan:'2'});buttonLabel=SPAN({'class':'editor-section-text'},"Make Layer Visible");button=INPUT({type:'checkbox'});button.checked=button.defaultChecked=!this.entry.getHidden();this.listeners.push(connect(button,"onclick",this,this.onVisiblityStateChange));col1.appendChild(button);col1.appendChild(buttonLabel);tbody.appendChild(TR({},col1));col1=TD({colSpan:'2',colspan:'2'});buttonLabel=SPAN({'class':'editor-section-text'},"Make Layer Queryable");button=INPUT({type:'checkbox'});button.checked=button.defaultChecked=this.entry.getQueryable();this.listeners.push(connect(button,"onclick",this,this.onQueryableStateChange));col1.appendChild(button);col1.appendChild(buttonLabel);tbody.appendChild(TR({},col1));col1=TD({colSpan:'2',colspan:'2'});buttonLabel=SPAN({'class':'editor-section-text'},"Proxy Layer");button=INPUT({type:'checkbox'});button.checked=button.defaultChecked=this.entry.getProxied();this.listeners.push(connect(button,"onclick",this,this.onProxiedStateChange));col1.appendChild(button);col1.appendChild(buttonLabel);tbody.appendChild(TR({},col1));};$prototype.onInputChange=function(event){if(this.editable){this.setProperty("dirty",true);}
disconnect(this.changeListener);this.changeListener=null;};$prototype.doSave=function(){if(this.editable){this.input.doSave();}};$prototype.onVisiblityStateChange=function(event){this.entry.setHidden(!this.entry.getHidden());};$prototype.onQueryableStateChange=function(event){this.entry.setQueryable(!this.entry.getQueryable());};$prototype.onProxiedStateChange=function(event){this.entry.setProxied(!this.entry.getProxied());};$prototype.onOpacityChange=function(){var opacity=this.opacityDT.format.parseObject(this.opacityWidget.selected);this.entry.setOpacity(opacity);};$prototype.validateOpacity=function(event){var input=event.src();var value=input.value;if(!isNaN(value)){this.entry.setOpacity(value*1);}else{input.value=this.entry.getOpacity();}};$prototype.contributeToActionBars=function(tbmgr){if(userSmarts.sx!=undefined&&userSmarts.sx.Plugin!=undefined&&userSmarts.sx.Plugin.isUserInRole("EDIT_LAYER")){this.editable=true;this.saveAction=new userSmarts.wt.action.Action({id:'saveAction',text:'Save',toolTipText:'Save Changes',run:bind(this.doSave,this),image:"image.save"});tbmgr.add(this.saveAction);}else{this.editable=false;}};namespace("userSmarts.maps.editors");$namespace.LayerPageTwo=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Keywords";this.listeners=[];};$prototype.createPartControl=function(){if(!this.control){this.control=new userSmarts.wt.widgets.Control({'class':'user-editor'});this.entry=this.input.getEntry();}
if(this.entry)this.updateControl();return this.control;};$prototype.findPath=function(path){return userSmarts.runtime.Platform.find('com.usersmarts.rcp.sx.maps',path);};$prototype.updateControl=function(){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);}
if(!this.entry)return;var button;var node=this.control.getNode();replaceChildNodes(node,[]);var col1;var col2;var tbody=TBODY({});var table=TABLE({cellpadding:"1",cellPadding:"1",cellspacing:"0",cellSpacing:"0",border:"0",width:"100%"},tbody);node.appendChild(table);col1=TD({width:"250px",'class':'editor-section-title'},"Keywords");col2=TD({},"");tbody.appendChild(TR({},col1,col2));for(var i=0;i<this.entry.keywords.length;++i){col1=TD({width:"250px",valign:'top',vAlign:'top'});col2=TD({});input=INPUT();input.id="keyword-"+i;input.type="text";input.size=50;input.value=this.entry.keywords[i];col1.appendChild(input);button=BUTTON({},"Remove");this.listeners.push(connect(button,'onclick',this,this.removeKeyword));this.listeners.push(connect(input,'onchange',this,this.editKeyword));col2.appendChild(button);tbody.appendChild(TR({},col1,col2));}
col1=TD({colspan:'2',colSpan:'2'});button=BUTTON({},"Add");this.listeners.push(connect(button,'onclick',this,this.addKeyword));col1.appendChild(button);tbody.appendChild(TR({},col1));};$prototype.removeKeyword=function(event){var button=event.src();var input=button.previousSibling;var keyword=input.id.substring(input.id.length-1,input.id.length)*1;this.entry.keywords.splice(keyword,1);if(!this.dirty){this.setProperty("dirty",true);}
this.updateControl();};$prototype.editKeyword=function(event){var input=event.src();var keyword=input.id.substring(input.id.length-1,input.id.length)*1;var value=input.value;this.entry.keywords[keyword]=value;if(!this.dirty){this.setProperty("dirty",true);}}
$prototype.addKeyword=function(event){var keyword=prompt("Enter the new keyword:","");if(keyword){this.entry.keywords.push(keyword);if(!this.dirty){this.setProperty("dirty",true);}
this.updateControl();}};namespace("userSmarts.maps.editors");$namespace.LayerPageThree=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Server";this.listeners=[];};$prototype.createPartControl=function(){if(!this.control){this.control=new userSmarts.wt.widgets.Control({'class':'user-editor'});this.entry=this.input.getEntry();}
if(this.entry)this.updateControl();return this.control;};$prototype.findPath=function(path){return userSmarts.runtime.Platform.find('com.usersmarts.rcp.sx.maps',path);};$prototype.updateControl=function(){for(var i=0;i<this.listeners.length;++i){disconnect(this.listeners[i]);}
if(!this.entry)return;var button;var node=this.control.getNode();replaceChildNodes(node,[]);var col1;var col2;var tbody=TBODY({});var table=TABLE({cellpadding:"3",cellPadding:"3",cellspacing:"0",cellSpacing:"0",border:"0",width:"100%"},tbody);node.appendChild(table);col1=TD({width:"75px",'class':'editor-section-title'},"Server");col2=TD({},"");tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Title: "));box=new userSmarts.wt.forms.Field({size:50,parent:null,binding:new BeanPropertyBinding(this.entry,'serverTitle')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"Service: "));box=new userSmarts.wt.forms.Field({size:20,parent:null,binding:new BeanPropertyBinding(this.entry,'service')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));col1=TD({width:"75px",valign:'top',vAlign:'top'});col2=TD({});col1.appendChild(SPAN({'class':'editor-section-field-label'},"URL: "));box=new userSmarts.wt.forms.Field({size:100,parent:null,binding:new BeanPropertyBinding(this.entry,'onlineResource')});col2.appendChild(box.paint());tbody.appendChild(TR({},col1,col2));};namespace("userSmarts.maps.editors");$namespace.MapEditor=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superClass,desc){superClass.call(this,desc);setdefault(this,{width:650,height:425,timeout:3000,toolbar:true,layerbar:false,location:true,scale:true,imageBase:""});};$prototype.init=function(site,input){userSmarts.ui.EditorPart.prototype.init.call(this,site,input);site.setPropertyProvider(this);this.parseCallback=bind(this.parseMap,this);this.errback=bind(function(arg){handleResponseError(arg);var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();page.closeEditor(this,false);userSmarts.runtime.Platform.getPropertyService().setProperty("maps","deleted",null);},this);this.setupListeners();this.setupMap(input);this.contributeToActionBars();};$prototype.dispose=function(){if(this.ctxChangeListener){disconnect(this.ctxChangeListener);this.ctxChangeListener=null;}
if(this.contextListener){disconnect(this.contextListener);this.contextListener=null;}
if(this.viewListener){disconnect(this.viewListener);this.viewListener=null;}
if(this.locationListener){disconnect(this.locationListener);this.locationListener=null;}
this.vcmodel=null;this.legendModel=null;this.parseCallback=null;this.errback=null;this.map.dispose();userSmarts.ui.EditorPart.prototype.dispose.call(this);}
$prototype.setupListeners=function(){this.ctxChangeListener=connect(this,"context",this,this.onContextChange);var ctx=userSmarts.maps.Plugin.getDefault().bundle.getBundleContext();this.tracker=new userSmarts.service.ServiceTracker(ctx,"userSmarts.maps.context.Layer",function(event){var l=event.getReference().getService();return(l instanceof userSmarts.maps.context.Layer);},this);this.tracker.open();};$prototype.addingService=function(reference){var layer=reference.getService();this.context.addLayer(layer);return layer;};$prototype.modifiedService=function(reference,service){this.context.setView(this.context.getView());};$prototype.removedService=function(reference,service){var layer=service;this.context.removeLayer(layer);};$prototype.onContextChange=function(event){var context=this.context;if(!context||!(context instanceof userSmarts.maps.context.ViewContext)){alert("Invalid context being set");return;}
context.width=this.width;context.height=this.height;if(this.contextListener){disconnect(this.contextListener);}
this.contextListener=connect(context,userSmarts.maps.context.ViewContext.CHANGE_EVENT_PROPERTY,this,this.onContextModified);if(this.viewListener){disconnect(this.viewListener);}
this.viewListener=connect(context,userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this,this.onViewModified);var ctx=userSmarts.maps.Plugin.getDefault().bundle.getBundleContext();var layerRefs=ctx.getServiceReferences("userSmarts.maps.context.Layer");for(var i=0;i<layerRefs.length;++i){context.addLayer(layerRefs[i].getService());}
this.map.setContext(context);if(this.vcmodel){this.vcmodel.setProperty('context',context);}
this.onViewModified(null);};$prototype.onContextModified=function(event){this.setProperty("contextModified",this.context);};$prototype.onViewModified=function(event){var aoi=this.context.getView();this.setProperty("aoi",aoi);};$prototype.setupMap=function(input){this.map=this.buildMap();var def=input.get();def.addCallback(this.parseCallback);def.addErrback(this.errback);};$prototype.parseMap=function(xml){var parser=new userSmarts.maps.context.ViewContextParser();var context=parser.fromXML(xml);if(!context.id&&this.input){context.id=this.input.id;}
if(!this.context){this.setProperty("aoi",context.getView());}
this.setProperty("context",context);};$prototype.createPartControl=function(){if(!this.control){var div=DIV({'class':'map-holder'});div.style.overflow="hidden";if(this.map instanceof userSmarts.maps.widget.Widget){div.appendChild(this.map.paint());}
this.control=new userSmarts.maps.widget.MapControl({adapter:this,node:div});}
return this.control;};$prototype.populateMapToolbar=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();if(this.toolbar){var toolFactory=new ToolIconFactory(this.imageBase);var toolbarModel=new userSmarts.maps.widget.ToolBarModel({factory:toolFactory});this.map.register('toolbar-model',toolbarModel);var tool;tool=new userSmarts.maps.tools.DragTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomToBoxTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.MeasureTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));}};$prototype.contributeToActionBars=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();this.populateMapToolbar();var saveContextAction=new userSmarts.wt.action.Action({id:'saveMapAction',text:'Save Map',toolTipText:'Save Map',run:bind(this.saveContext,this),image:"image.save"});if(userSmarts.workspaces.Plugin!=undefined){if(userSmarts.workspaces.Plugin.isUserInRole("EDIT_MAP")){tbmgr.add(saveContextAction);mbmgr.add(saveContextAction);}}else{tbmgr.add(saveContextAction);mbmgr.add(saveContextAction);}
if(this.location){this.location.paint();this.location.hide();this.locationListener=connect(this.location,'location',this,this.onLocationChange);}};$prototype.onLocationChange=function(event){var actionbars=this.getSite().getActionBars();var slmgr=actionbars.getStatusLineManager();var value=event.newValue;slmgr.setMessage(value);};$prototype.resizeMap=function(width,height){if(!this.map)return;var ctxmgr=this.map.locate('context-mgr');if(ctxmgr){this.map.unregister('context-mgr');}
var tbmodel=this.map.locate('toolbar-model');if(tbmodel){var tools=tbmodel.getTools();var numTools=tools.length;for(var i=0;i<numTools;i++){tools[i].setProperty("enabled",false);}
this.map.unregister('toolbar-model');}
if(typeof(this.location)=='object'){this.map.unregister('location-bar');}
var layerbar=this.map.locate('layer-control');if(layerbar){this.map.unregister('layer-control');}
this.map.dispose();this.map=null;this.map=this.buildMap(width,height);if(tbmodel)this.map.register('toolbar-model',tbmodel);if(ctxmgr)this.map.register('context-mgr',ctxmgr);if(layerbar)this.map.register('layer-control',layerbar);if(typeof(this.location)=='object')this.map.register('location-bar',this.location);if(typeof(this.context)=='object'){this.map.setContext(this.context);this.onViewModified(null);}
if(this.legendModel){this.legendModel.populate(0);}};$prototype.buildMap=function(width,height){if(width){this.width=width;}
if(height){this.height=height;}
var widget=userSmarts.maps.widget.Manager.createMap({id:"main",showScale:true,debug:false,timeout:this.timeout,width:this.width,height:this.height});if(this.control){replaceChildNodes(this.control.getNode(),widget.paint());}
if(this.location&&typeof(this.location)!='object'){this.location=new userSmarts.maps.widget.LocationBar();widget.register('location-bar',this.location);}
return widget;};$prototype.saveContext=function(){var context=this.map.context;var id=this.map.context.id;var title=this.map.context.title;var xml=this.map.context.toXml();var def=this.input.put(xml);def.addErrback(this.errback);var actionbars=this.getSite().getActionBars();var slmgr=actionbars.getStatusLineManager();slmgr.setMessage("Map saved");var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("maps","updated",{id:id,url:this.input.resource.url,label:this.input.name});};$prototype.getViewContextModel=function(){if(!this.vcmodel){this.vcmodel=new userSmarts.maps.models.ViewContextTableModel({context:this.context});}
return this.vcmodel;};$prototype.getLegendModel=function(){if(!this.legendModel){this.legendModel=new userSmarts.maps.models.LegendModel({adapter:this});this.legendModel.populate(0);}
return this.legendModel;};$prototype.getMap=function(){return this.map;};$prototype.onMapUpdatedExternally=function(event){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("maps","updated");if(selection&&selection.url&&selection.label){if(this.input&&this.input.resource&&selection.label!=this.input.name){if(selection.url==this.input.resource.url){this.input.get().addCallback(this.parseCallback);}}}};namespace("userSmarts.maps.editors");$namespace.PrimaryMapEditor=Class.create(userSmarts.maps.editors.MapEditor);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{closeable:false});superClass.call(this,properties);};$prototype.init=function(site,input){userSmarts.maps.editors.MapEditor.prototype.init.call(this,site,input);};$prototype.contributeToActionBars=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();this.populateMapToolbar();mbmgr.add(new userSmarts.maps.actions.ResetAOIAction());mbmgr.add(new userSmarts.maps.actions.SaveMapAsAction());if(this.location){this.location.paint();this.location.hide();this.locationListener=connect(this.location,'location',this,this.onLocationChange);}};$prototype.populateMapToolbar=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();if(this.toolbar){var toolFactory=new ToolIconFactory(this.imageBase);var toolbarModel=new userSmarts.maps.widget.ToolBarModel({factory:toolFactory});this.map.register('toolbar-model',toolbarModel);var tool;tool=new userSmarts.maps.tools.DragTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomToBoxTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.MeasureTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));}};namespace("userSmarts.maps.editors");$namespace.MapEditorInput=Class.create(userSmarts.ui.EditorInput);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{});userSmarts.ui.EditorInput.call(this,properties);this.resource=new userSmarts.pub.Resource({url:this.url,params:{format:"text/xml"}});}
$prototype.equals=function(other){var result=false;result=this.url==other.url;if(result){result=this.name==other.getName();}
return result;};$prototype.get=function(){return this.resource.get();};$prototype.put=function(content){return this.resource.put(content);};$prototype.del=function(content){return this.resource.del(content);};namespace("userSmarts.maps.editors");$namespace.MultiPageMapEditor=Class.create(userSmarts.ui.MultiPageEditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);};$prototype.init=function(site,input){userSmarts.ui.MultiPageEditorPart.prototype.init.call(this,site,input);connect(input,"loaded",this,this.onInputLoaded);input.load();};$prototype.createPages=function(){if(!this.hasPages()){var page=new userSmarts.maps.editors.MapPageOne();this.addPage(page);page=new userSmarts.maps.editors.MapPageTwo();this.addPage(page);page=new userSmarts.maps.editors.MapPageThree();this.addPage(page);}};$prototype.doSave=function(){this.input.save();};$prototype.onInputLoaded=function(event){var success=event.newValue;if(success){if(!this.outer){this.createPartControl();}
this.createPages();this.outer.update();userSmarts.runtime.Platform.getPropertyService().setProperty("editor","initialized",this);}else{var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();page.closeEditor(this,false);userSmarts.runtime.Platform.getPropertyService().setProperty("users","deleted",null);}};$prototype.createPartControl=function(parent){if(!this.outer){this.outer=new userSmarts.wt.widgets.Composite({'class':'multi-editor',updateOnBoundsChange:true,layoutData:{width:'100%',height:'100%'}});this.outer.setLayout(new userSmarts.wt.layout.RowLayout({type:"vertical"}));this.createPageContainer();this.tabControl=new userSmarts.wt.widgets.Composite({parent:this.outer,"class":"btabs",layoutData:{width:"100%",height:'25px'}});}
return this.outer;};$prototype.getViewContext=function(){return this.input.getViewContext();};$prototype.getProperty=function(propertyName){if(propertyName=="context"){return this.getViewContext();}else{userSmarts.ui.MultiPageEditorPart.prototype.getProperty.call(this,propertyName);}};namespace("userSmarts.maps.editors");$namespace.MultiPageMapEditorInput=Class.create(userSmarts.ui.EditorInput);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);this.resource=new userSmarts.pub.Resource({url:this.url,params:{format:"text/xml"}});this.errback=bind(function(arg){handleResponseError(arg);this.setProperty("loaded",false);userSmarts.runtime.Platform.getPropertyService().setProperty("maps","deleted",null);},this);}
$prototype.equals=function(other){return this.url==other.url;};$prototype.get=function(){return this.resource.get();};$prototype.put=function(content){return this.resource.put(content);};$prototype.del=function(content){return this.resource.del(content);};$prototype.load=function(){var def=this.get();def.addCallback(bind(this.onInputLoaded,this));def.addErrback(this.errback);};$prototype.onInputLoaded=function(xml){var parser=new userSmarts.maps.context.ViewContextParser();var context=parser.fromXML(xml);if(!context.id){context.id=id;}
this.viewContext=context;this.viewListener=connect(context,userSmarts.maps.context.ViewContext.VIEW_CHANGE_EVENT_PROPERTY,this,this.onViewModified);this.onViewModified(null);this.setProperty("loaded",true);};$prototype.onViewModified=function(event){var aoi=this.getViewContext().getView();this.setProperty("aoi",aoi);};$prototype.doSave=function(){var def=this.put(this.entry.toXml());def.addCallback(bind(function(){this.dirty=false;alert("Map saved!");},this));def.addErrback(bind(function(arg){handleResponseError(arg);userSmarts.runtime.Platform.getPropertyService().setProperty("maps","deleted",null);},this));};$prototype.getViewContext=function(){return this.viewContext;};$prototype.setViewContext=function(context){this.viewContext=context;};$prototype.getMap=function(){return this.map;};$prototype.setMap=function(map){this.map=map;};$prototype.getViewContextModel=function(){if(!this.viewContextModel){this.viewContextModel=new userSmarts.maps.models.ViewContextTableModel({context:this.getViewContext()});}
return this.viewContextModel;};$prototype.getLegendModel=function(){if(!this.legendModel){this.legendModel=new userSmarts.maps.models.LegendModel({adapter:this});this.legendModel.populate(0);}
return this.legendModel;};namespace("userSmarts.maps.editors");$namespace.MapPageOne=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Map";};$prototype.createPartControl=function(){if(!this.control){var div=DIV({'class':'map-holder'});div.style.overflow="hidden";this.control=new userSmarts.maps.widget.MapControl({adapter:this,node:div,label:this.label});if(this.input){var map=this.buildMap(600,500);this.map=map;this.context=this.input.getViewContext();map.setContext(this.context);}}
return this.control;};$prototype.populateMapToolbar=function(){var actionbars=this.getSite().getActionBars();var tbmgr=actionbars.getToolbarManager();var mbmgr=actionbars.getMenuBarManager();if(this.toolbar){var toolFactory=new ToolIconFactory(this.imageBase);var toolbarModel=new userSmarts.maps.widget.ToolBarModel({factory:toolFactory});this.map.register('toolbar-model',toolbarModel);var tool;tool=new userSmarts.maps.tools.DragTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.ZoomToBoxTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));tool=new userSmarts.maps.tools.MeasureTool({factory:toolFactory,debug:this.debug});toolbarModel.addTool(tool);tbmgr.add(new userSmarts.maps.widget.ToolContributionItem({tool:tool}));}};$prototype.onLocationChange=function(event){var actionbars=this.getSite().getActionBars();var slmgr=actionbars.getStatusLineManager();var value=event.newValue;slmgr.setMessage(value);};$prototype.getMap=function(){return this.map;};$prototype.getViewContext=function(){return this.input.getViewContext();};$prototype.resizeMap=function(width,height){if(!this.map)return;var ctxmgr=this.map.locate('context-mgr');if(ctxmgr){this.map.unregister('context-mgr');}
var tbmodel=this.map.locate('toolbar-model');if(tbmodel){var tools=tbmodel.getTools();var numTools=tools.length;for(var i=0;i<numTools;i++){tools[i].setProperty("enabled",false);}
this.map.unregister('toolbar-model');}
if(typeof(this.location)=='object'){this.map.unregister('location-bar');}
var layerbar=this.map.locate('layer-control');if(layerbar){this.map.unregister('layer-control');}
this.map.dispose();this.map=null;this.map=this.buildMap(width,height);if(tbmodel)this.map.register('toolbar-model',tbmodel);if(ctxmgr)this.map.register('context-mgr',ctxmgr);if(layerbar)this.map.register('layer-control',layerbar);if(typeof(this.location)=='object')this.map.register('location-bar',this.location);if(typeof(this.context)=='object'){this.map.setContext(this.context);this.input.onViewModified(null);}
if(this.legendModel){this.legendModel.populate(0);}};$prototype.buildMap=function(width,height){if(width){this.width=width;}
if(height){this.height=height;}
var widget=userSmarts.maps.widget.Manager.createMap({id:"main",showScale:true,debug:false,timeout:this.timeout,width:this.width,height:this.height});this.input.setMap(widget);if(this.control){replaceChildNodes(this.control.getNode(),widget.paint());}
if(this.location&&typeof(this.location)!='object'){this.location=new userSmarts.maps.widget.LocationBar();widget.register('location-bar',this.location);}
return widget;};namespace("userSmarts.maps.editors");$namespace.MapPageTwo=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Layers";this.table=new userSmarts.wt.widgets.Table({model:this.model,showFooter:false});connect(this.table,"selected",this,this.selectLayer);this.updateCheck=bind(this.checkIfUpdated,this);if(this.autoRefresh){if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.createPartControl=function(){if(!this.model){this.model=this.input.getViewContextModel();this.table.setProperty("model",this.model);}
return this.table;};$prototype.contributeToActionBars=function(tbmgr){var removeAction=bind(function(){if(this.selected){var layer=this.selected;var ok=userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Layer?","Are you sure you want to delete the selected layer? ('"+
layer.getLayerName()+"')");if(ok){var context=this.getViewContext();if(context){context.removeLayer(layer);this.setProperty("selected",null);}}}else{alert("You must select a layer before attempting to delete one!");}},this);var selectAllAction=bind(function(){for(var i=0;i<this.table.model.context.layers.length;i++){this.table.model.context.layers[i].visible=true;}
var context=this.getViewContext();if(context)context.touch();},this);var unSelectAllAction=bind(function(){for(var i=0;i<this.table.model.context.layers.length;i++){this.table.model.context.layers[i].visible=false;}
var context=this.getViewContext();if(context)context.touch();},this);tbmgr.add(new userSmarts.wt.action.Action({id:'refreshAction',text:'Refresh',toolTipText:'Refresh the map',run:bind(function(){var context=this.getViewContext();if(context)context.touch();},this),image:"image.refresh"}));tbmgr.add(new userSmarts.wt.action.StatefulAction({id:'autoRefreshAction',text:'Auto Ref',toolTipText:'Automatically Refresh Map',checked:true,run:bind(function(){this.toggleAutoRefresh();},this),image:"image.refresh.auto"}));tbmgr.add(new userSmarts.wt.action.Action({id:'topAction',text:'Shift Top',toolTipText:'Shift selected layer to top',run:bind(function(){this.moveLayer(-1,true);},this),image:"image.layer.shift.top"}));tbmgr.add(new userSmarts.wt.action.Action({id:'botAction',text:'Shift Bot',toolTipText:'Shift selected layer to bottom',run:bind(function(){this.moveLayer(1,true);},this),image:"image.layer.shift.bottom"}));tbmgr.add(new userSmarts.wt.action.Action({id:'upAction',text:'Shift Up',toolTipText:'Shift selected layer up',run:bind(function(){this.moveLayer(-1,false);},this),image:"image.layer.shift.up"}));tbmgr.add(new userSmarts.wt.action.Action({id:'downAction',text:'Shift Down',toolTipText:'Shift selected layer down',run:bind(function(){this.moveLayer(1,false);},this),image:"image.layer.shift.down"}));var selAllAction=new userSmarts.wt.action.Action({id:'selectAllAction',toolTipText:'Make all layers visible',run:selectAllAction,image:"image.layer.check"});tbmgr.add(selAllAction);var unSelAllAction=new userSmarts.wt.action.Action({id:'unSelectAllAction',toolTipText:'Make all layers hidden',run:unSelectAllAction,image:"image.layer.uncheck"});tbmgr.add(unSelAllAction);var remAction=new userSmarts.wt.action.Action({id:'removeAction',toolTipText:'Remove selected layer',run:removeAction,image:"image.layer.delete"});tbmgr.add(remAction);};$prototype.selectLayer=function(event){this.setProperty("selected",event.newValue);};$prototype.moveLayer=function(direction,allTheWay){var context=this.getViewContext();if(!context){return;}
var layer=this.selected;if(!layer){return;}
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.table.model.populate(0);this.updatesPending=true;};$prototype.toggleAutoRefresh=function(){if(typeof(this.autoRefresh)=="undefined")
this.autoRefresh=false;this.autoRefresh=!this.autoRefresh;if(this.autoRefresh){if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh enabled");}
this.checkIfUpdated();}else{if(this.timeoutFunc){clearTimeout(this.timeoutFunc);}
if(userSmarts.maps.DEBUG_FLAG){logDebug("LayerBar auto-refresh disabled");}}};$prototype.checkIfUpdated=function(){if(this.updatesPending){var context=this.getViewContext();if(context){context.touch();}
this.updatesPending=false;}
if(this.autoRefresh){var check=this.updateCheck;this.timeoutFunc=setTimeout(check,this.timeout);}};$prototype.getViewContext=function(){return this.input.getViewContext();};namespace("userSmarts.maps.editors");$namespace.MapPageThree=Class.create(userSmarts.ui.EditorPart);$prototype.initialize=function(superclass,properties){superclass.call(this,properties);this.label="Legend";this.table=new userSmarts.wt.widgets.Table({'class':'legend-view',showFooter:false});};$prototype.createPartControl=function(){if(!this.model){this.model=this.input.getLegendModel();this.table.setProperty("model",this.model);}
return this.table;};$prototype.contributeToActionBars=function(tbmgr){};$prototype.updateLegend=function(){if(this.table.model){this.table.model.populate(0);}};namespace("userSmarts.maps.actions");namespace("userSmarts.maps.actions");namespace("userSmarts.maps.actions");$namespace.NewMapAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'newMapAction',text:"New Map",toolTipText:'Create New Map',image:"image.map.new"});superClass.call(this,properties);this.run=this.runMethod;};$prototype.runMethod=function(){var ws=userSmarts.runtime.Platform.getWorkspace();var defMapLink=ws.getLink("defaultMap");if(defMapLink){var url=defMapLink.href;if(url){var res=new userSmarts.pub.Resource({url:url});var def=res.get();def.addCallback(bind(this.onMapRetrieved,this));}}};$prototype.onMapRetrieved=function(xml){var parser=new userSmarts.maps.context.ViewContextParser();var context=parser.fromXML(xml);var dialog=new userSmarts.maps.dialogs.EditMapInfoDialog({map:context});var def=dialog.open();def.addCallback(bind(this.onInfoEdited,this,dialog));};$prototype.onInfoEdited=function(dialog,okPressed){if(!okPressed)return;var ws=userSmarts.runtime.Platform.getWorkspace();var mapLink=ws.getLink("maps");if(mapLink){var context=dialog.getMap();var content=context.toXml();setNodeAttribute(content,"collectionId",ws.id);var id=context.id;var url=mapLink.href;var res=new userSmarts.pub.Resource({url:url});var def=res.post(content);def.addCallback(bind(this.onMapCreated,this));def.addErrback(handleResponseError);}else{alert("No map collections specified for the current workspace!");}};$prototype.onMapCreated=function(xml){var root=xml.responseXML.documentElement;var id=getNodeAttribute(root,"id");userSmarts.runtime.Platform.getPropertyService().setProperty("maps","created",id);};namespace("userSmarts.maps.actions");$namespace.EditMapAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'editMapAction',text:"View Map",toolTipText:'View Selected Map',image:"image.map.edit",editable:true});superClass.call(this,properties);};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("maps","selected");if(selection&&selection.url){var label=selection.label||selection.id;if(label.length>10){label=label.substring(0,10)+"...";}
var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var input=new userSmarts.maps.editors.MapEditorInput({name:label,url:selection.url});page.openEditor(input,"userSmarts.maps.editors.MapEditor",true);}else{alert("No Map Selected!");}};namespace("userSmarts.maps.actions");$namespace.OpenKmlAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'OpenKmlAction',text:"Download KML",toolTipText:'View Selected Map as KML',image:"image.map.kml",editable:true});superClass.call(this,properties);this.run=this.runMethod;};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("maps","selected");if(selection&&selection.url){var label=selection.label||selection.id;if(label.length>10){label=label.substring(0,10)+"...";}
var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var href=selection.url.replace(".atom",".kml");window.open(href);}else{alert("No Map Selected!");}};namespace("userSmarts.maps.actions");$namespace.SaveMapAsAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'saveMapAsAction',text:"Save As",toolTipText:'Save Map As...',image:"image.save.as"});superClass.call(this,properties);this.run=this.runMethod;};$prototype.runMethod=function(){var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var activeEditor=page.getActiveEditor();if(activeEditor&&activeEditor instanceof userSmarts.maps.editors.MapEditor){var context=activeEditor.getProperty("context");var dialog=new userSmarts.maps.dialogs.EditMapInfoDialog({map:context});var def=dialog.open();def.addCallback(bind(this.onInfoEdited,this,dialog));}};$prototype.onInfoEdited=function(dialog,okPressed){if(!okPressed)return;var ws=userSmarts.runtime.Platform.getWorkspace();var mapLink=ws.getLink("maps");if(mapLink){var context=dialog.getMap();var content=context.toXml();setNodeAttribute(content,"collectionId",ws.id);var url=mapLink.href;var res=new userSmarts.pub.Resource({url:url});var def=res.post(content);def.addCallback(bind(this.onMapCreated,this));def.addErrback(handleResponseError);}else{alert("No map collections specified for the current workspace!");}};$prototype.onMapCreated=function(xml){var root=xml.responseXML.documentElement;var id=getNodeAttribute(root,"id");userSmarts.runtime.Platform.getPropertyService().setProperty("maps","created",id);};namespace("userSmarts.maps.actions");$namespace.DeleteMapAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'deleteMapAction',text:"Delete Map",toolTipText:'Delete Selected Map',image:"image.map.delete"});superClass.call(this,properties);};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("maps","selected");if(selection&&selection.url){var label=selection.label||selection.id||"[map]";if(userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Map","Are you sure you want to delete '"+label+"'?")){var res=new userSmarts.pub.Resource({url:selection.url});var def=res.del();def.addCallback(bind(this.onMapDeleted,this));def.addErrback(handleResponseError);}}else{alert("Must select a map to delete first!");}};$prototype.onMapDeleted=function(){var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("maps","deleted",null);ps.setProperty("maps","selected",null);};namespace("userSmarts.maps.actions");$namespace.ResetAOIAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'resetAOIAction',text:"Reset AOI",toolTipText:'Reset map to workspace aoi',image:"image.map.aoi.reset"});superClass.call(this,properties);this.run=this.runMethod;};$prototype.runMethod=function(){var ws=userSmarts.runtime.Platform.getWorkspace();var aoi=ws.aoi;var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var refs=page.getEditorReferences();var editor;for(var i=0;i<refs.length;++i){editor=refs[i].getEditor();if(editor instanceof userSmarts.maps.editors.PrimaryMapEditor){editor.getProperty("context").setView(aoi);break;}}};namespace("userSmarts.maps.actions");$namespace.NewLayerAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'newLayerAction',text:"New Layer",toolTipText:'New Layer',image:"image.layer.new"});superClass.call(this,properties);};$prototype.run=function(){var title=prompt("Enter the new layer's title:","New Layer")||"New Layer";var entry=new userSmarts.maps.pub.LayerEntry();entry.setLayerName("MyNewLayer");entry.setTitle(title);entry.setSRS("EPSG:4326");entry.setSummary("A New Layer");entry.setKeywords(["Sample Keyword"]);entry.setQueryable(false);entry.setHidden(true);entry.setOpacity(1.0);entry.setMetadataURL("metadata url");var bbox=new Geometry("Box");bbox.addPoint(new Point(-125,20));bbox.addPoint(new Point(-66,60));entry.setBoundingBox(bbox);entry.setServerTitle("New Server");entry.setService("WMS");entry.setVersion("1.1.1");entry.setOnlineResource("server url");var content=entry.toXml();var res=new userSmarts.pub.Resource({url:"pub/layers.atom",params:{mode:'edit'}});var def=res.post(content);def.addCallback(bind(this.onLayerCreated,this));def.addErrback(handleResponseError);};$prototype.onLayerCreated=function(xml){var entry=new userSmarts.maps.pub.LayerEntry({node:xml.responseXML.documentElement});var id=entry.getLayerId();var label=entry.getTitle();if(label.length>10){label=label.substring(0,10)+"...";}
var page=userSmarts.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();var input=new userSmarts.maps.editors.LayerEditorInput({name:label,id:id});page.openEditor(input,"userSmarts.maps.editors.LayerEditor",true);userSmarts.runtime.Platform.getPropertyService().setProperty("layers","created",id);};namespace("userSmarts.maps.actions");$namespace.EditLayerAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'editLayerAction',text:"Edit Layer",toolTipText:'Edit Selected Layer',image:"image.layer.edit"});superClass.call(this,properties);};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("layers","selected");if(selection&&selection.id){var label=selection.label||selection.id;if(label.length>10){label=label.substring(0,10)+"...";}
var wb=userSmarts.ui.PlatformUI.getWorkbench();var page=wb.getActiveWorkbenchWindow().getActivePage();var input=new userSmarts.maps.editors.LayerEditorInput({name:label,id:selection.id});page.openEditor(input,"userSmarts.maps.editors.LayerEditor",true);}};namespace("userSmarts.maps.actions");$namespace.DeleteLayerAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'deleteLayerAction',text:"Delete Layer",toolTipText:'Delete Selected Layer',image:"image.layer.delete"});superClass.call(this,properties);};$prototype.run=function(){var ps=userSmarts.runtime.Platform.getPropertyService();var selection=ps.getProperty("layers","selected");if(selection&&selection.id){var label=selection.label||selection.id;if(userSmarts.wt.dialogs.MessageDialog.openConfirm("Delete Layer","Are you sure you want to delete '"+label+"'?")){var res=new userSmarts.maps.pub.LayerResource({id:selection.id});var def=res.del();def.addCallback(bind(this.onLayerDeleted,this));def.addErrback(handleResponseError);}}else{alert("Must select a layer first!");}};$prototype.onLayerDeleted=function(){var ps=userSmarts.runtime.Platform.getPropertyService();ps.setProperty("layers","deleted",null);ps.setProperty("layers","selected",null);};namespace("userSmarts.maps.actions");$namespace.AddLayerAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'addLayerAction',text:"Add to Map",toolTipText:'Add Selected Layer to Current Map',image:"image.layer.add"});superClass.call(this,properties);this.callback=bind(this.onLayerRetrieved,this);this.errback=handleResponseError;};$prototype.run=function(){var wb=userSmarts.ui.PlatformUI.getWorkbench();var page=wb.getActiveWorkbenchWindow().getActivePage();var view=page.findView("userSmarts.maps.views.LayersListView");if(view){var selection=view.selected;if(selection){var res=new userSmarts.maps.pub.LayerResource({id:selection});var def=res.get();def.addCallback(this.callback);def.addErrback(this.errback);}}};$prototype.onLayerRetrieved=function(xml){var parser=new userSmarts.maps.context.ViewContextParser();var layer=parser.readLayerInformation(xml.documentElement);this.addLayerToActiveEditor(layer);};$prototype.addLayerToActiveEditor=function(layer){var wb=userSmarts.ui.PlatformUI.getWorkbench();var page=wb.getActiveWorkbenchWindow().getActivePage();var editor=page.getActiveEditor();if(editor){var context=editor.context;if(!context){if(typeof(editor.getViewContext)=="function"){context=editor.getViewContext();}}
if(context&&context instanceof userSmarts.maps.context.ViewContext){context.addLayer(layer);}else{alert("Could not add selected layer to the current map,\n"+"possibly because it already exists!");}}else{alert("Layers may only be added to a map.\n"+"Make sure a map is visible before adding additional layers!");}};namespace("userSmarts.maps.actions");$namespace.ConstrainLayersAction=Class.create(userSmarts.wt.action.Action);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{id:'constrainLayersAction',text:"Constrain",toolTipText:'Constrain layers using keywords',image:"image.layer.constrain"});superClass.call(this,properties);};$prototype.run=function(){if(this.model){var keywords=this.model.getKeywords();var keystr=keywords.toString()||"";keystr=prompt("Enter additional keywords separated by commas (',')."+"\nWildcards ('*' and '?') may also be used.",keystr);if(keystr){keys=keystr.split(",");}else{keys=[];}
this.model.setKeywords(keys);}else{logWarning("No model configured for ConstrainLayersAction");}};namespace("userSmarts.maps.dialogs");namespace("userSmarts.maps.dialogs");$namespace.EditMapInfoDialog=Class.create(userSmarts.wt.dialogs.Dialog);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{modal:false,width:350,height:350,title:"Edit Map Information",description:"Edit the following information about the map:"});superClass.call(this,properties);};$prototype.createDialogArea=function(parent){if(!this.map)return DIV();var intFormat=new IntegerFormat();var floatFormat=new FloatFormat();parent.appendChild(DIV({},this.description))
parent.appendChild(BR());parent.appendChild(B({},"Title: "));parent.appendChild(BR());var box=new userSmarts.wt.forms.Field({size:45,parent:null,binding:new BeanPropertyBinding(this.map,'title')});this.titleBox=box;parent.appendChild(box.paint());parent.appendChild(BR());parent.appendChild(BR());parent.appendChild(B({},"Abstract: "));parent.appendChild(BR());box=new userSmarts.wt.forms.TextArea({rows:3,cols:50,parent:this,binding:new BeanPropertyBinding(this.map,'abstr')});parent.appendChild(box.paint());parent.appendChild(BR());parent.appendChild(BR());parent.appendChild(B({},"Width: "));box=new userSmarts.wt.forms.Field({size:7,parent:this,format:intFormat,binding:new BeanPropertyBinding(this.map,'width')});parent.appendChild(box.paint());parent.appendChild(B({}," Height: "));box=new userSmarts.wt.forms.Field({size:7,parent:this,format:intFormat,binding:new BeanPropertyBinding(this.map,'width')});parent.appendChild(box.paint());parent.appendChild(BR());parent.appendChild(BR());var bboxDIV=DIV({});bboxDIV.style.width="100%";bboxDIV.style.textAlign="center";parent.appendChild(bboxDIV);bboxDIV.appendChild(B({},"North"));box=new userSmarts.wt.forms.Field({size:15,parent:this,format:floatFormat,binding:new BeanPropertyBinding(this.map.boundingBox,'maxY')});bboxDIV.appendChild(box.paint());bboxDIV.appendChild(BR());bboxDIV.appendChild(B({},"West: "));box=new userSmarts.wt.forms.Field({size:15,parent:this,format:floatFormat,binding:new BeanPropertyBinding(this.map.boundingBox,'minX')});bboxDIV.appendChild(box.paint());bboxDIV.appendChild(B({}," East: "));box=new userSmarts.wt.forms.Field({size:15,parent:this,format:floatFormat,binding:new BeanPropertyBinding(this.map.boundingBox,'maxX')});bboxDIV.appendChild(box.paint());bboxDIV.appendChild(BR());bboxDIV.appendChild(B({},"South: "));box=new userSmarts.wt.forms.Field({size:15,parent:this,format:floatFormat,binding:new BeanPropertyBinding(this.map.boundingBox,'minY')});bboxDIV.appendChild(box.paint());};$prototype.getMap=function(){return this.map;};$prototype.focus=function(){if(this.titleBox){this.titleBox.focus();}};$prototype.validate=function(){var result=(this.testIsNumber(this.map.width)&&this.testInRange(this.map.width,0,null)&&this.testIsNumber(this.map.height)&&this.testInRange(this.map.height,0,null)&&this.testIsNumber(this.map.boundingBox.minX)&&this.testInRange(this.map.boundingBox.minX,-180,180)&&this.testIsNumber(this.map.boundingBox.maxX)&&this.testInRange(this.map.boundingBox.maxX,this.map.boundingBox.minX,180)&&this.testIsNumber(this.map.boundingBox.minY)&&this.testInRange(this.map.boundingBox.minY,-90,90)&&this.testIsNumber(this.map.boundingBox.maxY)&&this.testInRange(this.map.boundingBox.maxY,this.map.boundingBox.minY,90));var okButton=this.getOKButton();if(!result){okButton.disabled=true;}else{okButton.disabled=false;}};$prototype.testIsNumber=function(value){var result=false;value=value*1;if(!isNaN(value)){result=true;}
return result;};$prototype.testInRange=function(value,lower,upper){var result=true;value=value*1;result=!(lower&&value<lower);result=!(upper&&value>upper);return result;};namespace("userSmarts.maps.pub");namespace("userSmarts.maps.pub");namespace("userSmarts.maps.pub");$namespace.LayerEntry=Class.create(userSmarts.pub.atom.Entry);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{});superClass.call(this,properties);connect(this,"keywords",this,this.onKeywordsChanged);};$prototype.onKeywordsChanged=function(event){this.setKeywords(this.keywords);};$prototype.getLayer=function(){var parser=new userSmarts.maps.context.ViewContextParser();var layer=parser.readLayerInformation(this.node);layer.lid=this.getLayerId();this.setLayer(layer);return layer;};$prototype.setLayer=function(layer){if(layer instanceof userSmarts.maps.context.Layer){this.setLayerId(layer.lid||"");this.setLayerName(layer.getLayerId());this.setTitle(layer.getLayerName());this.setOpacity(layer.opacity);this.setHidden(!layer.visible);this.setQueryable(layer.queryable);this.setSRS(layer.srs||"EPSG:4326");this.setSummary(layer.abstr||"");this.setMetadataURL(layer.metadataURL||"");this.setKeywords(layer.keywords||[]);this.setBoundingBox(layer.bbox);var server=layer.getServer();var serverTitle=server.title;var onlineResource=server.url;var version=server.version||"1.1.1";var service=server.service||"WMS";}};$prototype.getLayerId=function(){if(!this.layerId&&this.node){this.layerId=getNodeAttribute(this.node,"id");}
return this.layerId;};$prototype.setLayerId=function(id){this.layerId=id;};$prototype.getQueryable=function(){if(this.queryable==undefined&&this.node){this.queryable=(getNodeAttribute(this.node,"queryable","1")=="1");}
return this.queryable;};$prototype.setQueryable=function(queryable){this.queryable=(queryable==true);};$prototype.getHidden=function(){if(this.hidden==undefined&&this.node){this.hidden=(getNodeAttribute(this.node,"hidden","1")=="1");}
return this.hidden;};$prototype.setHidden=function(hidden){this.hidden=(hidden==true);};$prototype.getOpacity=function(){if(this.opacity==undefined&&this.node){this.opacity=getNodeAttribute(this.node,"opacity",1.0);}
return this.opacity;};$prototype.setOpacity=function(opacity){this.opacity=opacity;};$prototype.getProxied=function(){if(this.proxied==undefined&&this.node){this.proxied=(getNodeAttribute(this.node,"proxied","0")=="1");}
return this.proxied;};$prototype.setProxied=function(proxied){this.proxied=(proxied==true);}
$prototype.getLayerName=function(){return this.getValue("layerName","Name","");};$prototype.setLayerName=function(name){this.layerName=name;};$prototype.getTitle=function(){return this.getValue("title","Title","");};$prototype.setTitle=function(title){this.title=title;}
$prototype.getSummary=function(){return this.getValue("summary","Abstract","");};$prototype.setSummary=function(summ){this.summary=summ;};$prototype.getMetadataURL=function(){return this.getValue("murl","MetadataURL","");};$prototype.setMetadataURL=function(url){this.murl=url;};$prototype.getKeywords=function(){if(!this.keywords){var str=this.getValue("keywordStr","Keywords","");this.keywords=str.split(",");}
return this.keywords;};$prototype.setKeywords=function(keys){var keywords;if(typeof(keys)=='string'){keywords=keys.split(",");}else if(typeof(keys.push)=='function'){keywords=keys;}
this.keywords=keywords;};$prototype.getSRS=function(){return this.getValue("srs","SRS","");};$prototype.setSRS=function(srs){this.srs=srs;};$prototype.getBoundingBox=function(){var bbox=this.bbox;if(!bbox){var node=DOMUtils.getChild(this.node,"LatLonBoundingBox");if(node){var maxx=getNodeAttribute(node,"maxx");var minx=getNodeAttribute(node,"minx");var maxy=getNodeAttribute(node,"maxy");var miny=getNodeAttribute(node,"miny");var bbox=new Geometry("Box");bbox.addPoint(new Point(minx,miny));bbox.addPoint(new Point(maxx,maxy));this.bbox=bbox;}}
return bbox;};$prototype.setBoundingBox=function(bbox){if(bbox instanceof Geometry){this.bbox=bbox;}};$prototype.getServerTitle=function(){var value=this.serverTitle;if(!value){var node=this.getFirstElement(this.node,"Server",null);if(node){value=this.serverTitle=getNodeAttribute(node,"title");}}
return value;};$prototype.setServerTitle=function(title){this.serverTitle=title;};$prototype.getService=function(){var value=this.service;if(!value){var node=this.getFirstElement(this.node,"Server",null);if(node){value=this.service=getNodeAttribute(node,"service");}}
return value;};$prototype.setService=function(service){this.service=service;};$prototype.getVersion=function(){var value=this.version;if(!value){var node=this.getFirstElement(this.node,"Server",null);if(node){value=this.version=getNodeAttribute(node,"version");}}
return value;};$prototype.setVersion=function(version){this.version=version;};$prototype.getOnlineResource=function(){var value=this.onlineResource;if(!value){var node=this.getFirstElement(this.node,"Server",null);if(node){var nodes=node.getElementsByTagName("OnlineResource");if(nodes.length>0){node=nodes[0];value=this.onlineResource=getNodeAttribute(node,"xlink:href");}}}
return value;};$prototype.setOnlineResource=function(url){this.onlineResource=url;};$prototype.toXml=function(doc){var NS='http://www.opengis.net/context';if(!doc||doc.nodeType!=9){doc=createXMLDocument('Layer',NS,null);}
var layer=createElementNS(NS,'Layer',doc);var layerId=this.getLayerId();if(layerId){setNodeAttribute(layer,"id",layerId);}
setNodeAttribute(layer,"queryable",Coerce.toString(this.getQueryable()));setNodeAttribute(layer,"hidden",Coerce.toString(this.getHidden()));setNodeAttribute(layer,"proxied",Coerce.toString(this.getProxied()));setNodeAttribute(layer,"opacity",Coerce.toString(this.getOpacity()));this.appendElementWithText(layer,NS,'Name',this.getLayerName());this.appendElementWithText(layer,NS,'Title',this.getTitle());this.appendElementWithText(layer,NS,'Abstract',this.getSummary());this.appendElementWithText(layer,NS,'SRS',this.getSRS());this.appendElementWithText(layer,NS,'Keywords',this.getKeywords().toString());this.appendElementWithText(layer,NS,'MetadataURL',this.getMetadataURL());var box=this.getBoundingBox();if(box){box=box.getEnvelope();var points=box.getPoints();var bbox=createElementNS(NS,"LatLonBoundingBox",doc);setNodeAttribute(bbox,"minx",points[0].x);setNodeAttribute(bbox,"miny",points[0].y);setNodeAttribute(bbox,"maxx",points[1].x);setNodeAttribute(bbox,"maxy",points[1].y);layer.appendChild(bbox);}
var server=createElementNS(NS,"Server",doc);setNodeAttribute(server,"title",this.getServerTitle());setNodeAttribute(server,"service",this.getService());setNodeAttribute(server,"version",this.getVersion());layer.appendChild(server);var ore=createElementNS(NS,"OnlineResource",doc);setNodeAttribute(ore,"xmlns:xlink","http://www.w3.org/1999/xlink");setNodeAttribute(ore,"xlink:href",this.getOnlineResource());server.appendChild(ore);return layer;};namespace("userSmarts.maps.pub");$namespace.LayerResource=Class.create(userSmarts.pub.Resource);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{params:{format:"text/xml"}});superClass.call(this,properties);this.setURL("pub/layers/"+this.id+".atom");};namespace("userSmarts.maps.pub");$namespace.MapResource=Class.create(userSmarts.pub.Resource);$prototype.initialize=function(superClass,properties){properties=setdefault(properties,{params:{format:"text/xml"}});superClass.call(this,properties);};namespace("userSmarts.maps");namespace("userSmarts.maps");$namespace.Plugin=Class.create(userSmarts.runtime.Activator);$prototype.initialize=function(superClass,properties){superClass.call(this,properties);userSmarts.maps.Plugin.instance=this;};$namespace.Plugin.getDefault=function(){return userSmarts.maps.Plugin.instance;};$prototype.start=function(bundleContext){this.controller=new userSmarts.maps.widget.MapController();};$namespace.Plugin.find=function(path){return userSmarts.maps.Plugin.getDefault().getURI(path);};