add support for provider attribution and logo, as required by Bing. Add an entry...
[potlatch2.git] / net / systemeD / potlatch2 / collections / Imagery.as
1 package net.systemeD.potlatch2.collections {
2
3         import flash.events.EventDispatcher;
4         import flash.events.Event;
5         import flash.display.*;
6         import flash.net.*;
7         import flash.text.TextField;
8         import net.systemeD.halcyon.DebugURLRequest;
9         import net.systemeD.halcyon.Map;
10         import net.systemeD.halcyon.MapEvent;
11         import net.systemeD.potlatch2.FunctionKeyManager;
12         import net.systemeD.potlatch2.Yahoo;
13         import mx.collections.ArrayCollection;
14
15         /*
16                 There's lots of further tidying we can do:
17                 - remove all the horrid Yahoo stuff
18                 - remove the backreferences to _map and send events instead
19                 but this will do for now and help remove the clutter from potlatch2.mxml.
20         */
21
22         public class Imagery extends EventDispatcher {
23
24         private static const GLOBAL_INSTANCE:Imagery = new Imagery();
25         public static function instance():Imagery { return GLOBAL_INSTANCE; }
26
27                 public var collection:Array=[];
28                 public var selected:Object={};
29
30                 private var _yahooDefault:Boolean=false;
31                 private var _map:Map;
32                 private var _overlay:Sprite;
33                 private var _yahoo:Yahoo;
34
35                 /* Load catalogue file */
36
37                 public function init(map:Map, overlay:Sprite, yahoo:Yahoo, yahooDefault:Boolean):void {
38                         _map = map;
39                         _overlay = overlay;
40                         _yahoo = yahoo;
41                         _yahooDefault = yahooDefault;
42
43                         // load imagery file
44                 var request:DebugURLRequest = new DebugURLRequest("imagery.xml");
45                 var loader:URLLoader = new URLLoader();
46                 loader.addEventListener(Event.COMPLETE, onImageryLoad);
47                 loader.load(request.request);
48
49                         // create map listeners
50                         map.addEventListener(MapEvent.MOVE, moveHandler);
51                         map.addEventListener(MapEvent.RESIZE, resizeHandler);
52                 }
53
54         private function onImageryLoad(event:Event):void {
55                         var xml:XML = new XML(URLLoader(event.target).data);
56                         var saved:Object;
57                         var bg:Object;
58                         if (SharedObject.getLocal("user_state").data['background_url']) {
59                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
60                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
61                         } else {
62                                 saved={ url: ''};
63                         }
64
65                         var isSet:Boolean=false;
66             var backgroundSet:Boolean = false;
67
68                         // Read all values from XML file
69             collection=new Array(
70                                 { name: "None", url: "" },
71                                 { name: "Yahoo", url: "yahoo", sourcetag: "Yahoo" } );
72                         for each(var set:XML in xml.set) {
73                                 var obj:Object={};
74                                 var a:XML;
75                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
76                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
77                 collection.push(obj);
78                                 if ((obj.url ==saved.url) ||
79                                     (obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
80                         }
81
82                         // Add user's previous preference (from SharedObject) if we didn't find it in the XML file
83             if (!isSet && saved.name && saved.url && saved.url!='' && saved.url!='yahoo') {
84                 collection.push(saved);
85                 isSet=true;
86             }
87
88                         // Automatically select the user's previous preference
89                         for each (bg in collection) {
90                                 if (bg.name==saved.name || bg.url==saved.url) {
91                                         setBackground(bg);
92                     backgroundSet = true;
93                                 }
94                         }
95
96             // Otherwise, set Yahoo as default (if this was passed in as an option from the embedding page)
97             if (!backgroundSet && _yahooDefault) {
98                 setBackground(collection[1]);
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;
173                         setLogo(); setAttribution();
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                         if (!selected.attribution) return;
193                         var attr:Array=[];
194                         for (var provider:String in selected.attribution) {
195                                 for each (var bounds:Array in selected.attribution[provider]) {
196                                         if (_map.scale>=bounds[0] && _map.scale<=bounds[1] &&
197                                           ((_map.edge_l>bounds[3] && _map.edge_l<bounds[5]) ||
198                                            (_map.edge_r>bounds[3] && _map.edge_r<bounds[5]) ||
199                                    (_map.edge_l<bounds[3] && _map.edge_r>bounds[5])) &&
200                                           ((_map.edge_b>bounds[2] && _map.edge_b<bounds[4]) ||
201                                            (_map.edge_t>bounds[2] && _map.edge_t<bounds[4]) ||
202                                            (_map.edge_b<bounds[2] && _map.edge_t>bounds[4]))) {
203                                                 attr.push(provider);
204                                         }
205                                 }
206                         }
207                         TextField(_overlay.getChildAt(0)).text="Background "+attr.join(", ");
208                 }
209                 private function resizeHandler(event:MapEvent):void {
210                         if (!selected.logoData) return;
211                         _overlay.getChildAt(1).y=event.params.height-5-selected.logoHeight;
212                 }
213                 private function setLogo():void {
214                         if (!selected.logoData) return;
215                         while (_overlay.numChildren>1) { _overlay.removeChildAt(1); }
216                         var logo:Bitmap=new Bitmap(selected.logoData);
217                         logo.x=5; logo.y=_map.mapheight-5-selected.logoHeight;
218                         _overlay.addChild(logo);
219                 }
220
221                 [Bindable(event="collection_changed")]
222                 public function getAvailableImagery():ArrayCollection {
223                         var available:Array=[];
224                         for each (var bg:Object in collection) {
225                                 if (bg.minlon) {
226                                         // if there's a bbox, check the current viewport intersects it
227                                         if (((_map.edge_l>bg.minlon && _map.edge_l<bg.maxlon) ||
228                                              (_map.edge_r>bg.minlon && _map.edge_r<bg.maxlon) ||
229                                              (_map.edge_l<bg.minlon && _map.edge_r>bg.maxlon)) &&
230                                             ((_map.edge_b>bg.minlat && _map.edge_b<bg.maxlat) ||
231                                              (_map.edge_t>bg.minlat && _map.edge_t<bg.maxlat) ||
232                                              (_map.edge_b<bg.minlat && _map.edge_t>bg.maxlat))) {
233                                                 available.push(bg);
234                                         }
235                                 } else {
236                                         // if there's no bbox (i.e. global set), include it anyway
237                                         available.push(bg);
238                                 }
239                         }
240                         return new ArrayCollection(available);
241                 }
242
243         }
244         
245 }