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