Selecting and unselecting an empty input field in simple editor shouldn't trig TAG_CH...
[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.events.DragEvent;
112         import mx.events.CloseEvent;
113         import mx.managers.DragManager;
114         import mx.core.DragSource;
115         import mx.controls.Alert;
116         import com.mindspace.l10n.events.LocaleEvent;
117
118         public var theMap:Map;
119         public var theController:EditController;
120                 public var yahoo:Yahoo;
121                 public var trackLoader:TrackLoader;
122                 public var toolbox:Toolbox;
123         public var bugLoader:BugLoader;
124         public var bikeShopLoader:BikeShopLoader;
125
126                 private var savecount:uint=0;
127                 private var loadcount:uint=0;
128                 private var saveLabel:String='Save';
129                 private var saveTimer:Timer;
130
131         include "version.as";
132
133                 private function startInit():void {
134             /* For reasons that I don't yet understand, the en_US locale is the default and doesn't work at all. */
135             /* Change this to another locale (e.g. fr_FR) to see the differences. */
136             if (loaderInfo.parameters['locale']) {
137               dispatchEvent(new LocaleEvent(LocaleEvent.LOAD_LOCALE,loaderInfo.parameters['locale']));
138             }
139
140                         // Load font and don't do anything until that's done
141                         var loader:Loader = new Loader();
142                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, continueInit);
143                         loader.load(new URLRequest("FontLibrary.swf"));
144                 }
145                 
146                 private function continueInit(r:Event):void {
147                         // Set font
148                         var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
149                         Font.registerFont(FontLibrary.DejaVu);
150
151                         Globals.vars.map_area = map_area;
152                         Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
153                         var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
154                         Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
155                         Globals.vars.flashvars = loaderInfo.parameters;
156
157                         // Remember localised Save text, because we change this dynamically
158                         saveLabel=saveButton.label;
159
160                         // populate sharedObject with loaderInfo parameters if supplied
161                         var obj:SharedObject = SharedObject.getLocal("user_state");
162                         var objChanged:Boolean = false;
163                         if (loaderInfo.parameters['tileurl']) {
164                                 obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
165                                 obj.setProperty('background_name','Custom'); 
166                                 objChanged=true;
167                         }
168                         if (loaderInfo.parameters['style']) { 
169                                 obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
170                                 obj.setProperty('stylesheet_name','Custom');
171                                 objChanged=true; 
172                         }
173                         if (objChanged) { obj.flush(); }
174
175                         // map backdrop object
176             var w:uint = map_area.width;
177             var h:uint = map_area.height;
178             var b:Sprite = new Sprite();
179             b.height=h; b.width=w;
180             b.graphics.beginFill(0xFFFFEA,100); 
181             b.graphics.drawRect(0,0,w,h); 
182             b.graphics.endFill();
183                         _root.addChild(b);
184
185                         // pass additional parameters to map
186                         var params:Object={}; var k:String;
187                         for (k in this.loaderInfo.parameters) params[k]=this.loaderInfo.parameters[k];
188                         for (k in SharedObject.getLocal('user_state').data) params[k]=SharedObject.getLocal('user_state').data[k];
189
190                         // Create map
191                         theMap=new Map();
192                         theMap.backdrop=b;
193             theMap.updateSize(w,h);
194                         theMap.addEventListener(MapEvent.SCALE, scaleHandler);
195
196                         yahoo=new Yahoo(theMap);
197                         yahoo.hide();
198                         _root.addChild(yahoo);
199                         _root.addChild(theMap);
200
201                         // Initialise stylesheets
202                         Stylesheets.instance().init();
203                         Stylesheets.instance().addEventListener(CollectionEvent.SELECT,
204                                 function(e:CollectionEvent):void { theMap.editableLayer.setStyle(String(e.data)); }
205                         );
206
207                         // Add core data layer
208                         var conn:Connection = new XMLConnection("Main", params['api'], params['policy'], params);
209             conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
210             conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
211             conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
212             conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
213             conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
214             conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
215                         conn.addEventListener(MapEvent.ERROR, onMapError);
216                         conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
217                         conn.addEventListener(AttentionEvent.ALERT, onAlert);
218                         theMap.addLayer(conn, Stylesheets.instance().selected, false, true);
219
220             // Auto-load vector backgrounds from config
221             theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
222
223                         // Set start position of map
224                         // ** FIXME: if lat/lon/zoom aren't supplied, we need to keep the map in a non-loading state 
225                         //           until the user has decided where to start editing (e.g. when the first GPX loads)
226                         theMap.init(params['lat'], params['lon'], params['zoom']);
227
228                         // add attribution/logo sprite
229                         var overlay:Sprite=new Sprite();
230                         var attribution:TextField=new TextField();
231                         attribution.width=220; attribution.height=300;
232                         attribution.multiline=true;
233                         attribution.wordWrap=true;
234                         attribution.selectable=false;
235                         attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
236                         overlay.addChild(attribution);
237                         var terms:TextField=new TextField();
238                         terms.width=200; terms.height=15;
239                         terms.selectable=false;
240                         terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
241                         overlay.addChild(terms);
242                         _root.addChild(overlay);
243
244                         // mouse-up handler attached to stage, so the user can release outside the map
245                         stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
246                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
247                         Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
248
249                         // initialise imagery
250                         theMap.tileset.blocks=[new RegExp("google","i")];       // hard-coded block on Google tiles
251                         theMap.tileset.setDimming(params['background_dim']    ==null ? true  : params['background_dim']);
252                         theMap.tileset.setSharpen(params['background_sharpen']==null ? false : params['background_sharpen']);
253                         Imagery.instance().init(theMap, overlay, yahoo);
254                         Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
255                         Imagery.instance().addEventListener(CollectionEvent.SELECT,
256                                 function(e:CollectionEvent):void { theMap.tileset.init(e.data, e.data!=''); }
257                         );
258
259                         // keyboard event attached to stage
260                         stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
261             
262                         // mouse-position listener for co-ordinate display
263             theMap.addEventListener(MapEvent.MOUSE_MOVE, mouseoverHandler);
264
265                         // position toolbox
266                         toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
267                         toolbox.init(theController);
268                         toolbox.x=stage.stageWidth-toolbox.width-5;
269                         toolbox.y=stage.stageHeight-toolbox.height-5;
270
271                         // add debug field
272                         var t:TextField=new TextField();
273                         t.width=500; t.height=150; t.border=true;
274                         t.multiline=true;
275                         _root.addChild(t);
276                         Globals.vars.debug=t;
277             t.visible = loaderInfo.parameters["show_debug"] == 'true';
278                         Globals.vars.root=theMap;       // just for the addDebug function
279
280                         // create controller
281             theController = new EditController(theMap, tagViewer, toolbox);
282             theController.setActive();
283                         theController.addEventListener(AttentionEvent.ATTENTION, onAttention);
284                         theController.addEventListener(AttentionEvent.ALERT, onAlert);
285             
286             // set the access token from saved cookie
287             var tokenObject:SharedObject = SharedObject.getLocal("access_token");
288             conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
289
290             // Load any requested GPX track
291             if (loaderInfo.parameters['gpx']) {
292                 var id:Number = loaderInfo.parameters['gpx'];
293                 if (conn.hasAccessToken()) { 
294                     loadTrace(id);
295                 } else {
296                     SaveManager.ensureAccess(function ():void { loadTrace(id); }, conn);
297                 }
298             }
299
300                         // Load arbitrary GPX from provided URL
301                         if (loaderInfo.parameters['gpx_url']) {
302
303                 var gpx_url:String = loaderInfo.parameters['gpx_url'];
304
305                 var connection:Connection = new Connection(name, gpx_url, null, null);
306                 var gpx:GpxImporter=new GpxImporter(connection, theMap, [gpx_url],
307                                                 function(success:Boolean,message:String=null):void {
308                                                     if (!success) return;
309                                                     var paint:MapPaint = theMap.addLayer(connection, "stylesheets/gpx.css");
310                                                     paint.updateEntityUIs(false, false);
311                                                     dispatchEvent(new Event("layers_changed"));
312                                                 }, false);
313                         }
314
315                         // create GPS trackloader
316                         trackLoader=new TrackLoader(theMap,conn.apiBase);
317
318             // Force authentication on startup, if required
319             // force_auth == force => checks for access token, and displays OAuth panel if needed
320             var force_auth:String = loaderInfo.parameters["force_auth"];
321             if (!conn.hasAccessToken() && force_auth == 'force') {
322               SaveManager.ensureAccess(onAccessChecked, conn);
323             }
324
325             // show help dialog on startup, if required
326             // show_help == always => on every startup
327             // show_help == once => show on first startup only
328             var show_help:String = loaderInfo.parameters["show_help"];
329
330             if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
331               new HelpDialog().init();
332             }
333
334             // Check if Tiger highlighting should be enabled from saved object
335             Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
336                 }
337                 
338                 public function onMapError(mapEvent:MapEvent):void {
339                         var buttons:uint=0;
340                         if (mapEvent.params.no) { trace("no is set"); }
341                         if (mapEvent.params.yes             ) buttons|=mx.controls.Alert.YES;
342                         if (mapEvent.params.no              ) buttons|=mx.controls.Alert.NO;
343                         if (mapEvent.params.cancel          ) buttons|=mx.controls.Alert.CANCEL;
344                         if (mapEvent.params.ok || buttons==0) buttons|=mx.controls.Alert.OK;
345                         trace("showing alert with "+buttons);
346                         Alert.show(mapEvent.params.message, 'Error', buttons, null, function(closeEvent:CloseEvent):void { 
347                                 switch (closeEvent.detail) {
348                                         case mx.controls.Alert.CANCEL:  mapEvent.params.cancel(); break; //fixme? this gets called if user presses escape, even if there's no cancel button.
349                                         case mx.controls.Alert.YES:             mapEvent.params.yes(); break;
350                                         case mx.controls.Alert.NO:              mapEvent.params.no(); break;
351                                         default:                                                if (mapEvent.params.ok) mapEvent.params.ok();
352                                 }
353                         });
354                 }
355
356                 /** Highlight an entity in response to an 'attention' event */
357
358                 public function onAttention(event:AttentionEvent):void {
359                         var entity:Entity=event.entity;
360                         if (entity is Relation) {
361                                 // If it's a relation, just bring up the editor panel
362                                 var panel:RelationEditorPanel = RelationEditorPanel(
363                                         PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
364                                 panel.setRelation(entity as Relation);
365                                 PopUpManager.centerPopUp(panel);
366                                 return;
367                         }
368
369                         var lat:Number, lon:Number;
370                         var panTo:Boolean=true;
371                         if (entity is Way) {
372                                 // If it's a way, find if it's on-screen
373                                 for (var i:uint=0; i<Way(entity).length; i++) {
374                                         var node:Node=Way(entity).getNode(i)
375                                         if (node.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
376                                         lat=node.lat; lon=node.lon;
377                                 }
378                         } else if (entity is Node) {
379                                 // If it's a node, check if it's on-screen
380                                 if (entity.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
381                                 lat=Node(entity).lat; lon=Node(entity).lon;
382                         }
383                         // Pan if required, and select the object
384                         if (panTo) { theMap.moveMapFromLatLon(lat,lon); }
385                         theController.setState(theController.findStateForSelection([entity]));
386                 }
387
388                 /** Display floating warning in response to an 'alert' event */
389
390                 public function onAlert(event:AttentionEvent):void {
391                         var alert:FloatingAlert=new FloatingAlert(event.message);
392                         stage.addChild(alert);
393                 }
394
395         public function onResizeMap():void {
396             if ( theMap != null )
397                 theMap.updateSize(map_area.width, map_area.height);
398
399                         if (toolbox) {
400                                 toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
401                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
402                         }
403         }
404                 private function bumpHandler(e:MapEvent):void {
405                         if (toolbox) {
406                                 toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
407                         }
408                 }
409
410         private function mouseoverHandler(e:MapEvent):void {
411             if (coordsbox.visible) {
412                 coordsbox.text= Number(e.params.x).toFixed(5) + "\n " + Number(e.params.y).toFixed(5); // Not sure if 5 dp's really required.
413             }
414         }
415
416         private function onDataStart(event:Event):void {
417                         switch (event.type) {
418                                 case Connection.LOAD_STARTED:   loadcount++; break;
419                                 case Connection.SAVE_STARTED:   savecount++; break;
420                         }
421                         updateDataWorking();
422         }
423         private function onDataComplete(event:Event):void {
424                         switch (event.type) {
425                                 case Connection.LOAD_COMPLETED: loadcount--; break;
426                                 case Connection.SAVE_COMPLETED: savecount--; break;
427                         }
428             updateDataWorking();
429         }
430                 private function updateDataWorking():void {
431                         if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
432                         else if (loadcount>0)           { dataWorking.text="Loading data..."; }
433                         else if (savecount>0)           { dataWorking.text="Saving data..."; }
434                         else                            { dataWorking.text=""; }
435                         dataWorking.visible=(dataWorking.text!="");
436                 }
437         private function onDataDirty(event:Event):void {
438                         saveButton.enabled=true;
439             if (ExternalInterface.available) {
440               ExternalInterface.call("markChanged", false);
441             }
442                         if (!saveTimer || !saveTimer.running) {
443                                 saveTimer=new Timer(60*1000,0);
444                                 saveTimer.addEventListener(TimerEvent.TIMER,saveTimeUpdate);
445                                 saveTimer.start();
446                         }
447                 }
448                 private function onDataClean(event:Event):void {
449                         saveButton.enabled=false;
450             if (ExternalInterface.available) {
451               ExternalInterface.call("markChanged", true);
452             }
453             if (saveTimer && saveTimer.running) {
454                                 saveTimer.stop();
455                                 saveTimer.removeEventListener(TimerEvent.TIMER,saveTimeUpdate);
456                                 saveTimeWrite(0);
457                         }
458                 }
459                 private function saveTimeUpdate(event:TimerEvent):void {
460                         var timer:Timer=Timer(event.target);
461                         saveTimeWrite(uint(timer.delay*timer.currentCount/1000/60));
462                 }
463                 private function saveTimeWrite(minutes:uint):void {
464                         if (minutes<5) {
465                                 saveButton.label=saveLabel;
466                         } else {
467                                 saveButton.label=saveLabel+" ("+minutes+"m"+")"; 
468                                 if (minutes>=20 && minutes/5==int(minutes/5)) {
469                                         theController.dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, minutes+"m since last save - please save regularly"));
470                                 }
471                         }
472                 }
473
474                 private function scaleHandler(event:MapEvent):void {
475                         dispatchEvent(new Event("rescale"));
476                 }
477                 
478                 [Bindable(event="rescale")]
479                 private function getScale():String {
480                         return String(theMap.scale);
481                 }
482
483         private function dragEnterHandler(event:DragEvent):void {
484             // Get the drop target component from the event object.
485             var dropTarget:Canvas=event.currentTarget as Canvas;
486             // Accept the drag only if the user is dragging poi with tags
487             if (event.dragSource.hasFormat('tags')) 
488             {
489                 DragManager.acceptDragDrop(dropTarget);
490             }
491         }
492         
493         private function dragDropHandler(event:DragEvent):void {
494                         // Deselect the dragged icon
495                         if (event.dragSource.dataForFormat('container')) {
496                                 event.dragSource.dataForFormat('container').selectedItem=-1;
497                         }
498
499                         // Get the tags
500             var tags:Array = event.dragSource.dataForFormat('tags') as Array;
501
502             // If you dnd quick enough, this exposes a flex bug and event.stageX/Y become negative.
503             // Take the mouse positions from a displayObject's stage for consistent results.
504             var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.target.stage.mouseX, event.target.stage.mouseY));
505             var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
506             var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
507             
508             var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
509             
510                         var conn:Connection = theMap.editableLayer.connection;
511             var node:Node = conn.createNode({}, lat, lon, createAction.push);
512             for each ( var tag:Object in tags ) {
513                 node.setTag(tag.k, tag.v, createAction.push);
514             }
515                         conn.registerPOI(node);
516                         MainUndoStack.getGlobalStack().addAction(createAction);
517             theController.setState(new SelectedPOINode(node));
518         }
519
520         /* Called when forcing an initial access token check. */
521         private function onAccessChecked():void {
522             // Floaty panel message "You now have access";
523         }
524
525         private function loadTrace(id:Number):void {
526             var conn:Connection = theMap.editableLayer.connection;
527             conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
528                 for each (var trace:Trace in conn.getTraces()) {
529                     if (trace.id == id) { trace.addToMap(); }
530                 }
531             });
532             conn.fetchUserTraces();
533         }
534
535         ]]></mx:Script>
536
537 </mx:Application>
538