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