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