kill stupid tab bug
[potlatch2.git] / net / systemeD / potlatch2 / collections / Imagery.as
1 package net.systemeD.potlatch2.collections {
2
3         import flash.events.*;
4         import flash.display.*;
5         import flash.net.*;
6         import flash.text.TextField;
7         import net.systemeD.halcyon.DebugURLRequest;
8         import net.systemeD.halcyon.Map;
9         import net.systemeD.halcyon.MapEvent;
10         import net.systemeD.potlatch2.FunctionKeyManager;
11         import net.systemeD.potlatch2.Yahoo;
12         import mx.collections.ArrayCollection;
13
14         /*
15                 There's lots of further tidying we can do:
16                 - remove all the horrid Yahoo stuff
17                 - remove the backreferences to _map and send events instead
18                 but this will do for now and help remove the clutter from potlatch2.mxml.
19         */
20
21         public class Imagery extends EventDispatcher {
22
23         private static const GLOBAL_INSTANCE:Imagery = new Imagery();
24         public static function instance():Imagery { return GLOBAL_INSTANCE; }
25
26                 public var collection:Array=[];
27                 public var selected:Object={};
28
29                 private var _map:Map;
30                 private var _overlay:Sprite;
31                 private var _yahoo:Yahoo;
32
33                 /* Load catalogue file */
34
35                 public function init(map:Map, overlay:Sprite, yahoo:Yahoo):void {
36                         _map = map;
37                         _overlay = overlay;
38                         _yahoo = yahoo;
39
40                         // load imagery file
41                 var request:DebugURLRequest = new DebugURLRequest("imagery.xml");
42                 var loader:URLLoader = new URLLoader();
43                 loader.addEventListener(Event.COMPLETE, onImageryLoad);
44                 loader.load(request.request);
45
46                         // create map listeners
47                         map.addEventListener(MapEvent.MOVE, moveHandler);
48                         map.addEventListener(MapEvent.RESIZE, resizeHandler);
49                 }
50
51         private function onImageryLoad(event:Event):void {
52                         var xml:XML = new XML(URLLoader(event.target).data);
53                         var saved:Object;
54                         var bg:Object;
55                         if (SharedObject.getLocal("user_state").data['background_url']) {
56                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
57                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
58                         } else {
59                                 saved={ url: ''};
60                         }
61
62                         var isSet:Boolean=false;
63             var backgroundSet:Boolean = false;
64
65                         // Read all values from XML file
66             collection=new Array(
67                                 { name: "None", url: "" },
68                                 { name: "Yahoo", url: "yahoo", sourcetag: "Yahoo" } );
69                         for each(var set:XML in xml.set) {
70                                 var obj:Object={};
71                                 var a:XML;
72                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
73                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
74                 collection.push(obj);
75                                 if ((obj.url ==saved.url) ||
76                                     (obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
77                         }
78
79                         // Add user's previous preference (from SharedObject) if we didn't find it in the XML file
80             if (!isSet && saved.name && saved.url && saved.url!='' && saved.url!='yahoo') {
81                 collection.push(saved);
82                 isSet=true;
83             }
84
85                         // Automatically select the user's previous preference
86                         var defaultBackground:Object=null;
87                         for each (bg in collection) {
88                                 if (bg.name==saved.name || bg.url==saved.url) {
89                                         setBackground(bg);
90                     backgroundSet = true;
91                                 } else if (bg.default) {
92                                         defaultBackground=bg;
93                                 }
94                         }
95
96             // Otherwise, set whatever's specified as default
97             if (!backgroundSet && defaultBackground) {
98                 setBackground(defaultBackground);
99             }
100
101                         // Get any attribution and logo details
102                         for each (bg in collection) {
103                                 if (bg.logo) {
104                                         // load the logo
105                                         var loader:Loader = new Loader();
106                                         var thisbg1:Object = bg;                        // scope it for the closure
107                                         loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void { onLogoLoad(e,thisbg1); });
108                                         loader.load(new URLRequest(bg.logo));
109                                 }
110                                 if (bg.attribution_url) {
111                                         // load the attribution
112                                         trace("requesting "+bg.attribution_url);
113                                 var urlloader:URLLoader = new URLLoader();
114                                         var thisbg2:Object = bg;                        // scope it for the closure
115                                         urlloader.addEventListener(Event.COMPLETE, function(e:Event):void { onAttributionLoad(e,thisbg2); });
116                                 urlloader.load(new URLRequest(bg.attribution_url));
117                                 }
118                         }
119
120                         // Tell the function key manager that we'd like to receive function key calls
121                         FunctionKeyManager.instance().registerListener('Background imagery',
122                                 function(o:String):void { setBackground(findBackgroundWithName(o)); });
123                         dispatchEvent(new Event("collection_changed"));
124                 }
125                 
126                 public function onLogoLoad(e:Event, bg:Object):void {
127                         bg.logoData  = Bitmap(LoaderInfo(e.target).content).bitmapData;
128                         bg.logoWidth = e.target.loader.width;
129                         bg.logoHeight= e.target.loader.height;
130                         setLogo();
131                 }
132                 
133                 public function onAttributionLoad(e:Event,bg: Object):void {
134                         trace ("onAttributionLoad");
135                         // if we ever need to cope with non-Microsoft attribution, then this should look at bg.scheme
136                         // someone who actually likes XML can replace the following with the 'proper' way of doing it
137                         var xmlnsPattern:RegExp = new RegExp("xmlns[^\"]*\"[^\"]*\"", "gi");
138                         var xsiPattern:RegExp = new RegExp("xsi[^\"]*\"[^\"]*\"", "gi");
139                         var s:String=e.target.data;
140                         var xml:XML = new XML(s.replace(xmlnsPattern, "").replace(xsiPattern, ""));
141                         var attribution:Object = {};
142                         for each (var ResourceSets:XML in xml.child("ResourceSets")) {
143                                 for each (var ResourceSet:XML in ResourceSets.child("ResourceSet")) {
144                                         for each (var Resources:XML in ResourceSet.child("Resources")) {
145                                                 for each (var ImageryMetadata:XML in Resources.child("ImageryMetadata")) {
146                                                         for each (var ImageryProvider:XML in ImageryMetadata.child("ImageryProvider")) {
147                                                                 var areas:Array=[];
148                                                                 for each (var CoverageArea:XML in ImageryProvider.child("CoverageArea")) {
149                                                                         areas.push([CoverageArea.ZoomMin,
150                                                                                     CoverageArea.ZoomMax,
151                                                                                     CoverageArea.BoundingBox.SouthLatitude,
152                                                                                     CoverageArea.BoundingBox.WestLongitude,
153                                                                                     CoverageArea.BoundingBox.NorthLatitude,
154                                                                                     CoverageArea.BoundingBox.EastLongitude]);
155                                                                 }
156                                                                 attribution[ImageryProvider.Attribution]=areas;
157                                                         }
158                                                 }
159                                         }
160                                 }
161                         }
162                         bg.attribution=attribution;
163                         setAttribution();
164                 }
165
166                 public function setBackground(bg:Object):void {
167                         // set background
168                         selected=bg;
169                         if (bg.url=='yahoo') { _map.setBackground({url:''}); _yahoo.show(); }
170                                         else { _map.setBackground(bg      ); _yahoo.hide(); }
171                         // update attribution and logo
172                         _overlay.visible=bg.attribution || bg.logo || bg.terms_url;
173                         setLogo(); setAttribution(); setTerms();
174                         // save as SharedObject for next time
175                         var obj:SharedObject = SharedObject.getLocal("user_state");
176                         obj.setProperty('background_url' ,String(bg.url));
177                         obj.setProperty('background_name',String(bg.name));
178                         obj.flush();
179                 }
180                 
181                 private function findBackgroundWithName(name:String):Object {
182                         for each (var bg:Object in collection) {
183                                 if (bg.name==name) { return bg; }
184                         }
185                         return { url:'' };
186                 }
187
188                 private function moveHandler(event:MapEvent):void {
189                         setAttribution();
190                 }
191                 private function setAttribution():void {
192                         var tf:TextField=TextField(_overlay.getChildAt(0));
193                         tf.text='';
194                         if (!selected.attribution) return;
195                         var attr:Array=[];
196                         for (var provider:String in selected.attribution) {
197                                 for each (var bounds:Array in selected.attribution[provider]) {
198                                         if (_map.scale>=bounds[0] && _map.scale<=bounds[1] &&
199                                           ((_map.edge_l>bounds[3] && _map.edge_l<bounds[5]) ||
200                                            (_map.edge_r>bounds[3] && _map.edge_r<bounds[5]) ||
201                                    (_map.edge_l<bounds[3] && _map.edge_r>bounds[5])) &&
202                                           ((_map.edge_b>bounds[2] && _map.edge_b<bounds[4]) ||
203                                            (_map.edge_t>bounds[2] && _map.edge_t<bounds[4]) ||
204                                            (_map.edge_b<bounds[2] && _map.edge_t>bounds[4]))) {
205                                                 attr.push(provider);
206                                         }
207                                 }
208                         }
209                         if (attr.length==0) return;
210                         tf.text="Background "+attr.join(", ");
211                         tf.x=_map.mapwidth  - 5 - tf.textWidth;
212                         tf.y=_map.mapheight - 5 - tf.textHeight;
213                         dispatchEvent(new MapEvent(MapEvent.BUMP, { y: tf.textHeight }));       // don't let the toolbox obscure it
214                 }
215                 private function resizeHandler(event:MapEvent):void {
216                         if (!selected.logoData) return;
217                         _overlay.getChildAt(2).y=event.params.height - 5 - selected.logoHeight - (selected.terms_url ? 10 : 0);
218                 }
219                 private function setLogo():void {
220                         while (_overlay.numChildren>2) { _overlay.removeChildAt(2); }
221                         if (!selected.logoData) return;
222                         var logo:Sprite=new Sprite();
223                         logo.addChild(new Bitmap(selected.logoData));
224                         logo.x=5; logo.y=_map.mapheight - 5 - selected.logoHeight - (selected.terms_url ? 10 : 0);
225                         if (selected.logo_url) { logo.buttonMode=true; logo.addEventListener(MouseEvent.CLICK, launchLogoLink, false, 0, true); }
226                         _overlay.addChild(logo);
227                 }
228                 private function launchLogoLink(e:Event):void {
229                         if (!selected.logo_url) return;
230                         navigateToURL(new URLRequest(selected.logo_url), '_blank');
231                 }
232                 private function setTerms():void {
233                         var terms:TextField=TextField(_overlay.getChildAt(1));
234                         if (!selected.terms_url) { terms.text=''; return; }
235                         terms.text="Background terms of use";
236                         terms.x=5; terms.y=_map.mapheight - 15;
237                         terms.addEventListener(MouseEvent.CLICK, launchTermsLink, false, 0, true);
238                 }
239                 private function launchTermsLink(e:Event):void {
240                         if (!selected.terms_url) return;
241                         navigateToURL(new URLRequest(selected.terms_url), '_blank');
242                 }
243
244                 [Bindable(event="collection_changed")]
245                 public function getAvailableImagery():ArrayCollection {
246                         var available:Array=[];
247                         for each (var bg:Object in collection) {
248                                 if (bg.minlon) {
249                                         // if there's a bbox, check the current viewport intersects it
250                                         if (((_map.edge_l>bg.minlon && _map.edge_l<bg.maxlon) ||
251                                              (_map.edge_r>bg.minlon && _map.edge_r<bg.maxlon) ||
252                                              (_map.edge_l<bg.minlon && _map.edge_r>bg.maxlon)) &&
253                                             ((_map.edge_b>bg.minlat && _map.edge_b<bg.maxlat) ||
254                                              (_map.edge_t>bg.minlat && _map.edge_t<bg.maxlat) ||
255                                              (_map.edge_b<bg.minlat && _map.edge_t>bg.maxlat))) {
256                                                 available.push(bg);
257                                         }
258                                 } else {
259                                         // if there's no bbox (i.e. global set), include it anyway
260                                         available.push(bg);
261                                 }
262                         }
263                         return new ArrayCollection(available);
264                 }
265
266         }
267         
268 }