Fix compiler warnings
[potlatch2.git] / potlatch2.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:Application
3     xmlns:fx="http://ns.adobe.com/mxml/2009"
4         xmlns:mx="library://ns.adobe.com/flex/mx"
5     xmlns:s="library://ns.adobe.com/flex/spark"
6         xmlns:halcyon="net.systemeD.halcyon.*"
7         xmlns:potlatch2="net.systemeD.potlatch2.*"
8         layout="vertical"
9         horizontalScrollPolicy="off"
10         verticalScrollPolicy="off"
11         horizontalAlign="center" 
12         addedToStage="startInit()"
13         preloader="net.systemeD.potlatch2.Preloader">
14
15
16
17         <fx:Style source="styles/Application.css"/>
18
19     <fx:Declarations>
20         <map:LocalizationMap xmlns:map="l10n.map.*" />
21         <mx:Glow id="glowImage" duration="100"
22             alphaFrom="0.3" alphaTo="1.0"
23             blurXFrom="0.0" blurXTo="5.0"
24             blurYFrom="0.0" blurYTo="5.0"
25             color="0xFF8000"/>
26         <mx:Glow id="unglowImage" duration="100"
27             alphaFrom="1.0" alphaTo="0.3"
28             blurXFrom="5.0" blurXTo="0.0"
29             blurYFrom="5.0" blurYTo="0.0"
30             color="0xFF8000"/>
31         <mx:WipeLeft id="wipeOut" duration="250"/>
32         <mx:WipeRight id="wipeIn" duration="250"/>
33     </fx:Declarations>
34
35     <mx:ApplicationControlBar id="controlbar" dock="true">
36         <mx:PopUpButton id="bgButton" label="Background" openAlways="true" styleName="appBarButton"
37             creationComplete="bgButton.popUp = new BackgroundSelector();"/>
38         <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true" styleName="appBarButton"
39             creationComplete="styleButton.popUp = new StyleSelector();"/>
40                 <mx:PopUpMenuButton id="gpsButton" styleName="appBarButton"
41                     itemClick="if (event.index==0) { trackLoader.load(); } 
42                           else if (event.index==1) { new MyGpxDialog().init(); } 
43                                               else { mx.controls.Menu(gpsButton.popUp).selectedIndex=0; 
44                                                      mx.controls.Menu(gpsButton.popUp).selectedIndex=0; /* Yes, we do need to call it twice */
45                                                      theMap.removeLayerByName('GPS tracks'); }">
46                         <mx:dataProvider>
47                                 <fx:Array>
48                                         <fx:Object label="GPS data" id="gpsData" />
49                                         <fx:Object label="My tracks" id="myTracks" />
50                                         <fx:Object label="Clear" id="clearGps" />
51                                 </fx:Array>
52                         </mx:dataProvider>
53                 </mx:PopUpMenuButton>
54         <mx:Spacer width="100%"/>
55         <mx:Button id="undo" label="Undo" click="MainUndoStack.getGlobalStack().undo();" styleName="appBarButton"
56             enabled="{MainUndoStack.getGlobalStack().canUndo()}"
57             toolTip="{MainUndoStack.getGlobalStack().getUndoDescription() ? 'Undo '+MainUndoStack.getGlobalStack().getUndoDescription() : 'Undo last action'}" />
58         <mx:Button id="redo" label="Redo" click="MainUndoStack.getGlobalStack().redo();" styleName="appBarButton"
59             enabled="{MainUndoStack.getGlobalStack().canRedo()}"
60             toolTip="{MainUndoStack.getGlobalStack().getRedoDescription() ? 'Redo '+MainUndoStack.getGlobalStack().getRedoDescription() : 'Redo last action'}" />
61         <mx:Spacer width="100%"/>
62         <mx:Button id="helpButton" label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
63         <mx:Button id="optionsButton" label="Options" click="new OptionsDialog().init();" styleName="appBarButton" />
64         <mx:Button label="Save" icon="@Embed('embedded/upload.svg')" disabledIcon="@Embed('embedded/upload_disabled.svg')" styleName="appBarButton"
65                         click="SaveManager.saveChanges(theMap.editableLayer.connection);" id="saveButton" enabled="false"/>
66     </mx:ApplicationControlBar>
67     
68     <mx:HDividedBox width="100%" height="100%">
69
70           <!-- Tag viewer -->
71           <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
72
73       <mx:Canvas width="75%" height="100%">
74         <mx:Canvas id="map_area" resize="onResizeMap()"
75             top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
76         </mx:Canvas>
77         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
78             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
79         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
80             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
81         <mx:Image source="@Embed('embedded/search.svg')" right="3" top="40" click="new FindDialog().init();"
82             rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="Find place" />
83         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
84             enabled="false" borderThickness="0"
85             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
86         <mx:TextArea id="coordsbox" left="0" top="0" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="33"
87             width="57" enabled="false" borderThickness="0" visible="false"/>
88
89     </mx:Canvas>
90
91     </mx:HDividedBox>
92
93         <fx:Script><![CDATA[
94                 import net.systemeD.halcyon.*;
95                 import net.systemeD.halcyon.connection.*;
96                 import net.systemeD.potlatch2.*;
97                 import net.systemeD.potlatch2.save.SaveManager;
98                 import net.systemeD.potlatch2.find.*;
99                 import net.systemeD.potlatch2.collections.*;
100                 import net.systemeD.potlatch2.controller.*;
101                 import net.systemeD.potlatch2.help.*;
102                 import net.systemeD.potlatch2.options.*;
103                 import net.systemeD.potlatch2.utils.*;
104         import net.systemeD.potlatch2.mygpx.*;
105                 import net.systemeD.controls.FloatingAlert;
106                 import mx.managers.PopUpManager;
107                 import flash.system.Security;
108                 import flash.net.*;
109                 import flash.utils.Timer;
110                 import flash.events.TimerEvent;
111                 import flash.events.MouseEvent;
112                 import flash.display.Sprite;
113                 import mx.core.IChildList;
114         import mx.containers.Canvas;
115                 import mx.core.Application;
116                 import mx.core.FlexGlobals;
117         import mx.events.DragEvent;
118         import mx.events.CloseEvent;
119         import mx.managers.DragManager;
120         import mx.core.DragSource;
121         import mx.controls.Alert;
122         import com.mindspace.l10n.events.LocaleEvent;
123
124         public var theMap:Map;
125         public var theController:EditController;
126                 public var yahoo:Yahoo;
127                 public var trackLoader:TrackLoader;
128                 public var toolbox:Toolbox;
129         public var bugLoader:BugLoader;
130         public var bikeShopLoader:BikeShopLoader;
131
132                 private var savecount:uint=0;
133                 private var loadcount:uint=0;
134                 private var saveLabel:String='Save';
135                 private var saveTimer:Timer;
136
137         include "version.as";
138
139                 private function startInit():void {
140             /* For reasons that I don't yet understand, the en_US locale is the default and doesn't work at all. */
141             /* Change this to another locale (e.g. fr_FR) to see the differences. */
142             if (loaderInfo.parameters['locale']) {
143               dispatchEvent(new LocaleEvent(LocaleEvent.LOAD_LOCALE,loaderInfo.parameters['locale']));
144             }
145
146                         // Load font and don't do anything until that's done
147                         var loader:Loader = new Loader();
148                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, continueInit);
149                         loader.load(new URLRequest("FontLibrary.swf"));
150                 }
151                 
152                 private function continueInit(r:Event):void {
153                         controlbar.setStyle('dropShadowEnabled',"false");       // Flex 4 doesn't permit this in Application.css
154
155                         // Set font
156                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
157                         Font.registerFont(FontLibrary.DejaVu);
158
159                         Globals.vars.map_area = map_area;
160                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
161                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
162                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
163                         Globals.vars.flashvars = loaderInfo.parameters;
164
165                         // Remember localised Save text, because we change this dynamically
166                         saveLabel=saveButton.label;
167
168                         // populate sharedObject with loaderInfo parameters if supplied
169                         var obj:SharedObject = SharedObject.getLocal("user_state");
170                         var objChanged:Boolean = false;
171                         if (loaderInfo.parameters['tileurl']) {
172                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
173                                 obj.setProperty('background_name','Custom'); 
174                                 objChanged=true;
175                         }
176                         if (loaderInfo.parameters['style']) { 
177                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
178                                 obj.setProperty('stylesheet_name','Custom');
179                                 objChanged=true; 
180                         }
181                         if (objChanged) { obj.flush(); }
182
183                         // map backdrop object
184             var w:uint = map_area.width;
185             var h:uint = map_area.height;
186             var b:Sprite = new Sprite();
187             b.height=h; b.width=w;
188             b.graphics.beginFill(0xFFFFEA,100); 
189             b.graphics.drawRect(0,0,w,h); 
190             b.graphics.endFill();
191                         _root.addChild(b);
192
193                         // pass additional parameters to map
194                         var params:Object={}; var k:String;
195                         for (k in this.loaderInfo.parameters) params[k]=this.loaderInfo.parameters[k];
196                         for (k in SharedObject.getLocal('user_state').data) params[k]=SharedObject.getLocal('user_state').data[k];
197
198                         // Create map
199                         theMap=new Map();
200                         theMap.backdrop=b;
201             theMap.updateSize(w,h);
202                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
203
204                         yahoo=new Yahoo(theMap);
205                         yahoo.hide();
206                         _root.addChild(yahoo);
207                         _root.addChild(theMap);
208
209                         // Initialise stylesheets
210                         Stylesheets.instance().init();
211                         Stylesheets.instance().addEventListener(CollectionEvent.SELECT,
212                                 function(e:CollectionEvent):void { theMap.editableLayer.setStyle(String(e.data)); }
213                         );
214
215                         // Add core data layer
216                         var conn:Connection = new XMLConnection("Main", params['api'], params['policy'], params);
217             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
218             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
219             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
220             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
221             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
222             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
223                         conn.addEventListener(MapEvent.ERROR, onMapError);
224                         conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
225                         conn.addEventListener(AttentionEvent.ALERT, onAlert);
226                         theMap.addLayer(conn, Stylesheets.instance().selected, false, true);
227
228             // Auto-load vector backgrounds from config
229             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
230
231                         // Set start position of map
232                         // ** FIXME: if lat/lon/zoom aren't supplied, we need to keep the map in a non-loading state 
233                         //           until the user has decided where to start editing (e.g. when the first GPX loads)
234                         theMap.init(params['lat'], params['lon'], params['zoom']);
235
236                         // add attribution/logo sprite
237                         var overlay:Sprite=new Sprite();
238                         var attribution:TextField=new TextField();
239                         attribution.width=220; attribution.height=300;
240                         attribution.multiline=true;
241                         attribution.wordWrap=true;
242                         attribution.selectable=false;
243                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
244                         overlay.addChild(attribution);
245                         var terms:TextField=new TextField();
246                         terms.width=200; terms.height=15;
247                         terms.selectable=false;
248                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
249                         overlay.addChild(terms);
250                         _root.addChild(overlay);
251
252                         // mouse-up handler attached to stage, so the user can release outside the map
253                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
254                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
255                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
256
257                         // initialise imagery
258                         theMap.tileset.blocks=[new RegExp("google","i")];       // hard-coded block on Google tiles
259                         theMap.tileset.setDimming(params['background_dim']    ==null ? true  : params['background_dim']);
260                         theMap.tileset.setSharpen(params['background_sharpen']==null ? false : params['background_sharpen']);
261                         Imagery.instance().init(theMap, overlay, yahoo);
262                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
263                         Imagery.instance().addEventListener(CollectionEvent.SELECT,
264                                 function(e:CollectionEvent):void { theMap.tileset.init(e.data, e.data!=''); }
265                         );
266
267                         // keyboard event attached to stage
268                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
269             
270                         // mouse-position listener for co-ordinate display
271             theMap.addEventListener(MapEvent.MOUSE_MOVE, mouseoverHandler);
272
273                         // position toolbox
274                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
275                         toolbox.init(theController);
276                         toolbox.x=stage.stageWidth-toolbox.width-5;
277                         toolbox.y=stage.stageHeight-toolbox.height-5;
278
279                         // add debug field
280                         var t:TextField=new TextField();
281                         t.width=500; t.height=150; t.border=true;
282                         t.multiline=true;
283                         _root.addChild(t);
284                         Globals.vars.debug=t;
285             t.visible = loaderInfo.parameters["show_debug"] == 'true';
286                         Globals.vars.root=theMap;       // just for the addDebug function
287
288                         // create controller
289             theController = new EditController(theMap, tagViewer, toolbox);
290             theController.setActive();
291                         theController.addEventListener(AttentionEvent.ATTENTION, onAttention);
292                         theController.addEventListener(AttentionEvent.ALERT, onAlert);
293             
294             // set the access token from saved cookie
295             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
296             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
297
298             // Load any requested GPX track
299             if (loaderInfo.parameters['gpx']) {
300                 var id:Number = loaderInfo.parameters['gpx'];
301                 if (conn.hasAccessToken()) { 
302                     loadTrace(id);
303                 } else {
304                     SaveManager.ensureAccess(function ():void { loadTrace(id); }, conn);
305                 }
306             }
307
308                         // Load arbitrary GPX from provided URL
309                         if (loaderInfo.parameters['gpx_url']) {
310
311                 var gpx_url:String = loaderInfo.parameters['gpx_url'];
312
313                 var connection:Connection = new Connection(name, gpx_url, null, null);
314                 var gpx:GpxImporter=new GpxImporter(connection, theMap, [gpx_url],
315                                                 function(success:Boolean,message:String=null):void {
316                                                     if (!success) return;
317                                                     var paint:MapPaint = theMap.addLayer(connection, "stylesheets/gpx.css");
318                                                     paint.updateEntityUIs(false, false);
319                                                     dispatchEvent(new Event("layers_changed"));
320                                                 }, false);
321                         }
322
323                         // create GPS trackloader
324                         trackLoader=new TrackLoader(theMap,conn.apiBase);
325
326             // Force authentication on startup, if required
327             // force_auth == force => checks for access token, and displays OAuth panel if needed
328             var force_auth:String = loaderInfo.parameters["force_auth"];
329             if (!conn.hasAccessToken() && force_auth == 'force') {
330               SaveManager.ensureAccess(onAccessChecked, conn);
331             }
332
333             // show help dialog on startup, if required
334             // show_help == always => on every startup
335             // show_help == once => show on first startup only
336             var show_help:String = loaderInfo.parameters["show_help"];
337
338             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
339               new HelpDialog().init();
340             }
341
342             // Check if Tiger highlighting should be enabled from saved object
343             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
344                 }
345                 
346                 public function onMapError(mapEvent:MapEvent):void {
347                         var buttons:uint=0;
348                         if (mapEvent.params.no) { trace("no is set"); }
349                         if (mapEvent.params.yes             ) buttons|=mx.controls.Alert.YES;
350                         if (mapEvent.params.no              ) buttons|=mx.controls.Alert.NO;
351                         if (mapEvent.params.cancel          ) buttons|=mx.controls.Alert.CANCEL;
352                         if (mapEvent.params.ok || buttons==0) buttons|=mx.controls.Alert.OK;
353                         trace("showing alert with "+buttons);
354                         Alert.show(mapEvent.params.message, 'Error', buttons, null, function(closeEvent:CloseEvent):void { 
355                                 switch (closeEvent.detail) {
356                                         case mx.controls.Alert.CANCEL:  mapEvent.params.cancel(); break; //fixme? this gets called if user presses escape, even if there's no cancel button.
357                                         case mx.controls.Alert.YES:             mapEvent.params.yes(); break;
358                                         case mx.controls.Alert.NO:              mapEvent.params.no(); break;
359                                         default:                                                if (mapEvent.params.ok) mapEvent.params.ok();
360                                 }
361                         });
362                 }
363
364                 /** Highlight an entity in response to an 'attention' event */
365
366                 public function onAttention(event:AttentionEvent):void {
367                         var entity:Entity=event.entity;
368                         if (entity is Relation) {
369                                 // If it's a relation, just bring up the editor panel
370                                 var panel:RelationEditorPanel = RelationEditorPanel(
371                                         PopUpManager.createPopUp(Application(FlexGlobals.topLevelApplication), RelationEditorPanel, true));
372                                 panel.setRelation(entity as Relation);
373                                 PopUpManager.centerPopUp(panel);
374                                 return;
375                         }
376
377                         var lat:Number, lon:Number;
378                         var panTo:Boolean=true;
379                         if (entity is Way) {
380                                 // If it's a way, find if it's on-screen
381                                 for (var i:uint=0; i<Way(entity).length; i++) {
382                                         var node:Node=Way(entity).getNode(i)
383                                         if (node.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
384                                         lat=node.lat; lon=node.lon;
385                                 }
386                         } else if (entity is Node) {
387                                 // If it's a node, check if it's on-screen
388                                 if (entity.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
389                                 lat=Node(entity).lat; lon=Node(entity).lon;
390                         }
391                         // Pan if required, and select the object
392                         if (panTo) { theMap.moveMapFromLatLon(lat,lon); }
393                         theController.setState(theController.findStateForSelection([entity]));
394                 }
395
396                 /** Display floating warning in response to an 'alert' event */
397
398                 public function onAlert(event:AttentionEvent):void {
399                         var alert:FloatingAlert=new FloatingAlert(event.message);
400                         stage.addChild(alert);
401                 }
402
403         public function onResizeMap():void {
404             if ( theMap != null )
405                 theMap.updateSize(map_area.width, map_area.height);
406
407                         if (toolbox) {
408                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
409                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
410                         }
411         }
412                 private function bumpHandler(e:MapEvent):void {
413                         if (toolbox) {
414                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
415                         }
416                 }
417
418         private function mouseoverHandler(e:MapEvent):void {
419             if (coordsbox.visible) {
420                 coordsbox.text= Number(e.params.x).toFixed(5) + "\n " + Number(e.params.y).toFixed(5); // Not sure if 5 dp's really required.
421             }
422         }
423
424         private function onDataStart(event:Event):void {
425                         switch (event.type) {
426                                 case Connection.LOAD_STARTED:   loadcount++; break;
427                                 case Connection.SAVE_STARTED:   savecount++; break;
428                         }
429                         updateDataWorking();
430         }
431         private function onDataComplete(event:Event):void {
432                         switch (event.type) {
433                                 case Connection.LOAD_COMPLETED: loadcount--; break;
434                                 case Connection.SAVE_COMPLETED: savecount--; break;
435                         }
436             updateDataWorking();
437         }
438                 private function updateDataWorking():void {
439                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
440                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
441                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
442                         else                            { dataWorking.text=""; }
443                         dataWorking.visible=(dataWorking.text!="");
444                 }
445         private function onDataDirty(event:Event):void {
446                         saveButton.enabled=true;
447             if (ExternalInterface.available) {
448               ExternalInterface.call("markChanged", false);
449             }
450                         if (!saveTimer || !saveTimer.running) {
451                                 saveTimer=new Timer(60*1000,0);
452                                 saveTimer.addEventListener(TimerEvent.TIMER,saveTimeUpdate);
453                                 saveTimer.start();
454                         }
455                 }
456                 private function onDataClean(event:Event):void {
457                         saveButton.enabled=false;
458             if (ExternalInterface.available) {
459               ExternalInterface.call("markChanged", true);
460             }
461             if (saveTimer && saveTimer.running) {
462                                 saveTimer.stop();
463                                 saveTimer.removeEventListener(TimerEvent.TIMER,saveTimeUpdate);
464                                 saveTimeWrite(0);
465                         }
466                 }
467                 private function saveTimeUpdate(event:TimerEvent):void {
468                         var timer:Timer=Timer(event.target);
469                         saveTimeWrite(uint(timer.delay*timer.currentCount/1000/60));
470                 }
471                 private function saveTimeWrite(minutes:uint):void {
472                         if (minutes<5) {
473                                 saveButton.label=saveLabel;
474                         } else {
475                                 saveButton.label=saveLabel+" ("+minutes+"m"+")"; 
476                                 if (minutes>=20 && minutes/5==int(minutes/5)) {
477                                         theController.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, minutes+"m since last save - please save regularly"));
478                                 }
479                         }
480                 }
481
482                 private function scaleHandler(event:MapEvent):void {
483                         dispatchEvent(new Event("rescale"));
484                 }
485                 
486                 [Bindable(event="rescale")]
487                 private function getScale():String {
488                         return String(theMap.scale);
489                 }
490
491         private function dragEnterHandler(event:DragEvent):void {
492             // Get the drop target component from the event object.
493             var dropTarget:Canvas=event.currentTarget as Canvas;
494             // Accept the drag only if the user is dragging poi with tags
495             if (event.dragSource.hasFormat('tags')) 
496             {
497                 DragManager.acceptDragDrop(dropTarget);
498             }
499         }
500         
501         private function dragDropHandler(event:DragEvent):void {
502                         // Deselect the dragged icon
503                         if (event.dragSource.dataForFormat('container')) {
504                                 event.dragSource.dataForFormat('container').selectedItem=-1;
505                         }
506
507                         // Get the tags
508             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
509
510             // If you dnd quick enough, this exposes a flex bug and event.stageX/Y become negative.
511             // Take the mouse positions from a displayObject's stage for consistent results.
512             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.target.stage.mouseX, event.target.stage.mouseY));
513             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
514             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
515             
516             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
517             
518                         var conn:Connection = theMap.editableLayer.connection;
519             var node:Node = conn.createNode({}, lat, lon, createAction.push);
520             for each ( var tag:Object in tags ) {
521                 node.setTag(tag.k, tag.v, createAction.push);
522             }
523                         conn.registerPOI(node);
524                         MainUndoStack.getGlobalStack().addAction(createAction);
525             theController.setState(new SelectedPOINode(node));
526         }
527
528         /* Called when forcing an initial access token check. */
529         private function onAccessChecked():void {
530             // Floaty panel message "You now have access";
531         }
532
533         private function loadTrace(id:Number):void {
534             var conn:Connection = theMap.editableLayer.connection;
535             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
536                 for each (var trace:Trace in conn.getTraces()) {
537                     if (trace.id == id) { trace.addToMap(); }
538                 }
539             });
540             conn.fetchUserTraces();
541         }
542
543         ]]></fx:Script>
544
545 </mx:Application>
546