forked from jpatokal/openflights
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openflights.js
3350 lines (3050 loc) · 107 KB
/
openflights.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
/**
* openflights.js -- for openflights.org
* by Jani Patokallio <jani at contentshare dot sg>
*/
// Core map features
var map, proj, drawControls, selectControl, selectedFeature, lineLayer, currentPopup;
var paneStack = [ "ad" ];
// User settings (defaults)
var privacy = "Y", flightTotal = 0, prefs_editor = "B", elite = "";
// Filter selections and currently chosen airport
var filter_user = 0, filter_trid = 0, filter_alid = 0, filter_year = 0, apid = 0;
var tripname, tripurl;
// Current list of flights
var fidList, fidPtr = 0, fid = 0;
// Query and description of current list
var lastQuery, lastDesc;
// Temporary variables for current flight being edited
var alid = 0, plane;
var logged_in = false, demo_mode = true, initializing = true;
var input_srcmarker, input_dstmarker, input_line, input_toggle, input_al_toggle;
var changed = false, majorEdit = false;
// Some helpers for multiinput handling
var multiinput_order = [ "src_ap1", "dst_ap1", "dst_ap2", "dst_ap3", "dst_ap4" ];
var multiinput_ids = [ "src_ap1id", "src_ap2id", "src_ap3id", "src_ap4id",
"dst_ap1id", "dst_ap2id", "dst_ap3id", "dst_ap4id",
"airline1id", "airline2id", "airline3id", "airline4id" ];
var multiinput_rows = 1;
var URL_FLIGHTS = "/php/flights.php";
var URL_GETCODE = "/php/autocomplete.php";
var URL_LOGIN = "/php/login.php";
var URL_LOGOUT = "/php/logout.php";
var URL_MAP = "/php/map.php";
var URL_ROUTES = "/php/routes.php";
var URL_STATS = "/php/stats.php";
var URL_SUBMIT = "/php/submit.php";
var URL_TOP10 = "/php/top10.php";
var CODE_FAIL = 0;
var CODE_ADDOK = 1;
var CODE_EDITOK = 2;
var CODE_DELETEOK = 100;
var INPUT_MAXLEN = 50;
var SELECT_MAXLEN = 25;
var COLOR_NORMAL = "#ee9900"; //orange
var COLOR_ROUTE = "#99ee00"; //yellow
var COLOR_TRAIN = "#ee5555"; //dull red
var COLOR_ROAD = "#9f6500"; //brown
var COLOR_SHIP = "#00ccff"; //cyany blue
var COLOR_HIGHLIGHT = "#007fff"; //deeper blue
var airportMaxFlights = 0;
var airportIcons = [ [ '/img/icon_plane-13x13.png', 13 ],
[ '/img/icon_plane-15x15.png', 15 ],
[ '/img/icon_plane-17x17.png', 17 ],
[ '/img/icon_plane-19x19b.png', 19 ],
[ '/img/icon_plane-19x19b.png', 19 ],
[ '/img/icon_plane-19x19.png', 19 ] ];
// Redefined with localized strings under init
var classes, seattypes, reasons, classes_short, reasons_short, modenames, modesegments, modeoperators, topmodes;
var modecolors = { "F":COLOR_NORMAL, "T":COLOR_TRAIN, "R":COLOR_ROAD, "S":COLOR_SHIP };
var modeicons = { "F":'/img/icon_airline.png', "T": '/img/icon_train.png',
"R": '/img/icon_car.png', "S": '/img/icon_ship.png' };
var modespeeds = { "F":500, "T":100, "R":60, "S":40 };
var toplimits = { "10":"Top 10", "20":"Top 20", "50":"Top 50", "-1":"All" };
// Validate YYYY*MM*DD date; contains groups, leading zeroes not required for month, date)
var re_date = /^((19|20)\d\d)[- /.]?([1-9]|0[1-9]|1[012])[- /.]?([1-9]|0[1-9]|[12][0-9]|3[01])$/;
// Validate numeric value
var re_numeric = /^[0-9]*$/;
// avoid pink tiles
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadErrorColor = "transparent";
// Init Google Charts
google.load('visualization', '1', {packages: ['corechart']});
// Call init after google is done initing.
google.setOnLoadCallback(init);
function init(){
$("helplink").style.display = 'inline';
gt = new Gettext({ 'domain' : 'messages' });
classes = {"Y": gt.gettext("Economy"), "P": gt.gettext("Prem.Eco"), "C":gt.gettext("Business"), "F":gt.gettext("First"), "": ""};
seattypes = {"W":gt.gettext("Window"), "A":gt.gettext("Aisle"), "M":gt.gettext("Middle"), "": ""};
reasons = {"B":gt.gettext("Work"), "L":gt.gettext("Leisure"), "C":gt.gettext("Crew"), "O": gt.gettext("Other"), "": ""};
classes_short = {"Y":gt.gettext("Econ"), "P":gt.gettext("P.Eco"), "C":gt.gettext("Biz"), "F":gt.gettext("1st"), "": ""};
reasons_short = {"B":gt.gettext("Work"), "L":gt.gettext("Leis."), "C":gt.gettext("Crew"), "O":gt.gettext("Other"), "": ""};
modenames = { "F":gt.gettext("Flight"), "T":gt.gettext("Train"), "R":gt.gettext("Road"), "S":gt.gettext("Ship") };
modesegments = { "F":gt.gettext("flight"), "T":gt.gettext("train"), "R":gt.gettext("road trip"), "S":gt.gettext("ship") };
modeoperators = { "F":gt.gettext("airline"), "T":gt.gettext("railway"), "R":gt.gettext("road transport"), "S":gt.gettext("shipping") };
topmodes = { "F":gt.gettext("Segments"), "D":gt.gettext("Mileage") };
var projectionName = "EPSG:4326"; // spherical Mercator
proj = new OpenLayers.Projection(projectionName);
map = new OpenLayers.Map('map', {
center: new OpenLayers.LonLat(0, 1682837.6144925),
controls: [
new OpenLayers.Control.PanZoom(),
new OpenLayers.Control.Navigation({'title': gt.gettext("Toggle pan and region select mode")}),
new OpenLayers.Control.LayerSwitcher({'ascending':false, 'title': gt.gettext('Switch map layers')}),
new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.OverviewMap({'title': gt.gettext("Toggle overview map")})
] });
// Horrible hack to stop OpenLayers 2 from showing ZL < 2
map.events.register('zoomend', this, function (event) {
if(map.getZoom() < 2) { map.zoomTo(2); }
});
var poliLayer = new OpenLayers.Layer.XYZ(
"Political",
[
"http://a.basemaps.cartocdn.com/light_nolabels/${z}/${x}/${y}.png",
"http://b.basemaps.cartocdn.com/light_nolabels/${z}/${x}/${y}.png",
"http://c.basemaps.cartocdn.com/light_nolabels/${z}/${x}/${y}.png",
"http://d.basemaps.cartocdn.com/light_nolabels/${z}/${x}/${y}.png"
], {
attribution: "Map tiles by <a href='http://cartodb.com'>CartoDB</a> (CC BY 3.0), data by <a href='/http://openstreetmap.com'>OSM</a> (ODbL)",
sphericalMercator: true,
transitionEffect: 'resize',
wrapDateLine: true
});
var artLayer = new OpenLayers.Layer.XYZ(
"Artistic",
[
"http://c.tile.stamen.com/watercolor/${z}/${x}/${y}.png"
], {
attribution: "Tiles © <a href='http://maps.stamen.com/'>Stamen</a>",
sphericalMercator: true,
transitionEffect: 'resize',
wrapDateLine: true
});
artLayer.setVisibility(false);
var earthLayer = new OpenLayers.Layer.XYZ(
"Satellite",
[
"http://otile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png",
"http://otile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png",
"http://otile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png",
"http://otile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png"
], {
attribution: "Tiles by <a href='http://open.mapquest.co.uk/' target='_blank'>MapQuest</a>",
sphericalMercator: true,
transitionEffect: 'resize',
wrapDateLine: true
});
earthLayer.setVisibility(false);
lineLayer = new OpenLayers.Layer.Vector(gt.gettext("Flights"),
{ projection: projectionName,
styleMap: new OpenLayers.StyleMap({
strokeColor: "${color}",
strokeOpacity: 1,
strokeWidth: "${count}",
strokeDashstyle: "${stroke}"
})
});
var style = new OpenLayers.Style({graphicTitle: "${name}",
externalGraphic: "${icon}",
graphicWidth: "${size}",
graphicHeight: "${size}",
graphicXOffset: "${offset}",
graphicYOffset: "${offset}",
graphicOpacity: "${opacity}",
pointerEvents: "visiblePainted",
label : "\xA0${code}",
fontColor: "#000000",
fontSize: "9px",
fontFamily: "Calibri, Verdana, Arial, sans-serif",
labelAlign: "lt",
fillColor: "black"
}, { context: {
name: function(feature) {
if(feature.cluster) {
// Last airport is always the largest
last = feature.cluster.length - 1;
if(feature.cluster[last].attributes.index > 2) {
// One airport is dominant, copy its attributes into cluster
feature.attributes.apid = feature.cluster[last].attributes.apid;
feature.attributes.coreid = feature.cluster[last].attributes.coreid;
feature.attributes.code = feature.cluster[last].attributes.code + "+";
feature.attributes.desc = feature.cluster[last].attributes.desc;
feature.attributes.rdesc = feature.cluster[last].attributes.rdesc;
feature.attributes.icon = feature.cluster[last].attributes.icon;
feature.attributes.size = feature.cluster[last].attributes.size;
feature.attributes.offset = feature.cluster[last].attributes.offset;
feature.attributes.name = feature.cluster[last].attributes.name + " \u2295";
} else {
// No dominant airport, show cluster icon with aggregate info
name = "";
for(c = last; c >= 0; c--) {
if(c < last) name += ", ";
name += feature.cluster[c].attributes.code;
}
feature.attributes.icon = "/img/icon_cluster.png";
feature.attributes.code = "";
feature.attributes.size = clusterRadius(feature);
feature.attributes.offset = -clusterRadius(feature) / 2;
feature.attributes.name = name;
}
}
return feature.attributes.name;
},
icon: function(feature) { return feature.attributes.icon; },
size: function(feature) { return feature.attributes.size; },
offset: function(feature) { return feature.attributes.offset; },
opacity: function(feature) {
return feature.cluster ? 1 : feature.attributes.opacity;
},
code: function(feature) { return feature.attributes.code; }
}});
var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
var strategy = new OpenLayers.Strategy.Cluster({distance: 15, threshold: 3});
airportLayer = new OpenLayers.Layer.Vector("Airports",
{ projection: projectionName,
styleMap: new OpenLayers.StyleMap
({'default': style,
'select':{
fillOpacity: 1.0,
pointerEvents: "visiblePainted",
label : ""
}}),
renderers: renderer,
strategies: [strategy]});
map.addLayers([poliLayer, artLayer, earthLayer, lineLayer, airportLayer]);
selectControl = new OpenLayers.Control.SelectFeature(airportLayer, {onSelect: onAirportSelect,
onUnselect: onAirportUnselect});
map.addControl(selectControl);
selectControl.activate();
// When using the earth map layer, change the font color from black to white, since the map is mostly dark colors.
map.events.on({
"changelayer":function () {
if(earthLayer.visibility) {
style.defaultStyle.fontColor = "#fff";
} else {
style.defaultStyle.fontColor = "#000";
}
}
});
// Extract any arguments from URL
var query;
arguments = parseUrl();
switch(arguments[0]) {
case "trip":
filter_trid = arguments[1];
break;
case "user":
filter_user = arguments[1];
break;
case "query":
case "airport":
case "airline":
query = arguments[1];
}
initHintTextboxes();
new Ajax.Autocompleter("qs", "qsAC", "/php/autocomplete.php",
{afterUpdateElement : getQuickSearchId,
indicator: ajaxstatus, minChars: 2});
// Are we viewing another user's flights or trip?
if(filter_user != "0" || filter_trid != 0) {
demo_mode = false;
$("loginstatus").style.display = 'inline';
if(filter_trid != 0) {
$("filter_tripselect").style.display = 'none';
}
} else {
$("news").style.display = 'inline';
$("quicksearch").style.display = 'inline';
// Nope, set up hinting and autocompletes for editor
ac_airport = [ "src_ap", "src_ap1", "src_ap2", "src_ap3", "src_ap4",
"dst_ap", "dst_ap1", "dst_ap2", "dst_ap3", "dst_ap4" ];
ac_airline = [ "airline", "airline1", "airline2", "airline3", "airline4" ];
ac_plane = [ "plane" ];
for(ac = 0; ac < ac_airport.length; ac++) {
new Ajax.Autocompleter(ac_airport[ac], ac_airport[ac] + "AC", "php/autocomplete.php",
{afterUpdateElement : getSelectedApid});
}
for(ac = 0; ac < ac_airline.length; ac++) {
new Ajax.Autocompleter(ac_airline[ac], ac_airline[ac] + "AC", "php/autocomplete.php",
{afterUpdateElement : getSelectedAlid});
}
for(ac = 0; ac < ac_plane.length; ac++) {
new Ajax.Autocompleter(ac_plane[ac], ac_plane[ac] + "AC", "php/autocomplete.php",
{afterUpdateElement : getSelectedPlid});
}
// No idea why this is needed, but FF3 disables random buttons without it...
for(i=0;i<document.forms['inputform'].elements.length;i++){
document.forms['inputform'].elements[i].disabled=false;
}
for(i=0;i<document.forms['multiinputform'].elements.length;i++){
document.forms['multiinputform'].elements[i].disabled=false;
}
$('b_less').disabled = true;
map.zoomTo(2);
}
OpenLayers.Util.alphaHack = function() { return false; };
if(query) {
xmlhttpPost(URL_ROUTES, 0, query);
} else {
xmlhttpPost(URL_MAP, 0, true);
}
}
function clusterRadius(feature) {
var radius = feature.attributes.count * 5;
if(radius > 29) radius = 29;
return radius;
}
// Extract arguments from URL (/command/value, eg. /trip/123 or /user/foo)
function parseUrl()
{
// http://foobar.com/name/xxx#blah *or* xxx?blah=blah
// 0 1 2 3 4 3 4
var urlbits = window.location.href.split(/[\/#?]+/);
if(urlbits.length > 3) {
return [urlbits[2], unescape(urlbits[3])];
} else return [null,null];
}
function projectedPoint(x, y) {
var point = new OpenLayers.Geometry.Point(x, y);
point.transform(proj, map.getProjectionObject());
return point;
}
function projectedLine(points) {
var line = new OpenLayers.Geometry.LineString(points);
line.transform(proj, map.getProjectionObject());
return line;
}
// Draw a flight connecting (x1,y1)-(x2,y2)
// Note: Values passed in *must already be parsed as floats* or very strange things happen
function drawLine(x1, y1, x2, y2, count, distance, color, stroke) {
if(! color) {
color = COLOR_NORMAL;
}
if(! stroke) {
stroke = "solid";
}
// 1,2 flights as single pixel
count = Math.floor(Math.sqrt(count) + 0.5);
var paths = [ gcPath(new OpenLayers.Geometry.Point(x1, y1), new OpenLayers.Geometry.Point(x2, y2)) ];
// Path is in or extends into east (+) half, so we have to make a -360 copy
if(x1 > 0 || x2 > 0) {
paths.push(gcPath(new OpenLayers.Geometry.Point(x1-360, y1), new OpenLayers.Geometry.Point(x2-360, y2)));
}
// Path is in or extends into west (-) half, so we have to make a +360 copy
if(x1 < 0 || x2 < 0) {
paths.push(gcPath(new OpenLayers.Geometry.Point(x1+360, y1), new OpenLayers.Geometry.Point(x2+360, y2)));
}
var features = [];
for(i = 0; i < paths.length; i++) {
features.push(new OpenLayers.Feature.Vector(projectedLine(paths[i]),
{count: count, color: color, stroke: stroke}));
}
return features;
}
//
// Draw airport (or just update marker if it exists already)
// Returns true if a new marker was created, or false if it existed already
//
// coreid -- apid of "core" airport at the center of a map of routes
//
function drawAirport(airportLayer, apdata, name, city, country, count, formattedName, opacity, coreid) {
var apcols = apdata.split(":");
var code = apcols[0];
var apid = apcols[1];
var x = apcols[2];
var y = apcols[3];
// Description
var desc = name + " (<B>" + code + "</B>)<br><small>" + city + ", " + country + "</small><br>Flights: " + count;
var rdesc = name + " (<B>" + code + "</B>)<br><small>" + city + ", " + country + "</small>";
// Select icon based on number of flights (0...airportIcons.length-1)
var colorIndex = Math.floor((count / airportMaxFlights) * airportIcons.length) + 1;
// Two or less flights: smallest dot
if(count <= 2 || colorIndex < 0) {
colorIndex = 0;
}
// More than two flights: at least 2nd smallest
if(count > 2) {
colorIndex = Math.max(1, colorIndex);
}
// Max out at top color
// Core airport of route map always uses max color
if(colorIndex >= airportIcons.length || apid == coreid) {
colorIndex = airportIcons.length - 1;
}
// This should never happen
if(! airportIcons[colorIndex]) {
$("news").style.display = 'inline';
$("news").innerHTML = "ERROR: " + name + ":" + colorIndex + " of " + airportMaxFlights + ".i<br>Please hit CTRL-F5 to force refresh, and <a href='/about.html'>report</a> this error if it does not go away.";
colorIndex = 0;
return;
}
var feature = new OpenLayers.Feature.Vector(projectedPoint(x,y));
feature.attributes = {
apid: apid,
coreid: coreid,
code: code,
name: formattedName,
apdata: apdata,
desc: desc,
rdesc: rdesc,
opacity: opacity,
icon: airportIcons[colorIndex][0],
size: airportIcons[colorIndex][1],
index: count,
offset: Math.floor(-airportIcons[colorIndex][1]/2)
};
return feature;
}
// Run when the user clicks on an airport marker
function onAirportSelect(airport) {
apid = airport.attributes.apid;
code = airport.attributes.code;
coreid = airport.attributes.coreid;
rdesc = airport.attributes.rdesc;
// Single airport?
if(!airport.cluster) {
// Add toolbar to popup
desc = "<span style='position: absolute; right: 5; bottom: 1;'>" +
"<a href='#' onclick='JavaScript:selectAirport(" + apid + ", true);'><img src='/img/icon_plane-src.png' width=17 height=17 title='" + gt.gettext("Select this airport") + "' id='popup" + apid + "' style='visibility: hidden'></a>";
if(coreid == 0) {
// Detailed flights accessible only if...
// 1. user is logged in, or
// 2. system is in "demo mode", or
// 3. privacy is set to (O)pen
if( logged_in || demo_mode || privacy == "O") {
// Get list of user flights
desc += " <a href='#' onclick='JavaScript:xmlhttpPost(\"" + URL_FLIGHTS + "\"," + apid + ", \"" + encodeURI(airport.attributes.desc) + "\");'><img src='/img/icon_copy.png' width=16 height=16 title='" + gt.gettext("List my flights") + "'></a>";
}
} else {
if(code.length == 3) {
// Get list of airport routes
if(coreid.startsWith("L")) {
idstring = coreid + "," + apid;
} else {
idstring = "R" + apid + "," + coreid;
}
desc += " <a href='#' onclick='JavaScript:xmlhttpPost(\"" + URL_FLIGHTS + "\",\"" + idstring + "\", \"" + encodeURI(rdesc) + "\");'><img src='/img/icon_copy.png' width=16 height=16 title='" + gt.gettext("List routes") + "'></a> ";
}
}
if(code.length == 3) {
// IATA airport, we know its routes
desc += " <a href='#' onclick='JavaScript:xmlhttpPost(\"" + URL_ROUTES + "\"," + apid + ");'><img src='/img/icon_routes.png' width=17 height=17 title='" + gt.gettext("Map of routes from this airport") + "'></a>";
}
desc += " <a href='#' onclick='JavaScript:popNewAirport(null, " + apid + ")'><img src='/img/icon_edit.png' width=16 height=16 title='" + gt.gettext("View airport details") + "'></a>";
desc += "</span>" + airport.attributes.desc.replace("Flights:", gt.gettext("Flights:"));
} else {
// Cluster, generate clickable list of members in reverse order (most flights first)
desc = "<b>" + gt.gettext("Airports") + "</b><br>";
edit = isEditMode() ? "true" : "false";
cmax = airport.cluster.length - 1;
for(c = cmax; c >= 0; c--) {
if(c < cmax) {
desc += ", ";
if((cmax-c) % 6 == 0) desc += "<br>";
}
desc += "<a href='#' onclick='JavaScript:selectAirport(" + airport.cluster[c].attributes.apid + ","
+ edit + ")'>" + airport.cluster[c].attributes.code + "</a>";
}
}
desc = "<img src=\"/img/close.gif\" onclick=\"JavaScript:closePopup(true);\" width=17 height=17> " + desc;
closePopup(false);
if (airport.popup == null) {
airport.popup = new OpenLayers.Popup.FramedCloud("airport",
airport.geometry.getBounds().getCenterLonLat(),
new OpenLayers.Size(200,80),
desc, null, false);
airport.popup.minSize = new OpenLayers.Size(200,80);
airport.popup.overflow = "auto";
map.addPopup(airport.popup);
airport.popup.show();
} else {
airport.popup.setContentHTML(desc);
airport.popup.toggle();
}
if(airport.popup.visible()) {
currentPopup = airport.popup;
} else {
closePane();
}
// Show or hide toolbar when applicable
if($('popup' + apid)) {
if(isEditMode()) {
$('popup' + apid).style.visibility = "visible";
} else {
$('popup' + apid).style.visibility = "hidden";
}
}
}
function onAirportUnselect(airport) {
// do nothing
}
function toggleControl(element) {
for(key in drawControls) {
var control = drawControls[key];
if(element.value == key && element.checked) {
control.activate();
} else {
control.deactivate();
onPopupClose();
}
}
}
function xmlhttpPost(strURL, id, param) {
var xmlHttpReq = false;
var self = this;
var query = "";
if(! initializing) closeNews();
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Process results of query
// First make sure session is still up
// (note: sessionfree PHPs do not return this string)
if(self.xmlHttpReq.responseText.substring(0, 13) == "Not logged in") {
logout(self.xmlHttpReq.responseText);
return;
}
if(strURL == URL_FLIGHTS) {
switch(param) {
case "COPY":
case "EDIT":
editFlight(self.xmlHttpReq.responseText, param);
break;
case "RELOAD":
param = lastDesc;
// param contains previously escaped semi-random HTML title
// fallthru
case "MAP":
default:
listFlights(self.xmlHttpReq.responseText, unescape(param), id);
break;
}
$("ajaxstatus").style.display = 'none';
}
if(strURL == URL_GETCODE) {
var cols = self.xmlHttpReq.responseText.split(";");
switch(param) {
case 'qs':
var alid = cols[0];
if(alid != "" && alid != 0) {
if(cols[0].indexOf(":") > 0) {
$('qsid').value = cols[0].split(":")[1]; // airport
} else {
$('qsid').value = "L" + cols[0]; // airline
}
$('qs').autocompleted = true;
$('qs').value = cols[1];
$('qs').style.color = '#000000';
$('qsgo').disabled = false;
$('qsgo').focus();
} else {
$('qs').autocompleted = false;
$('qsid').value = 0;
$('qs').style.color = '#FF0000';
$('qsgo').disabled = true;
}
break;
case 'airline':
case 'airline1':
case 'airline2':
case 'airline3':
case 'airline4':
var alid = cols[0];
if(alid != "" && alid != 0) {
$(param + 'id').value = cols[0];
$(param).value = cols[1];
$(param).style.color = '#000000';
$(param).autocompleted = true;
replicateSelection(param);
markAsChanged(true); // new airline, force refresh on save
} else {
$(param).style.color = '#FF0000';
$(param + 'id').value = 0;
$(param).autocompleted = false;
}
break;
case 'src_ap':
case 'dst_ap':
case 'src_ap1':
case 'dst_ap1':
case 'src_ap2':
case 'dst_ap2':
case 'src_ap3':
case 'dst_ap3':
case 'src_ap4':
case 'dst_ap4':
var apdata = cols[0];
var apid = apdata.split(":")[1];
if(apid && apid != 0) {
$(param + 'id').value = apdata;
$(param).value = cols[1];
$(param).style.color = '#000000';
$(param).autocompleted = true;
replicateSelection(param);
markAirport(param); // new airport, force refresh on save
markAsChanged(true);
} else {
invalidateAirport(param);
}
break;
}
}
if(strURL == URL_LOGIN) {
login(self.xmlHttpReq.responseText, param);
}
if(strURL == URL_LOGOUT) {
logout(self.xmlHttpReq.responseText);
}
if(strURL == URL_MAP || strURL == URL_ROUTES) {
var str = self.xmlHttpReq.responseText;
if(str.substring(0,6) == "Signup") {
window.location = "/html/settings?new=yes&vbulletin=true"
}
if(str.substring(0,5) == "Error") {
$("result").innerHTML = "<h4>" + str.split(';')[1] + "</h4><br><h6><a href='/'>Home</a></h6>";
$("ajaxstatus").style.display = 'none';
openPane("result");
} else {
// Zoom map to fit when first loading another's flights/trip
updateMap(str, strURL);
if(! logged_in && ! demo_mode && initializing) {
closePane();
var extent = airportLayer.getDataExtent();
if(extent) map.zoomToExtent(extent);
}
if(strURL == URL_MAP) {
if(param) {
updateFilter(str);
}
$("maptitle").innerHTML = getMapTitle(true);
} else {
updateFilter(str);
closePopup(true);
$('qs').value = $('qs').hintText;
$('qs').style.color = '#888';
$('qs').autocompleted = false;
$('qsid').value = 0;
$('qsgo').disabled = true;
if(filter_alid == 0) {
var extent = airportLayer.getDataExtent();
if(extent) map.zoomToExtent(extent);
}
}
// Map now completely drawn for the first time
if(initializing) {
initializing = false;
}
}
}
if(strURL == URL_STATS) {
showStats(self.xmlHttpReq.responseText);
$("ajaxstatus").style.display = 'none';
}
if(strURL == URL_TOP10) {
showTop10(self.xmlHttpReq.responseText);
$("ajaxstatus").style.display = 'none';
}
if(strURL == URL_SUBMIT) {
var result = self.xmlHttpReq.responseText.split(";");
code = result[0];
text = result[1];
if(getCurrentPane() == "multiinput") {
$("multiinput_status").innerHTML = '<B>' + text + '</B>';
} else {
$("input_status").innerHTML = '<B>' + text + '</B>';
}
setCommitAllowed(false);
// Something went wrong, so we just abort
if(code == CODE_FAIL) {
return;
}
// If flight was successfully deleted...
if(code == CODE_DELETEOK) {
//... and we're in input mode, move to another flight
if(getCurrentPane() == "input") {
// Last flight deleted
if(fidList.length == 1) {
clearStack();
} else {
// Remove current flight
fidList.splice(fidPtr, 1);
// Edit next if you can
if(fidPtr < fidList.length) {
editPointer(0);
} else {
// Move back
editPointer(-1);
}
}
} else {
// Not in edit mode, so reload currently displayed list of flights
xmlhttpPost(URL_FLIGHTS, 0, "RELOAD");
}
majorEdit = true; // trigger map refresh
}
if(code == CODE_EDITOK || code == CODE_ADDOK) {
// If adding new flights (not editing), swap last destination to be new source and focus on date
if(getCurrentPane() == "input") {
if($("addflighttitle").style.display == 'inline') {
swapAirports(false);
document.forms['inputform'].seat.value = "";
document.forms['inputform'].seat_type.selectedIndex = 0;
document.forms['inputform'].src_date.focus();
}
} else {
clearInput(); // Always clear multiview
}
}
// A change that affected the map was made, so redraw
if(majorEdit) {
if(code == CODE_DELETEOK) {
setTimeout('refresh(true)', 1000); // wait for earlier ops to complete...
} else {
refresh(true); // ...else do it right now
}
} else {
$("ajaxstatus").style.display = 'none';
}
majorEdit = false;
} // end URL_SUBMIT
}
}
// End result processing
// Start query string generation
switch(strURL) {
case URL_SUBMIT:
var inputform = document.forms['inputform'];
// Deleting needs only the fid, and can be run without the inputform
if(param != "DELETE") {
if(getCurrentPane() == "multiinput") {
query = 'multi=' + multiinput_rows + '&';
var indexes = [];
for(i = 1; i <= multiinput_rows; i++) {
indexes.push(i);
}
} else {
var indexes = [ "" ];
}
for(i = 0; i < indexes.length; i++) {
var src_date = $('src_date' + indexes[i]).value;
if(! re_date.test(src_date)) {
alert(gt.gettext("Please enter a full date in year/month/date order, eg. 2008/10/30 for 30 October 2008. Valid formats include YYYY-MM-DD, YYYY/MM/DD, YYYY.MM.DD and YYYY MM DD."));
$('src_date' + indexes[i]).focus();
return;
}
var src_apid = getApid('src_ap' + indexes[i]);
if(! src_apid || src_apid == "0") {
alert(gt.gettext("Please enter a valid source airport."));
$('src_ap' + indexes[i]).focus();
return;
}
var dst_apid = getApid('dst_ap' + indexes[i]);
if(! dst_apid || dst_apid == "0") {
alert(gt.gettext("Please enter a valid destination airport."));
$('dst_ap' + indexes[i]).focus();
return;
}
var alid = $('airline' + indexes[i] + 'id').value;
var airline = $('airline' + indexes[i]).value.trim();
if(! alid || alid == 0) {
if(airline == "" || airline == $('airline').hintText) {
alid = "-1"; // UNKNOWN
} else {
mode = getMode();
if(confirm(Gettext.strargs(gt.gettext("'%1' not found in %2 database. Do you want to add it as a new %2 company?"), [airline, modeoperators[mode], modeoperators[mode]]))) {
popNewAirline('airline' + indexes[i], airline, mode);
} else {
$('airline' + indexes[i]).focus();
}
return;
}
}
query +='alid' + indexes[i] + '=' + encodeURIComponent(alid) + '&' +
'src_date' + indexes[i] + '=' + encodeURIComponent(src_date) + '&' +
'src_apid' + indexes[i] + '=' + encodeURIComponent(src_apid) + '&' +
'dst_apid' + indexes[i] + '=' + encodeURIComponent(dst_apid) + '&';
}
if(getCurrentPane() == "input") {
src_time = $('src_time').value;
if(src_time != "" && src_time != "HH:MM") {
if(! RE_TIME.test(src_time)) {
alert(gt.gettext("Please enter times in 24-hour format with a colon between hour and minute, eg. 21:37 for 9:37 PM."));
$('src_time').focus();
return;
}
query += 'src_time=' + encodeURIComponent(src_time) + '&';
}
var type = inputform.seat_type.value;
if(type == "-") type = "";
var myClass = radioValue(inputform.myClass);
var reason = radioValue(inputform.reason);
var plane = inputform.plane.value;
if(plane == gt.gettext("Enter plane model")) {
plane = "";
}
var trid = 0;
if(inputform.trips) {
trid = inputform.trips[inputform.trips.selectedIndex].value.split(";")[0];
}
if(trid == 0) trid = "NULL";
var registration = inputform.registration.value;
var note = inputform.note.value;
var duration = $('duration').value;
if(! RE_TIME.test(duration)) {
alert(gt.gettext("Please enter flight duration as hours and minutes with a colon between hour and minute, eg. 5:37 for 5 hours, 37 minutes. You can blank the duration to have it recalculated automatically."));
$('duration').focus();
return;
}
var distance = $('distance').value;
if(! re_numeric.test(distance)) {
alert(gt.gettext("Please enter flight distance as miles, with no fractional parts. You can blank the distance to have it re-calculated automatically."));
$('distance').focus();
return;
}
var number = inputform.number.value;
var seat = inputform.seat.value;
var mode = inputform.mode.value;
} else {
var number = "";
var seat = "";
var type = "";
var myClass = "";
var reason = "";
var plane = "";
var trid = "NULL";
var registration = "";
var note = "";
var duration = "";
var distance = "";
var mode = "F";
}
}
query += 'duration=' + encodeURIComponent(duration) + '&' +
'distance=' + encodeURIComponent(distance) + '&' +
'number=' + encodeURIComponent(number) + '&' +
'seat=' + encodeURIComponent(seat) + '&' +
'type=' + encodeURIComponent(type) + '&' +
'class=' + encodeURIComponent(myClass) + '&' +
'reason=' + encodeURIComponent(reason) + '&' +
'registration=' + encodeURIComponent(registration) + '&' +
'note=' + encodeURIComponent(note) + '&' +
'plane=' + encodeURIComponent(plane) + '&' +
'trid=' + encodeURIComponent(trid) + '&' +
'mode=' + encodeURIComponent(mode) + '&' +
'fid=' + encodeURIComponent(fid) + '&' +
'param=' + encodeURIComponent(param);
if(getCurrentPane() == "multiinput") {
$("multiinput_status").innerHTML = '<B>Saving...</B>';
} else {
$("input_status").innerHTML = '<B>Saving...</B>';
}
break;
case URL_LOGIN:
$("ajaxstatus").style.display = 'inline';
var name = document.forms['login'].name.value;
var pw = document.forms['login'].pw.value;
var challenge = document.forms['login'].challenge.value;
hash = hex_md5(challenge + hex_md5(pw + name.toLowerCase()));
legacy_hash = hex_md5(challenge + hex_md5(pw + name));
query = 'name=' + encodeURIComponent(name) + '&pw=' + encodeURIComponent(hash) + '&lpw=' + encodeURIComponent(legacy_hash) + "&challenge=" + encodeURIComponent(challenge);
break;
case URL_GETCODE:
query = encodeURIComponent(param) + '=' + encodeURIComponent(id) + '&quick=true&mode=' + getMode();
break;
case URL_LOGOUT:
// no parameters needed
break;
case URL_FLIGHTS:
if(param == "RELOAD") {
query = lastQuery;
break;
}
// ...else fallthru and generate new query
// URL_MAP, URL_ROUTES, URL_FLIGHTS, URL_STATS, URL_TOP10
default:
$("ajaxstatus").style.display = 'inline';
var form = document.forms['filterform'];
if(! initializing && form.Trips) {
filter_trid = form.Trips.value.split(";")[0];
}
filter_alid = form.Airlines.value.split(";")[0];
filter_year = form.Years.value;
query = 'user=' + encodeURIComponent(filter_user) + '&' +
'trid=' + encodeURIComponent(filter_trid) + '&' +
'alid=' + encodeURIComponent(filter_alid) + '&' +
'year=' + encodeURIComponent(filter_year) + '&' +
'param=' + encodeURIComponent(param);
guestpw = $('guestpw');
if(guestpw) {
query += "&guestpw=" + hex_md5(guestpw.value + filter_user.toLowerCase());
}
filter_extra_key = form.Extra.value;
if(filter_extra_key != "" && $('filter_extra_value')) {
filter_extra_value = $('filter_extra_value').value;
query += '&xkey=' + filter_extra_key +
'&xvalue=' + filter_extra_value;
}
if(strURL == URL_ROUTES) {
query += '&apid=' + encodeURIComponent(id);
}
if(strURL == URL_FLIGHTS) {
switch(param) {
case "EDIT":
case "COPY":
query += '&fid=' + encodeURIComponent(id);
break;
default:
query += '&id=' + encodeURIComponent(id);
lastQuery = query;
lastDesc = param;
}
}
if(strURL == URL_TOP10) {
if(param) {
query += '&' + param;