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