Merge branch 'localfile'
[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.FileBank;
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                 private 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             FileBank.getInstance().addFromFile("imagery.xml", onImageryLoad);
42
43                         // create map listeners
44                         map.addEventListener(MapEvent.MOVE, moveHandler);
45                         map.addEventListener(MapEvent.RESIZE, resizeHandler);
46                 }
47
48                 private function onImageryLoad(fileBank:FileBank, filename:String):void {
49                         var xml:XML = new XML(fileBank.getAsString(filename));
50                         var saved:Object = {};
51                         var bg:Object;
52                         if (SharedObject.getLocal("user_state").data['background_url']!=undefined) {
53                                 saved={ name: SharedObject.getLocal("user_state").data['background_name'],
54                                                 url:  SharedObject.getLocal("user_state").data['background_url' ] };
55                         }
56
57                         var isSet:Boolean=false;
58             var backgroundSet:Boolean = false;
59
60                         // Read all values from XML file
61                         collection=new Array({ name: "None", url: "" });
62                         for each(var set:XML in xml.set) {
63                                 var obj:Object={};
64                                 var a:XML;
65                                 for each (a in set.@*) { obj[a.name().localName]=a.toString(); }
66                                 for each (a in set.* ) { obj[a.name()          ]=a.toString(); }
67                 collection.push(obj);
68                                 if ((saved.url  && obj.url ==saved.url) ||
69                                     (saved.name && obj.name==saved.name && obj.name!='Custom')) { isSet=true; }
70                         }
71
72                         // Add user's previous preference (from SharedObject) if we didn't find it in the XML file
73             if (!isSet && saved.name && saved.url && saved.url!='') {
74                 collection.push(saved);
75                 isSet=true;
76             }
77
78                         // Automatically select the user's previous preference
79                         var defaultBackground:Object=null;
80                         for each (bg in collection) {
81                                 if (bg.name==saved.name || bg.url==saved.url) {
82                                         setBackground(bg);
83                     backgroundSet = true;
84                                 } else if (bg.default) {
85                                         defaultBackground=bg;
86                                 }
87                         }
88
89             // Otherwise, set whatever's specified as default
90             if (!backgroundSet && defaultBackground) {
91                 setBackground(defaultBackground);
92             }
93
94                         // Get any attribution and logo details
95                         collection.forEach(function(bg:Object, index:int, array:Array):void {
96                                 if (bg.logo) {
97                                         // load the logo
98                     FileBank.getInstance().addFromFile(bg.logo, function (fb:FileBank, name:String):void {
99                         bg.logoData = fb.getAsBitmapData(name);
100                         bg.logoWidth = fb.getWidth(name);
101                         bg.logoHeight = fb.getHeight(name);
102                         setLogo();
103                     });
104                                 }
105                                 if (bg.attribution_url) {
106                                         // load the attribution
107                                 var urlloader:URLLoader = new URLLoader();
108                                         urlloader.addEventListener(Event.COMPLETE, function(e:Event):void { onAttributionLoad(e,bg); });
109                                         urlloader.addEventListener(IOErrorEvent.IO_ERROR, onError);
110                                         urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
111                                 urlloader.load(new URLRequest(bg.attribution_url));
112                                 }
113                         });
114
115                         // Tell the function key manager that we'd like to receive function key calls
116                         FunctionKeyManager.instance().registerListener('Background imagery',
117                                 function(o:String):void { setBackground(findBackgroundWithName(o)); });
118                         dispatchEvent(new Event("collection_changed"));
119                 }
120                 
121                 private function onError(e:Event):void {
122                         // placeholder error routine so exception isn't thrown
123                 }
124                 
125                 public function onAttributionLoad(e:Event,bg: Object):void {
126                         // if we ever need to cope with non-Microsoft attribution, then this should look at bg.scheme
127             default xml namespace = Namespace("http://schemas.microsoft.com/search/local/ws/rest/v1");
128             var xml:XML = new XML(e.target.data);
129                         var attribution:Object = {};
130             for each (var ImageryProvider:XML in xml..ImageryProvider) {
131                 var areas:Array=[];
132                 for each (var CoverageArea:XML in ImageryProvider.CoverageArea) {
133                     areas.push([CoverageArea.ZoomMin,
134                                 CoverageArea.ZoomMax,
135                                 CoverageArea.BoundingBox.SouthLatitude,
136                                 CoverageArea.BoundingBox.WestLongitude,
137                                 CoverageArea.BoundingBox.NorthLatitude,
138                                 CoverageArea.BoundingBox.EastLongitude]);
139                 }
140                 attribution[ImageryProvider.Attribution]=areas;
141             }
142                         default xml namespace = new Namespace("");
143                         bg.attribution=attribution;
144                         setAttribution();
145                 }
146
147                 public function setBackground(bg:Object):void {
148                         // set background
149                         _selected=bg;
150                         if (bg.url=='yahoo') { dispatchEvent(new CollectionEvent(CollectionEvent.SELECT, {url:''})); _yahoo.show(); }
151                                         else { dispatchEvent(new CollectionEvent(CollectionEvent.SELECT, bg      )); _yahoo.hide(); }
152                         // update attribution and logo
153                         _overlay.visible=bg.attribution || bg.logo || bg.terms_url;
154                         setLogo(); setAttribution(); setTerms();
155                         // save as SharedObject for next time
156                         var obj:SharedObject = SharedObject.getLocal("user_state");
157                         obj.setProperty('background_url' ,String(bg.url));
158                         obj.setProperty('background_name',String(bg.name));
159                         obj.flush();
160                 }
161                 
162                 public function get selected():Object { return _selected; }
163                 
164                 private function findBackgroundWithName(name:String):Object {
165                         for each (var bg:Object in collection) {
166                                 if (bg.name==name) { return bg; }
167                         }
168                         return { url:'' };
169                 }
170
171                 private function moveHandler(event:MapEvent):void {
172                         setAttribution();
173                         dispatchEvent(new Event("collection_changed"));
174                 }
175                 private function setAttribution():void {
176                         var tf:TextField=TextField(_overlay.getChildAt(0));
177                         tf.text='';
178                         if (!_selected.attribution) return;
179                         var attr:Array=[];
180                         for (var provider:String in _selected.attribution) {
181                                 for each (var bounds:Array in _selected.attribution[provider]) {
182                                         if (_map.scale>=bounds[0] && _map.scale<=bounds[1] &&
183                                           ((_map.edge_l>bounds[3] && _map.edge_l<bounds[5]) ||
184                                            (_map.edge_r>bounds[3] && _map.edge_r<bounds[5]) ||
185                                    (_map.edge_l<bounds[3] && _map.edge_r>bounds[5])) &&
186                                           ((_map.edge_b>bounds[2] && _map.edge_b<bounds[4]) ||
187                                            (_map.edge_t>bounds[2] && _map.edge_t<bounds[4]) ||
188                                            (_map.edge_b<bounds[2] && _map.edge_t>bounds[4]))) {
189                                                 attr.push(provider);
190                                         }
191                                 }
192                         }
193                         if (attr.length==0) return;
194                         tf.text="Background "+attr.join(", ");
195                         positionAttribution();
196                         dispatchEvent(new MapEvent(MapEvent.BUMP, { y: tf.textHeight }));       // don't let the toolbox obscure it
197                 }
198                 private function positionAttribution():void {
199                         var tf:TextField=TextField(_overlay.getChildAt(0));
200                         tf.x=_map.mapwidth  - 5 - tf.textWidth;
201                         tf.y=_map.mapheight - 5 - tf.textHeight;
202                 }
203
204                 private function setLogo():void {
205                         while (_overlay.numChildren>2) { _overlay.removeChildAt(2); }
206                         if (!_selected.logoData) return;
207                         var logo:Sprite=new Sprite();
208                         logo.addChild(new Bitmap(_selected.logoData));
209                         if (_selected.logo_url) { logo.buttonMode=true; logo.addEventListener(MouseEvent.CLICK, launchLogoLink, false, 0, true); }
210                         _overlay.addChild(logo);
211                         positionLogo();
212                 }
213                 private function positionLogo():void {
214                         _overlay.getChildAt(2).x=5;
215                         _overlay.getChildAt(2).y=_map.mapheight - 5 - _selected.logoHeight - (_selected.terms_url ? 10 : 0);
216                 }
217                 private function launchLogoLink(e:Event):void {
218                         if (!_selected.logo_url) return;
219                         navigateToURL(new URLRequest(_selected.logo_url), '_blank');
220                 }
221                 private function setTerms():void {
222                         var terms:TextField=TextField(_overlay.getChildAt(1));
223                         if (!_selected.terms_url) { terms.text=''; return; }
224                         terms.text="Background terms of use";
225                         positionTerms();
226                         terms.addEventListener(MouseEvent.CLICK, launchTermsLink, false, 0, true);
227                 }
228                 private function positionTerms():void {
229                         _overlay.getChildAt(1).x=5;
230                         _overlay.getChildAt(1).y=_map.mapheight - 15;
231                 }
232                 private function launchTermsLink(e:Event):void {
233                         if (!_selected.terms_url) return;
234                         navigateToURL(new URLRequest(_selected.terms_url), '_blank');
235                 }
236
237                 private function resizeHandler(event:MapEvent):void {
238                         if (_selected.logoData) positionLogo();
239                         if (_selected.terms_url) positionTerms();
240                         if (_selected.attribution) positionAttribution();
241                 }
242
243                 [Bindable(event="collection_changed")]
244                 public function getAvailableImagery():ArrayCollection {
245                         var available:Array=[];
246                         for each (var bg:Object in collection) {
247                                 if (bg.minlon) {
248                                         // if there's a bbox, check the current viewport intersects it
249                                         if (((_map.edge_l>bg.minlon && _map.edge_l<bg.maxlon) ||
250                                              (_map.edge_r>bg.minlon && _map.edge_r<bg.maxlon) ||
251                                              (_map.edge_l<bg.minlon && _map.edge_r>bg.maxlon)) &&
252                                             ((_map.edge_b>bg.minlat && _map.edge_b<bg.maxlat) ||
253                                              (_map.edge_t>bg.minlat && _map.edge_t<bg.maxlat) ||
254                                              (_map.edge_b<bg.minlat && _map.edge_t>bg.maxlat))) {
255                                                 available.push(bg);
256                                         }
257                                 } else {
258                                         // if there's no bbox (i.e. global set), include it anyway
259                                         available.push(bg);
260                                 }
261                         }
262                         return new ArrayCollection(available);
263                 }
264
265         }
266         
267 }