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