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