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