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