Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2931 lines (2549 loc) · 109 KB
/
Copy pathscript.js
File metadata and controls
2931 lines (2549 loc) · 109 KB
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
let routeData = [];
let progressInterval;
// ====== AVIATION WEATHER API CONFIGURATION ======
const AVIATION_API_CONFIG = {
baseUrl: 'https://aviationweather.gov/api/data',
endpoints: {
metar: '/metar',
taf: '/taf',
pirep: '/pirep',
sigmet: '/sigmet',
afd: '/afd',
stationinfo: '/stationinfo',
current: '/current',
forecast: '/forecast',
notam: '/notam',
airmet: '/airmet',
gairmet: '/gairmet',
winds: '/winds',
icing: '/icing',
turbulence: '/turbulence'
}
};
// Backend API Configuration
const BACKEND_API_CONFIG = {
baseUrl: 'http://localhost:3001',
endpoints: {
summary: '/aviation/summary',
weather: '/weather',
route: '/route',
health: '/health',
stationinfo: '/data/stationinfo',
routeStations: '/route/stations',
metarDecoded: '/data/metar'
}
};
// Aviation Weather API Helper Functions
async function fetchAviationData(endpoint, params = {}) {
try {
const url = `${AVIATION_API_CONFIG.baseUrl}${AVIATION_API_CONFIG.endpoints[endpoint]}`;
const queryString = new URLSearchParams(params).toString();
const fullUrl = queryString ? `${url}?${queryString}` : url;
const response = await fetch(fullUrl);
if (!response.ok) {
// Handle specific error cases
if (response.status === 400) {
console.warn(`${endpoint.toUpperCase()} API: Bad Request - Invalid parameters:`, params);
return null; // Return null for bad requests instead of throwing
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`${endpoint.toUpperCase()} API Error:`, error);
return null;
}
}
async function fetchWeatherData(icaoCode) {
return await fetchAviationData('metar', {
ids: icaoCode,
format: 'json',
hours: 2
});
}
// Removed AQI integration
// ===== Optional: TFR Integration Stub =====
// Replace implementation when TFR/Restricted Areas API is available
async function fetchTfrForRoute(routeIcaos) {
try {
// Example target may accept polyline/route or list of ICAOs
// const response = await fetch(`${WEATHER_API_CONFIG.baseUrl}${WEATHER_API_CONFIG.endpoints.tfr}`, { method: 'POST', body: JSON.stringify({ route: routeIcaos })});
// const data = await response.json();
// return data; // shape suggestion: { hasRestrictions: boolean, items: [...] }
return null; // placeholder
} catch (error) {
console.error('TFR API Error:', error);
return null;
}
}
async function fetchMetarData(icaoCode) {
return await fetchAviationData('metar', {
ids: icaoCode,
format: 'json',
hours: 2
});
}
async function searchWeatherReports(query) {
// Use backend API for comprehensive search
try {
const response = await fetch(`${BACKEND_API_CONFIG.baseUrl}${BACKEND_API_CONFIG.endpoints.summary}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
});
const data = await response.json();
return data.summary || [];
} catch (error) {
console.error('Search API Error:', error);
return [];
}
}
// Station Information API Functions
async function fetchStationInfo(icaoCode) {
try {
const response = await fetch(`${BACKEND_API_CONFIG.baseUrl}${BACKEND_API_CONFIG.endpoints.stationinfo}?station=${icaoCode}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Station Info API Error for ${icaoCode}:`, error);
return null;
}
}
async function fetchRouteStations(routeIcaos) {
try {
const routeString = routeIcaos.join(',');
const response = await fetch(`${BACKEND_API_CONFIG.baseUrl}${BACKEND_API_CONFIG.endpoints.routeStations}/${routeString}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Route Stations API Error:', error);
return null;
}
}
async function fetchDecodedMetar(stationCode) {
try {
const response = await fetch(`${BACKEND_API_CONFIG.baseUrl}${BACKEND_API_CONFIG.endpoints.metarDecoded}?station=${stationCode}&hours=1`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Decoded METAR API Error for ${stationCode}:`, error);
return null;
}
}
// Page 1: Form validation and submission
document.getElementById('routeForm').addEventListener('submit', function(e) {
e.preventDefault();
const icaoInput = document.getElementById('icaoCodes').value.trim();
const errorElement = document.getElementById('icaoError');
// Validate ICAO codes
if (!validateICAOCodes(icaoInput)) {
return;
}
// Process and store route data
routeData = icaoInput.split(',').map(code => code.trim().toUpperCase());
// Store route data globally for access across functions
window.routeData = {
stations: routeData,
takeoff: routeData[0],
landing: routeData[routeData.length - 1],
waypoints: routeData.slice(1, -1)
};
console.log('🛫 Route configured:', {
takeoff: window.routeData.takeoff,
landing: window.routeData.landing,
waypoints: window.routeData.waypoints,
totalStations: window.routeData.stations.length
});
// Navigate to page 2
showPage(2);
initializeDashboard();
});
function validateICAOCodes(input) {
const errorElement = document.getElementById('icaoError');
if (!input) {
showError('Please enter ICAO codes');
return false;
}
const codes = input.split(',').map(code => code.trim());
if (codes.length < 2) {
showError('Please enter at least 2 ICAO codes');
return false;
}
const icaoPattern = /^[A-Z]{4}$/i;
for (let code of codes) {
if (!icaoPattern.test(code)) {
showError(`Invalid ICAO code format: ${code}. ICAO codes must be 4 letters.`);
return false;
}
}
hideError();
return true;
function showError(message) {
errorElement.textContent = message;
errorElement.style.display = 'block';
document.getElementById('icaoCodes').style.borderColor = '#e74c3c';
}
function hideError() {
errorElement.style.display = 'none';
document.getElementById('icaoCodes').style.borderColor = '#e0e0e0';
}
}
// Page navigation
function showPage(pageNumber) {
document.querySelectorAll('.page').forEach(page => {
page.style.display = 'none';
});
document.getElementById(`page${pageNumber}`).style.display = 'flex';
// Update nav active state
document.querySelectorAll('.nav-link').forEach(btn => btn.classList.remove('active'));
const activeMap = { 1: 'navPage1', 2: 'navPage2', 3: 'navPage3' };
const activeBtn = document.getElementById(activeMap[pageNumber]);
if (activeBtn) activeBtn.classList.add('active');
}
// Page 2: Dashboard initialization
async function initializeDashboard() {
// Set route title with takeoff and landing stations
const routeTitle = document.getElementById('routeTitle');
if (routeTitle && window.routeData) {
routeTitle.textContent = `${window.routeData.takeoff} → ${window.routeData.landing}`;
}
// Update flight information section with takeoff and landing
updateFlightInformationDisplay();
// Create animated map visualization
createAnimatedMap();
// FETCH REAL WEATHER DATA FOR ROUTE
await loadRouteWeatherData();
// Update flight information
updateFlightInfo();
// Initialize dynamic weather wallpaper
initializeWeatherWallpaper();
}
// Create professional animated map visualization with real station data
async function createAnimatedMap() {
const mapContainer = document.getElementById('flightMap');
const waypointPins = document.getElementById('waypointPins');
const weatherStops = document.getElementById('weatherStops');
// Fetch real station information for the route
const stationData = await fetchRouteStations(routeData);
console.log('Station data:', stationData);
const flightProgress = document.getElementById('flightProgress');
// Clear existing content
waypointPins.innerHTML = '';
weatherStops.innerHTML = '';
// Create professional pushpin waypoints with real station data
routeData.forEach((waypoint, index) => {
// Position pins along the route
const leftPercent = 10 + (index * 80 / (routeData.length - 1));
// Get real station information
let stationInfo = null;
let fullName = waypoint;
let city = 'Unknown';
let country = '';
let elevation = '';
if (stationData && stationData.stations && stationData.stations[waypoint]) {
stationInfo = stationData.stations[waypoint];
// Extract station information from API response
if (Array.isArray(stationInfo) && stationInfo.length > 0) {
const station = stationInfo[0];
fullName = station.name || waypoint;
city = station.city || 'Unknown';
country = station.country || '';
elevation = station.elevation ? `${station.elevation}ft` : '';
} else if (stationInfo.name) {
fullName = stationInfo.name;
city = stationInfo.city || 'Unknown';
country = stationInfo.country || '';
elevation = stationInfo.elevation ? `${stationInfo.elevation}ft` : '';
}
}
// Create display name with real data
const displayName = `${fullName}${city !== 'Unknown' ? ` - ${city}` : ''}${country ? `, ${country}` : ''}`;
// Determine pin type based on configured takeoff and landing stations
let pinType = 'waypoint';
if (window.routeData && window.routeData.takeoff && waypoint === window.routeData.takeoff) {
pinType = 'departure';
} else if (window.routeData && window.routeData.landing && waypoint === window.routeData.landing) {
pinType = 'destination';
} else if (index === 0) {
pinType = 'departure';
} else if (index === routeData.length - 1) {
pinType = 'destination';
}
// Create pin with real station data
const pin = createWaypointPin(waypoint, displayName, leftPercent, 50, pinType, stationInfo);
waypointPins.appendChild(pin);
});
// Create weather stops with precipitation
createWeatherStops();
// Animate flight progress
setTimeout(() => {
flightProgress.style.left = '92%';
}, 1000);
// Load aviation weather summary
loadAviationSummary();
}
// Create professional weather stops with precipitation
function createWeatherStops() {
const weatherStops = document.getElementById('weatherStops');
const weatherTypes = [
{ symbol: '🌤️', label: 'Clear', class: 'clear' },
{ symbol: '⚡', label: 'Turbulence', class: 'turbulence' },
{ symbol: '🌩️', label: 'Storm', class: 'storm' },
{ symbol: '🌧️', label: 'Precipitation', class: 'precipitation' }
];
// Create stops between waypoints
for (let i = 0; i < routeData.length - 1; i++) {
const stop = document.createElement('div');
stop.className = 'weather-stop';
// Random weather type for demo (including precipitation)
const weatherIndex = Math.floor(Math.random() * weatherTypes.length);
const weatherType = weatherTypes[weatherIndex];
stop.textContent = weatherType.symbol;
stop.classList.add(weatherType.class);
// Position between waypoints
const leftPercent = 10 + ((i + 0.5) * 80 / (routeData.length - 1));
stop.style.left = `${leftPercent}%`;
stop.style.top = '50%';
// Add tooltip
stop.title = weatherType.label;
// Add hover tooltip
stop.addEventListener('mouseenter', (e) => {
showTooltip(e.target, weatherType.label);
});
stop.addEventListener('mouseleave', () => {
hideTooltip();
});
weatherStops.appendChild(stop);
}
}
// Tooltip functions
function showTooltip(element, text) {
const tooltip = document.createElement('div');
tooltip.className = 'weather-tooltip show';
tooltip.textContent = text;
tooltip.id = 'weatherTooltip';
document.body.appendChild(tooltip);
const rect = element.getBoundingClientRect();
tooltip.style.left = `${rect.left + rect.width / 2}px`;
tooltip.style.top = `${rect.top - 40}px`;
}
function hideTooltip() {
const tooltip = document.getElementById('weatherTooltip');
if (tooltip) {
tooltip.remove();
}
}
// Load aviation weather summary from backend
async function loadAviationSummary() {
const summaryPoints = document.getElementById('summaryPoints');
try {
// Prepare query with route stations
const query = {
stations: routeData.join(','),
metar: { hours: 2 },
taf: { hours: 6 },
pirep: { hours: 4 },
sigmet: { hours: 6 },
afd: { hours: 6 }
};
// Call backend API
const response = await fetch(`${BACKEND_API_CONFIG.baseUrl}${BACKEND_API_CONFIG.endpoints.summary}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(query)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (data.summary && data.summary.length > 0) {
displaySummaryPoints(data.summary);
// Update all dashboard components
updateDashboardComponents(data.data, data.stations);
} else {
summaryPoints.innerHTML = '<div class="loading">No weather data available for this route</div>';
}
} catch (error) {
console.error('Failed to load aviation summary:', error);
summaryPoints.innerHTML = `
<div class="loading">
Backend unavailable. Using sample data...
<br><small>Start the Flask server: python python.py</small>
</div>
`;
// Fallback: Show sample aviation points with various data sources
setTimeout(() => {
displaySummaryPoints([
"SIGMET: Convective activity over KJFK area - Severe turbulence and icing possible",
"PIREP: Moderate to severe turbulence reported at FL350 - Expect rough ride",
"METAR: KJFK visibility 2SM with thunderstorms - Monitor closely",
"TAF: KLAX deteriorating conditions expected 18Z - Plan fuel reserves",
"AFD: High pressure system moving east - Generally favorable conditions",
"NOTAM: KORD Runway 10L/28R closed for maintenance - Expect delays"
]);
}, 2000);
}
}
// Function to categorize data source
function categorizeDataSource(point) {
const pointLower = point.toLowerCase();
// Overview category: SIGMET, METAR, TAF, PIREP
if (pointLower.includes('sigmet') || pointLower.includes('significant weather') ||
pointLower.includes('metar') || pointLower.includes('current weather') || pointLower.includes('observation') ||
pointLower.includes('taf') || pointLower.includes('forecast') || pointLower.includes('terminal forecast') ||
pointLower.includes('pirep') || pointLower.includes('pilot report') || pointLower.includes('aircraft report')) {
return 'overview';
}
// Attention category: AFD, NOTAM, and everything else
return 'attention';
}
// Function to detect data source and return appropriate tag
function detectDataSource(point) {
const pointLower = point.toLowerCase();
// PIREP detection - pilot reports
if (pointLower.includes('pirep') || pointLower.includes('pilot report') || pointLower.includes('aircraft report')) {
return { tag: 'pilot-advice', label: 'PILOT ADVICE' };
}
// AFD detection - Area Forecast Discussion (expert analysis)
if (pointLower.includes('afd') || pointLower.includes('area forecast') || pointLower.includes('forecast discussion')) {
return { tag: 'expert', label: 'EXPERT' };
}
// SIGMET detection - significant meteorological information
if (pointLower.includes('sigmet') || pointLower.includes('significant weather')) {
return { tag: 'alert', label: 'ALERT' };
}
// NOTAM detection - notices to airmen
if (pointLower.includes('notam') || pointLower.includes('notice to airmen')) {
return { tag: 'alert', label: 'ALERT' };
}
// No tag for METAR, TAF, or other sources
return null;
}
// Function to clean the point text by removing data source prefixes
function cleanPointText(point) {
// Remove common data source prefixes
return point
.replace(/^(PIREP|SIGMET|METAR|TAF|AFD|NOTAM):\s*/i, '')
.replace(/^(Pilot Report|Aircraft Report|Area Forecast|Terminal Forecast|Notice to Airmen):\s*/i, '')
.trim();
}
// Format summary text with proper HTML formatting
function formatSummaryText(text) {
if (!text) return '<div class="no-data">No data available</div>';
// Convert line breaks to HTML and format bullet points
return text
.split('\n')
.filter(line => line.trim())
.map(line => {
if (line.startsWith('•')) {
return `<div class="summary-bullet">${line}</div>`;
} else {
return `<div class="summary-text">${line}</div>`;
}
})
.join('');
}
// Format weather briefing summary in original format with categories
function formatOriginalWeatherBriefing(text) {
if (!text) return '<div class="no-data">No weather briefing summary available</div>';
// Split the text into lines and process each line
const lines = text.split('\n').filter(line => line.trim());
let html = '';
let currentCategory = '';
let titleAdded = false;
for (const line of lines) {
// Handle main title (only add once)
if (line.includes('🌤️ WEATHER BRIEFING SUMMARY') && !titleAdded) {
html += `<div class="weather-briefing-title">${line}</div>`;
titleAdded = true;
}
// Handle Overview category
else if (line.includes('📊 OVERVIEW:')) {
currentCategory = 'overview';
html += `<div class="category-header overview-header">📊 OVERVIEW</div>`;
}
// Handle Attention category
else if (line.includes('⚠️ ATTENTION:')) {
currentCategory = 'attention';
html += `<div class="category-header attention-header">⚠️ ATTENTION</div>`;
}
// Handle bullet points with tags and "See why" links
else if (line.startsWith('•')) {
// Extract the main content, tags, and "See why" link
let content = line.replace(/<[^>]*>/g, ''); // Remove HTML tags for processing
// Remove any "see why" text that appears in the content
content = content.replace(/\s*see why\s*/gi, '').trim();
const hasTags = line.includes('<span class="tag');
const hasSeeWhy = line.includes('<a href="#" class="see-why"');
let bulletHtml = `<div class="summary-bullet ${currentCategory}-bullet">`;
bulletHtml += `<div class="bullet-content">`;
bulletHtml += content;
bulletHtml += `</div>`;
// Add tags and "See why" link in a flex container for proper alignment
if (hasTags || hasSeeWhy) {
bulletHtml += `<div class="bullet-actions">`;
// Extract the HTML parts from the original line
const tagMatch = line.match(/<span class="tag[^"]*"[^>]*>([^<]*)<\/span>/);
const seeWhyMatch = line.match(/<a href="#" class="see-why"[^>]*>([^<]*)<\/a>/);
if (tagMatch) {
bulletHtml += `<span class="tag ${tagMatch[1].toLowerCase().replace(/\s+/g, '-')}">${tagMatch[1]}</span>`;
}
if (seeWhyMatch) {
// Extract data attributes for the "See why" link
const dataStation = line.match(/data-station="([^"]*)"/);
const dataType = line.match(/data-type="([^"]*)"/);
const dataAttrs = dataStation && dataType ?
`data-station="${dataStation[1]}" data-type="${dataType[1]}"` : '';
bulletHtml += `<a href="#" class="see-why" ${dataAttrs}>See why</a>`;
}
bulletHtml += `</div>`;
}
bulletHtml += '</div>';
html += bulletHtml;
}
// Handle other content
else {
html += `<div class="summary-text">${line}</div>`;
}
}
return html;
}
// Format weather briefing summary with enhanced headings (legacy function)
function formatWeatherBriefing(text) {
if (!text) return '<div class="no-data">No weather briefing summary available</div>';
// Convert the weather briefing text to HTML with enhanced headings
return text
.split('\n')
.filter(line => line.trim())
.map(line => {
// Handle Overview heading
if (line.includes('📊 OVERVIEW:')) {
return `<div class="overview-heading">📊 OVERVIEW</div>`;
}
// Handle Attention heading
else if (line.includes('⚠️ ATTENTION:')) {
return `<div class="attention-heading">⚠️ ATTENTION</div>`;
}
// Handle bullet points
else if (line.startsWith('•')) {
return `<div class="summary-bullet">${line}</div>`;
}
// Handle numbered items
else if (line.match(/^\d+\./)) {
return `<div class="numbered-item">${line}</div>`;
}
// Handle regular text
else {
return `<div class="summary-text">${line}</div>`;
}
})
.join('');
}
// "See why" functionality (same as Python version)
function handleSeeWhyClick(event) {
event.preventDefault();
const station = event.target.getAttribute('data-station');
const type = event.target.getAttribute('data-type');
if (!station || !type) {
console.error('Missing station or type data');
return;
}
// Show loading state
showExplanationModal('Loading detailed analysis...', 'Please wait while we fetch detailed weather information...');
// Fetch detailed explanation
fetch(`${BACKEND_API_CONFIG.baseUrl}/see-why?station=${station}&type=${type}`)
.then(response => response.json())
.then(data => {
if (data.detailedExplanation) {
showExplanationModal(
`Detailed ${type.toUpperCase()} Analysis for ${station}`,
data.detailedExplanation,
data.rawData
);
} else {
showExplanationModal(
'Analysis Unavailable',
'Detailed analysis is not available for this weather data.',
data.rawData || 'No raw data available'
);
}
})
.catch(error => {
console.error('Error fetching detailed explanation:', error);
showExplanationModal(
'Error',
'Unable to fetch detailed weather analysis. Please try again later.',
''
);
});
}
// Show explanation modal
function showExplanationModal(title, content, rawData = '') {
const modal = document.getElementById('explanationModal');
const titleElement = document.getElementById('explanationTitle');
const bodyElement = document.getElementById('explanationBody');
titleElement.textContent = title;
let bodyContent = content;
if (rawData) {
bodyContent += `<div class="raw-data"><strong>Raw Data:</strong><br>${rawData}</div>`;
}
bodyElement.innerHTML = bodyContent;
modal.style.display = 'block';
// Add click outside to close
modal.onclick = function(event) {
if (event.target === modal) {
closeExplanationModal();
}
};
}
// Close explanation modal
function closeExplanationModal() {
const modal = document.getElementById('explanationModal');
modal.style.display = 'none';
}
// Add event listeners for "See why" buttons
function addSeeWhyListeners() {
// Use event delegation for dynamically added content
document.addEventListener('click', function(event) {
if (event.target.classList.contains('see-why')) {
handleSeeWhyClick(event);
}
});
}
// Update professional widgets with real data
function updateProfessionalWidgets(weatherData) {
console.log('🎯 Updating professional widgets with data:', weatherData);
// Update Visibility Widget
if (weatherData.metar && weatherData.metar.length > 0) {
const metar = weatherData.metar[0];
const visibility = metar.visib || 'N/A';
let visibilityText = 'N/A';
console.log('🔍 Visibility widget debug:', { visibility, metar: metar.icaoId });
if (visibility === '10+') {
visibilityText = '10+ miles';
} else if (typeof visibility === 'string' && visibility.includes('SM')) {
visibilityText = visibility;
} else if (typeof visibility === 'number') {
visibilityText = visibility >= 10 ? '10+ miles' : `${visibility} miles`;
}
console.log('🔍 Visibility text:', visibilityText);
const visibilityElement = document.getElementById('visibilityValue');
if (visibilityElement) {
visibilityElement.textContent = visibilityText;
console.log('✅ Visibility widget updated:', visibilityText);
} else {
console.error('❌ Visibility element not found!');
}
} else {
console.log('❌ No METAR data available for visibility widget');
}
// Update Weather Score Widget
let weatherScore = 85; // Default score
if (weatherData.metar && weatherData.metar.length > 0) {
const metar = weatherData.metar[0];
const visibility = metar.visib || 'N/A';
const windSpeed = metar.wspd || 0;
// Calculate weather score based on conditions
let visibilityValue = 0;
if (visibility === '10+') {
visibilityValue = 10;
} else if (typeof visibility === 'string' && visibility.includes('SM')) {
const match = visibility.match(/(\d+(?:\.\d+)?)/);
visibilityValue = match ? parseFloat(match[1]) : 0;
} else if (typeof visibility === 'number') {
visibilityValue = visibility;
}
if (visibilityValue >= 10 && windSpeed < 20) weatherScore = 95;
else if (visibilityValue >= 5 && windSpeed < 30) weatherScore = 80;
else if (visibilityValue >= 3 && windSpeed < 40) weatherScore = 65;
else weatherScore = 45;
}
const weatherScoreElement = document.getElementById('weatherScoreValue');
if (weatherScoreElement) {
weatherScoreElement.textContent = `${weatherScore}%`;
}
// Update TFR Status Widget
const tfrElement = document.getElementById('tfrValue');
if (tfrElement) {
tfrElement.textContent = 'Clear'; // Default to clear
}
// Update Wind Conditions Widget
const windConditionsElement = document.getElementById('windConditionsValue');
if (windConditionsElement && weatherData.metar && weatherData.metar.length > 0) {
const metar = weatherData.metar[0];
const windSpeed = metar.wspd || 0;
const windDirection = metar.wdir || 0;
if (windSpeed > 0 && windDirection >= 0) {
const directionText = getWindDirection(windDirection);
windConditionsElement.textContent = `${windSpeed}kt ${directionText}`;
} else {
windConditionsElement.textContent = 'Calm';
}
}
// Update Temperature Widget
const temperatureElement = document.getElementById('temperatureValue');
if (temperatureElement && weatherData.metar && weatherData.metar.length > 0) {
const metar = weatherData.metar[0];
const temperature = metar.temp;
if (temperature !== null && temperature !== undefined) {
temperatureElement.textContent = `${Math.round(temperature)}°C`;
} else {
temperatureElement.textContent = 'N/A';
}
}
// Update Turbulence Widget
const turbulenceElement = document.getElementById('turbulenceValue');
if (turbulenceElement && weatherData.metar && weatherData.metar.length > 0) {
const metar = weatherData.metar[0];
const windSpeed = metar.wspd || 0;
const windGust = metar.wgst || 0;
const maxWind = Math.max(windSpeed, windGust);
let turbulenceLevel = 'Light';
if (maxWind > 30) {
turbulenceLevel = 'Severe';
} else if (maxWind > 20) {
turbulenceLevel = 'Moderate';
} else if (maxWind > 15) {
turbulenceLevel = 'Light-Moderate';
} else {
turbulenceLevel = 'Light';
}
turbulenceElement.textContent = turbulenceLevel;
}
}
// Update takeoff and landing weather conditions section
function updateCurrentWeatherConditions(weatherData) {
console.log('🌤️ Updating takeoff and landing weather conditions with data:', weatherData);
const currentWeatherContent = document.getElementById('currentWeatherContent');
if (!currentWeatherContent) return;
// Use configured takeoff and landing stations if available
let takeoffStation, landingStation;
if (window.routeData && window.routeData.takeoff && window.routeData.landing) {
takeoffStation = window.routeData.takeoff;
landingStation = window.routeData.landing;
console.log(`🛫 Using configured stations - Takeoff: ${takeoffStation}, Landing: ${landingStation}`);
}
if (weatherData.metar && weatherData.metar.length >= 2) {
// Get takeoff and landing airports based on configured stations
let takeoffMetar, landingMetar;
if (takeoffStation && landingStation) {
// Find METAR data for configured takeoff and landing stations
takeoffMetar = weatherData.metar.find(metar => metar.icaoId === takeoffStation);
landingMetar = weatherData.metar.find(metar => metar.icaoId === landingStation);
// Fallback to first and last if not found
if (!takeoffMetar) takeoffMetar = weatherData.metar[0];
if (!landingMetar) landingMetar = weatherData.metar[weatherData.metar.length - 1];
} else {
// Default to first and last airports
takeoffMetar = weatherData.metar[0];
landingMetar = weatherData.metar[weatherData.metar.length - 1];
}
const takeoffDecoded = decodeMETAR(takeoffMetar);
const landingDecoded = decodeMETAR(landingMetar);
currentWeatherContent.innerHTML = `
<div class="weather-airport">
<div class="weather-airport-title">✈️ Takeoff - ${takeoffMetar.icaoId}</div>
<div class="weather-parameters">
<div class="weather-parameter">
<div class="weather-parameter-label">Temperature</div>
<div class="weather-parameter-value">${takeoffDecoded.temperature || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Wind</div>
<div class="weather-parameter-value">${takeoffDecoded.wind || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Visibility</div>
<div class="weather-parameter-value">${takeoffDecoded.visibility || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Pressure</div>
<div class="weather-parameter-value">${takeoffDecoded.pressure || 'N/A'}</div>
</div>
</div>
<div class="weather-summary">
<div class="weather-summary-text">${formatWeatherSummary(takeoffMetar, takeoffDecoded)}</div>
</div>
</div>
<div class="weather-airport">
<div class="weather-airport-title">🛬 Landing - ${landingMetar.icaoId}</div>
<div class="weather-parameters">
<div class="weather-parameter">
<div class="weather-parameter-label">Temperature</div>
<div class="weather-parameter-value">${landingDecoded.temperature || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Wind</div>
<div class="weather-parameter-value">${landingDecoded.wind || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Visibility</div>
<div class="weather-parameter-value">${landingDecoded.visibility || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Pressure</div>
<div class="weather-parameter-value">${landingDecoded.pressure || 'N/A'}</div>
</div>
</div>
<div class="weather-summary">
<div class="weather-summary-text">${formatWeatherSummary(landingMetar, landingDecoded)}</div>
</div>
</div>
`;
} else if (weatherData.metar && weatherData.metar.length === 1) {
// Only one airport available
const metar = weatherData.metar[0];
const decoded = decodeMETAR(metar);
currentWeatherContent.innerHTML = `
<div class="weather-airport">
<div class="weather-airport-title">✈️ Airport - ${metar.icaoId}</div>
<div class="weather-parameters">
<div class="weather-parameter">
<div class="weather-parameter-label">Temperature</div>
<div class="weather-parameter-value">${decoded.temperature || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Wind</div>
<div class="weather-parameter-value">${decoded.wind || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Visibility</div>
<div class="weather-parameter-value">${decoded.visibility || 'N/A'}</div>
</div>
<div class="weather-parameter">
<div class="weather-parameter-label">Pressure</div>
<div class="weather-parameter-value">${decoded.pressure || 'N/A'}</div>
</div>
</div>
<div class="weather-summary">
<div class="weather-summary-text">${formatWeatherSummary(metar, decoded)}</div>
</div>
</div>
`;
} else {
currentWeatherContent.innerHTML = `
<div class="weather-airport">
<div class="weather-airport-title">No Weather Data</div>
<div class="weather-summary">
<div class="weather-summary-text">No weather data available for this route</div>
</div>
</div>
`;
}
}
// Format weather summary with proper text wrapping
function formatWeatherSummary(metar, decoded) {
const airportName = metar.icaoId || 'Unknown';
const timestamp = new Date().toLocaleString('en-US', {
timeZone: 'UTC',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: true
});
const wind = decoded.wind || 'No wind data';
const visibility = decoded.visibility || 'No visibility data';
const temperature = decoded.temperature || 'No temperature data';
const pressure = decoded.pressure || 'No pressure data';
return `${airportName}, report issued on ${timestamp} UTC. ${wind}. ${visibility}. ${temperature}. ${pressure}. No significant change expected.`;
}
// Enhanced route map with hover tooltips showing full airport names
function createEnhancedRouteMap(stations) {
console.log('🗺️ Creating enhanced route map for stations:', stations);
const routeMapContainer = document.querySelector('.route-map-container');