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