-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
656 lines (557 loc) · 24.5 KB
/
script.js
File metadata and controls
656 lines (557 loc) · 24.5 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
// Global variables
let currentCity = 'Mecca';
let currentCountry = 'Saudi Arabia';
let currentDate = new Date().toISOString().split('T')[0]; // Format: YYYY-MM-DD
let currentPrayerTimes = null;
let currentMonthlyData = null;
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth() + 1; // JavaScript months are 0-indexed
let currentNarrator = 'muslim'; // Default narrator for hadiths
let hadithsData = {
bukhari: [],
muslim: [],
tirmidhi: [],
'abu-dawud': []
};
let currentView = 'prayer-times'; // Default view
// DOM Elements
const loadingOverlay = document.getElementById('loading-overlay');
const loadingText = document.getElementById('loading-text');
const themeToggle = document.getElementById('theme-toggle');
const sunIcon = document.getElementById('sun-icon');
const moonIcon = document.getElementById('moon-icon');
const currentDateElement = document.getElementById('current-date');
const currentTimeElement = document.getElementById('current-time');
const selectedLocationElement = document.getElementById('selected-location');
const locationButton = document.getElementById('location-button');
const locationDropdown = document.getElementById('location-dropdown');
const cityInput = document.getElementById('city');
const countryInput = document.getElementById('country');
const applyLocationButton = document.getElementById('apply-location');
const popularLocationButtons = document.querySelectorAll('.popular-locations button');
const selectedDateElement = document.getElementById('selected-date');
const dateButton = document.getElementById('date-button');
const dateDropdown = document.getElementById('date-dropdown');
const datePicker = document.getElementById('date-picker');
const todayButton = document.getElementById('today-button');
const applyDateButton = document.getElementById('apply-date');
const islamicDateElement = document.getElementById('islamic-date');
const dailyPrayersElement = document.getElementById('daily-prayers');
const importantTimesElement = document.getElementById('important-times');
const dailyTab = document.getElementById('daily-tab');
const monthlyTab = document.getElementById('monthly-tab');
const monthlyView = document.getElementById('monthly-view');
const prevMonthButton = document.getElementById('prev-month');
const nextMonthButton = document.getElementById('next-month');
const monthYearElement = document.getElementById('month-year');
const monthlyTableBody = document.getElementById('monthly-tbody');
// Navigation elements
const prayerTimesLink = document.getElementById('prayer-times-link');
const hadithsLink = document.getElementById('hadiths-link');
const prayerTimesSection = document.getElementById('prayer-times-section');
const hadithsSection = document.getElementById('hadiths-section');
// Hadiths elements
const narratorTabs = document.querySelectorAll('.narrator-tab');
const hadithsList = document.getElementById('hadiths-list');
// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
initializeNavigation();
initializeDateAndTime();
initializeThemeToggle();
initializeLocationSelector();
initializeDateSelector();
initializeTabs();
initializeNarratorTabs();
loadPrayerTimes();
});
// Initialize navigation
function initializeNavigation() {
prayerTimesLink.addEventListener('click', (e) => {
e.preventDefault();
showView('prayer-times');
});
hadithsLink.addEventListener('click', (e) => {
e.preventDefault();
showView('hadiths');
});
}
// Show the selected view
function showView(view) {
currentView = view;
prayerTimesLink.classList.toggle('active', view === 'prayer-times');
hadithsLink.classList.toggle('active', view === 'hadiths');
// Show/hide sections
prayerTimesSection.classList.toggle('hidden', view !== 'prayer-times');
hadithsSection.classList.toggle('hidden', view !== 'hadiths');
// Load data for the selected view
if (view === 'prayer-times') {
// Prayer times are loaded on init
} else if (view === 'hadiths') {
loadHadiths(currentNarrator);
}
}
// Initialize date and time display
function initializeDateAndTime() {
updateDateTime();
// Update time every second
setInterval(updateDateTime, 1000);
}
// Update date and time display
function updateDateTime() {
const now = new Date();
// Format date: thursday, March 27, 2025
currentDateElement.textContent = now.toLocaleDateString('fr-FR', {
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric'
});
// Format time:
currentTimeElement.textContent = now.toLocaleTimeString('fr-FR', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
// Update current prayer highlight
if (currentPrayerTimes) {
highlightCurrentPrayer();
}
}
// Initialize theme
function initializeThemeToggle() {
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark');
sunIcon.classList.toggle('hidden');
moonIcon.classList.toggle('hidden');
});
}
// Initialize location select
function initializeLocationSelector() {
// Show/hide location dropdown
locationButton.addEventListener('click', () => {
locationDropdown.classList.toggle('hidden');
// Hide date dropdown if open
dateDropdown.classList.add('hidden');
});
// Handle popular location selection
popularLocationButtons.forEach(button => {
button.addEventListener('click', () => {
const city = button.dataset.city;
const country = button.dataset.country;
cityInput.value = city;
countryInput.value = country;
});
});
// Apply location button
applyLocationButton.addEventListener('click', () => {
currentCity = cityInput.value;
currentCountry = countryInput.value;
selectedLocationElement.textContent = `${currentCity}, ${currentCountry}`;
locationDropdown.classList.add('hidden');
loadPrayerTimes();
});
// Close dropdown when clicking outside
document.addEventListener('click', (event) => {
if (!locationButton.contains(event.target) && !locationDropdown.contains(event.target)) {
locationDropdown.classList.add('hidden');
}
});
}
// Initialize date selector
function initializeDateSelector() {
// Set initial date
datePicker.value = currentDate;
updateSelectedDateDisplay();
// Show/hide date dropdown
dateButton.addEventListener('click', () => {
dateDropdown.classList.toggle('hidden');
// Hide location dropdown if open
locationDropdown.classList.add('hidden');
});
// Today button
todayButton.addEventListener('click', () => {
const today = new Date().toISOString().split('T')[0];
datePicker.value = today;
});
// Apply date button
applyDateButton.addEventListener('click', () => {
currentDate = datePicker.value;
updateSelectedDateDisplay();
dateDropdown.classList.add('hidden');
loadPrayerTimes();
});
// Close when clicking outside
document.addEventListener('click', (event) => {
if (!dateButton.contains(event.target) && !dateDropdown.contains(event.target)) {
dateDropdown.classList.add('hidden');
}
});
}
// Update selected date display
function updateSelectedDateDisplay() {
const date = new Date(currentDate);
selectedDateElement.textContent = date.toLocaleDateString('fr-FR', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
}
// Initialize tabs
function initializeTabs() {
dailyTab.addEventListener('click', () => {
dailyTab.classList.add('active');
monthlyTab.classList.remove('active');
monthlyView.classList.add('hidden');
});
monthlyTab.addEventListener('click', () => {
monthlyTab.classList.add('active');
dailyTab.classList.remove('active');
monthlyView.classList.remove('hidden');
if (!currentMonthlyData) {
loadMonthlyData();
}
});
// Month navigation
prevMonthButton.addEventListener('click', () => {
if (currentMonth === 1) {
currentMonth = 12;
currentYear--;
} else {
currentMonth--;
}
updateMonthYearDisplay();
loadMonthlyData();
});
nextMonthButton.addEventListener('click', () => {
if (currentMonth === 12) {
currentMonth = 1;
currentYear++;
} else {
currentMonth++;
}
updateMonthYearDisplay();
loadMonthlyData();
});
// Initialize month/year display
updateMonthYearDisplay();
}
// Initialize narrator tabs for hadiths
function initializeNarratorTabs() {
narratorTabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs
narratorTabs.forEach(t => t.classList.remove('active'));
// Add active class to clicked tab
tab.classList.add('active');
// Update current narrator and load hadiths
currentNarrator = tab.dataset.narrator;
loadHadiths(currentNarrator);
});
});
}
// Update month/year display
function updateMonthYearDisplay() {
const date = new Date(currentYear, currentMonth - 1, 1);
monthYearElement.textContent = date.toLocaleDateString('en-US', {
month: 'long',
year: 'numeric'
});
}
// aply prayer times API
async function loadPrayerTimes() {
try {
showLoading('Loading prayer times...');
const url = `https://api.aladhan.com/v1/timingsByCity/${currentDate}?city=${encodeURIComponent(currentCity)}&country=${encodeURIComponent(currentCountry)}&method=2`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
currentPrayerTimes = data;
// Update UI with prayer times
updatePrayerTimesUI();
hideLoading();
} catch (error) {
console.error('Error loading prayer times:', error);
hideLoading();
alert('Failed to load prayer times. Please try again.');
}
}
// aply month prayer times from API
async function loadMonthlyData() {
try {
showLoading('Loading monthly data...');
const url = `https://api.aladhan.com/v1/calendarByCity/${currentYear}/${currentMonth}?city=${encodeURIComponent(currentCity)}&country=${encodeURIComponent(currentCountry)}&method=2`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
currentMonthlyData = data;
// Update UI with monthly data
updateMonthlyCalendarUI();
hideLoading();
} catch (error) {
console.error('Error loading monthly data:', error);
hideLoading();
alert('Failed to load monthly prayer times. Please try again.');
}
}
// aply hadiths for the selected narrator
async function loadHadiths(narrator) {
try {
// Simulate API call with mock data
await new Promise(resolve => setTimeout(resolve, 10));
// Load mock data based on narrator
hadithsData[narrator] = getMockHadithsData(narrator);
renderHadiths(hadithsData[narrator]);
hideLoading();
} catch (error) {
console.error('Error loading hadiths:', error);
hideLoading();
alert('Failed to load hadiths. Please try again.');
}
}
// Render hadiths to the UI
function renderHadiths(hadiths) {
hadithsList.innerHTML = '';
// Add each hadith to the list
hadiths.forEach(hadith => {
const hadithCard = document.createElement('div');
hadithCard.className = 'hadith-card';
hadithCard.innerHTML = `
<p class="hadith-text">"${hadith.text}"</p>
<p class="hadith-arabic">${hadith.arabic}</p>
<div class="hadith-footer">
<span class="hadith-narrator">Rapporté par ${hadith.narrator}</span>
<span class="hadith-source">Source: ${hadith.source}</span>
</div>
`;
hadithsList.appendChild(hadithCard);
});
}
// Get mock hadiths data based on narrator
function getMockHadithsData(narrator) {
const collections = {
'bukhari': {
source: 'Sahih Al-Bukhari',
hadiths: [
{
text: "Les actes ne valent que par leurs intentions. Chacun n'aura que selon son intention. Celui qui a émigré pour Allah et Son Messager, son émigration sera pour Allah et Son Messager. Et celui qui a émigré pour obtenir un bien mondain ou pour épouser une femme, son émigration sera pour ce vers quoi il a émigré.",
arabic: "إنما الأعمـال بالنيات، وإنما لكل امرئ ما نوى. فمن كانت هجرته إلى الله ورسوله فهجرته إلى الله ورسوله، ومن كانت هجرته لدنيا يصيبها أو امرأة ينكحها فهجرته إلى ما هاجر إليه.",
narrator: "Omar Ibn Al-Khattab",
source: "Sahih Al-Bukhari"
},
{
text: "Le Messager d'Allah a dit : « Le musulman est celui dont les musulmans sont à l'abri de sa langue et de sa main, et l'émigrant est celui qui délaisse ce qu'Allah a interdit. »",
arabic: "المسلم من سلم المسلمون من لسانه ويده، والمهاجر من هجر ما نهى الله عنه.",
narrator: "Abdullah Ibn Amr",
source: "Sahih Al-Bukhari"
},
{
text: "Quiconque croit en Allah et au Jour Dernier, qu'il dise du bien ou qu'il se taise. Quiconque croit en Allah et au Jour Dernier, qu'il honore son voisin. Quiconque croit en Allah et au Jour Dernier, qu'il honore son hôte.",
arabic: "من كان يؤمن بالله واليوم الآخر فليقل خيرا أو ليصمت، ومن كان يؤمن بالله واليوم الآخر فليكرم جاره، ومن كان يؤمن بالله واليوم الآخر فليكرم ضيفه.",
narrator: "Abu Hurayrah",
source: "Sahih Al-Bukhari"
}
]
},
'muslim': {
source: 'Sahih Muslim',
hadiths: [
{
text: "Celui qui suit un chemin à la recherche de la science, Allah lui facilite un chemin vers le Paradis.",
arabic: "من سلك طريقا يلتمس فيه علما سهل الله له به طريقا إلى الجنة.",
narrator: "Abu Hurayrah",
source: "Sahih Muslim"
},
{
text: "Le monde est une prison pour le croyant et un paradis pour le mécréant.",
arabic: "الدنيا سجن المؤمن وجنة الكافر.",
narrator: "Abu Hurayrah",
source: "Sahih Muslim"
},
{
text: "La bonté est un bon caractère, et le péché est ce qui agite ton âme et que tu n'aimerais pas que les gens découvrent.",
arabic: "البر حسن الخلق، والإثم ما حاك في نفسك وكرهت أن يطلع عليه الناس.",
narrator: "An-Nawwas Ibn Sam'an",
source: "Sahih Muslim"
}
]
},
'tirmidhi': {
source: 'Jami At-Tirmidhi',
hadiths: [
{
text: "Le croyant qui fréquente les gens et endure patiemment leurs torts est meilleur que celui qui ne les fréquente pas et n'endure pas patiemment leurs torts.",
arabic: "المؤمن الذي يخالط الناس ويصبر على أذاهم أعظم أجرا من المؤمن الذي لا يخالط الناس ولا يصبر على أذاهم.",
narrator: "Ibn Umar",
source: "Jami At-Tirmidhi"
},
{
text: "Crains Allah où que tu sois, fais suivre la mauvaise action par une bonne action qui l'effacera, et comporte-toi avec les gens de la meilleure façon.",
arabic: "اتق الله حيثما كنت، وأتبع السيئة الحسنة تمحها، وخالق الناس بخلق حسن.",
narrator: "Abu Dharr",
source: "Jami At-Tirmidhi"
},
{
text: "Celui qui ne remercie pas les gens ne remercie pas Allah.",
arabic: "من لا يشكر الناس لا يشكر الله.",
narrator: "Abu Hurayrah",
source: "Jami At-Tirmidhi"
}
]
},
'abu-dawud': {
source: 'Sunan Abu Dawud',
hadiths: [
{
text: "Celui qui aime pour Allah, déteste pour Allah, donne pour Allah et refuse pour Allah a parfait sa foi.",
arabic: "من أحب لله وأبغض لله وأعطى لله ومنع لله فقد استكمل الإيمان.",
narrator: "Abu Umamah",
source: "Sunan Abu Dawud"
},
{
text: "Celui qui appelle à la guidée aura une récompense similaire à celles de ceux qui le suivent, sans que leurs récompenses ne soient diminuées en rien.",
arabic: "من دعا إلى هدى كان له من الأجر مثل أجور من تبعه لا ينقص ذلك من أجورهم شيئا.",
narrator: "Abu Hurayrah",
source: "Sunan Abu Dawud"
},
{
text: "Celui qui cache un défaut d'un musulman, Allah cachera ses défauts dans ce monde et dans l'au-delà.",
arabic: "من ستر مسلما ستره الله في الدنيا والآخرة.",
narrator: "Abu Hurayrah",
source: "Sunan Abu Dawud"
}
]
}
};
return collections[narrator].hadiths;
}
function updatePrayerTimesUI() {
if (!currentPrayerTimes || !currentPrayerTimes.data) return;
const { timings, date } = currentPrayerTimes.data;
// Update daily prayers
updatePrayerTime('Fajr', timings.Fajr);
updatePrayerTime('Dhuhr', timings.Dhuhr);
updatePrayerTime('Asr', timings.Asr);
updatePrayerTime('Maghrib', timings.Maghrib);
updatePrayerTime('Isha', timings.Isha);
// Update important times
updatePrayerTime('Sunrise', timings.Sunrise, 'important-times');
updatePrayerTime('Sunset', timings.Sunset, 'important-times');
updatePrayerTime('Imsak', timings.Imsak, 'important-times');
updatePrayerTime('Iftar', timings.Maghrib, 'important-times');
updatePrayerTime('Midnight', timings.Midnight, 'important-times');
// Update Islamic date
islamicDateElement.querySelector('span').textContent = `${date.gregorian.date} | ${date.hijri.day} ${date.hijri.month.en} ${date.hijri.year}`;
// Highlight current prayer
highlightCurrentPrayer();
}
// Update a specific prayer time in the UI
function updatePrayerTime(name, time, container = 'daily-prayers') {
const containerElement = document.getElementById(container);
const prayerElement = containerElement.querySelector(`[data-prayer="${name}"]`);
if (prayerElement) {
const timeElement = prayerElement.querySelector('.prayer-time');
timeElement.textContent = formatTime(time);
}
}
// Format time API (HH:MM format)
function formatTime(timeString) {
// Remove any (GMT+X) suffix if present
return timeString.substring(0, 5);
}
// Highlight the current prayer
function highlightCurrentPrayer() {
if (!currentPrayerTimes || !currentPrayerTimes.data) return;
const { timings } = currentPrayerTimes.data;
const now = new Date();
const currentTime = now.getHours() * 60 + now.getMinutes();
const prayers = [
{ name: 'Fajr', time: convertToMinutes(timings.Fajr) },
{ name: 'Dhuhr', time: convertToMinutes(timings.Dhuhr) },
{ name: 'Asr', time: convertToMinutes(timings.Asr) },
{ name: 'Maghrib', time: convertToMinutes(timings.Maghrib) },
{ name: 'Isha', time: convertToMinutes(timings.Isha) }
];
// Sort prayers by time
prayers.sort((a, b) => a.time - b.time);
// Remove active class from all prayers
const prayerItems = dailyPrayersElement.querySelectorAll('.prayer-item');
prayerItems.forEach(item => item.classList.remove('active'));
// Find the next prayer
let currentPrayer = null;
for (const prayer of prayers) {
if (currentTime < prayer.time) {
currentPrayer = prayer.name;
break;
}
}
// If all prayers have passed, the next prayer is the first one tomorrow
if (!currentPrayer) {
currentPrayer = prayers[0].name;
}
// Add active class to current prayer
const currentPrayerElement = dailyPrayersElement.querySelector(`[data-prayer="${currentPrayer}"]`);
if (currentPrayerElement) {
currentPrayerElement.classList.add('active');
}
}
function convertToMinutes(timeString) {
const [hours, minutes] = timeString.substring(0, 5).split(':').map(Number);
return hours * 60 + minutes;
}
// Update monthly calendar UI
function updateMonthlyCalendarUI() {
if (!currentMonthlyData || !currentMonthlyData.data) return;
const { data } = currentMonthlyData;
const today = new Date();
const isCurrentMonth = today.getMonth() + 1 === currentMonth && today.getFullYear() === currentYear;
const todayDate = today.getDate();
// Clear table body
monthlyTableBody.innerHTML = '';
// Add rows for each day
data.forEach(day => {
const date = new Date(day.date.gregorian.date);
const dayOfMonth = date.getDate();
const isToday = isCurrentMonth && dayOfMonth === todayDate;
const row = document.createElement('tr');
if (isToday) {
row.classList.add('today');
}
const dateCell = document.createElement('td');
dateCell.classList.add('date-cell');
dateCell.innerHTML = `
<div>${day.date.gregorian.day}</div>
<div class="hijri-date">${day.date.hijri.day} ${day.date.hijri.month.en}</div>
`;
row.appendChild(dateCell);
// Prayer time
addTimeCell(row, day.timings.Fajr);
addTimeCell(row, day.timings.Sunrise);
addTimeCell(row, day.timings.Dhuhr);
addTimeCell(row, day.timings.Asr);
addTimeCell(row, day.timings.Maghrib);
addTimeCell(row, day.timings.Isha);
addTimeCell(row, day.timings.Imsak);
addTimeCell(row, day.timings.Midnight);
monthlyTableBody.appendChild(row);
});
}
// Add a time to a table row
function addTimeCell(row, time) {
const cell = document.createElement('td');
cell.textContent = formatTime(time);
row.appendChild(cell);
}
// Show loading overlay
function showLoading(message = 'Loading...') {
loadingText.textContent = message;
loadingOverlay.style.display = 'flex';
}
// Hide loading overlay
function hideLoading() {
loadingOverlay.style.display = 'none';
}