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