Provide a new 'View data' button in the upload dialogue.
[potlatch2.git] / potlatch2.mxml
old mode 100755 (executable)
new mode 100644 (file)
index 668388a..9ad7000
@@ -4,9 +4,14 @@
        xmlns:halcyon="net.systemeD.halcyon.*"
        xmlns:potlatch2="net.systemeD.potlatch2.*"
        layout="vertical"
+       horizontalScrollPolicy="off"
+       verticalScrollPolicy="off"
        horizontalAlign="center" 
-       addedToStage="initApp()">
-       
+       addedToStage="startInit()"
+       preloader="net.systemeD.potlatch2.Preloader">
+
+    <map:LocalizationMap xmlns:map="l10n.map.*" />
+
        <mx:Style source="styles/Application.css"/>
 
     <mx:Glow id="glowImage" duration="100" 
     <mx:WipeRight id="wipeIn" duration="250"/>
 
     <mx:ApplicationControlBar dock="true">
+        <mx:PopUpButton id="bgButton" label="Background" openAlways="true" styleName="appBarButton"
+            creationComplete="bgButton.popUp = new BackgroundSelector();"/>
+        <mx:PopUpButton id="styleButton" label="Map Style" openAlways="true" styleName="appBarButton"
+            creationComplete="styleButton.popUp = new StyleSelector();"/>
+               <mx:PopUpMenuButton id="gpsButton" styleName="appBarButton"
+                   itemClick="if (event.index==0) { trackLoader.load(); } 
+                         else if (event.index==1) { new MyGpxDialog().init(); } 
+                                             else { mx.controls.Menu(gpsButton.popUp).selectedIndex=0; 
+                                                    mx.controls.Menu(gpsButton.popUp).selectedIndex=0; /* Yes, we do need to call it twice */
+                                                    theMap.removeLayerByName('GPS tracks'); }">
+                       <mx:dataProvider>
+                               <mx:Array>
+                                       <mx:Object label="GPS data" id="gpsData" />
+                                       <mx:Object label="My tracks" id="myTracks" />
+                                       <mx:Object label="Clear" id="clearGps" />
+                               </mx:Array>
+                       </mx:dataProvider>
+               </mx:PopUpMenuButton>
+        <mx:Spacer width="100%"/>
+        <mx:Button id="undo" label="Undo" click="MainUndoStack.getGlobalStack().undo();" styleName="appBarButton"
+            enabled="{MainUndoStack.getGlobalStack().canUndo()}"
+            toolTip="{MainUndoStack.getGlobalStack().getUndoDescription() ? 'Undo '+MainUndoStack.getGlobalStack().getUndoDescription() : 'Undo last action'}" />
+        <mx:Button id="redo" label="Redo" click="MainUndoStack.getGlobalStack().redo();" styleName="appBarButton"
+            enabled="{MainUndoStack.getGlobalStack().canRedo()}"/>
         <mx:Spacer width="100%"/>
-        <mx:Button label="Help" click="new HelpDialog().init();" />
-        <mx:Button label="Options" click="new OptionsDialog().init();" />
-        <mx:Button label="Save" icon="@Embed('embedded/save.svg')" click="SaveManager.saveChanges();"/>
+        <mx:Button id="helpButton" label="Help" click="new HelpDialog().init();" styleName="appBarButton" />
+        <mx:Button id="optionsButton" label="Options" click="new OptionsDialog().init();" styleName="appBarButton" />
+        <mx:Button label="Save" icon="@Embed('embedded/upload.svg')" disabledIcon="@Embed('embedded/upload_disabled.svg')" styleName="appBarButton"
+                       click="SaveManager.saveChanges(theMap.editableLayer.connection);" id="saveButton" enabled="false"/>
     </mx:ApplicationControlBar>
     
     <mx:HDividedBox width="100%" height="100%">
 
-       <!-- The left-hand accordion is to give access to a small number of options that the user 
-            may want to change rapidly: tags, of course; stylesheet; and background layer. Lesser-
-            used options should go in the options dialogue. Tools (e.g. split ways) should probably 
-            go in a floating palette or somesuch, so that there is access no matter which accordion 
-            pane is open. -->
-
-       <mx:Accordion height="100%" width="25%" headerStyleName="header">
-
-               <!-- Tag viewer -->
-               <mx:VBox height="100%" width="100%" horizontalAlign="right" label="Tags">
-                       <potlatch2:TagViewer width="100%" height="100%" id="tagViewer"/>
-               </mx:VBox>
-
-               <!-- Stylesheet -->
-               <!-- should be pretty much the same as the background selector below, with the
-                    added ability to enter your own stylesheet URL -->
-               <mx:VBox label="Map style" width="100%">
-               </mx:VBox>
-
-               <!-- Background -->
-               <mx:VBox label="Background" width="100%">
-           <mx:List width="100%" height="100%" id="background" change="updateBackground();"> 
-                       <!-- This should be pulled in from an XML file rather than sitting in the source -->
-               <mx:dataProvider>
-                   <mx:Object label="None" data="" />
-                   <mx:Object label="Yahoo!" data="yahoo" />
-                   <mx:Object label="New Popular Edition" data="http://npe.openstreetmap.org/$z/$x/$y.png" />
-                   <mx:Object label="OpenCycleMap" data="http://andy.sandbox.cloudmade.com/tiles/cycle/$z/$x/$y.png" />
-               </mx:dataProvider>
-           </mx:List>
-               <mx:CheckBox width="100%" label="Dim background" selected="true" id="dim" change="theMap.tileset.setDimming(dim.selected); yahoo.alpha = dim.selected ? 0.5 : 1" />
-               </mx:VBox>
-
-       </mx:Accordion>
+         <!-- Tag viewer -->
+         <potlatch2:TagViewer width="25%" height="100%" id="tagViewer"/>
 
       <mx:Canvas width="75%" height="100%">
         <mx:Canvas id="map_area" resize="onResizeMap()"
-            top="0" left="0" width="100%" height="100%">
+            top="0" left="0" width="100%" height="100%" dragEnter="dragEnterHandler(event);" dragDrop="dragDropHandler(event);">
         </mx:Canvas>
         <mx:Image source="@Embed('embedded/zoomIn.svg')" right="3" top="3" click="theMap.zoomIn();"
-            rollOverEffect="glowImage" rollOutEffect="unglowImage"/>
+            rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom in - currently z'+getScale()}" />
         <mx:Image source="@Embed('embedded/zoomOut.svg')" right="3" top="20" click="theMap.zoomOut();"
-            rollOverEffect="glowImage" rollOutEffect="unglowImage"/>
+            rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="{'Zoom out - currently z'+getScale()}" />
+        <mx:Image source="@Embed('embedded/search.svg')" right="3" top="40" click="new FindDialog().init();"
+            rollOverEffect="glowImage" rollOutEffect="unglowImage" toolTip="Find place" />
         <mx:TextArea id="dataWorking" text="" right="20" top="3" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="18"
             enabled="false" borderThickness="0"
             showEffect="{wipeIn}" hideEffect="{wipeOut}"/>
-      </mx:Canvas>
+        <mx:TextArea id="coordsbox" left="0" top="0" disabledColor="black" backgroundDisabledColor="0xFFFFEA" height="33"
+            width="57" enabled="false" borderThickness="0" visible="false"/>
+
+    </mx:Canvas>
+
     </mx:HDividedBox>
 
        <mx:Script><![CDATA[
                import net.systemeD.halcyon.connection.*;
                import net.systemeD.potlatch2.*;
                import net.systemeD.potlatch2.save.SaveManager;
+               import net.systemeD.potlatch2.find.*;
+               import net.systemeD.potlatch2.collections.*;
+               import net.systemeD.potlatch2.controller.*;
                import net.systemeD.potlatch2.help.*;
                import net.systemeD.potlatch2.options.*;
                import net.systemeD.potlatch2.utils.*;
+        import net.systemeD.potlatch2.mygpx.*;
+               import net.systemeD.controls.FloatingAlert;
                import mx.managers.PopUpManager;
                import flash.system.Security;
                import flash.net.*;
                import mx.core.IChildList;
         import mx.containers.Canvas;
                import mx.core.Application;
-               import com.yahoo.maps.api.YahooMap;
-               import com.yahoo.maps.api.YahooMapEvent;
-               import com.yahoo.maps.api.core.location.LatLon;
+        import mx.events.DragEvent;
+        import mx.events.CloseEvent;
+        import mx.managers.DragManager;
+        import mx.core.DragSource;
+        import mx.controls.Alert;
+        import com.mindspace.l10n.events.LocaleEvent;
 
         public var theMap:Map;
-               public var yahooListener:Object = new Object();
-               public var yahoo:YahooMap = new YahooMap(); 
-
-               private function initApp():void {
-
-                       Globals.vars.map_area=map_area;
-                       Globals.vars.root=map_area.rawChildren;                 // set up global reference to root level
-                       var _root:IChildList=map_area.rawChildren;              // convenient local shorthand
+        public var theController:EditController;
+               public var yahoo:Yahoo;
+               public var trackLoader:TrackLoader;
+               public var toolbox:Toolbox;
+        public var bugLoader:BugLoader;
+        public var bikeShopLoader:BikeShopLoader;
+
+               private var savecount:uint=0;
+               private var loadcount:uint=0;
+
+        include "version.as";
+
+               private function startInit():void {
+            /* For reasons that I don't yet understand, the en_US locale is the default and doesn't work at all. */
+            /* Change this to another locale (e.g. fr_FR) to see the differences. */
+            if (loaderInfo.parameters['locale']) {
+              dispatchEvent(new LocaleEvent(LocaleEvent.LOAD_LOCALE,loaderInfo.parameters['locale']));
+            }
+
+                       // Load font and don't do anything until that's done
+                       var loader:Loader = new Loader();
+                       loader.contentLoaderInfo.addEventListener(Event.COMPLETE, continueInit);
+                       loader.load(new URLRequest("FontLibrary.swf"));
+               }
+               
+               private function continueInit(r:Event):void {
+                       // Set font
+                       var FontLibrary:Class = r.target.applicationDomain.getDefinition("FontLibrary") as Class;
+                       Font.registerFont(FontLibrary.DejaVu);
+
+                       Globals.vars.map_area = map_area;
+                       Globals.vars.root = map_area.rawChildren;                       // set up global reference to root level
+                       var _root:IChildList = map_area.rawChildren;            // convenient local shorthand
+                       Globals.vars.nocache = loaderInfo.parameters['nocache'] == 'true';
+                       Globals.vars.flashvars = loaderInfo.parameters;
+
+                       // populate sharedObject with loaderInfo parameters if supplied
+                       var obj:SharedObject = SharedObject.getLocal("user_state");
+                       var objChanged:Boolean = false;
+                       if (loaderInfo.parameters['tileurl']) {
+                               obj.setProperty('background_url',loaderInfo.parameters['tileurl']); 
+                               obj.setProperty('background_name','Custom'); 
+                               objChanged=true;
+                       }
+                       if (loaderInfo.parameters['style']) { 
+                               obj.setProperty('stylesheet_url',loaderInfo.parameters['style']);
+                               obj.setProperty('stylesheet_name','Custom');
+                               objChanged=true; 
+                       }
+                       if (objChanged) { obj.flush(); }
 
                        // map backdrop object
             var w:uint = map_area.width;
             b.graphics.endFill();
                        _root.addChild(b);
 
-                       // Add Yahoo! background
-                       yahoo.init("f0a.sejV34HnhgIbNSmVHmndXFpijgGeun0fSIMG9428hW_ifF3pYKwbV6r9iaXojl1lU_dakekR", w, h);  
-                       yahoo.mapType="satellite";
-                       _root.addChild(yahoo);
-                       yahoo.visible=false;
-                       yahoo.alpha=0.5;
-
-                       // Yahoo! listeners
-                       yahooListener.yahooInit=function(event:YahooMapEvent):void {
-                               yahoo.zoomLevel = 18-theMap.scale;
-                               yahoo.centerLatLon = new LatLon(theMap.centre_lat, theMap.centre_lon);
-
-                               yahooListener.moveHandler=function(event:MapEvent):void {
-                                       if (!yahoo.visible) { return; }
-                                       yahoo.zoomLevel=18-event.params.scale;
-                                       yahoo.centerLatLon=new LatLon(event.params.lat, event.params.lon);
-                               };
-                               theMap.addEventListener(MapEvent.MOVE, yahooListener.moveHandler);
-
-                               yahooListener.resizeHandler=function(event:MapEvent):void {
-                                       yahoo.setSize(event.params.width, event.params.height);
-                               };
-                               theMap.addEventListener(MapEvent.RESIZE, yahooListener.resizeHandler);
-                       }
-                       yahoo.addEventListener(YahooMapEvent.MAP_INITIALIZE, yahooListener.yahooInit);
+                       // pass additional parameters to map
+                       var params:Object={}; var k:String;
+                       for (k in this.loaderInfo.parameters) params[k]=this.loaderInfo.parameters[k];
+                       for (k in SharedObject.getLocal('user_state').data) params[k]=SharedObject.getLocal('user_state').data[k];
 
-                       // add map
-                       theMap=new Map(this.loaderInfo.parameters);
+                       // Create map
+                       theMap=new Map();
                        theMap.backdrop=b;
+            theMap.updateSize(w,h);
+                       theMap.addEventListener(MapEvent.SCALE, scaleHandler);
+
+                       yahoo=new Yahoo(theMap);
+                       yahoo.hide();
+                       _root.addChild(yahoo);
                        _root.addChild(theMap);
-            theMap.updateSize(w, h);
-
-                       // add mask for map
-                       var s:Sprite=new Sprite();
-                       s.graphics.beginFill(0xFFFFFF,100);
-                       s.graphics.drawRect(0,0,w,h);
-                       s.graphics.endFill();
-                       _root.addChild(s);
-                       theMap.mask=s;
-
-                       // add crosshair
-                       /*s=new Sprite();
-                       s.graphics.lineStyle(2,0);
-                       s.graphics.moveTo(stage.stageWidth/2-20,stage.stageHeight/2);
-                       s.graphics.lineTo(stage.stageWidth/2+20,stage.stageHeight/2);
-                       s.graphics.moveTo(stage.stageWidth/2,stage.stageHeight/2-20);
-                       s.graphics.lineTo(stage.stageWidth/2,stage.stageHeight/2+20);
-                       _root.addChild(s);*/
+
+                       // Initialise 900913 background
+                       // >>>> REFACTOR: something odd about accessing map.tileparams here...
+                       theMap.tileset.blocks=[new RegExp("google","i")];       // hard-coded block on Google tiles
+                       theMap.tileset.init(theMap.tileparams, false, 
+                                           params['background_dim']    ==null ? true  : params['background_dim'],
+                                           params['background_sharpen']==null ? false : params['background_sharpen']);
+
+                       // Add core data layer
+                       // >>>> REFACTOR: shouldn't be hardcoded to XMLConnection
+                       var conn:Connection = new XMLConnection("Main", params['api'], params['policy'], params);
+            conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
+            conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
+            conn.addEventListener(Connection.SAVE_STARTED, onDataStart);
+            conn.addEventListener(Connection.SAVE_COMPLETED, onDataComplete);
+            conn.addEventListener(Connection.DATA_DIRTY, onDataDirty);
+            conn.addEventListener(Connection.DATA_CLEAN, onDataClean);
+                       conn.addEventListener(MapEvent.ERROR, onMapError);
+                       conn.addEventListener(AttentionEvent.ATTENTION, onAttention);
+                       conn.addEventListener(AttentionEvent.ALERT, onAlert);
+                       // >>>> REFACTOR: shouldn't be trying to find out stylesheet from here
+                       theMap.addLayer(conn,params['styleurl'] ? params['styleurl'] : 'stylesheets/potlatch.css',false);
+
+            // Auto-load vector backgrounds from config
+            theMap.addEventListener(MapEvent.INITIALISED, function(e:Event):void { VectorBackgrounds.instance().init(theMap); });
+
+                       // Set start position of map
+                       // >>>> REFACTOR: what happens if lat/lon/zoom not supplied? (Hurleston GPX case)
+                       theMap.init(params['lat'], params['lon'], params['zoom']);
+
+                       // add attribution/logo sprite
+                       var overlay:Sprite=new Sprite();
+                       var attribution:TextField=new TextField();
+                       attribution.width=220; attribution.height=300;
+                       attribution.multiline=true;
+                       attribution.wordWrap=true;
+                       attribution.selectable=false;
+                       attribution.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, false);
+                       overlay.addChild(attribution);
+                       var terms:TextField=new TextField();
+                       terms.width=200; terms.height=15;
+                       terms.selectable=false;
+                       terms.defaultTextFormat=new TextFormat("_sans", 9, 0, false, false, true);
+                       overlay.addChild(terms);
+                       _root.addChild(overlay);
 
                        // mouse-up handler attached to stage, so the user can release outside the map
                        stage.addEventListener(MouseEvent.MOUSE_UP, theMap.mouseUpHandler);
                        Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_MOVE, theMap.mouseMoveHandler);
                        Globals.vars.map_area.addEventListener(MouseEvent.MOUSE_DOWN, theMap.mouseDownHandler);
 
+                       // initialise imagery and stylesheets
+                       Imagery.instance().init(theMap, overlay, yahoo);
+                       Stylesheets.instance().init(theMap);
+                       Imagery.instance().addEventListener(MapEvent.BUMP, bumpHandler);
+
                        // keyboard event attached to stage
                        stage.addEventListener(KeyboardEvent.KEY_UP, theMap.keyUpHandler);
+            
+                       // mouse-position listener for co-ordinate display
+            theMap.addEventListener(MapEvent.MOUSE_MOVE, mouseoverHandler);
 
-                       // example listener event
-                       var myListenerObj:Object = new Object();
-                       myListenerObj.mapHandler=function(event:MapEvent):void {
-                               Globals.vars.debug.appendText("Download event fired - "+event.params.minlat+","+event.params.minlon+"\n");
-                       };
-                       theMap.addEventListener(MapEvent.DOWNLOAD, myListenerObj.mapHandler);
+                       // position toolbox
+                       toolbox=Toolbox(PopUpManager.createPopUp(this,Toolbox,false));
+                       toolbox.init(theController);
+                       toolbox.x=stage.stageWidth-toolbox.width-5;
+                       toolbox.y=stage.stageHeight-toolbox.height-5;
 
                        // add debug field
                        var t:TextField=new TextField();
             t.visible = loaderInfo.parameters["show_debug"] == 'true';
                        Globals.vars.root=theMap;       // just for the addDebug function
 
-            var controller:EditController = new EditController(theMap, tagViewer);
-            controller.setActive();
+            theController = new EditController(theMap, tagViewer, toolbox);
+            theController.setActive();
+                       theController.addEventListener(AttentionEvent.ATTENTION, onAttention);
+                       theController.addEventListener(AttentionEvent.ALERT, onAlert);
             
-            var conn:Connection = Connection.getConnectionInstance();
-            conn.addEventListener(Connection.LOAD_STARTED, onDataStart);
-            conn.addEventListener(Connection.LOAD_COMPLETED, onDataComplete);
+            // set the access token from saved cookie
+            var tokenObject:SharedObject = SharedObject.getLocal("access_token");
+            conn.setAccessToken(tokenObject.data["oauth_token"], tokenObject.data["oauth_token_secret"]);
+
+            // Load any requested GPX track
+            if (loaderInfo.parameters['gpx']) {
+                var id:Number = loaderInfo.parameters['gpx'];
+                if (conn.hasAccessToken()) { 
+                    loadTrace(id);
+                } else {
+                    SaveManager.ensureAccess(function ():void { loadTrace(id); }, conn);
+                }
+            }
+
+                       // Load arbitrary GPX from provided URL
+                       if (loaderInfo.parameters['gpx_url']) {
+
+                var gpx_url:String = loaderInfo.parameters['gpx_url'];
+
+                var connection:Connection = new Connection(name, gpx_url, null, null);
+                var gpx:GpxImporter=new GpxImporter(connection, theMap, [gpx_url],
+                                                function(success:Boolean,message:String=null):void {
+                                                    if (!success) return;
+                                                    var paint:MapPaint = theMap.addLayer(connection, "stylesheets/gpx.css");
+                                                    paint.updateEntityUIs(false, false);
+                                                    dispatchEvent(new Event("layers_changed"));
+                                                }, false);
+                       }
+
+                       // create GPS trackloader
+                       trackLoader=new TrackLoader(theMap,conn.apiBase);
+
+            // Force authentication on startup, if required
+            // force_auth == force => checks for access token, and displays OAuth panel if needed
+            var force_auth:String = loaderInfo.parameters["force_auth"];
+            if (!conn.hasAccessToken() && force_auth == 'force') {
+              SaveManager.ensureAccess(onAccessChecked, conn);
+            }
+
+            // show help dialog on startup, if required
+            // show_help == always => on every startup
+            // show_help == once => show on first startup only
+            var show_help:String = loaderInfo.parameters["show_help"];
+
+            if (show_help == 'always' || (show_help == 'once' && obj.data["help_shown"] != "true")) {
+              new HelpDialog().init();
+            }
+
+            // Check if Tiger highlighting should be enabled from saved object
+            Globals.vars.highlightTiger = obj.data['tiger_highlighted'];
+               }
+               
+               public function onMapError(mapEvent:MapEvent):void {
+                       var buttons:uint=0;
+                       if (mapEvent.params.no) { trace("no is set"); }
+                       if (mapEvent.params.yes             ) buttons|=mx.controls.Alert.YES;
+                       if (mapEvent.params.no              ) buttons|=mx.controls.Alert.NO;
+                       if (mapEvent.params.cancel          ) buttons|=mx.controls.Alert.CANCEL;
+                       if (mapEvent.params.ok || buttons==0) buttons|=mx.controls.Alert.OK;
+                       trace("showing alert with "+buttons);
+                       Alert.show(mapEvent.params.message, 'Error', buttons, null, function(closeEvent:CloseEvent):void { 
+                               switch (closeEvent.detail) {
+                                       case mx.controls.Alert.CANCEL:  mapEvent.params.cancel(); break; //fixme? this gets called if user presses escape, even if there's no cancel button.
+                                       case mx.controls.Alert.YES:             mapEvent.params.yes(); break;
+                                       case mx.controls.Alert.NO:              mapEvent.params.no(); break;
+                                       default:                                                if (mapEvent.params.ok) mapEvent.params.ok();
+                               }
+                       });
+               }
+
+               /** Highlight an entity in response to an 'attention' event */
+
+               public function onAttention(event:AttentionEvent):void {
+                       var entity:Entity=event.entity;
+                       if (entity is Relation) {
+                               // If it's a relation, just bring up the editor panel
+                               var panel:RelationEditorPanel = RelationEditorPanel(
+                                       PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
+                               panel.setRelation(entity as Relation);
+                               PopUpManager.centerPopUp(panel);
+                               return;
+                       }
+
+                       var lat:Number, lon:Number;
+                       var panTo:Boolean=true;
+                       if (entity is Way) {
+                               // If it's a way, find if it's on-screen
+                               for (var i:uint=0; i<Way(entity).length; i++) {
+                                       var node:Node=Way(entity).getNode(i)
+                                       if (node.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
+                                       lat=node.lat; lon=node.lon;
+                               }
+                       } else if (entity is Node) {
+                               // If it's a node, check if it's on-screen
+                               if (entity.within(theMap.edge_l,theMap.edge_r,theMap.edge_t,theMap.edge_b)) { panTo=false; }
+                               lat=Node(entity).lat; lon=Node(entity).lon;
+                       }
+                       // Pan if required, and select the object
+                       if (panTo) { theMap.moveMapFromLatLon(lat,lon); }
+                       theController.setState(theController.findStateForSelection([entity]));
+               }
+
+               /** Display floating warning in response to an 'alert' event */
 
-                       // and to import a shapefile...
-//                     var importer:ShpImporter = new ShpImporter(theMap, ["http://127.0.0.1/~richard/shp/wildrnp020.shp","http://127.0.0.1/~richard/shp/wildrnp020.shx","http://127.0.0.1/~richard/shp/wildrnp020.dbf"]);
+               public function onAlert(event:AttentionEvent):void {
+                       var alert:FloatingAlert=new FloatingAlert(event.message);
+                       stage.addChild(alert);
                }
 
         public function onResizeMap():void {
             if ( theMap != null )
                 theMap.updateSize(map_area.width, map_area.height);
+
+                       if (toolbox) {
+                               toolbox.x=Math.min(toolbox.x,stage.stageWidth-toolbox.width-5);
+                               toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-5);
+                       }
+        }
+               private function bumpHandler(e:MapEvent):void {
+                       if (toolbox) {
+                               toolbox.y=Math.min(toolbox.y,stage.stageHeight-toolbox.height-10-e.params.y);
+                       }
+               }
+
+        private function mouseoverHandler(e:MapEvent):void {
+            if (coordsbox.visible) {
+                coordsbox.text= Number(e.params.x).toFixed(5) + "\n " + Number(e.params.y).toFixed(5); // Not sure if 5 dp's really required.
+            }
         }
 
         private function onDataStart(event:Event):void {
-            dataWorking.text = event.type == Connection.LOAD_STARTED ? "Loading data..." : "Saving Data...";
-            dataWorking.visible = true;
+                       switch (event.type) {
+                               case Connection.LOAD_STARTED:   loadcount++; break;
+                               case Connection.SAVE_STARTED:   savecount++; break;
+                       }
+                       updateDataWorking();
         }
         private function onDataComplete(event:Event):void {
-            dataWorking.visible = false;
+                       switch (event.type) {
+                               case Connection.LOAD_COMPLETED: loadcount--; break;
+                               case Connection.SAVE_COMPLETED: savecount--; break;
+                       }
+            updateDataWorking();
         }
+               private function updateDataWorking():void {
+                       if (loadcount>0 && savecount>0) { dataWorking.text="Loading/saving..."; }
+                       else if (loadcount>0)           { dataWorking.text="Loading data..."; }
+                       else if (savecount>0)           { dataWorking.text="Saving data..."; }
+                       else                            { dataWorking.text=""; }
+                       dataWorking.visible=(dataWorking.text!="");
+               }
+        private function onDataDirty(event:Event):void {
+                       saveButton.enabled=true;
+            if (ExternalInterface.available) {
+              ExternalInterface.call("markChanged", false);
+            }
+               }
+               private function onDataClean(event:Event):void {
+                       saveButton.enabled=false;
+            if (ExternalInterface.available) {
+              ExternalInterface.call("markChanged", true);
+            }
+               }
+               
 
-               private function updateBackground():void {
-                       var bg:String=background.selectedItem.data;
-                       if (bg=='yahoo') {
-                               theMap.tileset.init('',false);
-                               yahoo.visible=true;
-                               yahoo.zoomLevel = 18-theMap.scale;
-                               yahoo.centerLatLon = new LatLon(theMap.centre_lat, theMap.centre_lon);
-                       } else {
-                               theMap.tileset.init(background.selectedItem.data,true);
-                               yahoo.visible=false;
-                       }
+
+               private function scaleHandler(event:MapEvent):void {
+                       dispatchEvent(new Event("rescale"));
                }
                
+               [Bindable(event="rescale")]
+               private function getScale():String {
+                       return String(theMap.scale);
+               }
+
+        private function dragEnterHandler(event:DragEvent):void {
+            // Get the drop target component from the event object.
+            var dropTarget:Canvas=event.currentTarget as Canvas;
+            // Accept the drag only if the user is dragging poi with tags
+            if (event.dragSource.hasFormat('tags')) 
+            {
+                DragManager.acceptDragDrop(dropTarget);
+            }
+        }
+        
+        private function dragDropHandler(event:DragEvent):void {
+                       // Deselect the dragged icon
+                       if (event.dragSource.dataForFormat('container')) {
+                               event.dragSource.dataForFormat('container').selectedItem=-1;
+                       }
+
+                       // Get the tags
+            var tags:Array = event.dragSource.dataForFormat('tags') as Array;
+
+            // If you dnd quick enough, this exposes a flex bug and event.stageX/Y become negative.
+            // Take the mouse positions from a displayObject's stage for consistent results.
+            var mapLoc:Point = Globals.vars.root.globalToLocal(new Point(event.target.stage.mouseX, event.target.stage.mouseY));
+            var lat:Number = Globals.vars.root.coord2lat(mapLoc.y);
+            var lon:Number = Globals.vars.root.coord2lon(mapLoc.x);
+            
+            var createAction:CompositeUndoableAction = new CompositeUndoableAction("Create POI");
+            
+                       var conn:Connection = theMap.editableLayer.connection;
+            var node:Node = conn.createNode({}, lat, lon, createAction.push);
+            for each ( var tag:Object in tags ) {
+                node.setTag(tag.k, tag.v, createAction.push);
+            }
+                       conn.registerPOI(node);
+                       MainUndoStack.getGlobalStack().addAction(createAction);
+            theController.setState(new SelectedPOINode(node));
+        }
+
+        /* Called when forcing an initial access token check. */
+        private function onAccessChecked():void {
+            // Floaty panel message "You now have access";
+        }
+
+        private function loadTrace(id:Number):void {
+            var conn:Connection = theMap.editableLayer.connection;
+            conn.addEventListener(Connection.TRACES_LOADED, function (e:Event):void {
+                for each (var trace:Trace in conn.getTraces()) {
+                    if (trace.id == id) { trace.addToMap(); }
+                }
+            });
+            conn.fetchUserTraces();
+        }
+
        ]]></mx:Script>
 
 </mx:Application>