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