-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
775 lines (693 loc) · 27.5 KB
/
script.js
File metadata and controls
775 lines (693 loc) · 27.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
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
function toggleSemesters(course) {
var semesterContainer = document.getElementById("semesters");
if (
semesterContainer.style.display === "none" ||
semesterContainer.style.display === ""
) {
semesterContainer.style.display = "block";
} else {
semesterContainer.style.display = "none";
}
}
// Intro animation - dots blend rapidly then form solid text
function setupIntroAnimation() {
const overlay = document.getElementById('intro-overlay');
const mainContent = document.getElementById('main-content');
if (!overlay || !mainContent) return;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.position = 'absolute';
canvas.style.top = '0';
canvas.style.left = '0';
canvas.style.width = '100%';
canvas.style.height = '100%';
overlay.appendChild(canvas);
// Create text shape for particles to form
const textCanvas = document.createElement('canvas');
const textCtx = textCanvas.getContext('2d');
textCanvas.width = canvas.width;
textCanvas.height = canvas.height;
// Draw text to get pixel data - increased size and moved up 10%
const fontSize = Math.min(canvas.width * 0.25, 300);
const verticalOffset = canvas.height * 0.4; // 10% higher than center (50% - 10% = 40%)
textCtx.font = `bold italic ${fontSize}px Roboto, sans-serif`;
textCtx.fillStyle = 'white';
textCtx.textAlign = 'center';
textCtx.textBaseline = 'middle';
textCtx.fillText('dumbAF', canvas.width / 2, verticalOffset);
// Get pixels where text exists
const imageData = textCtx.getImageData(0, 0, textCanvas.width, textCanvas.height);
const textPixels = [];
// Sample pixels from text (every pixel for maximum density)
for (let y = 0; y < imageData.height; y += 1) {
for (let x = 0; x < imageData.width; x += 1) {
const index = (y * imageData.width + x) * 4;
if (imageData.data[index + 3] > 128) { // If pixel is part of text
textPixels.push({ x, y });
}
}
}
// Create particles with truly random distribution
const particles = [];
const particleCount = Math.min(textPixels.length, 5600); // Increased 40% more: 4000 * 1.4 = 5600
for (let i = 0; i < particleCount; i++) {
const targetPixel = textPixels[Math.floor(Math.random() * textPixels.length)];
// Completely random starting positions across entire screen
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
targetX: targetPixel.x,
targetY: targetPixel.y,
size: Math.random() * 1 + 1, // Decreased from 1.5+1.5 to 1+1 (1-2px)
speedX: (Math.random() - 0.5) * 25,
speedY: (Math.random() - 0.5) * 25,
angle: Math.random() * Math.PI * 2, // Random rotation angle
rotationSpeed: (Math.random() - 0.5) * 0.1,
opacity: 0,
startDelay: Math.random() * 0.15 // Stagger particle appearance
});
}
const startTime = performance.now();
const duration = 3000; // 3 seconds
function animate(now) {
const elapsed = now - startTime;
const progress = Math.min(elapsed / duration, 1);
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Phase timings:
// 0-0.3s: Fade in particles
// 0.3-1.5s: Fast chaotic blending
// 1.5-3s: Form the text shape
const fadeInPhase = Math.min(progress / 0.1, 1); // 0 to 1 in first 0.3s
const blendPhase = Math.min(Math.max((progress - 0.1) / 0.4, 0), 1); // 0.3s to 1.5s
const formPhase = Math.max(0, (progress - 0.5) / 0.5); // 1.5s to 3s
particles.forEach((p, index) => {
// Check if particle should be visible yet (staggered start)
const particleStartProgress = Math.max(0, progress - (p.startDelay || 0));
if (particleStartProgress < 0.5) {
// Completely random chaotic motion - no wave patterns
const motionIntensity = fadeInPhase * (1 - blendPhase * 0.3);
// Add randomness to movement direction each frame
const randomOffsetX = (Math.random() - 0.5) * 2;
const randomOffsetY = (Math.random() - 0.5) * 2;
// Update angle for spiral/random motion
p.angle += p.rotationSpeed;
// Combine original speed with random walk and rotation
p.x += (p.speedX + randomOffsetX + Math.cos(p.angle) * 3) * motionIntensity;
p.y += (p.speedY + randomOffsetY + Math.sin(p.angle) * 3) * motionIntensity;
// Wrap around screen
if (p.x < 0) p.x = canvas.width;
if (p.x > canvas.width) p.x = 0;
if (p.y < 0) p.y = canvas.height;
if (p.y > canvas.height) p.y = 0;
// Smooth fade-in with random pulsing (not wave-based)
const baseFadeIn = Math.min(particleStartProgress / 0.1, 1) * 0.3;
const randomPulse = Math.sin(elapsed * 0.015 + index * 0.1) * 0.25;
p.opacity = baseFadeIn + randomPulse * fadeInPhase;
} else {
// Smoothly move to form text shape
const easeOut = 1 - Math.pow(1 - formPhase, 3);
const dx = p.targetX - p.x;
const dy = p.targetY - p.y;
p.x += dx * 0.12 * easeOut;
p.y += dy * 0.12 * easeOut;
// Increase opacity as they form text
p.opacity = 0.4 + formPhase * 0.6;
}
// Draw particle only if it has started
if (p.opacity > 0) {
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
ctx.fillStyle = `rgba(0, 71, 90, ${p.opacity})`;
ctx.fill();
}
});
if (elapsed < duration) {
requestAnimationFrame(animate);
} else {
// Animation complete - transition to main content without flashing
overlay.classList.add('hidden');
mainContent.classList.add('visible');
setTimeout(() => {
canvas.remove();
}, 500);
}
}
requestAnimationFrame(animate);
}
let allNotices = [];
let filteredNotices = [];
let currentPage = 1;
let noticesPerPage = 25;
// CORS proxy configuration with reliability scoring
const CORS_PROXIES = [
// Primary: Most reliable and actively maintained proxies
{
url: 'https://corsproxy.io/?url=',
encode: true,
type: 'prefix',
name: 'corsproxy.io'
},
{
url: 'https://api.allorigins.win/get?url=',
encode: true,
type: 'json',
name: 'allorigins.win'
},
{
url: 'https://api.codetabs.com/v1/proxy?quest=',
encode: true,
type: 'prefix',
name: 'codetabs'
},
// Secondary fallbacks
{
url: 'https://thingproxy.freeboard.io/fetch/',
encode: false,
type: 'prefix',
name: 'thingproxy'
},
{
url: 'https://cors.eu.org/',
encode: false,
type: 'prefix',
name: 'cors.eu.org'
},
{
url: 'https://api.cors.lol/?url=',
encode: true,
type: 'prefix',
name: 'cors.lol'
},
// Tertiary fallbacks with alternate format
{
url: 'https://corsproxy.org/?',
encode: true,
type: 'prefix',
name: 'corsproxy.org'
},
{
url: 'https://proxy.cors.sh/',
encode: false,
type: 'prefix',
name: 'cors.sh'
}
];
// Track proxy performance for intelligent selection
let proxyStats = {};
let lastWorkingProxy = null;
// Initialize proxy stats from localStorage if available
function initProxyStats() {
try {
const saved = localStorage.getItem('proxyStats');
if (saved) {
const parsed = JSON.parse(saved);
// Only use saved stats if they're less than 24 hours old
if (parsed.timestamp && Date.now() - parsed.timestamp < 86400000) {
proxyStats = parsed.stats || {};
lastWorkingProxy = parsed.lastWorkingProxy || null;
}
}
} catch (e) {
// Silent fail - stats will be reinitialized
}
// Initialize missing stats for any new proxies
CORS_PROXIES.forEach(proxy => {
if (!proxyStats[proxy.name]) {
proxyStats[proxy.name] = { successes: 0, failures: 0, lastAttempt: null, avgResponseTime: null };
}
});
}
// Save proxy stats to localStorage
function saveProxyStats() {
try {
localStorage.setItem('proxyStats', JSON.stringify({
stats: proxyStats,
lastWorkingProxy: lastWorkingProxy,
timestamp: Date.now()
}));
} catch (e) {
// Silent fail - localStorage might be unavailable
}
}
// Reset proxy stats (useful for debugging)
function resetProxyStats() {
CORS_PROXIES.forEach(proxy => {
proxyStats[proxy.name] = { successes: 0, failures: 0, lastAttempt: null, avgResponseTime: null };
});
lastWorkingProxy = null;
saveProxyStats();
}
// Get proxy health summary for debugging
function getProxyHealthSummary() {
const summary = CORS_PROXIES.map(proxy => {
const stats = proxyStats[proxy.name];
const total = stats.successes + stats.failures;
const rate = total > 0 ? Math.round((stats.successes / total) * 100) : 'N/A';
return {
name: proxy.name,
successRate: rate + '%',
successes: stats.successes,
failures: stats.failures,
avgResponseTime: stats.avgResponseTime ? Math.round(stats.avgResponseTime) + 'ms' : 'N/A',
isLastWorking: lastWorkingProxy === proxy.name
};
});
console.table(summary);
return summary;
}
// Initialize proxy stats on script load
initProxyStats();
const PTU_URLS = [
{ url: 'https://ptu.ac.in/noticeboard-main/', source: 'Main Board', defaultMax: 500 },
{ url: 'https://ptu.ac.in/main-campus-noticeboard/', source: 'Campus Board', defaultMax: 200 }
];
function parseDate(dateStr) {
if (!dateStr || dateStr.trim() === '') return new Date(0);
const parts = dateStr.trim().split('/');
if (parts.length !== 3) return new Date(0);
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
return new Date(year, month, day);
}
function formatDate(date) {
if (!date || date.getTime() === 0) return 'Date not available';
const options = {
year: 'numeric',
month: 'short',
day: 'numeric'
};
return date.toLocaleDateString('en-IN', options);
}
function extractNotices(doc, source, defaultMaxNotices) {
const notices = [];
const loadAll = document.getElementById('loadAllToggle')?.checked;
const maxNotices = loadAll ? Infinity : defaultMaxNotices;
const tableSelectors = [
'table tbody tr',
'.notice-table tbody tr',
'.table tbody tr',
'tbody tr',
'.content table tr',
'table tr'
];
let rows = [];
for (const selector of tableSelectors) {
rows = doc.querySelectorAll(selector);
if (rows.length > 0) break;
}
const rowsToProcess = Math.min(rows.length, maxNotices);
for (let i = 0; i < rowsToProcess; i++) {
const row = rows[i];
const cells = row.querySelectorAll('td');
if (cells.length < 3) continue;
let title = '', dateStr = '', pdfLink = '';
if (cells.length >= 4) {
title = cells[1]?.textContent?.trim() || '';
dateStr = cells[2]?.textContent?.trim() || '';
const linkElement = cells[3]?.querySelector('a');
if (linkElement) {
pdfLink = new URL(linkElement.getAttribute('href'), 'https://ptu.ac.in').href;
}
} else {
title = cells[0]?.textContent?.trim() || '';
dateStr = cells[1]?.textContent?.trim() || '';
const linkElement = cells[2]?.querySelector('a');
if (linkElement) {
pdfLink = new URL(linkElement.getAttribute('href'), 'https://ptu.ac.in').href;
}
}
title = title.replace(/^\d+\.?\s*/, '').trim();
if (title && title.length > 10 && !title.toLowerCase().includes('title')) {
notices.push({
title: title,
date: parseDate(dateStr),
dateStr: dateStr || 'Not specified',
pdfLink: pdfLink || '#',
source: source
});
}
}
return notices;
}
async function fetchWithFallback(url) {
let lastError;
// Sort proxies by reliability (successful requests and response time)
const sortedProxies = [...CORS_PROXIES].sort((a, b) => {
const statsA = proxyStats[a.name];
const statsB = proxyStats[b.name];
// Prioritize last working proxy
if (lastWorkingProxy === a.name) return -1;
if (lastWorkingProxy === b.name) return 1;
// Calculate success rate
const totalA = statsA.successes + statsA.failures;
const totalB = statsB.successes + statsB.failures;
const rateA = totalA > 0 ? statsA.successes / totalA : 0.5;
const rateB = totalB > 0 ? statsB.successes / totalB : 0.5;
return rateB - rateA;
});
for (const proxy of sortedProxies) {
const startTime = performance.now();
try {
// Build the proxy URL based on proxy configuration
const proxyUrl = proxy.encode
? proxy.url + encodeURIComponent(url)
: proxy.url + url;
const fetchOptions = {
method: 'GET',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
},
signal: AbortSignal.timeout(12000) // 12 second timeout
};
const response = await fetch(proxyUrl, fetchOptions);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Handle different response types
let htmlContent;
if (proxy.type === 'json') {
// allorigins.win returns JSON with contents property
const data = await response.json();
if (!data.contents || data.contents.length < 100) {
throw new Error('Empty or invalid JSON response');
}
htmlContent = data.contents;
} else {
htmlContent = await response.text();
}
// Validate response content
if (!htmlContent || htmlContent.length < 100) {
throw new Error('Response too short or empty');
}
// Check if it's actually HTML content (not an error page)
if (!htmlContent.includes('<') || htmlContent.includes('"error"')) {
throw new Error('Invalid HTML response');
}
// Update success stats
const responseTime = performance.now() - startTime;
proxyStats[proxy.name].successes++;
proxyStats[proxy.name].lastAttempt = Date.now();
proxyStats[proxy.name].avgResponseTime = proxyStats[proxy.name].avgResponseTime
? (proxyStats[proxy.name].avgResponseTime + responseTime) / 2
: responseTime;
lastWorkingProxy = proxy.name;
saveProxyStats();
return new Response(htmlContent, {
status: 200,
statusText: 'OK',
headers: { 'Content-Type': 'text/html' }
});
} catch (error) {
// Update failure stats
proxyStats[proxy.name].failures++;
proxyStats[proxy.name].lastAttempt = Date.now();
saveProxyStats();
lastError = error;
}
}
// All proxies failed - try direct fetch as last resort (might work in some environments)
try {
const directResponse = await fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(10000)
});
if (directResponse.ok) {
const htmlContent = await directResponse.text();
if (htmlContent && htmlContent.length > 100) {
return directResponse;
}
}
} catch (directError) {
// Direct fetch failed, will throw the last proxy error
}
throw lastError || new Error('All proxy attempts failed. Please check your internet connection.');
}
async function fetchAllNotices() {
const MAX_RETRIES = 2;
const RETRY_DELAY = 1500; // 1.5 seconds between retries
// Helper function to fetch with retry
async function fetchWithRetry(sourceInfo, attempt = 1) {
try {
const response = await fetchWithFallback(sourceInfo.url);
const htmlText = await response.text();
if (htmlText.length < 100) {
return [];
}
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const notices = extractNotices(doc, sourceInfo.source, sourceInfo.defaultMax);
return notices;
} catch (error) {
if (attempt < MAX_RETRIES) {
await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
return fetchWithRetry(sourceInfo, attempt + 1);
}
return [];
}
}
// Fetch from all sources with retry support
const fetchPromises = PTU_URLS.map(sourceInfo => fetchWithRetry(sourceInfo));
const allResults = await Promise.all(fetchPromises);
const results = allResults.flat();
if (results.length === 0) {
return [];
}
// Remove duplicates based on title
const uniqueNotices = results.filter((notice, index, self) =>
index === self.findIndex(n => n.title === notice.title)
);
uniqueNotices.sort((a, b) => b.date.getTime() - a.date.getTime());
return uniqueNotices;
}
function renderNoticesTable() {
const tbody = document.getElementById('noticesTableBody');
const startIndex = (currentPage - 1) * noticesPerPage;
const endIndex = startIndex + noticesPerPage;
const pageNotices = filteredNotices.slice(startIndex, endIndex);
tbody.innerHTML = '';
pageNotices.forEach((notice, index) => {
const row = document.createElement('tr');
const globalIndex = startIndex + index + 1;
row.innerHTML = `
<td>${globalIndex}</td>
<td class="notice-title">${notice.title}</td>
<td>${formatDate(notice.date)}</td>
<td>
${notice.pdfLink ?
`<a href="${notice.pdfLink}" target="_blank" class="download-link">Download</a>` :
'Not available'
}
</td>
`;
tbody.appendChild(row);
});
updatePaginationControls();
updateStatsDisplay();
}
function updatePaginationControls() {
const totalPages = Math.ceil(filteredNotices.length / noticesPerPage);
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const pageInfo = document.getElementById('pageInfo');
prevBtn.disabled = currentPage <= 1;
nextBtn.disabled = currentPage >= totalPages;
pageInfo.textContent = `Page ${currentPage} of ${totalPages}`;
}
function updateStatsDisplay() {
const statsDisplay = document.getElementById('statsDisplay');
const total = filteredNotices.length;
const showing = Math.min(noticesPerPage, total - (currentPage - 1) * noticesPerPage);
if (total === 0) {
statsDisplay.textContent = 'No notices found';
} else if (filteredNotices.length < allNotices.length) {
statsDisplay.textContent = `Showing ${showing} of ${total} notices (filtered from ${allNotices.length} total)`;
} else {
statsDisplay.textContent = `Showing ${showing} of ${total} notices`;
}
}
function changePage(direction) {
const totalPages = Math.ceil(filteredNotices.length / noticesPerPage);
const newPage = currentPage + direction;
if (newPage >= 1 && newPage <= totalPages) {
currentPage = newPage;
renderNoticesTable();
}
}
function filterNotices(searchTerm) {
if (!searchTerm.trim()) {
filteredNotices = [...allNotices];
} else {
const term = searchTerm.toLowerCase().trim();
filteredNotices = allNotices.filter(notice =>
notice.title.toLowerCase().includes(term)
);
}
currentPage = 1;
renderNoticesTable();
}
function showError(message) {
const errorContainer = document.getElementById('errorContainer');
if (!errorContainer) return;
errorContainer.innerHTML = `
<div class="error">
<h3>🚫 Error Loading Notices</h3>
<p>${message}</p>
<div class="error-solutions">
<h4>Possible Solutions:</h4>
<ul>
<li>Check your internet connection</li>
<li>Disable any ad blockers or VPN temporarily</li>
<li>Try refreshing the page in a few minutes</li>
<li>Try accessing from a different network</li>
</ul>
<button id="retryBtn" class="retry-btn">🔄 Retry</button>
</div>
</div>
`;
document.getElementById('retryBtn')?.addEventListener('click', refreshNotices);
}
async function refreshNotices() {
const refreshBtn = document.getElementById('refreshBtn');
if (refreshBtn.disabled) return;
refreshBtn.disabled = true;
refreshBtn.textContent = '🔄 Loading...';
await initializeNoticeboard();
refreshBtn.disabled = false;
refreshBtn.textContent = '🔄 Refresh';
}
function setupAutoRefresh() {
setInterval(async () => {
try {
const newNotices = await fetchAllNotices();
if (newNotices.length !== allNotices.length) {
allNotices = newNotices;
filteredNotices = [...allNotices];
renderNoticesTable();
const statsDisplay = document.getElementById('statsDisplay');
if (statsDisplay) {
const originalColor = statsDisplay.style.color;
statsDisplay.style.color = 'blue';
statsDisplay.textContent = `📢 Updated! Found ${newNotices.length} notices`;
setTimeout(() => {
statsDisplay.style.color = originalColor;
updateStatsDisplay();
}, 5000);
}
}
} catch (error) {
}
}, 600000);
}
async function initializeNoticeboard() {
const loadingIndicator = document.getElementById('loadingIndicator');
const tableContainer = document.getElementById('tableContainer');
const paginationContainer = document.getElementById('paginationContainer');
const errorContainer = document.getElementById('errorContainer');
try {
if (errorContainer) errorContainer.innerHTML = '';
if (loadingIndicator) {
loadingIndicator.style.display = 'block';
loadingIndicator.classList.remove('hidden');
}
if (tableContainer) {
tableContainer.style.display = 'none';
tableContainer.classList.add('hidden');
}
if (paginationContainer) {
paginationContainer.style.display = 'none';
paginationContainer.classList.add('hidden');
}
const loadingText = loadingIndicator?.querySelector('p');
if (loadingText) {
loadingText.textContent = 'Connecting to PTU servers... This may take a moment...';
}
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timeout - PTU servers are taking too long to respond')), 20000)
);
allNotices = await Promise.race([fetchAllNotices(), timeoutPromise]);
filteredNotices = [...allNotices];
if (loadingIndicator) {
loadingIndicator.style.display = 'none';
loadingIndicator.classList.add('hidden');
}
if (tableContainer) {
if (allNotices.length > 0) {
tableContainer.style.display = 'block';
tableContainer.classList.remove('hidden');
} else {
showError("Could not find any notices. The university website might be down or has changed its structure.");
}
}
if (paginationContainer) {
paginationContainer.style.display = 'flex';
paginationContainer.classList.remove('hidden');
}
renderNoticesTable();
const statsDisplay = document.getElementById('statsDisplay');
if (statsDisplay) {
const originalColor = statsDisplay.style.color;
statsDisplay.classList.add('status-success');
setTimeout(() => {
statsDisplay.classList.remove('status-success');
statsDisplay.style.color = originalColor;
}, 3000);
}
} catch (error) {
showError(error.message);
if (loadingIndicator) {
loadingIndicator.style.display = 'none';
loadingIndicator.classList.add('hidden');
}
}
}
function setupNoticeboard() {
const searchInput = document.getElementById('searchInput');
const refreshBtn = document.getElementById('refreshBtn');
const loadAllToggle = document.getElementById('loadAllToggle');
const pageSizeSelect = document.getElementById('pageSizeSelect');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
if (searchInput) {
searchInput.addEventListener('input', () => filterNotices(searchInput.value));
}
if (refreshBtn) {
refreshBtn.addEventListener('click', refreshNotices);
}
if (loadAllToggle) {
loadAllToggle.addEventListener('change', refreshNotices);
}
if (pageSizeSelect) {
pageSizeSelect.addEventListener('change', () => {
noticesPerPage = parseInt(pageSizeSelect.value, 10);
currentPage = 1;
renderNoticesTable();
});
}
if (prevBtn) {
prevBtn.addEventListener('click', () => changePage(-1));
}
if (nextBtn) {
nextBtn.addEventListener('click', () => changePage(1));
}
initializeNoticeboard();
setupAutoRefresh();
}
// Page initialization
(function() {
if (document.body.classList.contains('noticeboard-page')) {
document.addEventListener('DOMContentLoaded', setupNoticeboard);
} else {
document.addEventListener('DOMContentLoaded', () => {
setupIntroAnimation();
const main = document.getElementById('main-content');
if (main) {
// Keep main content hidden until intro completes; visibility handled in setupIntroAnimation
main.classList.remove('visible');
}
});
}
})();