Allow numpad + as well as "equals plus". (Like P1)
[potlatch2.git] / net / systemeD / potlatch2 / TagViewer.mxml
index c5cc3fe..0048866 100644 (file)
@@ -2,86 +2,94 @@
 <mx:VBox
        xmlns:mx="http://www.adobe.com/2006/mxml"
        xmlns:flexlib="flexlib.containers.*"
+       xmlns:controls="net.systemeD.controls.*"
+       xmlns:potlatch2="net.systemeD.potlatch2.*"
+    xmlns:sidepanel="net.systemeD.potlatch2.panels.*"
+       horizontalScrollPolicy="off"
     backgroundColor="white"
     initialize="loadFeatures()">
 
 <mx:ViewStack id="sidebar" width="100%" height="100%" creationPolicy="all">
-  <mx:VBox id="dndPanel" width="100%" height="100%">
-    <mx:Text text="Drag and Drop Points of Interest" />
-    <mx:TileList id="poiGrid" dataProvider="{MapFeatures.getInstance().pois}" width="100%">
-      <mx:itemRenderer>
-        <mx:Component>
-          <mx:VBox>
-            <mx:Script><![CDATA[
-              import mx.events.DragEvent;
-              import mx.managers.DragManager;
-              import mx.core.DragSource;
-                  
-              private function dragPOI(event:MouseEvent, tags:Array):void {
-                  // Get the drag initiator component from the event object.
-                  var dragInitiator:Image = event.currentTarget as Image;
-                  var dragSource:DragSource = new DragSource();
-                  dragSource.addData(tags, 'tags');
-                  
-                  var dragProxy:Image = new Image();
-                  dragProxy.source = dragInitiator.source;
-                  dragProxy.width = dragInitiator.width;   // must set width and height explicitly
-                  dragProxy.height = dragInitiator.height; // for non-embedded images
-                  DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
-              }
-            ]]></mx:Script>
-            <mx:Image id="foo" source="{data.image}" height="25" width="25" mouseMove="dragPOI(event, data.tags)"/>
-          </mx:VBox>
-        </mx:Component>
-      </mx:itemRenderer>
-    </mx:TileList>
+  <mx:VBox id="dndPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
+    <mx:Text id="dndPanelText" text="{dndPrompt}" width="100%" styleName="helpInfo" />
+       <mx:Repeater id="dndRep" dataProvider="{MapFeatures.getInstance().getCategoriesForType('point')}" styleName="dndRepeater">
+               <mx:HBox width="100%" styleName="dndPanelCategory">
+                       <mx:Label text="{dndRep.currentItem.name}:" styleName="dndPanelCategoryLabel"/>
+               </mx:HBox>
+
+               <mx:TileList dataProvider="{dndRep.currentItem.getFeaturesForType('point')}" width="100%" height="1"
+                                    rowHeight="32" columnWidth="32" updateComplete="resizePOIGrid(event)" styleName="dndPanelTileList">
+                       <mx:itemRenderer>
+                               <mx:Component>
+                                       <mx:VBox toolTip="{data.name}">
+                                               <mx:Script><![CDATA[
+                                                       import mx.events.DragEvent;
+                                                       import mx.managers.DragManager;
+                                                       import mx.core.DragSource;
+
+                                                       private function dragPOI(event:MouseEvent, tags:Array):void {
+                                                               // Get the drag initiator component from the event object.
+                                                               var dragInitiator:Image = event.currentTarget as Image;
+                                                               var dragSource:DragSource = new DragSource();
+                                                               dragSource.addData(tags, 'tags');
+                                                               dragSource.addData(event.target.parent.parent.parent.parent, 'container');
+
+                                                               var dragProxy:Image = new Image();
+                                                               dragProxy.source = dragInitiator.source;
+                                                               dragProxy.width = dragInitiator.width;   // must set width and height explicitly
+                                                               dragProxy.height = dragInitiator.height; // for non-embedded images
+                                                               DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
+                                                       }
+                                               ]]></mx:Script>
+                                               <mx:Image id="foo" source="{data.image}" height="24" width="24" mouseMove="dragPOI(event, data.tags)" toolTip="{data.name}" />
+                                       </mx:VBox>
+                               </mx:Component>
+                       </mx:itemRenderer>
+               </mx:TileList>
+       </mx:Repeater>
   </mx:VBox>
-  
-  <mx:VBox id="tagsPanel" width="100%" height="100%">
+
+  <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto">
     <mx:ViewStack id="stack" width="100%" height="100%">
-      <mx:VBox width="100%" height="100%" label="Simple">
-        <mx:HBox borderStyle="inset" verticalAlign="middle" width="100%" paddingLeft="3" id="iconContainer">
+      <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()" styleName="dndPanelVbox">
+        <mx:VBox width="100%" verticalGap="1" styleName="dndTagHeader">
+          <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
             <mx:Image id="iconImage"/>
-            <mx:VBox width="100%" verticalGap="1">
-              <mx:PopUpButton id="popupChange" creationComplete="initFeatureBox()" openAlways="true" width="100%"/>
-              <mx:Text condenseWhite="true" width="100%" id="iconText"/>
-            </mx:VBox>
-            <mx:LinkButton label="?" click="openDescription()" id="helpLabel"/>
-        </mx:HBox>
-        <flexlib:SuperTabNavigator id="editorStack" width="100%" height="100%" paddingLeft="2" paddingRight="2"
-            allowTabSqueezing="false" minTabWidth="10" closePolicy="close_never"
-            scrollSpeed="20" change="ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox)"/>
+            <mx:Text condenseWhite="true" width="100%" id="iconText" styleName="dndIconText"/>
+          </mx:HBox>
+          <mx:HBox width="100%">
+            <mx:PopUpButton id="popupChange" creationComplete="initFeatureBox()" openAlways="true" width="100%" styleName="dndTagPopUpMenu"/>
+            <mx:LinkButton icon="@Embed('../../../embedded/information.svg')" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
+          </mx:HBox>
+        </mx:VBox>
       </mx:VBox>
-
-      <mx:VBox width="100%" height="100%" label="Advanced" initialize="checkAdvanced()" verticalGap="1">
-        <mx:Label id="advancedID">
+      <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
+        <mx:Label id="advancedID" click="openEntityPage()">
           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
         </mx:Label>
 
-        <mx:DataGrid editable="true" width="100%" height="75%" id="advancedTagGrid">
-                <mx:columns>
-                    <mx:DataGridColumn editable="true" dataField="key" headerText="Key"/>
-                    <mx:DataGridColumn editable="true" dataField="value" headerText="Value"/>
-                </mx:columns>
-        </mx:DataGrid>
+               <potlatch2:TagGrid id="advancedTagGrid" width="100%" height="75%" />
 
         <mx:HBox horizontalAlign="right" width="100%">
-          <mx:LinkButton label="Delete" click="removeTag()" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
-          <mx:LinkButton label="Add" click="addNewTag()"/>
+          <mx:LinkButton label="Delete" click="advancedTagGrid.removeTag()" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
+          <mx:LinkButton label="Add" click="advancedTagGrid.addNewTag()" id="advancedAddButton"/>
         </mx:HBox>
-        
+
         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
             doubleClickEnabled="true"
-            itemDoubleClick="editRelation(relationsGrid.selectedItem.id)">
+            itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
+            doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
             <mx:columns>
                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
-                <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
+                <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
+                    <mx:itemEditor><mx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></mx:Component></mx:itemEditor>
+                </mx:DataGridColumn>
             </mx:columns>
         </mx:DataGrid>
 
         <mx:HBox horizontalAlign="right" width="100%">
-          <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)" 
+          <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)"
                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
           <mx:LinkButton label="Add to" click="addToRelation()"/>
         </mx:HBox>
           <mx:columns>
             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
-            <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
+            <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
+                               <mx:itemEditor><mx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></mx:Component></mx:itemEditor>
+                       </mx:DataGridColumn>
           </mx:columns>
         </mx:DataGrid>
       </mx:VBox>
-      
+
       </mx:ViewStack>
-    <mx:LinkBar dataProvider="{stack}"/>
+
+         <mx:HBox width="100%">
+               <mx:LinkBar dataProvider="{stack}"/>
+               <mx:Spacer width="100%"/>
+               <mx:LinkButton
+                       icon="@Embed('../../../embedded/view_tabbed.png')"
+                       disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
+                       click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6"
+                       toolTip="Show in tabs"
+                       enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
+               <mx:LinkButton
+                       icon="@Embed('../../../embedded/view_accordion.png')"
+                       disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
+                       click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
+                       toolTip="Show in sliding windows"
+                       enabled="{editorStack is SuperTabNavigator &amp;&amp; stack.selectedIndex==0}" />
+         </mx:HBox>
   </mx:VBox>
+
+  <mx:VBox id="multiplePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
+    <potlatch2:TagGrid id="multiAdvancedTagGrid" width="100%" height="75%" />
+       <mx:HBox horizontalAlign="right" width="100%">
+         <mx:LinkButton label="Delete" click="multiAdvancedTagGrid.removeTag()" enabled="{multiAdvancedTagGrid.selectedItem != null? true : false}"/>
+         <mx:LinkButton label="Add" click="multiAdvancedTagGrid.addNewTag()" />
+       </mx:HBox>
+  </mx:VBox>
+
+  <mx:VBox id="multipleInvalidPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
+       <mx:Text id="multipleInvalidPanelText" text="You have selected multiple items." width="100%" styleName="helpInfo" />
+  </mx:VBox>
+
+  <mx:VBox id="markerPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
+    <sidepanel:MarkerPanel id="markerPanelContents" width="100%"/>
+  </mx:VBox>
+
+  <mx:VBox id="bugPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
+    <sidepanel:BugPanel id="bugPanelContents" width="100%"/>
+  </mx:VBox>
+
 </mx:ViewStack>
 
   <mx:Script><![CDATA[
       import net.systemeD.halcyon.connection.*;
+      import net.systemeD.halcyon.VectorLayer;
       import net.systemeD.potlatch2.mapfeatures.*;
 
       import mx.collections.*;
       import mx.events.DragEvent;
       import mx.managers.DragManager;
       import mx.core.DragSource;
-      
-      private var mapFeatures:MapFeatures;
+      import flexlib.containers.SuperTabNavigator;
+
+      private static const dndPrompt:String="Add new points by dragging them onto the map";
+
+      private var editorStackTabNavigator:SuperTabNavigator;
+      private var editorStackAccordion:Accordion;
+      [Bindable] private var editorStack:Container;
+
+      public var mapFeatures:MapFeatures;
       private var selectedEntity:Entity;
-      private var tagDataProvider:ArrayCollection;
       private var tw:CategorySelector = null;
       private var feature:Feature = null;
 
-      public function setEntity(entity:Entity):void {
-          if ( selectedEntity != entity ) {
-              if ( selectedEntity != null )
-                  selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
-              selectedEntity = entity;
-              if ( selectedEntity != null )
-                  selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
-          }
+         public function setEntity(entities:Array, layer:VectorLayer=null):void {
+               UIComponent.suspendBackgroundProcessing();
+
+               var firstSelected:Entity=null;
+               if (entities.length==1) { firstSelected=entities[0]; }
+
+               if (selectedEntity!=firstSelected && selectedEntity!=null) {
+                       selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
+               }
+
+               if (entities.length==0) {
+                       // Nothing selected, so show drag-and-drop panel
+                       sidebar.selectedChild = dndPanel;
+
+               } else if (entities.length==1) {
+                       // Single entity selected, so show tag panel
+                       selectedEntity=firstSelected;
+                       if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
+                       if (advancedID!=null) { setupAdvanced(firstSelected); }
+                       if (firstSelected is Relation) { stack.addChild(membersVBox); }
+            if (selectedEntity is Marker && layer is BugLayer) {
+              bugPanelContents.init(selectedEntity, layer);
+              sidebar.selectedChild = bugPanel;
+            } else if (selectedEntity is Marker) {
+              markerPanelContents.init(selectedEntity, layer);
+              sidebar.selectedChild = markerPanel;
+            } else {
+              refreshFeatureIcon();
+              initialiseEditors();
+              sidebar.selectedChild = tagsPanel;
+            }
 
-          if ( advancedID != null )
-              setupAdvanced(entity);
-          if (entity is Relation) {
-              stack.addChild(membersVBox);
-          }
-          refreshFeatureIcon(); 
-          
-          if (selectedEntity == null) {
-            sidebar.selectedChild = dndPanel;
-          } else {
-            sidebar.selectedChild = tagsPanel;
-          }
+               } else if(isMultipleEditable(entities)) {
+                       selectedEntity = new EntityCollection(entities);
+                       selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
+            sidebar.selectedChild = multiplePanel;
+                       setupMultiAdvanced(selectedEntity);
+
+               } else {
+                       //The selection contains elements which can't be edited all together.
+                       sidebar.selectedChild = multipleInvalidPanel;
+               }
+               UIComponent.resumeBackgroundProcessing();
       }
 
       private function refreshFeatureIcon():void {
                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
               if ( feature != null )
                   feature.addEventListener("imageChanged", featureImageChanged);
-              initialiseEditors();
           }
 
-          if ( feature != null )
+          if ( feature != null && feature.name != null ) {
               setFeatureIcon(selectedEntity, feature);
-          else
+          } else {
               blankFeatureIcon(selectedEntity);
+          }
       }
 
       private function featureImageChanged(event:Event):void {
           setFeatureIcon(selectedEntity, feature);
       }
-      
+
       private function setFeatureIcon(entity:Entity, feature:Feature):void {
           //blankFeatureIcon(entity);
-          
+
           iconImage.source = feature.image;
 
           var txt:String = feature.htmlDetails(entity);
           tw.setSelectedFeature(feature);
           helpLabel.visible = feature.hasHelpURL();
       }
-      
+
+         private function isMultipleEditable(entities:Array):Boolean {
+               for each(var entity:Entity in entities) {
+                       if(!(entity is Node || entity is Way))
+                               return false;
+               }
+               return true;
+         }
+
       private function setLimitTypes(entity:Entity):void {
           var type:String = null;
           if ( entity is Node )
 
       private function blankFeatureIcon(entity:Entity):void {
           iconImage.source = null;
-          iconText.htmlText = entity == null ?
-               "<i>Nothing selected</i>" :
-               "<b>Not recognised</b><br/>Try looking at the tags under the advanced properties";
           popupChange.label = "unknown";
           setLimitTypes(entity);
-          tw.setSelectedFeature(null);
+                 if (entity == null) {
+                       iconText.htmlText = "<i>Nothing selected</i>";
+            tw.setNoSelectedFeature();
+                 } else if (entity.hasTags()) {
+                       iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
+            tw.setSelectedFeature(null);
+                 } else {
+                       iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
+            tw.setSelectedFeature(null);
+          }
           helpLabel.visible = false;
       }
 
       private var tabComponents:Object = {};
-      
+
       private function initialiseEditors():void {
           editorStack.removeAllChildren();
           if ( selectedEntity == null || feature == null )
               return;
-          
+
           var editorBox:VBox = createEditorBox();
           editorBox.label = "Basic";
           editorStack.addChild(editorBox);
-          
+
           var tabs:Object = {};
           tabComponents = {};
-          
+
           for each (var factory:EditorFactory in feature.editors) {
               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
                       editorBox.addChild(editor);
               }
               var category:String = factory.category;
-              var tab:VBox = tabs[category];
-              if ( tab == null ) {
-                  tab = createEditorBox();
-                  tab.label = category;
-                  editorStack.addChild(tab);
-                  tabs[category] = tab;
-                  tabComponents[tab] = [];
+              if (category!='') {
+                     var tab:VBox = tabs[category];
+                     if ( tab == null) {
+                         tab = createEditorBox();
+                         tab.label = category;
+                         editorStack.addChild(tab);
+                         tabs[category] = tab;
+                         tabComponents[tab] = [];
+                     }
+                     var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
+                     if ( catEditor != null )
+                         tabComponents[tab].push(catEditor);
+                     //    tab.addChild(catEditor);
               }
-              var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
-              if ( catEditor != null )
-                  tabComponents[tab].push(catEditor);
-              //    tab.addChild(catEditor);
           }
       }
-      
+
       private function createEditorBox():VBox {
           var box:VBox = new VBox();
           box.percentWidth = 100;
           box.percentHeight = 100;
+          box.styleName = "dndEditorContainer";
           return box;
       }
 
               tab.addChild(component);
           }
       }
-      
+
+       private function initEditorStackUIs():void {
+               editorStackTabNavigator = new SuperTabNavigator();
+               editorStackTabNavigator.allowTabSqueezing=false;
+               editorStackTabNavigator.minTabWidth=10;
+               editorStackTabNavigator.closePolicy="close_never";
+               editorStackTabNavigator.scrollSpeed=20;
+               editorStackTabNavigator.creationPolicy="auto";
+               editorStackTabNavigator.percentWidth=100;
+               editorStackTabNavigator.percentHeight=100;
+               editorStackTabNavigator.styleName="dndStackTab";
+               editorStackTabNavigator.popUpButtonPolicy="off"
+
+
+               editorStackAccordion = new Accordion();
+               editorStackAccordion.percentWidth=100;
+               editorStackAccordion.percentHeight=100;
+               editorStackAccordion.creationPolicy="auto";
+               editorStackAccordion.styleName="dndStackAccordion";
+
+               setEditorStackUI(true);
+       }
+
+       private function setEditorStackUI(isTabbed:Boolean):void {
+               var children:Array=[]; var i:uint;
+
+               if (editorStack) {
+                       // blank existing component
+                       editorStack.removeEventListener("change",editorStackUIChange);
+                       editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
+                       editorStack.removeAllChildren();
+                       editorContainer.removeChildAt(1);
+               }
+
+               // replace with new component
+               editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
+               editorContainer.addChild(editorStack);
+
+               // re-add children and listeners
+               initialiseEditors();
+               editorStack.addEventListener("change",editorStackUIChange);
+               editorStack.addEventListener("updateComplete",editorStackUIUpdate);
+       }
+
+       private function editorStackUIChange(event:Event):void {
+               ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
+       }
+
+       private function editorStackUIUpdate(event:Event):void {
+               if (editorStack is SuperTabNavigator) {
+                       var e:SuperTabNavigator = editorStack as SuperTabNavigator;
+                       if (e.selectedIndex<0) { return; }
+                       for (var i:uint=0; i<e.numChildren; i++) {
+                               e.getTabAt(i).selected=(i==e.selectedIndex);
+                       }
+               }
+       }
+
+
+       public function togglePanel():void {
+               if (stack.selectedChild==editorContainer && selectedEntity!=null) {
+                       stack.selectedChild=advancedContainer;
+               } else if (stack.selectedChild!=editorContainer) {
+                       stack.selectedChild=editorContainer;
+               }
+       }
+
       private function checkAdvanced():void {
           if ( selectedEntity != null )
              setupAdvanced(selectedEntity);
       }
 
+      /**
+      * When you enter a new tag and press enter, the focus moves to the add button
+      * Adding an event listener to the button and listening for + means that you
+      * can add two consecutive tags with the same keypress. This relies on focus
+      * moving to the "add" button, though, so it's not robust to rearranging the UI.
+      */
+      private function advancedAddButtonKeyboardEvent(event:KeyboardEvent):void {
+          switch (event.keyCode) {
+            case 187:   addNewTag(); break;                          // + - add tag
+            case 107:   addNewTag(); break;                          // numpad plus
+          }
+      }
+
       private var listeningToRelations:Array = [];
-      
+
       private function setupAdvanced(entity:Entity):void {
-          if ( tagDataProvider == null ) {
-              tagDataProvider = new ArrayCollection();
-              advancedTagGrid.dataProvider = tagDataProvider;
-          }
+               if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
+               advancedTagGrid.init(entity);
+        advancedAddButton.addEventListener(KeyboardEvent.KEY_DOWN, advancedAddButtonKeyboardEvent);
+
+               if ( entity == null ) {
+                       advancedID.htmlText = "";
+               } else {
+                       var entityText:String = "xx";
+                       if      ( entity is Node     ) entityText = "Node";
+                       else if ( entity is Way      ) entityText = "Way";
+                       else if ( entity is Relation ) entityText = "Relation";
+                       advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
+               }
+
+               removeRelationListeners();
+               if ( selectedEntity != null ) {
+                       selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
+                       selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
+               }
+
+               if ( entity == null ) {
+                       relationsGrid.dataProvider = null;
+               } else {
+                       resetRelationsGrid(entity);
+                       entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
+                       entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
+               }
+      }
 
-          tagDataProvider.removeAll();
-          
-          if ( entity == null ) {
-              advancedID.htmlText = "";
-          } else {
-              var entityText:String = "xx";
-              if ( entity is Node ) entityText = "Node";
-              else if ( entity is Way ) entityText = "Way";
-              else if ( entity is Relation ) entityText = "Relation";
-              advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
-
-              var tags:Array = entity.getTagArray();
-              tags.sortOn("key");
-              for each(var tag:Tag in tags)
-                  tagDataProvider.addItem(tag);
-          }
-                    
-          removeRelationListeners();
-          if ( selectedEntity != null ) {
-              selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
-              selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
-          }
-          
-          if ( entity == null ) {
-              relationsGrid.dataProvider = null;
-          } else {
-              resetRelationsGrid(entity);
-              entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
-              entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
-          }
+         private function setupMultiAdvanced(entity:Entity):void {
+               multiAdvancedTagGrid.init(entity);
       }
-      
+
+         public function addNewTag():void {
+               if (stack.selectedChild!=advancedContainer) { return; }
+               advancedTagGrid.addNewTag();
+         }
+
       private function addedToRelation(event:RelationMemberEvent):void {
          resetRelationsGrid(selectedEntity);
       }
               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
           }
           listeningToRelations = [];
+          relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
       }
-            
+
       private function resetRelationsGrid(entity:Entity):void {
           removeRelationListeners();
           var relations:Array = [];
 
                   relations.push(props);
               }
-              
+
               rel.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
               rel.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
               rel.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
               listeningToRelations.push(rel);
           }
           relationsGrid.dataProvider = relations;
+          relationsGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
+      }
+
+      private function relationRoleChanged(event:DataGridEvent):void {
+               if (event.dataField != 'role') { return; }      // shouldn't really happen
+
+               var relations:Array=event.currentTarget.dataProvider.toArray();
+               var props:Object=relations[event.rowIndex];
+
+               var relation:Relation=props['relation'];
+               var index:uint=props['index'];
+               var newRole:String=event.itemRenderer.data['role'];
+
+               relation.setMember(index, new RelationMember(selectedEntity,newRole));
       }
-      
+
       private function relationTagChanged(event:TagEvent):void {
           resetRelationsGrid(selectedEntity);
       }
       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
           resetRelationsGrid(selectedEntity);
       }
-      
+
       private function checkMembers():void {
           if (selectedEntity is Relation) {
             setupMembers(selectedEntity as Relation);
           }
       }
-      
+
       private function setupMembers(rel:Relation):void {
           var members:Array = [];
           for (var i:int=0 ; i<rel.length; i++) {
             props["id"] = member.entity.id;
             props["type"] = member.entity.getType();
             props["role"] = member.role;
-            
+
             members.push(props);
           }
           membersGrid.dataProvider = members;
-          membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
+          membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
       }
-      
+
       private function membersChange(event:Event):void {
           // Dropping all the members and re-adding them isn't exactly optimal
           // but is at least robust for any kind of change.
           // Figuring out a better way is someone else's FIXME
-          
+
           var conn:Connection = Connection.getConnectionInstance();
           var rel:Relation = selectedEntity as Relation
-          
+          var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
+
           // drop members
-          trace("Dropping "+rel.length+" members");
           for (var i:int=rel.length-1 ; i>=0; i--) {
-            rel.removeMemberByIndex(i);
+            rel.removeMemberByIndex(i, action.push);
           }
-          
+
           // add members in new order
           for each(var memberObject:Object in membersGrid.dataProvider) {
             var e:Entity;
-            var id:int = memberObject.id;
+            var id:Number = memberObject.id;
             if(memberObject.type == 'node') {
               e = conn.getNode(id);
             } else if (memberObject.type == 'way') {
             } else if (memberObject.type == 'relation') {
               e = conn.getRelation(id);
             }
-            rel.appendMember(new RelationMember(e, memberObject.role));
-            trace("added member "+memberObject.type+" "+id+" in role "+memberObject.role);
+            rel.appendMember(new RelationMember(e, memberObject.role), action.push);
           }
-          trace("complete: relation "+rel.id+" now has "+rel.length+" members");
+          MainUndoStack.getGlobalStack().addAction(action);
       }
-      
-      private function editRelation(id:uint):void {
-          trace("edit relation "+id);
+
+      private function editRelation(id:Number):void {
           var panel:RelationEditorPanel = RelationEditorPanel(
               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
           PopUpManager.centerPopUp(panel);
       }
-      
+
       private function tagChanged(event:TagEvent):void {
+             if(selectedEntity != null && selectedEntity is EntityCollection) {
+                       setupMultiAdvanced(selectedEntity);
+                   return;
+                 }
+
           refreshFeatureIcon();
-          
-          if ( tagDataProvider != null ) {
-              // check to see if the key is already in our list
-              var exists:Boolean = false;
-              var tag:Tag = null;
-              var i:uint;
-              for ( i = 0; i < tagDataProvider.length && !exists; i++ ) {
-                  tag = Tag(tagDataProvider.getItemAt(i));
-                  exists = tag.key == event.key;
-              }
-              if ( !exists ) {
-                  tag = new Tag(selectedEntity, event.key, event.newValue);
-                  tagDataProvider.addItem(tag);
-                  tagDataProvider.refresh();
-              } else {
-                  if ( event.newValue == null ) {
-                      tagDataProvider.removeItemAt(i-1);
-                      tagDataProvider.refresh();
-                  } else {
-                      tagDataProvider.itemUpdated(tag, "value");
-                  }
-              }
+          // if the advancedTagGrid has already been set up, it needs to be refreshed.
+          // FIXME make this better, maybe advancedTagGrid should be event listening.
+          if(advancedContainer.initialized) {
+            checkAdvanced();
           }
       }
 
       }
 
       public function openDescription():void {
-          trace("open description here");
           if ( feature != null && feature.hasHelpURL() )
               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
       }
 
-      public function addNewTag():void {
-          var newKey:String = "(new tag)";
-          var newTag:Tag = new Tag(selectedEntity, newKey, "(new value)");
-          tagDataProvider.addItem(newTag);
-          advancedTagGrid.editedItemPosition = {rowIndex: tagDataProvider.getItemIndex(newTag), columnIndex: 0};
+      public function openEntityPage():void {
+          if (selectedEntity != null && selectedEntity.id >= 0) {
+              // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
+              var urlBase:String = Connection.getConnectionInstance().apiBase + '../../browse/'
+              navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
+          }
       }
 
-      public function removeTag():void {
-          var k:String = advancedTagGrid.selectedItem.key;
-          selectedEntity.setTag(k, null, MainUndoStack.getGlobalStack().addAction);
-      }
-      
       public function addToRelation():void {
-          new RelationSelectPanel().init(selectedEntity);        
+          new RelationSelectPanel().init(selectedEntity,new Object());
       }
-      
-      public function removeFromRelation(id:Number, index:int):void {
-          Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index);
+
+      private function removeFromRelation(id:Number, index:int):void {
+          Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
       }
-      
+
       public function initFeatureBox():void {
           tw = new CategorySelector();
           tw.addEventListener("selectedType", changeFeatureType);
           popupChange.popUp = tw;
       }
-      
+
       public function changeFeatureType(event:Event):void {
           if ( selectedEntity == null )
               return;
 
+          UIComponent.suspendBackgroundProcessing();
           var newFeature:Feature = tw.selectedType;
           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
           var action:CompositeUndoableAction = new CompositeUndoableAction(
                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
+                 selectedEntity.suspend();
 
           // remove tags from the current feature
           if ( feature != null ) {
                   selectedEntity.setTag(oldtag["k"], null, action.push);
               }
           }
-          
+
           // set tags for new feature
           if ( newFeature != null ) {
               for each( var newtag:Object in newFeature.tags ) {
                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
               }
           }
-          
+
+                 selectedEntity.resume();
           undoStack(action);
           popupChange.close();
+          initialiseEditors();
+          UIComponent.resumeBackgroundProcessing();
       }
-      
-      private function dragPOI(event:MouseEvent, tags:Array):void {
-          // Get the drag initiator component from the event object.
-          var dragInitiator:Image = event.currentTarget as Image;
-          var dragSource:DragSource = new DragSource();
-          dragSource.addData(tags, 'tags');
-          
-          var dragProxy:Image = new Image();
-          dragProxy.source = event.currentTarget.source;
-          
-          DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
-      }
+
+       private function resizePOIGrid(event:Event):void {
+               var rows:Number=event.target.dataProvider.length/event.target.columnCount;
+               if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
+               event.target.height=rows*(event.target.rowHeight+1);
+       }
   ]]></mx:Script>
 </mx:VBox>