delete icon for tags
[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         horizontalScrollPolicy="off"
7     backgroundColor="white"
8     initialize="loadFeatures()">
9
10 <mx:ViewStack id="sidebar" width="100%" height="100%" creationPolicy="all">
11   <mx:VBox id="dndPanel" width="100%" height="100%" horizontalScrollPolicy="off" styleName="dndPanelVbox">
12     <mx:Text id="dndPanelText" text="{dndPrompt}" width="100%" styleName="helpInfo" />
13         <mx:Repeater id="dndRep" dataProvider="{MapFeatures.getInstance().getCategoriesForType('point')}">
14                 <mx:HBox width="100%"><mx:Label text="{dndRep.currentItem.name}:" styleName="dndPanelCategoryLabel"/></mx:HBox>
15
16                 <mx:TileList dataProvider="{dndRep.currentItem.getFeaturesForType('point')}" width="100%" height="1"
17                                      rowHeight="32" columnWidth="32" updateComplete="resizePOIGrid(event)" styleName="dndPanelTileList">
18                         <mx:itemRenderer>
19                                 <mx:Component>
20                                         <mx:VBox toolTip="{data.name}">
21                                                 <mx:Script><![CDATA[
22                                                         import mx.events.DragEvent;
23                                                         import mx.managers.DragManager;
24                                                         import mx.core.DragSource;
25
26                                                         private function dragPOI(event:MouseEvent, tags:Array):void {
27                                                                 // Get the drag initiator component from the event object.
28                                                                 var dragInitiator:Image = event.currentTarget as Image;
29                                                                 var dragSource:DragSource = new DragSource();
30                                                                 dragSource.addData(tags, 'tags');
31                                                                 dragSource.addData(event.target.parent.parent.parent.parent, 'container');
32
33                                                                 var dragProxy:Image = new Image();
34                                                                 dragProxy.source = dragInitiator.source;
35                                                                 dragProxy.width = dragInitiator.width;   // must set width and height explicitly
36                                                                 dragProxy.height = dragInitiator.height; // for non-embedded images
37                                                                 DragManager.doDrag(dragInitiator, dragSource, event, dragProxy);
38                                                         }
39                                                 ]]></mx:Script>
40                                                 <mx:Image id="foo" source="{data.image}" height="24" width="24" mouseMove="dragPOI(event, data.tags)" toolTip="{data.name}" />
41                                         </mx:VBox>
42                                 </mx:Component>
43                         </mx:itemRenderer>
44                 </mx:TileList>
45         </mx:Repeater>
46   </mx:VBox>
47   
48   <mx:VBox id="tagsPanel" width="100%" height="100%" creationPolicy="auto">
49     <mx:ViewStack id="stack" width="100%" height="100%">
50       <mx:VBox width="100%" height="100%" label="Simple" id="editorContainer" creationComplete="initEditorStackUIs()">
51         <mx:HBox width="100%" id="iconContainer" styleName="featureSelector">
52             <mx:Image id="iconImage"/>
53             <mx:VBox width="100%" verticalGap="1">
54               <mx:PopUpButton id="popupChange" creationComplete="initFeatureBox()" openAlways="true" width="100%"/>
55               <mx:Text condenseWhite="true" width="100%" id="iconText"/>
56             </mx:VBox>
57             <mx:LinkButton label="?" click="openDescription()" id="helpLabel" styleName="helpInfo"/>
58         </mx:HBox>
59       </mx:VBox>
60       <mx:VBox width="100%" height="100%" label="Advanced" id="advancedContainer" initialize="checkAdvanced()" verticalGap="1">
61         <mx:Label id="advancedID" click="openEntityPage()">
62           <mx:htmlText><![CDATA[<i>No Selection</i>]]></mx:htmlText>
63         </mx:Label>
64
65                 <!-- ** FIXME:
66                 
67                          This needs finishing and refactoring to:
68                          a) be a nice custom control which can be dropped in anywhere
69                          b) do autocomplete on values as well as keys
70                          c) do autocomplete on keys _properly_
71                          d) have proper lovely callback methods and events and stuff, rather than horrible parent.parent.parent.parent.badger.badger.badger hacks
72                          e) replace the big (X) with a little one
73                          f) be styled attractively
74                          g) generally suck less
75                         
76                 -->
77
78         <mx:DataGrid editable="true" width="100%" height="75%" id="advancedTagGrid" 
79             doubleClickEnabled="true"
80             doubleClick="if (event.target.parent==advancedTagGrid) { addNewTag(); }">
81                 <mx:columns>
82                     <mx:DataGridColumn editable="true" dataField="key" headerText="Key">
83                                                 <mx:itemEditor>
84                                                         <mx:Component>
85                                                                 <controls:AutoComplete 
86                                                                   dataProvider="{autoCompleteKeys()}" 
87                                                                   labelField="name" 
88                                                                   rowCount="10"
89                                                                   typedText="{getSelectedKey()}">
90                                                                         <mx:Script><![CDATA[
91                                                                                 import net.systemeD.potlatch2.mapfeatures.MapFeatures;
92                                                                                 import mx.collections.ArrayCollection;
93                                                                                 import mx.controls.DataGrid;
94
95                                                                                 public function autoCompleteKeys():Array {
96                                                                                         var a:Array=[];
97                                                                                         for each (var k:String in MapFeatures.getInstance().getAutoCompleteKeys()) {
98                                                                                                 a.push( { name: k } );
99                                                                                         }
100                                                                                         return a;
101                                                                                 }
102
103                                                                                 internal function getSelectedKey():String {
104                                                                                         return DataGrid(this.parent.parent).selectedItem.key;
105                                                                                 }
106                                                                         ]]></mx:Script>
107                                                                 </controls:AutoComplete>
108                                                         </mx:Component>
109                                                 </mx:itemEditor>
110                                         </mx:DataGridColumn>
111                     <mx:DataGridColumn editable="true" dataField="value" headerText="Value" />
112                                         <mx:DataGridColumn width="20" editable="false">
113                                                 <mx:itemRenderer>
114                                                         <mx:Component>
115                                                                 <mx:Image source="@Embed('../../../embedded/delete.svg')" 
116                                                                         click='event.stopPropagation();TagViewer(this.parent.parent.parent.parent.parent.parent.parent).removeTag();'
117                                                                 buttonMode="true" useHandCursor="true" />
118                                                         </mx:Component>
119                                                 </mx:itemRenderer>
120                                         </mx:DataGridColumn>
121                 </mx:columns>
122         </mx:DataGrid>
123
124         <mx:HBox horizontalAlign="right" width="100%">
125           <mx:LinkButton label="Delete" click="removeTag()" enabled="{advancedTagGrid.selectedItem != null? true : false}"/>
126           <mx:LinkButton label="Add" click="addNewTag()"/>
127         </mx:HBox>
128         
129         <mx:DataGrid editable="true" width="100%" height="25%" id="relationsGrid"
130             doubleClickEnabled="true"
131             itemDoubleClick="editRelation(relationsGrid.selectedItem.id)"
132             doubleClick="if (event.target.parent==relationsGrid) { addToRelation(); }">
133             <mx:columns>
134                 <mx:DataGridColumn editable="false" dataField="description" headerText="Relation"/>
135                 <mx:DataGridColumn editable="false" dataField="id_idx" headerText="ID"/>
136                 <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
137             </mx:columns>
138         </mx:DataGrid>
139
140         <mx:HBox horizontalAlign="right" width="100%">
141           <mx:LinkButton label="Remove from" click="removeFromRelation(relationsGrid.selectedItem.id, relationsGrid.selectedItem.index)" 
142                           enabled="{relationsGrid.selectedItem != null? true : false}"/>
143           <mx:LinkButton label="Add to" click="addToRelation()"/>
144         </mx:HBox>
145
146       </mx:VBox>
147
148       <mx:VBox width="100%" height="100%" label="Members" id="membersVBox" initialize="checkMembers()" verticalGap="1">
149         <mx:Label id="membersText" text="Relation Members"/>
150         <mx:DataGrid editable="true" width="100%" height="100%" id="membersGrid"
151                       dragEnabled="true" dragMoveEnabled="true" dropEnabled="true">
152           <mx:columns>
153             <mx:DataGridColumn editable="false" dataField="type" headerText="Type"/>
154             <mx:DataGridColumn editable="false" dataField="id" headerText="ID"/>
155             <mx:DataGridColumn editable="true" dataField="role" headerText="Role"/>
156           </mx:columns>
157         </mx:DataGrid>
158       </mx:VBox>
159       
160       </mx:ViewStack>
161
162           <mx:HBox width="100%">
163                 <mx:LinkBar dataProvider="{stack}"/>
164                 <mx:Spacer width="100%"/>
165                 <mx:LinkButton 
166                         icon="@Embed('../../../embedded/view_tabbed.png')"
167                         disabledIcon="@Embed('../../../embedded/view_tabbed_disabled.png')"
168                         click="setEditorStackUI(true)" id="tabNavigatorLabel" paddingTop="6" 
169                         toolTip="Show in tabs"
170                         enabled="{editorStack is Accordion &amp;&amp; stack.selectedIndex==0}" />
171                 <mx:LinkButton
172                         icon="@Embed('../../../embedded/view_accordion.png')" 
173                         disabledIcon="@Embed('../../../embedded/view_accordion_disabled.png')"
174                         click="setEditorStackUI(false)" id="accordionLabel" paddingTop="6"
175                         toolTip="Show in sliding windows"
176                         enabled="{editorStack is SuperTabNavigator &amp;&amp; stack.selectedIndex==0}" />
177           </mx:HBox>
178   </mx:VBox>
179 </mx:ViewStack>
180
181   <mx:Script><![CDATA[
182       import net.systemeD.halcyon.connection.*;
183       import net.systemeD.potlatch2.mapfeatures.*;
184
185       import mx.collections.*;
186       import mx.containers.*;
187       import mx.events.*;
188       import mx.core.*;
189       import mx.managers.PopUpManager;
190       import flash.geom.Point;
191       import flash.net.*;
192       import mx.events.DragEvent;
193       import mx.managers.DragManager;
194       import mx.core.DragSource;
195       import flexlib.containers.SuperTabNavigator;
196
197       private static const dndPrompt:String="Add new points by dragging them onto the map";
198
199       private var editorStackTabNavigator:SuperTabNavigator;
200       private var editorStackAccordion:Accordion;
201       [Bindable] private var editorStack:Container;
202
203       public var mapFeatures:MapFeatures;
204       private var selectedEntity:Entity;
205       private var tagDataProvider:ArrayCollection;
206       private var tw:CategorySelector = null;
207       private var feature:Feature = null;
208
209       public function setEntity(entity:Entity):void {
210           UIComponent.suspendBackgroundProcessing();
211           if ( selectedEntity != entity ) {
212               if ( selectedEntity != null )
213                   selectedEntity.removeEventListener(Connection.TAG_CHANGED, tagChanged);
214               selectedEntity = entity;
215               if ( selectedEntity != null )
216                   selectedEntity.addEventListener(Connection.TAG_CHANGED, tagChanged);
217           }
218
219           if ( advancedID != null )
220               setupAdvanced(entity);
221           if (entity is Relation) {
222               stack.addChild(membersVBox);
223           }
224           refreshFeatureIcon(); 
225           if (selectedEntity == null) {
226             sidebar.selectedChild = dndPanel;
227           } else {
228             initialiseEditors();
229             sidebar.selectedChild = tagsPanel;
230           }
231           UIComponent.resumeBackgroundProcessing();
232       }
233
234       private function refreshFeatureIcon():void {
235           var oldFeature:Feature = feature;
236           feature = selectedEntity == null ? null : mapFeatures.findMatchingFeature(selectedEntity);
237           if ( feature != oldFeature ) {
238               if ( oldFeature != null )
239                   oldFeature.removeEventListener("imageChanged", featureImageChanged);
240               if ( feature != null )
241                   feature.addEventListener("imageChanged", featureImageChanged);
242           }
243
244           if ( feature != null && feature.name != null ) {
245               setFeatureIcon(selectedEntity, feature);
246           } else {
247               blankFeatureIcon(selectedEntity);
248           }
249       }
250
251       private function featureImageChanged(event:Event):void {
252           setFeatureIcon(selectedEntity, feature);
253       }
254       
255       private function setFeatureIcon(entity:Entity, feature:Feature):void {
256           //blankFeatureIcon(entity);
257           
258           iconImage.source = feature.image;
259
260           var txt:String = feature.htmlDetails(entity);
261           iconText.htmlText = txt;
262           popupChange.label = feature.name;
263           setLimitTypes(entity);
264           tw.setSelectedFeature(feature);
265           helpLabel.visible = feature.hasHelpURL();
266       }
267       
268       private function setLimitTypes(entity:Entity):void {
269           var type:String = null;
270           if ( entity is Node )
271               type = "point";
272           else if ( entity is Way )
273               type = Way(entity).isArea() ? "area" : "line";
274           else if ( entity is Relation )
275               type = "relation";
276           tw.setLimitTypes(type);
277       }
278
279       private function blankFeatureIcon(entity:Entity):void {
280           iconImage.source = null;
281           popupChange.label = "unknown";
282           setLimitTypes(entity);
283                   if (entity == null) { 
284                         iconText.htmlText = "<i>Nothing selected</i>";
285             tw.setNoSelectedFeature();
286                   } else if (entity.hasTags()) {
287                         iconText.htmlText = "<b>Not recognised</b><br/>Try looking at the tags under the advanced properties";
288             tw.setSelectedFeature(null);
289                   } else {
290                         iconText.htmlText = "<b>No tags set</b><br/>Use the menu above to say what this "+entity.getType()+" is";
291             tw.setSelectedFeature(null);
292           }
293           helpLabel.visible = false;
294       }
295
296       private var tabComponents:Object = {};
297       
298       private function initialiseEditors():void {
299           editorStack.removeAllChildren();
300           if ( selectedEntity == null || feature == null )
301               return;
302           
303           var editorBox:VBox = createEditorBox();
304           editorBox.label = "Basic";
305           editorStack.addChild(editorBox);
306           
307           var tabs:Object = {};
308           tabComponents = {};
309           
310           for each (var factory:EditorFactory in feature.editors) {
311               if ( factory.presence.isEditorPresent(factory, selectedEntity, null) ) {
312                   var editor:DisplayObject = factory.createEditorInstance(selectedEntity);
313                   if ( editor != null )
314                       editorBox.addChild(editor);
315               }
316               var category:String = factory.category;
317               if (category!='') {
318                       var tab:VBox = tabs[category];
319                       if ( tab == null) {
320                           tab = createEditorBox();
321                           tab.label = category;
322                           editorStack.addChild(tab);
323                           tabs[category] = tab;
324                           tabComponents[tab] = [];
325                       }
326                       var catEditor:DisplayObject = factory.createEditorInstance(selectedEntity);
327                       if ( catEditor != null )
328                           tabComponents[tab].push(catEditor);
329                       //    tab.addChild(catEditor);
330               }
331           }
332       }
333       
334       private function createEditorBox():VBox {
335           var box:VBox = new VBox();
336           box.percentWidth = 100;
337           box.percentHeight = 100;
338           box.styleName = "editorContainer";
339           return box;
340       }
341
342       private function ensureEditorsPopulated(tab:VBox):void {
343           var components:Array = tabComponents[tab];
344           if ( components == null || tab == null || tab.numChildren >= components.length )
345               return;
346           for each (var component:DisplayObject in components ) {
347               tab.addChild(component);
348           }
349       }
350       
351         private function initEditorStackUIs():void {
352                 editorStackTabNavigator = new SuperTabNavigator();
353                 editorStackTabNavigator.allowTabSqueezing=false;
354                 editorStackTabNavigator.minTabWidth=10;
355                 editorStackTabNavigator.closePolicy="close_never";
356                 editorStackTabNavigator.scrollSpeed=20;
357                 editorStackTabNavigator.creationPolicy="auto";
358                 editorStackTabNavigator.percentWidth=100;
359                 editorStackTabNavigator.percentHeight=100;
360
361                 editorStackAccordion = new Accordion();
362                 editorStackAccordion.percentWidth=100;
363                 editorStackAccordion.percentHeight=100;
364                 editorStackAccordion.creationPolicy="auto";
365
366                 setEditorStackUI(true);
367         }
368
369         private function setEditorStackUI(isTabbed:Boolean):void {
370                 var children:Array=[]; var i:uint;
371
372                 if (editorStack) {
373                         // blank existing component
374                         editorStack.removeEventListener("change",editorStackUIChange);
375                         editorStack.removeEventListener("updateComplete",editorStackUIUpdate);
376                         editorStack.removeAllChildren();
377                         editorContainer.removeChildAt(1);
378                 }
379
380                 // replace with new component
381                 editorStack = (isTabbed ? editorStackTabNavigator : editorStackAccordion) as Container;
382                 editorContainer.addChild(editorStack);
383
384                 // re-add children and listeners
385                 initialiseEditors();
386                 editorStack.addEventListener("change",editorStackUIChange);
387                 editorStack.addEventListener("updateComplete",editorStackUIUpdate);
388         }
389         
390         private function editorStackUIChange(event:Event):void {
391                 ensureEditorsPopulated(IndexChangedEvent(event).relatedObject as VBox);
392         }
393
394         private function editorStackUIUpdate(event:Event):void {
395                 if (editorStack is SuperTabNavigator) {
396                         var e:SuperTabNavigator = editorStack as SuperTabNavigator;
397                         if (e.selectedIndex<0) { return; }
398                         for (var i:uint=0; i<e.numChildren; i++) {
399                                 e.getTabAt(i).selected=(i==e.selectedIndex);
400                         }
401                 }
402         }
403
404
405         public function togglePanel():void {
406                 if (stack.selectedChild==editorContainer && selectedEntity!=null) {
407                         stack.selectedChild=advancedContainer;
408                 } else if (stack.selectedChild!=editorContainer) {
409                         stack.selectedChild=editorContainer;
410                 }
411         }
412
413       private function checkAdvanced():void {
414           if ( selectedEntity != null )
415              setupAdvanced(selectedEntity);
416       }
417
418       private var listeningToRelations:Array = [];
419       
420       private function setupAdvanced(entity:Entity):void {
421           if ( tagDataProvider == null ) {
422               tagDataProvider = new ArrayCollection();
423               advancedTagGrid.dataProvider = tagDataProvider;
424           }
425
426           tagDataProvider.removeAll();
427           
428           if ( entity == null ) {
429               advancedID.htmlText = "";
430           } else {
431               var entityText:String = "xx";
432               if ( entity is Node ) entityText = "Node";
433               else if ( entity is Way ) entityText = "Way";
434               else if ( entity is Relation ) entityText = "Relation";
435               advancedID.htmlText = entityText+": <b>"+entity.id+"</b>";
436
437               var tags:Array = entity.getTagArray();
438               tags.sortOn("key");
439               for each(var tag:Tag in tags)
440                   tagDataProvider.addItem(tag);
441           }
442                     
443           removeRelationListeners();
444           if ( selectedEntity != null ) {
445               selectedEntity.removeEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
446               selectedEntity.removeEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
447           }
448           
449           if ( entity == null ) {
450               relationsGrid.dataProvider = null;
451           } else {
452               resetRelationsGrid(entity);
453               entity.addEventListener(Connection.ADDED_TO_RELATION, addedToRelation);
454               entity.addEventListener(Connection.REMOVED_FROM_RELATION, removedFromRelation);
455           }
456       }
457       
458       private function addedToRelation(event:RelationMemberEvent):void {
459          resetRelationsGrid(selectedEntity);
460       }
461
462       private function removedFromRelation(event:RelationMemberEvent):void {
463          resetRelationsGrid(selectedEntity);
464       }
465
466       private function removeRelationListeners():void {
467           for each( var rel:Relation in listeningToRelations ) {
468               rel.removeEventListener(Connection.TAG_CHANGED, relationTagChanged);
469               rel.removeEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
470               rel.removeEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
471           }
472           listeningToRelations = [];
473           relationsGrid.removeEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged);
474       }
475             
476       private function resetRelationsGrid(entity:Entity):void {
477           removeRelationListeners();
478           var relations:Array = [];
479           for each( var rel:Relation in entity.parentRelations ) {
480               for each( var memberIndex:int in rel.findEntityMemberIndexes(entity)) {
481                   var props:Object = {};
482                   props["relation"] = rel;
483                   props["id"] = rel.id;
484                   props["index"] = memberIndex;
485                   props["role"] = rel.getMember(memberIndex).role;
486                   props["description"] = rel.getDescription();
487                   props["id_idx"] = rel.id + "/"+memberIndex;
488
489                   relations.push(props);
490               }
491               
492               rel.addEventListener(Connection.TAG_CHANGED, relationTagChanged);
493               rel.addEventListener(Connection.RELATION_MEMBER_ADDED, entityRelationMemberChanged);
494               rel.addEventListener(Connection.RELATION_MEMBER_REMOVED, entityRelationMemberChanged);
495               listeningToRelations.push(rel);
496           }
497           relationsGrid.dataProvider = relations;
498           relationsGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, relationRoleChanged, false, -100);
499       }
500       
501       private function relationRoleChanged(event:DataGridEvent):void {
502                 if (event.dataField != 'role') { return; }      // shouldn't really happen
503
504                 var relations:Array=event.currentTarget.dataProvider.toArray();
505                 var props:Object=relations[event.rowIndex];
506
507                 var relation:Relation=props['relation'];
508                 var index:uint=props['index'];
509                 var newRole:String=event.itemRenderer.data['role'];
510
511                 relation.setMember(index, new RelationMember(selectedEntity,newRole));
512       }
513
514       private function relationTagChanged(event:TagEvent):void {
515           resetRelationsGrid(selectedEntity);
516       }
517
518       private function entityRelationMemberChanged(event:RelationMemberEvent):void {
519           resetRelationsGrid(selectedEntity);
520       }
521       
522       private function checkMembers():void {
523           if (selectedEntity is Relation) {
524             setupMembers(selectedEntity as Relation);
525           }
526       }
527       
528       private function setupMembers(rel:Relation):void {
529           var members:Array = [];
530           for (var i:int=0 ; i<rel.length; i++) {
531             var props:Object = {};
532             var member:RelationMember = rel.getMember(i);
533             props["id"] = member.entity.id;
534             props["type"] = member.entity.getType();
535             props["role"] = member.role;
536             
537             members.push(props);
538           }
539           membersGrid.dataProvider = members;
540           membersGrid.dataProvider.addEventListener('collectionChange', membersChange); 
541       }
542       
543       private function membersChange(event:Event):void {
544           // Dropping all the members and re-adding them isn't exactly optimal
545           // but is at least robust for any kind of change.
546           // Figuring out a better way is someone else's FIXME
547           
548           var conn:Connection = Connection.getConnectionInstance();
549           var rel:Relation = selectedEntity as Relation
550           
551           // drop members
552           for (var i:int=rel.length-1 ; i>=0; i--) {
553             rel.removeMemberByIndex(i);
554           }
555           
556           // add members in new order
557           for each(var memberObject:Object in membersGrid.dataProvider) {
558             var e:Entity;
559             var id:Number = memberObject.id;
560             if(memberObject.type == 'node') {
561               e = conn.getNode(id);
562             } else if (memberObject.type == 'way') {
563               e = conn.getWay(id);
564             } else if (memberObject.type == 'relation') {
565               e = conn.getRelation(id);
566             }
567             rel.appendMember(new RelationMember(e, memberObject.role));
568           }
569       }
570       
571       private function editRelation(id:Number):void {
572           var panel:RelationEditorPanel = RelationEditorPanel(
573               PopUpManager.createPopUp(Application(Application.application), RelationEditorPanel, true));
574           panel.setRelation(Connection.getConnectionInstance().getRelation(id));
575           PopUpManager.centerPopUp(panel);
576       }
577       
578       private function tagChanged(event:TagEvent):void {
579           refreshFeatureIcon();
580           
581           if ( tagDataProvider != null ) {
582               // check to see if the key is already in our list
583               var exists:Boolean = false;
584               var tag:Tag = null;
585               var i:uint;
586               for ( i = 0; i < tagDataProvider.length && !exists; i++ ) {
587                   tag = Tag(tagDataProvider.getItemAt(i));
588                   exists = tag.key == event.key;
589               }
590               if ( !exists ) {
591                   tag = new Tag(selectedEntity, event.key, event.newValue);
592                   tagDataProvider.addItem(tag);
593                   tagDataProvider.refresh();
594               } else {
595                   if ( event.newValue == null ) {
596                       tagDataProvider.removeItemAt(i-1);
597                       tagDataProvider.refresh();
598                   } else {
599                       tagDataProvider.itemUpdated(tag, "value");
600                   }
601               }
602           }
603       }
604
605       public function loadFeatures():void {
606           mapFeatures = MapFeatures.getInstance();
607           stack.removeChild(membersVBox); // remove by default, will be added if relation
608       }
609
610       public function openDescription():void {
611           if ( feature != null && feature.hasHelpURL() )
612               navigateToURL(new URLRequest(feature.helpURL), "potlatch_help");
613       }
614
615       public function openEntityPage():void {
616           if (selectedEntity != null && selectedEntity.id >= 0) {
617               // This is slightly hard-coded, but not drastically. The ../s could be changed for string manipulation of the apiBase
618               var urlBase:String = Connection.getConnectionInstance().apiBase + '../../browse/'
619               navigateToURL(new URLRequest(urlBase+selectedEntity.getType()+'/'+selectedEntity.id), "potlatch_browse");
620           }
621       }
622
623       public function addNewTag():void {
624           if (stack.selectedChild!=advancedContainer || selectedEntity == null) { return; }
625           var newKey:String = "(new tag)";
626           var newTag:Tag = new Tag(selectedEntity, newKey, "(new value)");
627           tagDataProvider.addItem(newTag);
628           advancedTagGrid.editedItemPosition = {rowIndex: tagDataProvider.getItemIndex(newTag), columnIndex: 0};
629       }
630
631       public function removeTag():void {
632           var k:String = advancedTagGrid.selectedItem.key;
633           selectedEntity.setTag(k, null, MainUndoStack.getGlobalStack().addAction);
634       }
635       
636       public function addToRelation():void {
637           new RelationSelectPanel().init(selectedEntity,new Object());
638       }
639       
640       public function removeFromRelation(id:Number, index:int):void {
641           Connection.getConnectionInstance().getRelation(id).removeMemberByIndex(index);
642       }
643       
644       public function initFeatureBox():void {
645           tw = new CategorySelector();
646           tw.addEventListener("selectedType", changeFeatureType);
647           popupChange.popUp = tw;
648       }
649       
650       public function changeFeatureType(event:Event):void {
651           if ( selectedEntity == null )
652               return;
653
654           UIComponent.suspendBackgroundProcessing();
655           var newFeature:Feature = tw.selectedType;
656           var undoStack:Function = MainUndoStack.getGlobalStack().addAction;
657           var action:CompositeUndoableAction = new CompositeUndoableAction(
658                   "Set "+selectedEntity.getType()+" "+selectedEntity.id+" to "+newFeature.name);
659                   selectedEntity.suspend();
660
661           // remove tags from the current feature
662           if ( feature != null ) {
663               for each( var oldtag:Object in feature.tags ) {
664                   selectedEntity.setTag(oldtag["k"], null, action.push);
665               }
666           }
667           
668           // set tags for new feature
669           if ( newFeature != null ) {
670               for each( var newtag:Object in newFeature.tags ) {
671                   selectedEntity.setTag(newtag["k"], newtag["v"], action.push);
672               }
673           }
674           
675                   selectedEntity.resume();
676           undoStack(action);
677           popupChange.close();
678           initialiseEditors();
679           UIComponent.resumeBackgroundProcessing();
680       }
681       
682         private function resizePOIGrid(event:Event):void {
683                 var rows:Number=event.target.dataProvider.length/event.target.columnCount;
684                 if (rows!=Math.floor(rows)) { rows=Math.floor(rows+1); }
685                 event.target.height=rows*(event.target.rowHeight+1);
686         }
687   ]]></mx:Script>
688 </mx:VBox>
689