Replace SuperTabNavigator (not compatible with Flex 4) with standard TabNavigator...
[potlatch2.git] / net / systemeD / potlatch2 / TagViewer.mxml
1 <?xml version="1.0" encoding="utf-8"?>
2 <mx:VBox
3     xmlns:fx="http://ns.adobe.com/mxml/2009"
4         xmlns:mx="library://ns.adobe.com/flex/mx"
5         xmlns:flexlib="flexlib.containers.*"
6         xmlns:controls="net.systemeD.controls.*"
7         xmlns:potlatch2="net.systemeD.potlatch2.*"
8     xmlns:sidepanel="net.systemeD.potlatch2.panels.*"
9         horizontalScrollPolicy="off"
10     backgroundColor="white"
11     initialize="loadFeatures()">
12
13 <mx:ViewStack id="sidebar" width="100%" height="100%" creationPolicy="all">
14
15   <!-- Drag & drop icon panel -->
16
17   <mx:VBox id="dndPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
18     <mx:Text id="dndPanelText" text="{dndPrompt}" width="100%" styleName="helpInfo" />
19         <mx:Repeater id="dndRep" dataProvider="{MapFeatures.getInstance().getCategoriesForType('point')}" styleName="dndRepeater">
20                 <mx:HBox width="100%" styleName="dndPanelCategory">
21                         <mx:Label text="{dndRep.currentItem.name}:" styleName="dndPanelCategoryLabel"/>
22                 </mx:HBox>
23
24                 <mx:TileList dataProvider="{dndRep.currentItem.getFeaturesForType('point', true)}" width="100%" height="1"
25                                      rowHeight="32" columnWidth="32" updateComplete="resizePOIGrid(event)" styleName="dndPanelTileList">
26                         <mx:itemRenderer>
27                                 <fx:Component>
28                                         <mx:VBox toolTip="{data.name}">
29                                                 <fx:Script><![CDATA[
30                                                         import mx.events.DragEvent;
31                                                         import mx.managers.DragManager;
32                                                         import mx.core.DragSource;
33
34                                                         private function dragPOI(event:MouseEvent, tags:Array):void {
35                                                                 // Get the drag initiator component from the event object.
36                                                                 var dragInitiator:Image = event.currentTarget as Image;
37                                                                 var dragSource:DragSource = new DragSource();
38                                                                 dragSource.addData(tags, 'tags');
39                                                                 dragSource.addData(event.target.parent.parent.parent.parent, 'container');
40
41                                                                 var dragProxy:Image = new Image();
42                                                                 dragProxy.source = dragInitiator.source;
43                                                                 dragProxy.width = dragInitiator.width;   // must set width and height explicitly
44                                                                 dragProxy.height = dragInitiator.height; // for non-embedded images
45                                                                 DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
46                                                         }
47                                                 ]]></fx:Script>
48                                                 <mx:Image id="foo" source="{data.dndimage}" height="24" width="24" mouseMove="dragPOI(event, data.tags)" toolTip="{data.name}" />
49                                         </mx:VBox>
50                                 </fx:Component>
51                         </mx:itemRenderer>
52                 </mx:TileList>
53         </mx:Repeater>
54   </mx:VBox>
55
56   <!-- Standard tagging panel -->
57
58   <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto">
59     <mx:ViewStack id="stack" width="100%" height="100%">
60       <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()" styleName="dndPanelVbox">
61         <mx:VBox width="100%" verticalGap="1" styleName="dndTagHeader">
62           <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
63             <mx:Image id="iconImage"/>
64             <mx:Text condenseWhite="true" width="100%" id="iconText" styleName="dndIconText"/>
65           </mx:HBox>
66           <mx:HBox width="100%">
67             <mx:PopUpButton id="popupChange" openAlways="true" width="100%" styleName="dndTagPopUpMenu" closeDuration="0" />
68             <mx:LinkButton icon="@Embed('../../../embedded/information.svg')" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
69           </mx:HBox>
70         </mx:VBox>
71       </mx:VBox>
72       <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
73         <mx:Label id="advancedID" click="openEntityPage()">
74           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
75         </mx:Label>
76
77                 <potlatch2:TagGrid id="advancedTagGrid" width="100%" height="75%" />
78
79         <mx:HBox horizontalAlign="right" width="100%">
80           <mx:LinkButton label="Delete" click="advancedTagGrid.removeTag()" id="advancedDeleteButton" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
81           <mx:LinkButton label="Add" click="advancedTagGrid.addNewTag()" id="advancedAddButton"/>
82         </mx:HBox>
83
84         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
85             doubleClickEnabled="true"
86             itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
87             doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
88             <mx:columns>
89                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
90                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
91                 <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
92                     <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
93                 </mx:DataGridColumn>
94                                 <mx:DataGridColumn width="20" editable="false">
95                                         <mx:itemRenderer>
96                                                 <fx:Component>
97                                     <mx:HBox horizontalAlign="center" verticalAlign="middle">
98                                                                 <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
99                                                                                 open="{outerDocument.updateRelationMenu(event);}" 
100                                                                                 creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
101                                                         </mx:HBox>
102                                                 </fx:Component>
103                                         </mx:itemRenderer>
104                                 </mx:DataGridColumn>
105             </mx:columns>
106         </mx:DataGrid>
107
108         <mx:HBox horizontalAlign="right" width="100%">
109           <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)"
110                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
111           <mx:LinkButton label="Add to" click="addToRelation()"/>
112         </mx:HBox>
113
114       </mx:VBox>
115
116       <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
117         <mx:Label id="membersText" text="Relation Members"/>
118         <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
119                       dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
120           <mx:columns>
121             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
122             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
123             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
124                                 <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
125                         </mx:DataGridColumn>
126           </mx:columns>
127         </mx:DataGrid>
128       </mx:VBox>
129
130       </mx:ViewStack>
131
132           <mx:HBox width="100%">
133                 <mx:LinkBar dataProvider="{stack}"/>
134                 <mx:Spacer width="100%"/>
135                 <mx:LinkButton
136                         icon="@Embed('../../../embedded/view_tabbed.png')"
137                         disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
138                         click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6"
139                         toolTip="Show in tabs"
140                         enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
141                 <mx:LinkButton
142                         icon="@Embed('../../../embedded/view_accordion.png')"
143                         disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
144                         click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
145                         toolTip="Show in sliding windows"
146                         enabled="{editorStack is TabNavigator &amp;&amp; stack.selectedIndex==0}" />
147           </mx:HBox>
148   </mx:VBox>
149
150   <!-- Multiple selection -->
151
152   <mx:VBox id="multiplePanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
153     <potlatch2:TagGrid id="multiAdvancedTagGrid" width="100%" height="75%" />
154         <mx:HBox horizontalAlign="right" width="100%">
155           <mx:LinkButton label="Delete" click="multiAdvancedTagGrid.removeTag()" enabled="{multiAdvancedTagGrid.selectedItem != null? true : false}"/>
156           <mx:LinkButton label="Add" click="multiAdvancedTagGrid.addNewTag()" />
157         </mx:HBox>
158
159     <mx:DataGrid editable="true" width="100%" height="25%" id="multiRelationsGrid"
160         doubleClickEnabled="true"
161         itemDoubleClick="editRelation(multiRelationsGrid.selectedItem.id)"
162         doubleClick="if (event.target.parent==multiRelationsGrid) { addToRelation(); }">
163         <mx:columns>
164             <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
165             <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
166             <mx:DataGridColumn editable="true" dataField="role" headerText="Role">
167                 <mx:itemEditor><fx:Component><mx:TextInput restrict="&#x0020;-&#x10FFFF;" /></fx:Component></mx:itemEditor>
168             </mx:DataGridColumn>
169                         <mx:DataGridColumn width="20" editable="false">
170                                 <mx:itemRenderer>
171                                         <fx:Component>
172                             <mx:HBox horizontalAlign="center" verticalAlign="middle">
173                                                         <mx:PopUpButton arrowButtonWidth="12" paddingLeft="0" paddingRight="0" width="12" height="12" 
174                                                                         open="{outerDocument.updateRelationMenu(event);}" 
175                                                                         creationComplete="{outerDocument.createRelationMenu(PopUpButton(event.target));}"/>
176                                                 </mx:HBox>
177                                         </fx:Component>
178                                 </mx:itemRenderer>
179                         </mx:DataGridColumn>
180         </mx:columns>
181     </mx:DataGrid>
182     <mx:HBox horizontalAlign="right" width="100%">
183       <mx:LinkButton label="Remove from" click="removeFromRelation(multiRelationsGrid.selectedItem.id)"
184                       enabled="{multiRelationsGrid.selectedItem != null? true : false}"/>
185       <mx:LinkButton label="Add to" click="addToRelation()"/>
186     </mx:HBox>
187
188   </mx:VBox>
189
190   <!-- Multiple selection but items cannot be edited -->
191
192   <mx:VBox id="multipleInvalidPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
193         <mx:Text id="multipleInvalidPanelText" text="You have selected multiple items." width="100%" styleName="helpInfo" />
194   </mx:VBox>
195
196   <!-- Generic marker panel -->
197
198   <mx:VBox id="markerPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
199     <sidepanel:MarkerPanel id="markerPanelContents" width="100%"/>
200   </mx:VBox>
201
202   <!-- Bug editing panel -->
203
204   <mx:VBox id="bugPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
205     <sidepanel:BugPanel id="bugPanelContents" width="100%"/>
206   </mx:VBox>
207
208   <!-- Background layer selection -->
209
210   <mx:VBox id="backgroundPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
211     <sidepanel:BackgroundPanel id="backgroundPanelContents" width="100%"/>
212   </mx:VBox>
213
214 </mx:ViewStack>
215
216   <fx:Script><![CDATA[
217       import net.systemeD.halcyon.connection.*;
218       import net.systemeD.halcyon.MapPaint;
219       import net.systemeD.potlatch2.mapfeatures.*;
220       import net.systemeD.potlatch2.utils.*;
221
222       import mx.collections.*;
223       import mx.containers.*;
224       import mx.events.*;
225       import mx.core.*;
226       import mx.managers.PopUpManager;
227       import mx.controls.Menu;
228       import mx.controls.Alert;
229       import flash.geom.Point;
230       import flash.net.*;
231       import mx.events.DragEvent;
232       import mx.managers.DragManager;
233       import mx.core.DragSource;
234       import mx.controls.TabBar;
235 //    import flexlib.containers.SuperTabNavigator;
236
237       [Bindable] [Embed(source="../../../embedded/tab_basic.png"       )] private var tabIconBasic:Class;
238       [Bindable] [Embed(source="../../../embedded/tab_address.png"     )] private var tabIconAddress:Class;
239       [Bindable] [Embed(source="../../../embedded/tab_cycle.png"       )] private var tabIconCycle:Class;
240       [Bindable] [Embed(source="../../../embedded/tab_details.png"     )] private var tabIconDetails:Class;
241       [Bindable] [Embed(source="../../../embedded/tab_restrictions.png")] private var tabIconRestrictions:Class;
242       [Bindable] [Embed(source="../../../embedded/tab_transport.png"   )] private var tabIconTransport:Class;
243       [Bindable] [Embed(source="../../../embedded/tab_walk.png"        )] private var tabIconWalk:Class;
244       private var tabIcons:Object= { Basic:tabIconBasic, Details:tabIconDetails, Address:tabIconAddress, Walk:tabIconWalk, Cycle:tabIconCycle, 
245                                          Transport:tabIconTransport, Restrictions:tabIconRestrictions};
246
247       [Bindable]
248       public var dndPrompt:String="Add new points by dragging them onto the map";
249
250       private var editorStackTabNavigator:TabNavigator;
251       private var editorStackAccordion:Accordion;
252       [Bindable] private var editorStack:Container;
253
254       public var mapFeatures:MapFeatures;
255       private var selectedEntity:Entity;
256       private var connection:Connection;
257       private var currentCategorySelector:CategorySelector;
258       private var categorySelectors:Object = {};        // hash of categorySelectors for each limitType
259       private var feature:Feature = null;
260
261       private var rowData:Object;               // relation membership reference, needed so it's accessible from relation actions menu
262
263           public function setEntity(entities:Array, layer:MapPaint=null):void {
264                 UIComponent.suspendBackgroundProcessing();
265                 connection=null;
266
267                 var firstSelected:Entity=null;
268                 if (entities.length==1) { firstSelected=entities[0]; }
269
270                 if (selectedEntity!=firstSelected && selectedEntity!=null) {
271                         selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
272                         selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
273                         selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
274                 }
275
276                 if (entities.length==0) {
277                         // Nothing selected, so show drag-and-drop panel
278                         sidebar.selectedChild = dndPanel;
279
280                 } else if (entities.length==1) {
281                         // Single entity selected, so show tag panel
282                         selectedEntity=firstSelected;
283                         connection=firstSelected.connection;
284                         if (selectedEntity!=null) { selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged); }
285                         if (advancedID!=null) { setupAdvanced(firstSelected); }
286                         if (firstSelected is Relation) { stack.addChild(membersVBox); }
287             if (selectedEntity is Marker && connection is BugConnection) {
288               bugPanelContents.init(selectedEntity, BugConnection(connection));
289               sidebar.selectedChild = bugPanel;
290             } else if (selectedEntity is Marker) {
291               markerPanelContents.init(selectedEntity, layer);
292               sidebar.selectedChild = markerPanel;
293             } else if (connection is SnapshotConnection) {
294               backgroundPanelContents.init(selectedEntity, layer);
295               sidebar.selectedChild = backgroundPanel;
296             } else {
297               refreshFeatureIcon();
298               initialiseEditors();
299               sidebar.selectedChild = tagsPanel;
300             }
301
302                 } else if(isMultipleEditable(entities)) {
303                         selectedEntity = new EntityCollection(entities);
304                         selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
305             sidebar.selectedChild = multiplePanel;
306                         setupMultiAdvanced(selectedEntity);
307                         connection=entities[0].connection;
308                         
309                 } else {
310                         //The selection contains elements which can't be edited all together.
311                         sidebar.selectedChild = multipleInvalidPanel;
312                 }
313                 UIComponent.resumeBackgroundProcessing();
314       }
315
316       private function refreshFeatureIcon():void {
317           var oldFeature:Feature = feature;
318           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
319           if ( feature != oldFeature ) {
320               if ( oldFeature != null )
321                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
322               if ( feature != null )
323                   feature.addEventListener("imageChanged", featureImageChanged);
324           }
325           setCategorySelector(selectedEntity, feature);
326       }
327
328       private function featureImageChanged(event:Event):void {
329           setCategorySelector(selectedEntity, feature);
330       }
331
332       /** Set the icon, categorySelector and help text for the current entity. */
333       private function setCategorySelector(entity:Entity, feature:Feature):void {
334                         // Remove the "user has selected something" event listener from previous categorySelector,
335                         // and make it invisible because Flex is crap at updating click areas otherwise
336                         if (currentCategorySelector) { 
337                                 currentCategorySelector.removeEventListener("selectedType", changeFeatureType);
338                                 currentCategorySelector.visible=false;
339                         }
340                         
341                         // Have we cached the categorySelector for this limitType? If not, create one
342                         var lt:String=limitType(entity);
343                         if (!categorySelectors[lt]) {
344                                 categorySelectors[lt]=new CategorySelector();
345                                 categorySelectors[lt].setLimitTypes(lt);
346                         }
347                         currentCategorySelector=categorySelectors[lt];
348                         currentCategorySelector.addEventListener("selectedType", changeFeatureType, false, 0, true);
349
350                         // Update surrounding icon/text display
351                         if (feature) {
352                                 iconImage.source = feature.image;
353                                 iconText.htmlText = feature.htmlDetails(entity);
354                                 popupChange.label = feature.name;
355                                 helpLabel.visible = feature.hasHelpURL();
356                                 currentCategorySelector.setSelectedFeature(feature);
357                         } else {
358                                 iconImage.source = null;
359                                 popupChange.label = "unknown";
360                                 helpLabel.visible = false;
361                                 if (entity==null) {
362                                         iconText.htmlText = "<i>Nothing selected</i>";
363                                 } else if (entity.hasTags()) {
364                                         iconText.htmlText = "<b>Not recognised</b><br/><font size='10pt'>Try looking at the tags under the advanced properties</font>";
365                                 } else {
366                                         iconText.htmlText = "<b>No tags set</b><br/><font size='10pt'>Please use the menu below to define what this "+entity.getType()+" is</font>";
367                                 }
368                                 currentCategorySelector.setSelectedFeature(null);
369                         }
370
371                         // Set it as the popup, and make sure it's visible
372                         popupChange.popUp=currentCategorySelector;
373                         currentCategorySelector.visible=true;
374       }
375
376           private function isMultipleEditable(entities:Array):Boolean {
377                 for each(var entity:Entity in entities) {
378                         if(!(entity is Node || entity is Way))
379                                 return false;
380                 }
381                 return true;
382           }
383
384       private function limitType(entity:Entity):String {
385           if      (entity is Node    ) return "point";
386           else if (entity is Way     ) return Way(entity).isArea() ? "area" : "line";
387           else if (entity is Relation) return "relation";
388           return null;
389       }
390
391       private var tabComponents:Object = {};
392
393       private function initialiseEditors():void {
394           editorStack.removeAllChildren();
395           if ( selectedEntity == null || feature == null )
396               return;
397
398           var editorBox:VBox = createEditorBox();
399           editorBox.label = "Basic";
400           editorBox.icon=tabIconBasic;
401           editorStack.addChild(editorBox);
402
403           var tabs:Object = {};
404           tabComponents = {};
405
406           // ** FIXME: we should do this so that the tabs are always in the same order
407           for each (var factory:EditorFactory in feature.editors) {
408               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
409                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
410                   if ( editor != null )
411                       editorBox.addChild(editor);
412               }
413               var category:String = factory.category;
414               if (category!='') {
415                       var tab:VBox = tabs[category];
416                       if ( tab == null) {
417                           tab = createEditorBox();
418                           tab.label = category;
419                           if (tabIcons[category]) tab.icon=tabIcons[category];
420                           editorStack.addChild(tab);
421                           tabs[category] = tab;
422                           tabComponents[tab] = [];
423                       }
424                       var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
425                       if ( catEditor != null )
426                           tabComponents[tab].push(catEditor);
427                       //    tab.addChild(catEditor);
428               }
429           }
430       }
431
432       private function createEditorBox():VBox {
433           var box:VBox = new VBox();
434           box.percentWidth = 100;
435           box.percentHeight = 100;
436           box.styleName = "dndEditorContainer";
437           return box;
438       }
439
440       private function ensureEditorsPopulated(tab:VBox):void {
441           var components:Array = tabComponents[tab];
442           if ( components == null || tab == null || tab.numChildren >= components.length )
443               return;
444           for each (var component:DisplayObject in components ) {
445               tab.addChild(component);
446           }
447       }
448
449         private function initEditorStackUIs():void {
450                 editorStackTabNavigator = new TabNavigator();
451 //              editorStackTabNavigator.allowTabSqueezing=false;
452 //              editorStackTabNavigator.minTabWidth=10;
453 //              editorStackTabNavigator.closePolicy="close_never";
454 //              editorStackTabNavigator.scrollSpeed=20;
455                 editorStackTabNavigator.creationPolicy="auto";
456                 editorStackTabNavigator.percentWidth=100;
457                 editorStackTabNavigator.percentHeight=100;
458                 editorStackTabNavigator.styleName="dndStackTab";
459 //              editorStackTabNavigator.popUpButtonPolicy="off"
460
461
462                 editorStackAccordion = new Accordion();
463                 editorStackAccordion.percentWidth=100;
464                 editorStackAccordion.percentHeight=100;
465                 editorStackAccordion.creationPolicy="auto";
466                 editorStackAccordion.styleName="dndStackAccordion";
467                 /* FIXME: the accordion icons should be right-aligned. See:
468                 http://www.kristoferjoseph.com/blog/2008/11/06/positioning-the-flex-accordion-header-icon
469                 http://blog.flexexamples.com/2007/09/13/changing-text-alignment-in-an-flex-accordion-header/
470                 */
471
472                 setEditorStackUI(true);
473         }
474
475         private function setEditorStackUI(isTabbed:Boolean):void {
476                 var children:Array=[]; var i:uint;
477
478                 if (editorStack) {
479                         // blank existing component
480                         editorStack.removeEventListener("change",editorStackUIChange);
481                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
482                         editorStack.removeAllChildren();
483                         editorContainer.removeChildAt(1);
484                 }
485
486                 // replace with new component
487                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
488                 editorContainer.addChild(editorStack);
489
490                 // re-add children and listeners
491                 initialiseEditors();
492                 editorStack.addEventListener("change",editorStackUIChange);
493                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
494         }
495
496         private function editorStackUIChange(event:Event):void {
497                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
498         }
499
500         private function editorStackUIUpdate(event:Event):void {
501                 if (editorStack is TabNavigator) {
502                         var e:TabNavigator = editorStack as TabNavigator;
503                         if (e.selectedIndex<0) { return; }
504                         for (var i:uint=0; i<e.numChildren; i++) {
505                                 e.getTabAt(i).selected=(i==e.selectedIndex);
506                         }
507                 }
508         }
509
510
511         public function togglePanel():void {
512                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
513                         stack.selectedChild=advancedContainer;
514                 } else if (stack.selectedChild!=editorContainer) {
515                         stack.selectedChild=editorContainer;
516                 }
517         }
518
519         public function selectAdvancedPanel():void {
520                 checkAdvanced();
521                 stack.selectedChild=advancedContainer;
522         }
523
524       private function checkAdvanced():void {
525           if ( selectedEntity != null )
526              setupAdvanced(selectedEntity);
527       }
528
529       private var listeningToRelations:Array = [];
530
531       private function setupAdvanced(entity:Entity):void {
532                 if (!advancedTagGrid) advancedContainer.createComponentsFromDescriptors();      // if Flex hasn't created it, force it
533                 advancedTagGrid.init(entity);
534
535                 if ( entity == null ) {
536                         advancedID.htmlText = "";
537                 } else {
538                         var entityText:String = "xx";
539                         if      ( entity is Node     ) entityText = "Node";
540                         else if ( entity is Way      ) entityText = "Way";
541                         else if ( entity is Relation ) entityText = "Relation";
542                         advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
543                 }
544
545                 removeRelationListeners();
546
547                 if ( entity == null ) {
548                         relationsGrid.dataProvider = null;
549                 } else {
550                         resetRelationsGrid(entity);
551                         entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
552                         entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
553                 }
554       }
555
556           private function setupMultiAdvanced(entity:Entity):void {
557                 multiAdvancedTagGrid.init(entity);
558                 resetRelationsGrid(entity);
559                 entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation, false, 0, true);
560                 entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation, false, 0, true);
561       }
562
563           public function addNewTag():void {
564                 if (stack.selectedChild!=advancedContainer) { return; }
565                 advancedTagGrid.addNewTag();
566           }
567
568       private function addedToRelation(event:RelationMemberEvent):void {
569          resetRelationsGrid(selectedEntity);
570       }
571
572       private function removedFromRelation(event:RelationMemberEvent):void {
573          resetRelationsGrid(selectedEntity);
574       }
575
576       private function removeRelationListeners():void {
577           for each( var rel:Relation in listeningToRelations ) {
578               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
579               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
580               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
581           }
582           listeningToRelations = [];
583           if (relationsGrid) relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
584           if (multiRelationsGrid) multiRelationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
585       }
586
587       private function resetRelationsGrid(entity:Entity):void {
588           removeRelationListeners();
589
590           var instance:DataGrid=relationsGrid;
591           if (entity is EntityCollection) instance=multiRelationsGrid;
592           var memberships:Array = entity.getRelationMemberships();
593           for each (var m:Object in memberships) {
594               m.relation.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
595               m.relation.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
596               m.relation.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
597               listeningToRelations.push(m.relation);
598           }
599           instance.dataProvider = memberships;
600           instance.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
601       }
602
603       private function relationRoleChanged(event:DataGridEvent):void {
604                 if (event.dataField != 'role') { return; }      // shouldn't really happen
605
606                 var relations:Array=event.currentTarget.dataProvider.toArray();
607                 var props:Object=relations[event.rowIndex];
608
609                 var relation:Relation=props['relation'];
610                 var newRole:String=event.itemRenderer.data['role'];
611
612                 if (selectedEntity is EntityCollection) {
613                         for each (var entity:Entity in EntityCollection(selectedEntity).entities) {
614                                 var indexes:Array=relation.findEntityMemberIndexes(entity);
615                                 for each (var index:int in indexes) {
616                                         relation.setMember(index, new RelationMember(entity,newRole), MainUndoStack.getGlobalStack().addAction);
617                                 }
618                         }
619                 } else {
620                         relation.setMember(props['index'], new RelationMember(selectedEntity,newRole), MainUndoStack.getGlobalStack().addAction);
621                 }
622       }
623
624       private function relationTagChanged(event:TagEvent):void {
625           resetRelationsGrid(selectedEntity);
626       }
627
628       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
629           resetRelationsGrid(selectedEntity);
630       }
631
632       private function checkMembers():void {
633           if (selectedEntity is Relation) {
634             setupMembers(selectedEntity as Relation);
635           }
636       }
637
638       private function setupMembers(rel:Relation):void {
639           var members:Array = [];
640           for (var i:int=0 ; i<rel.length; i++) {
641             var props:Object = {};
642             var member:RelationMember = rel.getMember(i);
643             props["id"] = member.entity.id;
644             props["type"] = member.entity.getType();
645             props["role"] = member.role;
646
647             members.push(props);
648           }
649           membersGrid.dataProvider = members;
650           membersGrid.dataProvider.addEventListener('collectionChange', membersChange);
651       }
652
653       private function membersChange(event:Event):void {
654           // Dropping all the members and re-adding them isn't exactly optimal
655           // but is at least robust for any kind of change.
656           // Figuring out a better way is someone else's FIXME
657
658           var rel:Relation = selectedEntity as Relation;
659           var action:CompositeUndoableAction = new CompositeUndoableAction("Rearrange relation members for "+rel);
660
661           // drop members
662           for (var i:int=rel.length-1 ; i>=0; i--) {
663             rel.removeMemberByIndex(i, action.push);
664           }
665
666           // add members in new order
667           for each(var memberObject:Object in membersGrid.dataProvider) {
668             var e:Entity;
669             var id:Number = memberObject.id;
670                         switch (memberObject.type) {
671                                 case 'node':            e = connection.getNode(id); break;
672                 case 'way':                     e = connection.getWay(id); break;
673                                 case 'relation':        e = connection.getRelation(id); break;
674             }
675             rel.appendMember(new RelationMember(e, memberObject.role), action.push);
676           }
677           MainUndoStack.getGlobalStack().addAction(action);
678       }
679
680       private function editRelation(id:Number):void {
681           var panel:RelationEditorPanel = RelationEditorPanel(
682               PopUpManager.createPopUp(Application(FlexGlobals.topLevelApplication), RelationEditorPanel, true));
683           panel.setRelation(connection.getRelation(id));
684           PopUpManager.centerPopUp(panel);
685       }
686
687         /** Create relation actions menu */
688
689         public function createRelationMenu(button:PopUpButton):void {
690                 var menu:Menu = new Menu(); 
691                 var dp:Object = [ {label: "Select all members"}, 
692                                                   {label: "Deselect all members"}, 
693                                                   {label: "Add selection to this relation", enabled: false},
694                                                   {label: "Delete relation"} ]; 
695                 menu.dataProvider = dp; 
696                 menu.addEventListener("itemClick", selectRelationMenu); 
697                 button.popUp = menu;
698         }
699
700         /** Enable 'add selection to...' entry only if some of the selection isn't in the relation.
701             Called each time the menu is clicked. */
702         
703         public function updateRelationMenu(event:Event):void {
704                 rowData=event.target.parent.data;       // this makes it accessible from selectRelationMenu
705                 var menu:Menu = Menu(event.target.popUp);
706                 var enable:Boolean = false;
707                 if (selectedEntity != null && selectedEntity is EntityCollection) {
708                         // Enable only if some entities aren't a member of the relation
709                         enable=!rowData.universal;
710                 }
711                 if (enable==menu.dataProvider[2].enabled) return;
712                 menu.dataProvider[2].enabled=enable;
713                 menu.invalidateList();
714         }
715
716         /** Do the action selected in the relation actions menu */
717
718         public function selectRelationMenu(event:MenuEvent):void {
719                 var rel:Relation=rowData.relation;
720                 var entities:Array;
721                 var controller:EditController=FlexGlobals.topLevelApplication.theController;
722                 switch (event.index) {
723                         case 0: // Select all members
724                                 entities=selectedEntity.entities.concat(rel.memberEntities);
725                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return arr.indexOf(e) == i } );      // remove duplicates
726                                 // ** FIXME: This is a really horrible way of changing the controller state
727                                 controller.setState(controller.findStateForSelection(entities));
728                                 break;
729
730                         case 1: // Deselect all members
731                                 entities=selectedEntity.entities;
732                                 entities=entities.filter(function(e:*, i:int, arr:Array):Boolean { return !e.hasParent(rel) } );
733                                 controller.setState(controller.findStateForSelection(entities));
734                                 break;
735
736                         case 2: // Add selection to this relation
737                                 var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
738                                 for each (var entity:Entity in selectedEntity.entities) {
739                                         if (!entity.hasParent(rel)) {
740                                                 rel.appendMember(new RelationMember(entity,''), undo.push);
741                                         }
742                                 }
743                                 MainUndoStack.getGlobalStack().addAction(undo);
744                                 break;
745                         
746                         case 3: // Delete relation
747                                 Alert.show("Do you really want to delete the relation?","Are you sure?",Alert.YES | Alert.CANCEL,null,
748                                         function(event:CloseEvent):void { 
749                                                 if (event.detail==Alert.CANCEL) return;
750                                                 rel.remove(MainUndoStack.getGlobalStack().addAction);
751                                         } );
752                                 break;
753                 }
754         }
755
756       private function tagChanged(event:TagEvent):void {
757           refreshFeatureIcon();
758       }
759
760       public function loadFeatures():void {
761           mapFeatures = MapFeatures.getInstance();
762           stack.removeChild(membersVBox); // remove by default, will be added if relation
763       }
764
765       /** Open up a new browser page, showing the help page as defined in Map Features XML file .*/
766       public function openDescription():void {
767           if ( feature != null && feature.hasHelpURL() )
768               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
769       }
770
771       /** Open up a new browser page showing OSM's view of the current entity. */
772       public function openEntityPage():void {
773           if (selectedEntity != null && selectedEntity.id >= 0) {
774               // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
775               var urlBase:String = connection.apiBase + '../../browse/'
776               navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
777           }
778       }
779
780       public function addToRelation():void {
781           new RelationSelectPanel().init(selectedEntity,new Object());
782       }
783
784       private function removeFromRelation(id:Number, index:int=-1):void {
785                 var rel:Relation=connection.getRelation(id);
786                 if (index>-1) {
787                         rel.removeMemberByIndex(index, MainUndoStack.getGlobalStack().addAction);
788                 } else if (selectedEntity is EntityCollection) {
789                         var undo:CompositeUndoableAction=new CompositeUndoableAction("Remove selection from relations");
790                         for each (var e:Entity in EntityCollection(selectedEntity).entities) rel.removeMember(e,undo.push);
791                         MainUndoStack.getGlobalStack().addAction(undo);
792                 }
793       }
794
795       public function changeFeatureType(event:Event):void {
796           if ( selectedEntity == null )
797               return;
798
799           UIComponent.suspendBackgroundProcessing();
800           var newFeature:Feature = currentCategorySelector.selectedType;
801           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
802           var action:CompositeUndoableAction = new CompositeUndoableAction(
803                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
804                   selectedEntity.suspend();
805
806           // remove tags from the current feature
807           if ( feature != null ) {
808               for each( var oldtag:Object in feature.tags ) {
809                   selectedEntity.setTag(oldtag["k"], null, action.push);
810               }
811           }
812
813           // set tags for new feature
814           if ( newFeature != null ) {
815               for each( var newtag:Object in newFeature.tags ) {
816                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
817               }
818           }
819
820                   selectedEntity.resume();
821           undoStack(action);
822           popupChange.close();
823           initialiseEditors();
824           UIComponent.resumeBackgroundProcessing();
825       }
826
827         private function resizePOIGrid(event:Event):void {
828                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
829                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
830                 event.target.height=rows*(event.target.rowHeight+1);
831         }
832   ]]></fx:Script>
833 </mx:VBox>
834