-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2129 lines (1843 loc) · 80.2 KB
/
script.js
File metadata and controls
2129 lines (1843 loc) · 80.2 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
// DOM Elements
const aqiCircle = document.getElementById('aqiCircle');
const aqiNumber = document.getElementById('aqiNumber');
const aqiCategory = document.getElementById('aqiCategory');
const updatedTime = document.getElementById('updatedTime');
const detailedInfo = document.getElementById('detailedInfo');
const advicePlaceholder = document.getElementById('advicePlaceholder');
const adviceContent = document.getElementById('adviceContent');
const characterImage = document.getElementById('characterImage');
const aqiCharacter = document.getElementById('aqiCharacter');
// Mobile menu elements
const mobileMenu = document.getElementById('mobileMenu');
const navCenter = document.getElementById('navCenter');
// Back button element
const backButton = document.getElementById('backButton');
// Account dropdown elements
const accountTrigger = document.getElementById('accountTrigger');
const accountDropdown = document.getElementById('accountDropdown');
const accountText = document.getElementById('accountText');
// Notification dropdown elements
const notificationBell = document.getElementById('notificationBell');
const notificationDropdown = document.getElementById('notificationDropdown');
// Detail elements
const detailHumidity = document.getElementById('detailHumidity');
const detailTemp = document.getElementById('detailTemp');
const detailWind = document.getElementById('detailWind');
const detailPm25 = document.getElementById('detailPm25');
const detailPm10 = document.getElementById('detailPm10');
// Weather elements
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('windSpeed');
const uvIndex = document.getElementById('uvIndex');
const pm25 = document.getElementById('pm25');
const pm10 = document.getElementById('pm10');
// Toggle mobile menu
if (mobileMenu && navCenter) {
mobileMenu.addEventListener('click', () => {
navCenter.classList.toggle('active');
mobileMenu.innerHTML = navCenter.classList.contains('active') ?
'<i class="fas fa-times"></i>' : '<i class="fas fa-bars"></i>';
});
}
// Close mobile menu when clicking outside
document.addEventListener('click', (event) => {
if (navCenter && mobileMenu && navCenter.classList.contains('active')) {
if (!navCenter.contains(event.target) && !mobileMenu.contains(event.target)) {
navCenter.classList.remove('active');
mobileMenu.innerHTML = '<i class="fas fa-bars"></i>';
}
}
});
// Account dropdown functionality
if (accountTrigger && accountDropdown) {
accountTrigger.addEventListener('click', function (e) {
e.preventDefault();
accountDropdown.classList.toggle('show');
});
// Close dropdown when clicking outside
document.addEventListener('click', function (e) {
if (!accountTrigger.contains(e.target) && !accountDropdown.contains(e.target)) {
accountDropdown.classList.remove('show');
}
});
// Initialize account dropdown
initializeAccountDropdown();
}
// Notification dropdown functionality
if (notificationBell && notificationDropdown) {
notificationBell.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
// Toggle the dropdown
notificationDropdown.classList.toggle('show');
// Add a slight delay before focusing to ensure the dropdown is visible
if (notificationDropdown.classList.contains('show')) {
setTimeout(() => {
notificationDropdown.focus();
}, 100);
}
});
// Close dropdown when clicking outside
document.addEventListener('click', function (e) {
if (notificationDropdown.classList.contains('show') &&
!notificationBell.contains(e.target) &&
!notificationDropdown.contains(e.target)) {
notificationDropdown.classList.remove('show');
}
});
// Close dropdown when pressing Escape key
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && notificationDropdown.classList.contains('show')) {
notificationDropdown.classList.remove('show');
notificationBell.focus();
}
});
// Prevent dropdown from closing when clicking inside it
notificationDropdown.addEventListener('click', function (e) {
e.stopPropagation();
});
}
// Google Maps functionality
function openGoogleMaps() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const googleMapsUrl = `https://www.google.com/maps?q=${lat},${lng}`;
window.open(googleMapsUrl, '_blank');
},
function (error) {
// If geolocation fails, open Google Maps without location
console.error('Geolocation error:', error);
window.open('https://www.google.com/maps', '_blank');
}
);
} else {
// If geolocation is not supported, open Google Maps without location
window.open('https://www.google.com/maps', '_blank');
}
}
// Add event listener for Google Maps link
document.addEventListener('DOMContentLoaded', function () {
const googleMapsLink = document.getElementById('googleMapsLink');
if (googleMapsLink) {
googleMapsLink.addEventListener('click', function (e) {
e.preventDefault();
openGoogleMaps();
});
}
});
// Initialize account dropdown based on login status
async function initializeAccountDropdown() {
const token = localStorage.getItem('authToken');
if (token) {
// User is logged in
try {
const response = await fetch('/api/user', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const userData = await response.json();
accountText.textContent = userData.name;
// Populate dropdown with logged-in content
accountDropdown.innerHTML = `
<div class="user-info-dropdown">
<div class="user-avatar-dropdown">
<img src="${userData.avatar_path ? userData.avatar_path : 'https://ui-avatars.com/api/?name=' + encodeURIComponent(userData.name) + '&background=random'}" alt="Avatar">
</div>
<div class="user-details-dropdown">
<div class="user-name-dropdown">${userData.name}</div>
<div class="user-email-dropdown">${userData.email}</div>
</div>
</div>
<div class="dropdown-divider"></div>
<a href="account.html" class="dropdown-item">
<i class="fas fa-user"></i> Account Dashboard
</a>
<a href="settings.html" class="dropdown-item">
<i class="fas fa-cog"></i> Settings
</a>
<div class="dropdown-divider"></div>
<a href="#" id="logoutButton" class="dropdown-item">
<i class="fas fa-sign-out-alt"></i> Logout
</a>
`;
// Add logout event listener
document.getElementById('logoutButton').addEventListener('click', logout);
} else {
// Token is invalid, clear it and show logged-out state
localStorage.removeItem('authToken');
showLoggedOutDropdown();
}
} catch (error) {
console.error('Error checking login status:', error);
showLoggedOutDropdown();
}
} else {
// User is not logged in
showLoggedOutDropdown();
}
}
// Show logged-out dropdown
function showLoggedOutDropdown() {
accountText.textContent = 'Account';
accountDropdown.innerHTML = `
<a href="auth.html" class="dropdown-item">
<i class="fas fa-sign-in-alt"></i> Login
</a>
<a href="auth.html" class="dropdown-item">
<i class="fas fa-user-plus"></i> Signup
</a>
`;
}
// Logout function - redirect to index.html
async function logout() {
const token = localStorage.getItem('authToken');
if (token) {
try {
await fetch('/api/auth/logout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
}
});
} catch (error) {
console.error('Error during logout:', error);
}
}
localStorage.removeItem('authToken');
// Redirect to index.html instead of just updating the dropdown
window.location.href = 'index.html';
}
// Apply user settings on page load
async function applyUserSettings() {
const token = localStorage.getItem('authToken');
if (!token) return;
try {
const response = await fetch('/api/preferences', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
const preferences = await response.json();
applySettings(preferences);
}
} catch (error) {
console.error('Error applying user settings:', error);
}
}
// Apply settings to the page
function applySettings(preferences) {
if (!preferences) return;
// Apply theme
if (preferences.theme) {
document.body.className = document.body.className.replace(/theme-\w+/g, '');
document.body.classList.add(`theme-${preferences.theme}`);
}
// Apply temperature unit (this would affect how temperatures are displayed)
if (preferences.temperature_unit) {
// In a full implementation, you would update all temperature displays
// For now, we'll just log it
console.log('Temperature unit set to:', preferences.temperature_unit);
}
// Apply AQI scale
if (preferences.aqi_scale) {
// In a full implementation, you would update how AQI is calculated/displayed
console.log('AQI scale set to:', preferences.aqi_scale);
}
// Load default city if set
if (preferences.default_city) {
// In a full implementation, you would load data for this city
console.log('Default city set to:', preferences.default_city);
}
// Apply display preferences
if (preferences.show_24hr_forecast !== undefined) {
// Toggle 24-hour forecast visibility
console.log('24-hour forecast visibility:', preferences.show_24hr_forecast);
}
if (preferences.show_week_prediction !== undefined) {
// Toggle week prediction visibility
console.log('Week prediction visibility:', preferences.show_week_prediction);
}
if (preferences.show_health_advice !== undefined) {
// Toggle health advice visibility
console.log('Health advice visibility:', preferences.show_health_advice);
}
if (preferences.show_global_compare !== undefined) {
// Toggle global comparison visibility
console.log('Global comparison visibility:', preferences.show_global_compare);
}
}
// Call applyUserSettings when the page loads
document.addEventListener('DOMContentLoaded', function () {
applyUserSettings();
});
// Back button functionality
if (backButton) {
backButton.addEventListener('click', () => {
hideDetailedInfo();
isShowingDetails = false;
});
}
// AQI data and categories
const aqiCategories = {
0: { level: 'Good', color: '#00e400', textColor: '#000' },
51: { level: 'Moderate', color: '#ffff00', textColor: '#000' },
101: { level: 'Unhealthy for Sensitive Groups', color: '#ff7e00', textColor: '#fff' },
151: { level: 'Unhealthy', color: '#ff0000', textColor: '#fff' },
201: { level: 'Very Unhealthy', color: '#8f3f97', textColor: '#fff' },
301: { level: 'Hazardous', color: '#7e0023', textColor: '#fff' }
};
// Get AQI category based on value
function getAQICategory(aqi) {
let category = aqiCategories[0];
for (const level in aqiCategories) {
if (aqi >= level) {
category = aqiCategories[level];
}
}
return category;
}
// Update AQI circle styling
function updateAQICircle(aqi) {
const category = getAQICategory(aqi);
aqiCircle.style.background = `radial-gradient(circle at center, ${category.color} 0%, ${darkenColor(category.color, 30)} 100%)`;
aqiCircle.style.boxShadow = `0 0 30px ${category.color}`;
aqiNumber.textContent = aqi;
aqiCategory.textContent = category.level;
aqiCategory.style.color = category.color; // Match category text color to AQI color
// Update character image based on AQI
updateCharacterImage(aqi);
}
// Darken a hex color
function darkenColor(color, percent) {
let R = parseInt(color.substring(1, 3), 16);
let G = parseInt(color.substring(3, 5), 16);
let B = parseInt(color.substring(5, 7), 16);
R = Math.floor(R * (100 - percent) / 100);
G = Math.floor(G * (100 - percent) / 100);
B = Math.floor(B * (100 - percent) / 100);
return `#${R.toString(16).padStart(2, '0')}${G.toString(16).padStart(2, '0')}${B.toString(16).padStart(2, '0')}`;
}
// Update character image based on AQI level
function updateCharacterImage(aqi) {
let imageSrc = '';
if (aqi <= 50) {
// Good - gd_char.png
imageSrc = 'gd_char.png';
} else if (aqi <= 100) {
// Moderate - md_char.png
imageSrc = 'md_char.png';
} else if (aqi <= 150) {
// Unhealthy for Sensitive Groups - SV_char.png
imageSrc = 'SV_char.png';
} else {
// Unhealthy, Very Unhealthy, Hazardous - haz_char.png
imageSrc = 'haz_char.png';
}
// Set the image source and show the container
characterImage.src = imageSrc;
characterImage.style.display = 'block';
aqiCharacter.style.display = 'block';
// Debug: Log to console to verify the image is being set
console.log('Setting character image to:', imageSrc);
}
// Show detailed info
function showDetailedInfo(data) {
// Populate detailed info
detailHumidity.textContent = `${data.humidity || '--'}%`;
detailTemp.textContent = `${data.temperature || '--'}°C`;
detailWind.textContent = `${data.wind_speed || '--'} km/h`;
detailPm25.textContent = `${data.pm25 || '--'} µg/m³`;
detailPm10.textContent = `${data.pm10 || '--'} µg/m³`;
// Populate weather info
humidity.textContent = `${data.humidity || '--'}%`;
windSpeed.textContent = `${data.wind_speed || '--'} km/h`;
uvIndex.textContent = data.uv_index || '--';
pm25.textContent = `${data.pm25 || '--'} µg/m³`;
pm10.textContent = `${data.pm10 || '--'} µg/m³`;
// Hide main info and show detailed info
document.querySelector('.main-info').style.display = 'none';
document.querySelector('.pm-values').style.display = 'none';
detailedInfo.style.display = 'grid';
}
// Hide detailed info
function hideDetailedInfo() {
document.querySelector('.main-info').style.display = 'flex';
document.querySelector('.pm-values').style.display = 'flex';
detailedInfo.style.display = 'none';
}
// Generate advice based on AQI
function generateAdvice(aqi) {
let advice = '';
if (aqi <= 50) {
advice = "Air quality is good. Safe for outdoor activities.";
} else if (aqi <= 100) {
advice = "Moderate air quality. Sensitive groups stay cautious.";
} else if (aqi <= 200) {
advice = "Unhealthy air. Reduce outdoor time. Wear a mask.";
} else if (aqi <= 300) {
advice = "Very unhealthy. Avoid going outside.";
} else {
advice = "Hazardous air. Stay indoors and use air purifiers.";
}
return advice;
}
// Update main page data
function updateMainPageData(data) {
// Update PM values
if (pm25 && data.pm25) {
pm25.textContent = `${data.pm25} µg/m³`;
}
if (pm10 && data.pm10) {
pm10.textContent = `${data.pm10} µg/m³`;
}
// Update temperature
const temperatureElement = document.querySelector('.temperature');
if (temperatureElement && data.temperature) {
temperatureElement.textContent = `${data.temperature}°C`;
}
// Update weather icon based on conditions
const weatherIcon = document.getElementById('weatherIcon');
if (weatherIcon) {
// Remove existing animation classes
weatherIcon.classList.remove('sunny', 'cloudy', 'rainy', 'snowy');
// Determine weather condition based on data
// For now, we'll use a simple approach based on temperature and precipitation
// In a real implementation, you would use actual weather condition data
let condition = 'sunny'; // default
if (data.temperature < 0) {
condition = 'snowy';
} else if (data.humidity > 80) {
condition = 'rainy';
} else if (data.humidity > 60) {
condition = 'cloudy';
}
// Apply appropriate animation class
weatherIcon.classList.add(condition);
}
// Update other weather info
if (humidity && data.humidity) {
humidity.textContent = `${data.humidity}%`;
}
if (windSpeed && data.wind_speed) {
windSpeed.textContent = `${data.wind_speed} km/h`;
}
if (uvIndex && data.uv_index) {
uvIndex.textContent = data.uv_index;
}
}
// Show advice after delay
function showAdvice(aqi) {
// Show placeholder
advicePlaceholder.style.display = 'flex';
adviceContent.style.display = 'none';
// After 1 second, show advice
setTimeout(() => {
advicePlaceholder.style.display = 'none';
adviceContent.textContent = generateAdvice(aqi);
adviceContent.style.display = 'block';
}, 1000);
}
// Find closest city from coordinates
function findClosestCity(lat, lon, cities) {
// Coordinates for cities in our dataset
const cityCoords = {
'delhi': { lat: 28.7041, lon: 77.1025 },
'mumbai': { lat: 19.0760, lon: 72.8777 },
'noida': { lat: 28.5355, lon: 77.3910 },
'lucknow': { lat: 26.8467, lon: 80.9462 },
'kolkata': { lat: 22.5726, lon: 88.3639 },
'bangalore': { lat: 12.9716, lon: 77.5946 },
'muzaffarnagar': { lat: 29.4709, lon: 77.7036 }
};
let closestCity = 'delhi';
let minDistance = Infinity;
for (const city in cityCoords) {
const cityLat = cityCoords[city].lat;
const cityLon = cityCoords[city].lon;
// Calculate distance using Haversine formula
const R = 6371; // Earth radius in km
const dLat = (cityLat - lat) * Math.PI / 180;
const dLon = (cityLon - lon) * Math.PI / 180;
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat * Math.PI / 180) * Math.cos(cityLat * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;
if (distance < minDistance) {
minDistance = distance;
closestCity = city;
}
}
return closestCity;
}
// Get user location
function getUserLocation() {
return new Promise((resolve, reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve({
lat: position.coords.latitude,
lon: position.coords.longitude
});
},
(error) => {
console.log('Location access denied or unavailable, using default location');
resolve(null);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 300000
}
);
} else {
console.log('Geolocation is not supported by this browser');
resolve(null);
}
});
}
// Fetch AQI data
async function fetchAQIData() {
try {
const response = await fetch('/api/aqi');
const jsonData = await response.json();
const dataArray = Object.values(jsonData.cities);
// Filter out cities with errors
const validCities = dataArray.filter(city => !city.error);
console.log('All cities from API:', Object.keys(jsonData.cities));
console.log('Valid cities:', validCities.map(city => ({ city: city.city, aqi: city.aqi })));
// Try to get user location
const location = await getUserLocation();
let selectedCityData;
if (location) {
// Find closest city
const closestCity = findClosestCity(location.lat, location.lon, validCities);
selectedCityData = validCities.find(city => city.city === closestCity);
console.log('Location-based selection:', selectedCityData ? selectedCityData.city : 'None');
} else {
// First try to find Muzaffarnagar specifically
selectedCityData = validCities.find(city => {
return city.city && city.city.toLowerCase() === 'muzaffarnagar';
});
// If Muzaffarnagar not found, try variations
if (!selectedCityData) {
selectedCityData = validCities.find(city => {
return city.city && city.city.toLowerCase().includes('muzaffarnagar');
});
}
// If still not found, use first valid city
if (!selectedCityData) {
selectedCityData = validCities[0];
console.log('Muzaffarnagar not found, using first valid city:', selectedCityData ? selectedCityData.city : 'None');
} else {
console.log('Successfully found Muzaffarnagar:', selectedCityData.city, 'with AQI:', selectedCityData.aqi);
}
}
// If still no city found, use first valid city
if (!selectedCityData) {
selectedCityData = validCities[0];
}
// Make sure we have valid city data before proceeding
if (!selectedCityData) {
throw new Error('No valid city data available');
}
// Map the data to expected structure
const data = {
aqi: selectedCityData.aqi,
pm25: selectedCityData.pm25,
pm10: selectedCityData.pm10,
humidity: 85, // Static realistic humidity value
temperature: selectedCityData.temp,
wind_speed: '8.5', // Static realistic wind speed
uv_index: 5, // Static realistic UV index
time: selectedCityData.time || new Date().toISOString(),
city: selectedCityData.city
};
console.log('Final selected city data:', data);
// Update location info
if (data.city) {
const cityName = data.city.charAt(0).toUpperCase() + data.city.slice(1).replace(/-/g, ' ');
document.getElementById('locationName').textContent = `${cityName}, India`;
} else {
document.getElementById('locationName').textContent = 'Live Data, India';
};
// Update UI with fetched data
const aqi = data.aqi || 0;
updateAQICircle(aqi);
updateAirInsightWithAQI(aqi);
updateCharacterImage(aqi);
// Update main page data
updateMainPageData(data);
// Update time
const updateTime = '2'; // Default to 2 minutes
updatedTime.textContent = `Updated ${updateTime} mins ago`;
document.getElementById('updateTime').textContent = `${updateTime} mins ago`;
document.getElementById('localTime').textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
// Show advice
showAdvice(aqi);
// Return data for detailed view
return data;
} catch (error) {
console.error('Error fetching AQI data:', error);
// Use fallback data
const fallbackData = {
aqi: 42,
humidity: 85, // Static realistic humidity value
temperature: 24,
wind_speed: '8.5', // Static realistic wind speed
uv_index: 5, // Static realistic UV index
pm25: 12,
pm10: 24,
time: '2023-06-15T14:25:00Z',
city: 'Default'
};
// Update location info
document.getElementById('locationName').textContent = 'Default Location';
document.getElementById('updateTime').textContent = '2 mins ago';
document.getElementById('localTime').textContent = '14:25';
updateAQICircle(fallbackData.aqi);
updateAirInsightWithAQI(fallbackData.aqi);
updateMainPageData(fallbackData);
updatedTime.textContent = 'Updated 2 mins ago';
showAdvice(fallbackData.aqi);
updateCharacterImage(fallbackData.aqi);
return fallbackData;
}
}
// Handle circle click
let isShowingDetails = false;
aqiCircle.addEventListener('click', () => {
// Add rotation animation
aqiCircle.style.animation = 'rotateCircle 0.8s cubic-bezier(0.4, 0.1, 0.2, 1) forwards';
// After rotation, toggle detailed view
setTimeout(() => {
if (!isShowingDetails) {
fetchAQIData().then(data => {
showDetailedInfo(data);
});
} else {
hideDetailedInfo();
}
isShowingDetails = !isShowingDetails;
// Reset animation
aqiCircle.style.animation = '';
}, 800);
});
// Initialize
document.addEventListener('DOMContentLoaded', () => {
// Fade in body
document.body.style.opacity = '1';
// Fetch initial data
fetchAQIData();
});
// Handle window resize
window.addEventListener('resize', () => {
// Close mobile menu on resize if open
if (navCenter && navCenter.classList.contains('active')) {
navCenter.classList.remove('active');
if (mobileMenu) {
mobileMenu.innerHTML = '<i class="fas fa-bars"></i>';
}
}
// Re-apply animations on resize if needed
});
// Today's Air Insight Card functionality
const airInsightCard = document.getElementById('airInsightCard');
const cardHeader = document.getElementById('cardHeader');
const cardContent = document.getElementById('cardContent');
const shortMessage = document.getElementById('shortMessage');
const fullMessage = document.getElementById('fullMessage');
const professionalAdvice = document.getElementById('professionalAdvice');
const insightTimestamp = document.getElementById('insightTimestamp');
// AQI-based content for the card
const aqiInsightContent = {
good: {
short: "Air quality is great today! 😌✨",
full: "This air feels amazing today 😌✨ Perfect for outdoor activities like jogging, cycling, or having a picnic in the park.",
advice: "Even though the air quality is excellent, it's always good to stay hydrated and protect your skin from UV exposure during extended outdoor activities.",
bgColor: "good"
},
moderate: {
short: "Air is okay today — slightly dusty 🤏🌫️",
full: "Air quality is acceptable but there may be a risk for some people, particularly those who are unusually sensitive.",
advice: "Unusually sensitive people should consider limiting prolonged outdoor exertion. Otherwise, general population can enjoy outdoor activities.",
bgColor: "moderate"
},
unhealthySensitive: {
short: "Air's a bit rough today, especially for kids & elderly 😕",
full: "Members of sensitive groups may experience health effects. The general public is less likely to be affected.",
advice: "Children, elderly, and people with respiratory disease should limit prolonged outdoor exertion. Everyone else can continue normal activities.",
bgColor: "unhealthy-sensitive"
},
unhealthy: {
short: "The air isn't friendly today 😷",
full: "Everyone may begin to experience health effects; members of sensitive groups may experience more serious health effects.",
advice: "Active children and adults, and people with respiratory disease should avoid prolonged outdoor exertion. General population should limit outdoor activities.",
bgColor: "unhealthy"
},
veryUnhealthy: {
short: "This is concerning. Please stay indoors ⚠️",
full: "Health alert: everyone may experience more serious health effects.",
advice: "Avoid all outdoor exertion. Stay indoors and keep activity levels low. Keep windows closed and use air purifiers if available.",
bgColor: "very-unhealthy"
},
hazardous: {
short: "Extremely hazardous conditions 🚨",
full: "Health warnings of emergency conditions. The entire population is more likely to be affected.",
advice: "Everyone should avoid all physical outdoor activities. Stay indoors and keep windows closed. Use air purifiers and masks if needed.",
bgColor: "hazardous"
}
};
// Update the card content based on AQI
function updateAirInsightCard(aqi) {
let content;
if (aqi <= 50) {
content = aqiInsightContent.good;
} else if (aqi <= 100) {
content = aqiInsightContent.moderate;
} else if (aqi <= 150) {
content = aqiInsightContent.unhealthySensitive;
} else if (aqi <= 200) {
content = aqiInsightContent.unhealthy;
} else if (aqi <= 300) {
content = aqiInsightContent.veryUnhealthy;
} else {
content = aqiInsightContent.hazardous;
}
// Update card content
shortMessage.textContent = content.short;
fullMessage.textContent = content.full;
professionalAdvice.innerHTML = `<strong>Professional Advice:</strong> ${content.advice}`;
// Update card background class
airInsightCard.className = 'air-insight-card';
if (content.bgColor) {
airInsightCard.classList.add(content.bgColor);
}
}
// Toggle card expansion
airInsightCard.addEventListener('click', () => {
cardContent.classList.toggle('expanded');
// Rotate card slightly for visual effect
airInsightCard.style.transform = cardContent.classList.contains('expanded') ?
'rotate(0.5deg) scale(1.01)' : 'rotate(0deg) scale(1)';
});
// Update the card when AQI data is fetched
function updateAirInsightWithAQI(aqi) {
updateAirInsightCard(aqi);
// Update timestamp
insightTimestamp.textContent = 'Updated 1 min ago';
}
// Expose function to be called when AQI updates
window.updateAirInsightWithAQI = updateAirInsightWithAQI;
// Today's Weather Section Implementation
(function () {
// Namespaced function to initialize the weather section
window.weatherSectionInit = function () {
const weatherSection = document.getElementById('weather-section');
if (!weatherSection) {
console.warn('Weather section container not found');
return;
}
// Create the weather section HTML structure
weatherSection.innerHTML = `
<div class="weather-section-header">
<h2 class="weather-section-title">Today's Weather</h2>
<div class="weather-section-toggle">
<button class="weather-section-toggle-btn active" data-period="today">Today</button>
<button class="weather-section-toggle-btn" data-period="tomorrow">Tomorrow</button>
</div>
</div>
<div class="weather-section-content">
<div class="weather-section-trend">
<div class="weather-section-trend-line"></div>
<div class="weather-section-trend-points"></div>
</div>
<div class="weather-section-scroll-container">
<div class="weather-section-scroll-wrapper" id="weatherCardsContainer">
<!-- Weather cards will be dynamically inserted here -->
</div>
</div>
</div>
`;
// Load weather data and render cards
loadWeatherData();
// Add event listeners for toggle buttons
const toggleButtons = weatherSection.querySelectorAll('.weather-section-toggle-btn');
toggleButtons.forEach(button => {
button.addEventListener('click', function () {
// Update active button
toggleButtons.forEach(btn => btn.classList.remove('active'));
this.classList.add('active');
// In a real implementation, you would load different data based on the selected period
// For now, we'll just reload the same data
loadWeatherData();
});
});
};
// Function to load weather data (in a real app, this would fetch from an API)
function loadWeatherData() {
// For demonstration purposes, we'll use dummy data
// Fetch real forecast data from our local API
fetch('/api/aqi')
.then(response => response.json())
.then(data => {
// Process the real data
const forecastData = [];
const now = new Date();
// Generate 24 hours of forecast data based on current conditions
for (let i = 0; i < 24; i++) {
const hour = new Date(now);
hour.setHours(now.getHours() + i);
// Use the current city's data as base and add some variation
const currentCity = Object.keys(data.cities).find(key =>
data.cities[key] && !data.cities[key].error
);
if (currentCity && data.cities[currentCity]) {
const current = data.cities[currentCity];
const aqiVariation = Math.floor(current.aqi + (Math.random() * 40 - 20)); // ±20 variation
const tempVariation = current.temp ? Math.floor(current.temp + (Math.random() * 5 - 2.5)) : 25; // ±2.5 variation
forecastData.push({
time: hour,
temperature: tempVariation,
precipitation: Math.floor(Math.random() * 30), // Random precipitation
humidity: Math.floor(40 + Math.random() * 40), // 40-80%
windSpeed: (Math.random() * 15).toFixed(1), // 0-15 km/h
aqi: Math.max(0, aqiVariation), // Ensure positive AQI
condition: getWeatherCondition(tempVariation, Math.random() * 100)
});
}
}
renderWeatherCards(forecastData);
renderTrendLine(forecastData);
})
.catch(error => {
console.error('Error fetching weather data:', error);
// Fallback to dummy data if API fetch fails
const forecastData = generateDummyForecastData();
renderWeatherCards(forecastData);
renderTrendLine(forecastData);
});
// Using dummy data for now
const forecastData = generateDummyForecastData();
renderWeatherCards(forecastData);
renderTrendLine(forecastData);
}
// Function to convert text condition to our format
function getWeatherConditionFromText(condition) {
switch (condition) {
case 'sunny':
case 'clear':
return 'sunny';
case 'cloudy':
case 'partly-cloudy':
return 'cloudy';
case 'rainy':
case 'rain':
return 'rainy';
default:
return 'sunny';
}
}
// Function to generate dummy forecast data
function generateDummyForecastData() {
const hours = [];
const now = new Date();
for (let i = 0; i < 24; i++) {
const hour = new Date(now);
hour.setHours(now.getHours() + i);
// Generate realistic weather data
const temp = Math.floor(20 + 10 * Math.sin((i - 6) * Math.PI / 12)); // Temperature curve
const precipitation = Math.floor(Math.random() * 30); // 0-30% chance of precipitation
const humidity = Math.floor(40 + Math.random() * 40); // 40-80% humidity
const windSpeed = (Math.random() * 15).toFixed(1); // 0-15 km/h wind
const aqi = Math.floor(30 + Math.random() * 120); // AQI between 30-150
hours.push({
time: hour,
temperature: temp,
precipitation: precipitation,
humidity: humidity,
windSpeed: windSpeed,
aqi: aqi,
condition: getWeatherCondition(temp, precipitation)