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