forked from cutting-room-floor/wax
/
wax.mm.js
1396 lines (1263 loc) · 51.1 KB
/
wax.mm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Reqwest! A x-browser general purpose XHR connection manager
* copyright Dustin Diaz 2011
* https://github.com/ded/reqwest
* license MIT
*/
!function(window){function serial(a){var b=a.name;if(a.disabled||!b)return"";b=enc(b);switch(a.tagName.toLowerCase()){case"input":switch(a.type){case"reset":case"button":case"image":case"file":return"";case"checkbox":case"radio":return a.checked?b+"="+(a.value?enc(a.value):!0)+"&":"";default:return b+"="+(a.value?enc(a.value):!0)+"&"}break;case"textarea":return b+"="+enc(a.value)+"&";case"select":return b+"="+enc(a.options[a.selectedIndex].value)+"&"}return""}function enc(a){return encodeURIComponent(a)}function reqwest(a,b){return new Reqwest(a,b)}function init(o,fn){function error(a){o.error&&o.error(a),complete(a)}function success(resp){o.timeout&&clearTimeout(self.timeout)&&(self.timeout=null);var r=resp.responseText;switch(type){case"json":resp=eval("("+r+")");break;case"js":resp=eval(r);break;case"html":resp=r}fn(resp),o.success&&o.success(resp),complete(resp)}function complete(a){o.complete&&o.complete(a)}this.url=typeof o=="string"?o:o.url,this.timeout=null;var type=o.type||setType(this.url),self=this;fn=fn||function(){},o.timeout&&(this.timeout=setTimeout(function(){self.abort(),error()},o.timeout)),this.request=getRequest(o,success,error)}function setType(a){if(/\.json$/.test(a))return"json";if(/\.jsonp$/.test(a))return"jsonp";if(/\.js$/.test(a))return"js";if(/\.html?$/.test(a))return"html";if(/\.xml$/.test(a))return"xml";return"js"}function Reqwest(a,b){this.o=a,this.fn=b,init.apply(this,arguments)}function getRequest(a,b,c){if(a.type!="jsonp"){var f=xhr();f.open(a.method||"GET",typeof a=="string"?a:a.url,!0),setHeaders(f,a),f.onreadystatechange=readyState(f,b,c),a.before&&a.before(f),f.send(a.data||null);return f}var d=doc.createElement("script"),e=getCallbackName(a);window[e]=generalCallback,d.type="text/javascript",d.src=a.url,d.async=!0,d.onload=function(){a.success&&a.success(lastValue),lastValue=undefined,head.removeChild(d)},head.insertBefore(d,topScript)}function generalCallback(a){lastValue=a}function getCallbackName(a){var b=a.jsonpCallback||"callback";if(a.url.substr(-(b.length+2))==b+"=?"){var c="reqwest_"+uniqid++;a.url=a.url.substr(0,a.url.length-1)+c;return c}var d=new RegExp(b+"=([\\w]+)");return a.url.match(d)[1]}function setHeaders(a,b){var c=b.headers||{};c.Accept="text/javascript, text/html, application/xml, text/xml, */*",c["X-Requested-With"]=c["X-Requested-With"]||"XMLHttpRequest";if(b.data){c["Content-type"]="application/x-www-form-urlencoded";for(var d in c)c.hasOwnProperty(d)&&a.setRequestHeader(d,c[d],!1)}}function readyState(a,b,c){return function(){a&&a.readyState==4&&(twoHundo.test(a.status)?b(a):c(a))}}var twoHundo=/^20\d$/,doc=document,byTag="getElementsByTagName",topScript=doc[byTag]("script")[0],head=topScript.parentNode,xhr="XMLHttpRequest"in window?function(){return new XMLHttpRequest}:function(){return new ActiveXObject("Microsoft.XMLHTTP")},uniqid=0,lastValue;Reqwest.prototype={abort:function(){this.request.abort()},retry:function(){init.call(this,this.o,this.fn)}},reqwest.serialize=function(a){var b=a[byTag]("input"),c=a[byTag]("select"),d=a[byTag]("textarea");return(v(b).chain().toArray().map(serial).value().join("")+v(c).chain().toArray().map(serial).value().join("")+v(d).chain().toArray().map(serial).value().join("")).replace(/&$/,"")},reqwest.serializeArray=function(a){for(var b=this.serialize(a).split("&"),c=0,d=b.length,e=[],f;c<d;c++)b[c]&&(f=b[c].split("="))&&e.push({name:f[0],value:f[1]});return e};var old=window.reqwest;reqwest.noConflict=function(){window.reqwest=old;return this},window.reqwest=reqwest}(this)// Instantiate objects based on a JSON "record". The record must be a statement
// array in the following form:
//
// [ "{verb} {subject}", arg0, arg1, arg2, ... argn ]
//
// Each record is processed from a passed `context` which starts from the
// global (ie. `window`) context if unspecified.
//
// - `@literal` Evaluate `subject` and return its value as a scalar. Useful for
// referencing API constants, object properties or other values.
// - `@new` Call `subject` as a constructor with args `arg0 - argn`. The
// newly created object will be the new context.
// - `@call` Call `subject` as a function with args `arg0 - argn` in the
// global namespace. The return value will be the new context.
// - `@chain` Call `subject` as a method of the current context with args `arg0
// - argn`. The return value will be the new context.
// - `@inject` Call `subject` as a method of the current context with args
// `arg0 - argn`. The return value will *not* affect the context.
// - `@group` Treat `arg0 - argn` as a series of statement arrays that share a
// context. Each statement will be called in serial and affect the context
// for the next statement.
//
// Requirements:
//
// - Underscore.js
// - jQuery @TODO: only used for $.browser check. Could probably be removed.
//
// Usage:
//
// var gmap = ['@new google.maps.Map',
// ['@call document.getElementById', 'gmap'],
// {
// center: [ '@new google.maps.LatLng', 0, 0 ],
// zoom: 2,
// mapTypeId: [ '@literal google.maps.MapTypeId.ROADMAP' ]
// }
// ];
// wax.Record(gmap);
var wax = wax || {};
wax.util = wax.util || {};
// From underscore
wax.util.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
wax.util.indexOf = function(array, item) {
var nativeIndexOf = Array.prototype.indexOf;
if (array == null) return -1;
var i, l;
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;
};
wax.util.isArray = Array.isArray || function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
wax.util.keys = Object.keys || function(obj) {
var hasOwnProperty = Object.prototype.hasOwnProperty;
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// TODO: replace with non-global-modifier
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initialValue */) {
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var k = 0;
var accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
do {
if (k in t) {
accumulator = t[k++];
break;
}
// if array contains no values, no initial value to return
if (++k >= len)
throw new TypeError();
}
while (true);
}
while (k < len) {
if (k in t)
accumulator = fun.call(undefined, accumulator, t[k], k, t);
k++;
}
return accumulator;
};
}
wax.Record = function(obj, context) {
var getFunction = function(head, cur) {
// TODO: strip out reduce
var ret = head.split('.').reduce(function(part, segment) {
return [part[1] || part[0], part[1] ? part[1][segment] : part[0][segment]];
}, [cur || window, null]);
if (ret[0] && ret[1]) {
return ret;
} else {
throw head + ' not found.';
}
};
var makeObject = function(fn_name, args) {
var fn_obj = getFunction(fn_name),
obj;
args = args.length ? wax.Record(args) : [];
// real browsers
if (Object.create) {
obj = Object.create(fn_obj[1].prototype);
fn_obj[1].apply(obj, args);
// lord have mercy on your soul.
} else {
switch (args.length) {
case 0: obj = new fn_obj[1](); break;
case 1: obj = new fn_obj[1](args[0]); break;
case 2: obj = new fn_obj[1](args[0], args[1]); break;
case 3: obj = new fn_obj[1](args[0], args[1], args[2]); break;
case 4: obj = new fn_obj[1](args[0], args[1], args[2], args[3]); break;
case 5: obj = new fn_obj[1](args[0], args[1], args[2], args[3], args[4]); break;
default: break;
}
}
return obj;
};
var runFunction = function(fn_name, args, cur) {
var fn_obj = getFunction(fn_name, cur);
var fn_args = args.length ? wax.Record(args) : [];
// @TODO: This is currently a stopgap measure that calls methods like
// `foo.bar()` in the context of `foo`. It will probably be necessary
// in the future to be able to call `foo.bar()` from other contexts.
if (cur && wax.util.indexOf('.', fn_name) === -1) {
return fn_obj[1].apply(cur, fn_args);
} else {
return fn_obj[1].apply(fn_obj[0], fn_args);
}
};
var isKeyword = function(string) {
return wax.util.isString(string) && (wax.util.indexOf([
'@new',
'@call',
'@literal',
'@chain',
'@inject',
'@group'
], string.split(' ')[0]) !== -1);
};
var altersContext = function(string) {
return wax.util.isString(string) && (wax.util.indexOf([
'@new',
'@call',
'@chain'
], string.split(' ')[0]) !== -1);
};
var getStatement = function(obj) {
if (wax.util.isArray(obj) && obj[0] && isKeyword(obj[0])) {
return {
verb: obj[0].split(' ')[0],
subject: obj[0].split(' ')[1],
object: obj.slice(1)
};
}
return false;
};
var i,
fn = false,
ret = null,
child = null,
statement = getStatement(obj);
if (statement) {
switch (statement.verb) {
case '@group':
for (i = 0; i < statement.object.length; i++) {
ret = wax.Record(statement.object[i], context);
child = getStatement(statement.object[i]);
if (child && altersContext(child.verb)) {
context = ret;
}
}
return context;
case '@new':
return makeObject(statement.subject, statement.object);
case '@literal':
fn = getFunction(statement.subject);
return fn ? fn[1] : null;
case '@inject':
return runFunction(statement.subject, statement.object, context);
case '@chain':
return runFunction(statement.subject, statement.object, context);
case '@call':
return runFunction(statement.subject, statement.object, null);
}
} else if (obj !== null && typeof obj === 'object') {
var keys = wax.util.keys(obj);
for (i = 0; i < keys.length; i++) {
var key = keys[i];
obj[key] = wax.Record(obj[key], context);
}
return obj;
} else {
return obj;
}
};
// Wax GridUtil
// ------------
// Wax header
var wax = wax || {};
wax.util = {
// From Bonzo
offset: function(el) {
var width = el.offsetWidth;
var height = el.offsetHeight;
var top = el.offsetTop;
var left = el.offsetLeft;
while (el = el.offsetParent) {
top += el.offsetTop;
left += el.offsetLeft;
}
return {
top: top,
left: left,
height: height,
width: width
};
},
// From underscore, minus funcbind for now.
bind: function(func, obj) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(Array.prototype.slice.call(arguments)));
};
}
};
// Request
// -------
// Request data cache. `callback(data)` where `data` is the response data.
wax.request = {
cache: {},
locks: {},
promises: {},
get: function(url, callback) {
// Cache hit.
if (this.cache[url]) {
return callback(this.cache[url]);
// Cache miss.
} else {
this.promises[url] = this.promises[url] || [];
this.promises[url].push(callback);
// Lock hit.
if (this.locks[url]) return;
// Request.
var that = this;
this.locks[url] = true;
reqwest({
url: url + '?callback=grid',
type: 'jsonp',
jsonpCallback: 'callback',
success: function(data) {
that.locks[url] = false;
that.cache[url] = data;
for (var i = 0; i < that.promises[url].length; i++) {
that.promises[url][i](that.cache[url]);
}
},
error: function() {
that.locks[url] = false;
that.cache[url] = null;
for (var i = 0; i < that.promises[url].length; i++) {
that.promises[url][i](that.cache[url]);
}
}
});
}
}
};
// GridInstance
// ------------
// GridInstances are queryable, fully-formed
// objects for acquiring features from events.
wax.GridInstance = function(grid_tile, formatter) {
this.grid_tile = grid_tile;
this.formatter = formatter;
this.tileRes = 4;
};
// Resolve the UTF-8 encoding stored in grids to simple
// number values.
// See the [utfgrid section of the mbtiles spec](https://github.com/mapbox/mbtiles-spec/blob/master/1.1/utfgrid.md)
// for details.
wax.GridInstance.prototype.resolveCode = function(key) {
if (key >= 93) key--;
if (key >= 35) key--;
key -= 32;
return key;
};
wax.GridInstance.prototype.getFeature = function(x, y, tile_element, options) {
if (!(this.grid_tile && this.grid_tile.grid)) return;
// IE problem here - though recoverable, for whatever reason
var offset = wax.util.offset(tile_element);
var tileX = offset.left;
var tileY = offset.top;
if (Math.floor((y - tileY) / this.tileRes) > 256 ||
Math.floor((x - tileX) / this.tileRes) > 256) return;
var key = this.grid_tile.grid[
Math.floor((y - tileY) / this.tileRes)
].charCodeAt(
Math.floor((x - tileX) / this.tileRes)
);
key = this.resolveCode(key);
// If this layers formatter hasn't been loaded yet,
// download and load it now.
if (this.grid_tile.keys[key]) {
return this.formatter.format(
options,
this.grid_tile.data[this.grid_tile.keys[key]]
);
}
};
// GridManager
// -----------
// Generally one GridManager will be used per map.
wax.GridManager = function() {
this.grid_tiles = {};
this.key_maps = {};
this.formatters = {};
this.locks = {};
};
// Get a grid - calls `callback` with either a `GridInstance`
// object or false. Behind the scenes, this calls `getFormatter`
// and gets grid data, and tries to avoid re-downloading either.
wax.GridManager.prototype.getGrid = function(url, callback) {
var that = this;
that.getFormatter(that.formatterUrl(url), function(f) {
if (!f) return callback(false);
wax.request.get(that.tileDataUrl(url), function(t) {
callback(new wax.GridInstance(t, f));
});
});
};
// Create a cross-browser event object
wax.GridManager.prototype.makeEvent = function(evt) {
return {
target: evt.target || evt.srcElement,
pX: evt.pageX || evt.clientX,
pY: evt.pageY || evt.clientY,
evt: evt
};
};
// Simplistically derive the URL of the grid data endpoint from a tile URL
wax.GridManager.prototype.tileDataUrl = function(url) {
return url.replace(/(\.png|\.jpg|\.jpeg)(\d*)/, '.grid.json');
};
// Simplistically derive the URL of the formatter function from a tile URL
wax.GridManager.prototype.formatterUrl = function(url) {
return url.replace(/\d+\/\d+\/\d+\.\w+/, 'layer.json');
};
// Request and save a formatter, passed to `callback()` when finished.
wax.GridManager.prototype.getFormatter = function(url, callback) {
var that = this;
// Formatter is cached.
if (typeof this.formatters[url] !== 'undefined') {
callback(this.formatters[url]);
return;
} else {
wax.request.get(url, function(data) {
if (data && data.formatter) {
that.formatters[url] = new wax.Formatter(data);
} else {
that.formatters[url] = false;
}
callback(that.formatters[url]);
});
}
};
// Formatter
// ---------
wax.Formatter = function(obj) {
// Prevent against just any input being used.
if (obj.formatter && typeof obj.formatter === 'string') {
try {
// Ugly, dangerous use of eval.
eval('this.f = ' + obj.formatter);
} catch (e) {
// Syntax errors in formatter
if (console) console.log(e);
}
} else {
this.f = function() {};
}
};
// Wrap the given formatter function in order to
// catch exceptions that it may throw.
wax.Formatter.prototype.format = function(options, data) {
try {
return this.f(options, data);
} catch (e) {
if (console) console.log(e);
}
};
// Wax Legend
// ----------
// Wax header
var wax = wax || {};
wax.Legend = function(context, container) {
this.context = context;
this.container = container || $('<div class="wax-legends"></div>')[0];
this.legends = {};
$(this.context).append(this.container);
};
wax.Legend.prototype.render = function(urls) {
$('.wax-legend', this.container).hide();
var render = wax.util.bind(function(url, content) {
if (!content) {
this.legends[url] = false;
} else if (this.legends[url]) {
this.legends[url].show();
} else {
this.legends[url] = $("<div class='wax-legend'></div>").append(content);
this.container.append(this.legends[url]);
}
}, this);
var renderLegend = function(data) {
if (data && data.legend) render(url, data.legend);
};
for (var i = 0; i < urls.length; i++) {
var url = this.legendUrl(urls[i]);
wax.request.get(url, renderLegend);
}
};
wax.Legend.prototype.legendUrl = function(url) {
return url.replace(/\d+\/\d+\/\d+\.\w+/, 'layer.json');
};
// TODO: rewrite without underscore
var w = function(self) {
self.melt = function(func, obj) {
func.apply(obj, [self, obj]);
return self;
};
return self;
};
// Requires: jQuery
//
// Wax GridUtil
// ------------
// Wax header
var wax = wax || {};
wax.tooltip = {};
// Get the active tooltip for a layer or create a new one if no tooltip exists.
// Hide any tooltips on layers underneath this one.
wax.tooltip.getToolTip = function(feature, context, index, evt) {
// var tooltip = $(context).children('div.wax-tooltip-' +
// index +
// ':not(.removed)');
// if (tooltip.size() === 0) {
tooltip = document.createElement('div');
tooltip.className = 'wax-tooltip wax-tooltip-' + index;
tooltip.innerHTML = feature;
// if (!$(context).triggerHandler('addedtooltip', [tooltip, context, evt])) {
context.appendChild(tooltip);
// }
// }
// for (var i = (index - 1); i > 0; i--) {
// var fallback = $('div.wax-tooltip-' + i + ':not(.removed)');
// if (fallback.size() > 0) {
// fallback.addClass('hidden').hide();
// }
// }
return tooltip;
};
// Expand a tooltip to be a "popup". Suspends all other tooltips from being
// shown until this popup is closed or another popup is opened.
wax.tooltip.click = function(feature, context, index) {
var tooltip = wax.tooltip.getToolTip(feature, context, index);
var close = document.createElement('a');
close.href = '#close';
close.className = 'close';
close.innerHTML = 'Close';
close.addListener('click', function() {
tooltip.parentNode.removeChild(tooltip);
return false;
});
tooltip.className += ' wax-popup';
tooltip.innerHTML = feature;
tooltip.appendChild(close);
};
// Show a tooltip.
wax.tooltip.select = function(feature, context, layer_id, evt) {
if (!feature) return;
wax.tooltip.getToolTip(feature, context, layer_id, evt);
context.style.cursor = 'pointer';
};
// Hide all tooltips on this layer and show the first hidden tooltip on the
// highest layer underneath if found.
wax.tooltip.unselect = function(feature, context, layer_id, evt) {
context.style.cursor = 'default';
/*
if (layer_id) {
$('div.wax-tooltip-' + layer_id + ':not(.wax-popup)')
.remove();
} else {
$('div.wax-tooltip:not(.wax-popup)')
.remove();
}
*/
// TODO: remove
// $('div.wax-tooltip:first')
// .removeClass('hidden')
// .show();
// $(context).triggerHandler('removedtooltip', [feature, context, evt]);
};
// Wax: Box Selector
// -----------------
wax = wax || {};
wax.boxselector = function(map, opts) {
var mouseDownPoint = null;
var callback = (typeof opts === 'function') ?
opts :
opts.callback;
var boxselector = {
add: function(map) {
this.containerDiv = document.createElement('div');
this.containerDiv.id = map.parent.id + '-zoombox';
this.containerDiv.className = 'boxselector-box-container';
this.containerDiv.style.width = map.dimensions.x + 'px';
this.containerDiv.style.height = map.dimensions.y + 'px';
this.boxDiv = document.createElement('div');
this.boxDiv.id = map.parent.id + '-boxselector-box';
this.boxDiv.className = 'boxselector-box';
this.containerDiv.appendChild(this.boxDiv);
map.parent.appendChild(this.containerDiv);
com.modestmaps.addEvent(this.containerDiv, 'mousedown', this.mouseDown());
map.addCallback('drawn', this.drawbox());
},
remove: function() {
this.containerDiv.parentNode.removeChild(this.containerDiv);
map.removeCallback('mousedown', this.drawbox());
},
getMousePoint: function(e) {
// start with just the mouse (x, y)
var point = new com.modestmaps.Point(e.clientX, e.clientY);
// correct for scrolled document
point.x += document.body.scrollLeft + document.documentElement.scrollLeft;
point.y += document.body.scrollTop + document.documentElement.scrollTop;
// correct for nested offsets in DOM
for (var node = map.parent; node; node = node.offsetParent) {
point.x -= node.offsetLeft;
point.y -= node.offsetTop;
}
return point;
},
mouseDown: function() {
return this._mouseDown = this._mouseDown || wax.util.bind(function(e) {
if (e.shiftKey) {
mouseDownPoint = this.getMousePoint(e);
this.boxDiv.style.left = mouseDownPoint.x + 'px';
this.boxDiv.style.top = mouseDownPoint.y + 'px';
com.modestmaps.addEvent(map.parent, 'mousemove', this.mouseMove());
com.modestmaps.addEvent(map.parent, 'mouseup', this.mouseUp());
map.parent.style.cursor = 'crosshair';
return com.modestmaps.cancelEvent(e);
}
}, this);
},
mouseMove: function(e) {
return this._mouseMove = this._mouseMove || wax.util.bind(function(e) {
var point = this.getMousePoint(e);
this.boxDiv.style.display = 'block';
if (point.x < mouseDownPoint.x) {
this.boxDiv.style.left = point.x + 'px';
} else {
this.boxDiv.style.left = mouseDownPoint.x + 'px';
}
this.boxDiv.style.width = Math.abs(point.x - mouseDownPoint.x) + 'px';
if (point.y < mouseDownPoint.y) {
this.boxDiv.style.top = point.y + 'px';
} else {
this.boxDiv.style.top = mouseDownPoint.y + 'px';
}
this.boxDiv.style.height = Math.abs(point.y - mouseDownPoint.y) + 'px';
return com.modestmaps.cancelEvent(e);
}, this);
},
mouseUp: function() {
return this._mouseUp = this._mouseUp || wax.util.bind(function(e) {
var point = boxselector.getMousePoint(e);
var l1 = map.pointLocation(point),
l2 = map.pointLocation(mouseDownPoint);
// Format coordinates like mm.map.getExtent().
var extent = [
new com.modestmaps.Location(
Math.max(l1.lat, l2.lat),
Math.min(l1.lon, l2.lon)),
new com.modestmaps.Location(
Math.min(l1.lat, l2.lat),
Math.max(l1.lon, l2.lon))
];
this.box = [l1, l2];
callback(extent);
com.modestmaps.removeEvent(map.parent, 'mousemove', this.mouseMove());
com.modestmaps.removeEvent(map.parent, 'mouseup', this.mouseUp());
map.parent.style.cursor = 'auto';
return com.modestmaps.cancelEvent(e);
}, this);
},
drawbox: function() {
return this._drawbox = this._drawbox || wax.util.bind(function(map, e) {
if (this.boxDiv) {
this.boxDiv.style.display = 'block';
this.boxDiv.style.height = 'auto';
this.boxDiv.style.width = 'auto';
var br = map.locationPoint(this.box[0]);
var tl = map.locationPoint(this.box[1]);
this.boxDiv.style.left = Math.max(0, tl.x) + 'px';
this.boxDiv.style.top = Math.max(0, tl.y) + 'px';
this.boxDiv.style.right = Math.max(0, map.dimensions.x - br.x) + 'px';
this.boxDiv.style.bottom = Math.max(0, map.dimensions.y - br.y) + 'px';
}
}, this);
}
};
return boxselector.add(map);
};
// Wax: Embedder Control
// -------------------
// namespacing!
if (!com) {
var com = { };
if (!com.modestmaps) {
com.modestmaps = { };
}
}
com.modestmaps.Map.prototype.embedder = function(options) {
options = options || {};
if ($('#' + this.el + '-script').length) {
$(this.parent).prepend($('<input type="text" class="embed-src" />')
.css({
'z-index': '9999999999',
'position': 'relative'
})
.val("<div id='" + this.el + "-script'>" + $('#' + this.el + '-script').html() + '</div>'));
}
return this;
};
// Wax: Fullscreen
// -----------------
// A simple fullscreen control for Modest Maps
wax = wax || {};
// Add zoom links, which can be styled as buttons, to a `modestmaps.Map`
// control. This function can be used chaining-style with other
// chaining-style controls.
wax.fullscreen = function(map, opts) {
var fullscreen = {
state: 1, // minimized
// Modest Maps demands an absolute height & width, and doesn't auto-correct
// for changes, so here we save the original size of the element and
// restore to that size on exit from fullscreen.
add: function(map) {
this.a = document.createElement('a');
this.a.className = 'wax-fullscreen';
this.a.href = '#fullscreen';
this.a.innerHTML = 'fullscreen';
map.parent.appendChild(this.a);
com.modestmaps.addEvent(this.a, 'click', this.click(map));
return this;
},
click: function(map) {
return this._click = this._click || wax.util.bind(function(e) {
if (e) e.preventDefault();
if (this.state) {
this.smallSize = [map.parent.offsetWidth, map.parent.offsetHeight];
map.parent.className += ' wax-fullscreen-map';
map.setSize(
map.parent.offsetWidth,
map.parent.offsetHeight);
} else {
map.parent.className = map.parent.className.replace('wax-fullscreen-map', '');
map.setSize(
this.smallSize[0],
this.smallSize[1]);
}
this.state = !this.state;
}, this);
}
};
return fullscreen.add(map);
};
// Wax: Hash
wax = wax || {};
// Ripped from underscore.js
// Internal function used to implement `_.throttle` and `_.debounce`.
var limit = function(func, wait, debounce) {
var timeout;
return function() {
var context = this, args = arguments;
var throttler = function() {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
var throttle = function(func, wait) {
return limit(func, wait, false);
};
// A basic manager dealing only in hashchange and `location.hash`.
// This **will interfere** with anchors, so a HTML5 pushState
// implementation will be prefered.
var locationHash = {
stateChange: function(callback) {
com.modestmaps.addEvent(window, 'hashchange', function() {
callback(location.hash);
}, false);
},
getState: function() {
return location.hash;
},
pushState: function(state) {
location.hash = state;
}
};
wax.hash = function(map, options) {
var s0, // cached location.hash
lat = 90 - 1e-8, // allowable latitude range
map;
var hash = {
map: this,
parser: function(s) {
var args = s.split('/').map(Number);
if (args.length < 3 || args.some(isNaN)) {
return true; // replace bogus hash
} else if (args.length == 3) {
map.setCenterZoom(new com.modestmaps.Location(args[1], args[2]), args[0]);
}
},
add: function(map) {
options.manager.getState() ?
hash.stateChange(options.manager.getState()) :
hash.initialize() && hash.move();
map.addCallback('drawn', throttle(hash.move, 500));
options.manager.stateChange(hash.stateChange);
},
formatter: function() {
var center = map.getCenter(),
zoom = map.getZoom(),
precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
return '#' + [zoom.toFixed(2),
center.lat.toFixed(precision),
center.lon.toFixed(precision)].join('/');
},
move: function() {
var s1 = hash.formatter();
if (s0 !== s1) {
s0 = s1;
options.manager.pushState(s0); // don't recenter the map!
}
},
stateChange: function(state) {
if (state === s0) return; // ignore spurious hashchange events
if (hash.parser((s0 = state).substring(1))) {
hash.move(); // replace bogus hash
}
},
// If a state isn't present when you initially load the map, the map should
// still get a center and zoom level.
initialize: function() {
if (options.defaultCenter) map.setCenter(options.defaultCenter);
if (options.defaultZoom) map.setZoom(options.defaultZoom);
}
};
return hash.add(map);
};
wax = wax || {};
// A chaining-style control that adds
// interaction to a modestmaps.Map object.
//
// Takes an options object with the following keys:
//
// * `callbacks` (optional): an `out`, `over`, and `click` callback.
// If not given, the `wax.tooltip` library will be expected.
// * `clickAction` (optional): **full** or **location**: default is
// **full**.
wax.interaction = function(map, options) {
var MM = com.modestmaps;
options = options || {};
// Our GridManager (from `gridutil.js`). This will keep the
// cache of grid information and provide friendly utility methods
// that return `GridTile` objects instead of raw data.
var interaction = {
modifyingEvents: ['zoomed', 'panned', 'centered',
'extentset', 'resized', 'drawn'],
waxGM: new wax.GridManager(),
// This requires wax.Tooltip or similar
callbacks: options.callbacks || {
out: wax.tooltip.unselect,
over: wax.tooltip.select,
click: wax.tooltip.click
},
clickAction: options.clickAction || 'full',
add: function() {
for (var i = 0; i < this.modifyingEvents.length; i++) {
map.addCallback(this.modifyingEvents[i], this.clearMap);
}
MM.addEvent(map.parent, 'mousemove', this.onMove());
MM.addEvent(map.parent, 'mousedown', this.mouseDown());
return this;
},
// Search through `.tiles` and determine the position,
// from the top-left of the **document**, and cache that data
// so that `mousemove` events don't always recalculate.
getTileGrid: function() {
// TODO: don't build for tiles outside of viewport
var zoom = map.getZoom();
// Calculate a tile grid and cache it, by using the `.tiles`
// element on this map.
return this._getTileGrid || (this._getTileGrid =
(function(t) {
var o = [];
for (var key in t) {
if (key.split(',')[0] == zoom) {
var offset = wax.util.offset(t[key]);
o.push([offset.top, offset.left, t[key]]);
}
}
return o;
})(map.tiles));
},
clearTileGrid: function(map, e) {
this._waxGetTileGrid = null;
},
getTile: function(evt) {
var tile;
var grid = this.getTileGrid();
for (var i = 0; i < grid.length; i++) {
if ((grid[i][0] < evt.pageY) &&
((grid[i][0] + 256) > evt.pageY) &&
(grid[i][1] < evt.pageX) &&
((grid[i][1] + 256) > evt.pageX)) {
tile = grid[i][2];
break;
}
}
return tile || false;
},
clearTimeout: function() {
if (this.clickTimeout) {
window.clearTimeout(this.clickTimeout);
this.clickTimeout = null;
return true;
} else {
return false;
}
},
onMove: function(evt) {
return this._onMove = this._onMove || wax.util.bind(function(evt) {
var tile = this.getTile(evt);
if (tile) {
this.waxGM.getGrid(tile.src, wax.util.bind(function(g) {
if (g) {
var feature = g.getFeature(evt.pageX, evt.pageY, tile, {
format: 'teaser'
});
// This and other Modest Maps controls only support a single layer.
// Thus a layer index of **0** is given to the tooltip library
if (feature) {
if (feature && this.feature !== feature) {
this.feature = feature;
this.callbacks.out(feature, map.parent, 0, evt);
this.callbacks.over(feature, map.parent, 0, evt);
} else if (!feature) {
this.feature = null;
this.callbacks.out(feature, map.parent, 0, evt);
}
} else {
this.feature = null;
this.callbacks.out({}, map.parent, 0, evt);
}
}
}, this));
}
}, this);
},
mouseDown: function(evt) {
return this._mouseDown = this._mouseDown || wax.util.bind(function(evt) {
// Ignore double-clicks by ignoring clicks within 300ms of
// each other.
if (this.clearTimeout()) {
return;