-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1375 lines (1209 loc) · 64.5 KB
/
script.js
File metadata and controls
1375 lines (1209 loc) · 64.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
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
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyBRlsk-knQs-AMlaTFxlneBMTwlSfwyFaQ",
authDomain: "dsmnru-data.firebaseapp.com",
projectId: "dsmnru-data",
storageBucket: "dsmnru-data.firebasestorage.app",
messagingSenderId: "62250453477",
appId: "1:62250453477:web:087c07403e4fead220470c",
measurementId: "G-VL6V3T96YX"
};
firebase.initializeApp(firebaseConfig);
// Firebase Storage and Firestore references
const db = firebase.firestore();
const storage = firebase.storage();
// User Upload Handler
function setupUserUploadHandler() {
const uploadForm = document.getElementById('userUploadForm');
if (!uploadForm) return;
uploadForm.addEventListener('submit', async function(e) {
e.preventDefault();
const title = document.getElementById('uploadTitle').value;
const course = document.getElementById('uploadCourse').value;
const semester = document.getElementById('uploadSemester').value;
const name = document.getElementById('uploadName').value;
const file = document.getElementById('uploadFile').files[0];
if (!file) {
alert('Please select a file');
return;
}
// Validate file size (unlimited for gofile, but set reasonable limit)
const maxSize = 500 * 1024 * 1024; // 500MB max
if (file.size > maxSize) {
alert('File size exceeds 500MB limit');
return;
}
// Validate file type
if (file.type !== 'application/pdf') {
alert('Only PDF files are allowed');
return;
}
const statusDiv = document.getElementById('uploadStatus');
const statusMessage = document.getElementById('uploadStatusMessage');
const progressDiv = document.getElementById('uploadProgress');
const progressBar = document.getElementById('uploadProgressBar');
statusDiv.style.display = 'block';
statusMessage.textContent = 'Uploading file to database...';
progressDiv.style.display = 'block';
try {
// Upload to gofile.io (CORS enabled, unlimited file storage)
// First, get an available server
const serverResponse = await fetch('https://api.gofile.io/servers');
if (!serverResponse.ok) {
throw new Error('Failed to get upload server');
}
const serverData = await serverResponse.json();
if (serverData.status !== 'ok' || !serverData.data || !serverData.data.servers || serverData.data.servers.length === 0) {
throw new Error('No upload servers available');
}
// Use the first available server
const server = serverData.data.servers[0];
const uploadUrl = `https://${server.name}.gofile.io/uploadFile`;
// Now upload the file
const formData = new FormData();
formData.append('file', file);
const response = await fetch(uploadUrl, {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`Upload failed with status ${response.status}`);
}
const result = await response.json();
if (result.status !== 'ok' || !result.data || !result.data.downloadPage) {
throw new Error('Upload failed: Invalid response from server');
}
// gofile.io returns downloadPage URL directly
const fileUrl = result.data.downloadPage;
progressBar.style.width = '100%';
statusMessage.textContent = 'File uploaded successfully! Saving metadata...';
// Save metadata to Firestore pendingUploads collection
await db.collection('pendingUploads').add({
title: title,
course: course,
semester: semester,
studentName: name,
fileName: file.name,
downloadUrl: fileUrl,
fileSize: file.size,
uploadedAt: firebase.firestore.FieldValue.serverTimestamp(),
status: 'pending'
});
statusMessage.innerHTML = '<strong class="text-success">✓ File uploaded successfully! Our team will review it soon.</strong>';
progressDiv.style.display = 'none';
uploadForm.reset();
// Hide success message after 5 seconds
setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
} catch (error) {
console.error('Upload error:', error);
statusMessage.innerHTML = `<strong class="text-danger">Error: ${error.message}</strong>`;
progressDiv.style.display = 'none';
}
});
}
document.addEventListener('DOMContentLoaded', function() {
// Initialize modals
const pdfModal = new bootstrap.Modal(document.getElementById('pdfModal'));
const shareModal = new bootstrap.Modal(document.getElementById('shareModal'));
const pdfViewer = document.getElementById('pdfViewer');
const downloadBtn = document.getElementById('downloadBtn');
const shareLink = document.getElementById('shareLink');
const copyLinkBtn = document.getElementById('copyLinkBtn');
const pyqList = document.getElementById('pyqList');
const syllabusList = document.getElementById('syllabusList');
// Global data storage
let allData = { pyqs: [], syllabus: [] };
let filteredPyqs = [];
let filteredSyllabus = [];
let bookmarks = { pyqs: [], syllabus: [] };
// Pagination variables for PYQs
let currentPage = 1;
const itemsPerPage = 10;
// Pagination variables for Syllabus
let currentPageSyllabus = 1;
const itemsPerPageSyllabus = 10;
// Pagination variables for Bookmarks
let currentPageBookmarks = 1;
const itemsPerPageBookmarks = 10;
// Function to extract year from title
function extractYearFromTitle(title) {
const yearMatch = title.match(/\{(\d{4})/);
return yearMatch ? parseInt(yearMatch[1]) : 0;
}
// Load data from Firestore
Promise.all([
db.collection('pyqs').get(),
db.collection('syllabus').get()
])
.then(([pyqSnap, syllabusSnap]) => {
allData.pyqs = pyqSnap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
allData.syllabus = syllabusSnap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// Add year to each item and sort
const processedPYQs = allData.pyqs.map(pyq => ({
...pyq,
year: extractYearFromTitle(pyq.title)
})).sort((a, b) => b.year - a.year);
const processedSyllabus = allData.syllabus.map(syllabus => ({
...syllabus,
year: extractYearFromTitle(syllabus.title)
})).sort((a, b) => b.year - a.year);
allData.pyqs = processedPYQs;
allData.syllabus = processedSyllabus;
filteredPyqs = [...processedPYQs];
filteredSyllabus = [...processedSyllabus];
loadBookmarks();
renderPYQs(filteredPyqs);
renderSyllabus(filteredSyllabus);
setupEventListeners();
setupUserUploadHandler();
})
.catch(error => {
console.error('Error loading data from Firestore:', error);
showEmptyState('pyqList', 'Error loading question papers');
showEmptyState('syllabusList', 'Error loading syllabus');
});
// Load and render contributors from Firestore
function loadContributors() {
db.collection('contributors').orderBy('name').get()
.then(snapshot => {
const contributorsGrid = document.getElementById('contributorsGrid');
if (!contributorsGrid) return;
contributorsGrid.innerHTML = '';
snapshot.forEach(doc => {
const contributor = { id: doc.id, ...doc.data() };
const card = document.createElement('div');
card.className = 'contributor-card';
card.innerHTML = `
<div class="contributor-avatar">${contributor.avatar}</div>
<h5>${contributor.name}</h5>
<p class="contributor-role">${contributor.role}</p>
`;
contributorsGrid.appendChild(card);
});
// Add the "Join our team" card at the end
const joinCard = document.createElement('div');
joinCard.className = 'contributor-more';
joinCard.innerHTML = `
<div class="more-avatar">+</div>
<h5>Join our team!</h5>
<p class="contributor-role">Become a contributor</p>
`;
contributorsGrid.appendChild(joinCard);
})
.catch(error => {
console.error('Error loading contributors:', error);
});
}
// Load contributors when page loads
loadContributors();
function renderPYQs(pyqs) {
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const pyqsToRender = filteredPyqs.slice(startIndex, endIndex);
if (!pyqsToRender.length) {
if (currentPage === 1) {
showEmptyState('pyqList', 'No question papers found matching your criteria');
}
document.getElementById('loadMoreBtn').style.display = 'none';
return;
}
if (currentPage === 1) {
pyqList.innerHTML = '';
}
pyqList.insertAdjacentHTML('beforeend', pyqsToRender.map((pyq, index) => `
<li class="pyq-item" style="animation-delay: ${0.1 + (startIndex + index) * 0.05}s">
<div class="pyq-info">
<div class="pdf-icon">
<i class="fas fa-file-pdf"></i>
</div>
<div class="pyq-details">
<h5 class="pyq-title">${pyq.title}</h5>
<div class="pyq-actions">
<button class="btn btn-action btn-preview" onclick="previewPDF('${pyq.file}', '${pyq.title.replace(/'/g, "\\'")}')">
<i class="fas fa-eye"></i> View
</button>
<button class="btn btn-action btn-share" onclick="shareDocument('${pyq.file}', '${pyq.title.replace(/'/g, "\\'")}')">
<i class="fas fa-share-alt"></i> Share
</button>
<button class="btn btn-action btn-bookmark ${isBookmarked('pyqs', pyq.file) ? 'bookmarked' : ''}" onclick="toggleBookmark('pyqs', '${pyq.file}')">
<i class="fas fa-bookmark"></i> ${isBookmarked('pyqs', pyq.file) ? 'Bookmarked' : 'Bookmark'}
</button>
</div>
</div>
</div>
</li>
`).join(''));
// Show or hide Load More button
const loadMoreBtn = document.getElementById('loadMoreBtn');
if (endIndex < filteredPyqs.length) {
loadMoreBtn.style.display = 'inline-block';
} else {
loadMoreBtn.style.display = 'none';
}
}
function renderSyllabus(syllabusItems) {
const startIndex = (currentPageSyllabus - 1) * itemsPerPageSyllabus;
const endIndex = startIndex + itemsPerPageSyllabus;
const syllabusToRender = filteredSyllabus.slice(startIndex, endIndex);
if (!syllabusToRender.length) {
if (currentPageSyllabus === 1) {
showEmptyState('syllabusList', 'No syllabus found matching your criteria');
}
document.getElementById('loadMoreSyllabusBtn').style.display = 'none';
return;
}
if (currentPageSyllabus === 1) {
syllabusList.innerHTML = '';
}
syllabusList.insertAdjacentHTML('beforeend', syllabusToRender.map((syllabus, index) => `
<li class="syllabus-item" style="animation-delay: ${0.1 + (startIndex + index) * 0.05}s">
<div class="syllabus-info">
<div class="syllabus-icon">
<i class="fas fa-book"></i>
</div>
<div class="syllabus-details">
<h5 class="syllabus-title">${syllabus.title}</h5>
<div class="syllabus-meta">
<span class="meta-tag course">${syllabus.course || 'General'}</span>
<span class="meta-tag semester">${syllabus.semester || 'All Semesters'}</span>
<span class="meta-tag">${syllabus.year || 'Latest'}</span>
</div>
<div class="syllabus-actions">
<button class="btn btn-action btn-preview" onclick="previewPDF('${syllabus.file}', '${syllabus.title.replace(/'/g, "\\'")}')">
<i class="fas fa-eye"></i> View
</button>
<button class="btn btn-action btn-share" onclick="shareDocument('${syllabus.file}', '${syllabus.title.replace(/'/g, "\\'")}')">
<i class="fas fa-share-alt"></i> Share
</button>
<button class="btn btn-action btn-bookmark ${isBookmarked('syllabus', syllabus.file) ? 'bookmarked' : ''}" onclick="toggleBookmark('syllabus', '${syllabus.file}')">
<i class="fas fa-bookmark"></i> ${isBookmarked('syllabus', syllabus.file) ? 'Bookmarked' : 'Bookmark'}
</button>
</div>
</div>
</div>
</li>
`).join(''));
// Show or hide Load More button
const loadMoreSyllabusBtn = document.getElementById('loadMoreSyllabusBtn');
if (endIndex < filteredSyllabus.length) {
loadMoreSyllabusBtn.style.display = 'inline-block';
} else {
loadMoreSyllabusBtn.style.display = 'none';
}
}
function renderBookmarks(searchTerm = '') {
const startIndex = (currentPageBookmarks - 1) * itemsPerPageBookmarks;
const endIndex = startIndex + itemsPerPageBookmarks;
// Collect all bookmarked items
let bookmarkedItems = [];
bookmarks.pyqs.forEach(filePath => {
const item = allData.pyqs.find(pyq => pyq.file === filePath);
if (item) {
bookmarkedItems.push({ ...item, type: 'pyq' });
}
});
bookmarks.syllabus.forEach(filePath => {
const item = allData.syllabus.find(syllabus => syllabus.file === filePath);
if (item) {
bookmarkedItems.push({ ...item, type: 'syllabus' });
}
});
// Filter by search term if provided
if (searchTerm) {
bookmarkedItems = bookmarkedItems.filter(item =>
item.title.toLowerCase().includes(searchTerm) ||
(item.course && item.course.toLowerCase().includes(searchTerm)) ||
(item.semester && item.semester.toLowerCase().includes(searchTerm))
);
}
// Sort by year descending
bookmarkedItems.sort((a, b) => b.year - a.year);
const bookmarksToRender = bookmarkedItems.slice(startIndex, endIndex);
if (!bookmarksToRender.length) {
if (currentPageBookmarks === 1) {
showEmptyState('bookmarksList', 'No bookmarked items yet. Bookmark items from PYQs or Syllabus tabs to see them here.');
}
document.getElementById('loadMoreBookmarksBtn').style.display = 'none';
return;
}
if (currentPageBookmarks === 1) {
document.getElementById('bookmarksList').innerHTML = '';
}
document.getElementById('bookmarksList').insertAdjacentHTML('beforeend', bookmarksToRender.map((item, index) => {
if (item.type === 'pyq') {
return `
<li class="pyq-item" style="animation-delay: ${0.1 + (startIndex + index) * 0.05}s">
<div class="pyq-info">
<div class="pdf-icon">
<i class="fas fa-file-pdf"></i>
</div>
<div class="pyq-details">
<h5 class="pyq-title">${item.title}</h5>
<div class="pyq-actions">
<button class="btn btn-action btn-preview" onclick="previewPDF('${item.file}', '${item.title.replace(/'/g, "\\'")}')">
<i class="fas fa-eye"></i> View
</button>
<button class="btn btn-action btn-share" onclick="shareDocument('${item.file}', '${item.title.replace(/'/g, "\\'")}')">
<i class="fas fa-share-alt"></i> Share
</button>
<button class="btn btn-action btn-bookmark bookmarked" onclick="toggleBookmark('pyqs', '${item.file}')">
<i class="fas fa-bookmark"></i> Bookmarked
</button>
</div>
</div>
</div>
</li>
`;
} else {
return `
<li class="syllabus-item" style="animation-delay: ${0.1 + (startIndex + index) * 0.05}s">
<div class="syllabus-info">
<div class="syllabus-icon">
<i class="fas fa-book"></i>
</div>
<div class="syllabus-details">
<h5 class="syllabus-title">${item.title}</h5>
<div class="syllabus-meta">
<span class="meta-tag course">${item.course || 'General'}</span>
<span class="meta-tag semester">${item.semester || 'All Semesters'}</span>
<span class="meta-tag">${item.year || 'Latest'}</span>
</div>
<div class="syllabus-actions">
<button class="btn btn-action btn-preview" onclick="previewPDF('${item.file}', '${item.title.replace(/'/g, "\\'")}')">
<i class="fas fa-eye"></i> View
</button>
<button class="btn btn-action btn-share" onclick="shareDocument('${item.file}', '${item.title.replace(/'/g, "\\'")}')">
<i class="fas fa-share-alt"></i> Share
</button>
<button class="btn btn-action btn-bookmark bookmarked" onclick="toggleBookmark('syllabus', '${item.file}')">
<i class="fas fa-bookmark"></i> Bookmarked
</button>
</div>
</div>
</div>
</li>
`;
}
}).join(''));
// Show or hide Load More button
const loadMoreBookmarksBtn = document.getElementById('loadMoreBookmarksBtn');
if (endIndex < bookmarkedItems.length) {
loadMoreBookmarksBtn.style.display = 'inline-block';
} else {
loadMoreBookmarksBtn.style.display = 'none';
}
}
function showEmptyState(containerId, message) {
document.getElementById(containerId).innerHTML = `
<div class="empty-state">
<i class="fas fa-search"></i>
<p>${message}</p>
</div>
`;
}
// Bookmark functions
function loadBookmarks() {
const savedBookmarks = localStorage.getItem('dsmnruBookmarks');
if (savedBookmarks) {
bookmarks = JSON.parse(savedBookmarks);
}
}
function saveBookmarks() {
localStorage.setItem('dsmnruBookmarks', JSON.stringify(bookmarks));
}
function toggleBookmark(type, filePath) {
const index = bookmarks[type].indexOf(filePath);
if (index > -1) {
bookmarks[type].splice(index, 1);
} else {
bookmarks[type].push(filePath);
}
saveBookmarks();
// Update all bookmark buttons in the DOM without re-rendering
document.querySelectorAll('.btn-bookmark').forEach(button => {
const onclick = button.getAttribute('onclick');
const match = onclick.match(/toggleBookmark\('([^']+)', '([^']+)'\)/);
if (match) {
const btnType = match[1];
const btnFilePath = match[2];
const isBookmarkedNow = isBookmarked(btnType, btnFilePath);
button.classList.toggle('bookmarked', isBookmarkedNow);
button.innerHTML = `<i class="fas fa-bookmark"></i> ${isBookmarkedNow ? 'Bookmarked' : 'Bookmark'}`;
}
});
// Refresh bookmarks tab if it's currently active
const activeTab = document.querySelector('.nav-link.active');
if (activeTab && activeTab.getAttribute('data-bs-target') === '#nav-bookmarks') {
currentPageBookmarks = 1;
renderBookmarks();
}
}
// Make toggleBookmark globally accessible for onclick handlers
window.toggleBookmark = toggleBookmark;
function isBookmarked(type, filePath) {
return bookmarks[type].includes(filePath);
}
function setupEventListeners() {
// Search functionality
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', performSearch);
// Load More button for PYQs
document.getElementById('loadMoreBtn').addEventListener('click', function() {
currentPage++;
renderPYQs();
});
// Load More button for Syllabus
document.getElementById('loadMoreSyllabusBtn').addEventListener('click', function() {
currentPageSyllabus++;
renderSyllabus();
});
// Load More button for Bookmarks
document.getElementById('loadMoreBookmarksBtn').addEventListener('click', function() {
currentPageBookmarks++;
renderBookmarks();
});
// Copy link button
copyLinkBtn.addEventListener('click', function() {
shareLink.select();
document.execCommand('copy');
const originalText = copyLinkBtn.innerHTML;
copyLinkBtn.innerHTML = '<i class="fas fa-check"></i> Copied!';
setTimeout(() => {
copyLinkBtn.innerHTML = originalText;
}, 2000);
});
// Tab switching
document.querySelectorAll('[data-bs-toggle="tab"]').forEach(tab => {
tab.addEventListener('shown.bs.tab', function(event) {
const targetTab = event.target.getAttribute('data-bs-target');
// Clear search when switching tabs
document.getElementById('searchInput').value = '';
performSearch();
// Render bookmarks when bookmarks tab is shown
if (targetTab === '#nav-bookmarks') {
currentPageBookmarks = 1;
renderBookmarks();
}
});
});
}
// Search function
window.performSearch = function() {
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
const activeTab = document.querySelector('.nav-link.active').getAttribute('data-bs-target');
if (activeTab === '#nav-pyq') {
const filtered = allData.pyqs.filter(pyq =>
pyq.title.toLowerCase().includes(searchTerm)
);
filteredPyqs = filtered;
currentPage = 1;
renderPYQs();
} else if (activeTab === '#nav-syllabus') {
const filtered = allData.syllabus.filter(syllabus =>
syllabus.title.toLowerCase().includes(searchTerm) ||
(syllabus.course && syllabus.course.toLowerCase().includes(searchTerm)) ||
(syllabus.semester && syllabus.semester.toLowerCase().includes(searchTerm))
);
filteredSyllabus = filtered;
currentPageSyllabus = 1;
renderSyllabus();
} else if (activeTab === '#nav-bookmarks') {
// For bookmarks, we need to filter the bookmarked items
// Since bookmarks are stored as file paths, we need to filter the actual items
currentPageBookmarks = 1;
renderBookmarks(searchTerm);
}
};
// PDF view function
window.previewPDF = function(filePath, title) {
window.open(filePath, '_blank');
};
// Share function
window.shareDocument = function(filePath, title) {
const currentUrl = window.location.origin + window.location.pathname;
const shareUrl = `${(filePath)}`;
shareLink.value = shareUrl;
// Update social sharing links
const whatsappShare = document.getElementById('whatsappShare');
const telegramShare = document.getElementById('telegramShare');
const emailShare = document.getElementById('emailShare');
const shareText = `Check out this ${title} from DSMNRU Academic Archive`;
whatsappShare.href = `https://wa.me/?text=${encodeURIComponent(shareText + ' ' + shareUrl)}`;
telegramShare.href = `https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(shareText)}`;
emailShare.href = `mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(shareText + '\n\n' + shareUrl)}`;
shareModal.show();
};
// Newsletter subscription
window.subscribeNewsletter = function(event) {
event.preventDefault();
const email = event.target.querySelector('input[type="email"]').value;
// Here you would typically send the email to your backend
alert(`Thank you for subscribing with email: ${email}. You'll receive updates about new uploads!`);
event.target.reset();
};
// Handle direct PDF links from URL hash
if (window.location.hash) {
const pdfPath = decodeURIComponent(window.location.hash.substring(1));
if (pdfPath.endsWith('.pdf')) {
previewPDF(pdfPath, 'Shared Document');
}
}
// Add loading states
function showLoading(containerId) {
document.getElementById(containerId).innerHTML = `
<div class="loading">
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Loading content...</p>
</div>
`;
}
// Enhanced error handling
function handleError(error, containerId, message) {
console.error('Error:', error);
document.getElementById(containerId).innerHTML = `
<div class="empty-state">
<i class="fas fa-exclamation-triangle"></i>
<p>${message}</p>
<button class="btn btn-outline-light mt-2" onclick="location.reload()">
<i class="fas fa-refresh"></i> Retry
</button>
</div>
`;
}
// Keyboard shortcuts
document.addEventListener('keydown', function(event) {
// Ctrl+K or Cmd+K to focus search
if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
event.preventDefault();
document.getElementById('searchInput').focus();
}
// Escape to close modals
if (event.key === 'Escape') {
if (pdfModal._isShown) pdfModal.hide();
if (shareModal._isShown) shareModal.hide();
}
});
// Add smooth scrolling for better UX
function smoothScrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
// Show scroll to top button when needed
window.addEventListener('scroll', function() {
const scrollButton = document.getElementById('scrollToTop');
if (window.pageYOffset > 300) {
if (scrollButton) scrollButton.style.display = 'block';
} else {
if (scrollButton) scrollButton.style.display = 'none';
}
});
// Add analytics tracking (placeholder)
function trackEvent(category, action, label) {
// Example: Google Analytics 4
if (typeof gtag !== 'undefined') {
gtag('event', action, {
event_category: category,
event_label: label
});
}
}
// Track downloads and shares
document.addEventListener('click', function(event) {
if (event.target.classList.contains('btn-download')) {
trackEvent('Download', 'PDF', event.target.closest('.pyq-item, .syllabus-item').querySelector('h5').textContent);
} else if (event.target.classList.contains('btn-share')) {
trackEvent('Share', 'PDF', event.target.closest('.pyq-item, .syllabus-item').querySelector('h5').textContent);
} else if (event.target.classList.contains('btn-preview')) {
trackEvent('Preview', 'PDF', event.target.closest('.pyq-item, .syllabus-item').querySelector('h5').textContent);
}
});
// Tool Information Modal Handler
function showToolInfo(toolId) {
const toolInfo = {
'cgpa': {
title: 'CGPA Calculator',
description: 'A comprehensive tool to calculate your Semester Grade Point Average (SGPA) for a set of subjects. Use it to compute semester performance quickly.',
features: [
'Calculate SGPA from letter grades and credits',
'Adjust subject count dynamically',
'Quick credit +/- controls',
'Results preview and last-calculation persistence'
],
benefits: [
'Quickly estimate semester performance',
'Plan target grades for upcoming subjects',
'Save and reuse values locally'
]
},
'attendance': {
title: 'Attendance Tracker',
description: 'Track daily attendance per subject and view monthly summaries. Mark Present/Absent for specific dates and monitor percent attendance for each subject.',
features: [
'Record attendance by date (Present / Absent)',
'Monthly summary and percentage calculation',
'Edit and delete subjects',
'Local persistence using localStorage'
],
benefits: [
'Keep a reliable local record of attendance',
'Identify subjects close to attendance warning thresholds',
'Simple offline-first design'
]
},
'planner': {
title: 'Study Planner',
description: 'Create tasks with due dates and reminders. Track progress and completion to stay organized during the semester.',
features: [
'Add / edit / delete study tasks',
'Mark tasks complete and track progress',
'Optional reminders for upcoming due dates',
'Lightweight local storage for quick start'
],
benefits: [
'Organize study sessions and assignments',
'Track completion rate visually',
'Receive simple reminders for priority tasks'
]
}
};
const info = toolInfo[toolId];
if (!info) return;
// Create modal HTML
const modalHTML = `
<div class="modal fade tool-info-modal" id="toolInfoModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="fas fa-info-circle me-2"></i>${info.title}
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p class="mb-4">${info.description}</p>
<div class="row">
<div class="col-md-6">
<h6><i class="fas fa-star text-warning me-2"></i>Key Features</h6>
<ul class="list-unstyled">
${info.features.map(feature => `<li><i class="fas fa-check text-success me-2"></i>${feature}</li>`).join('')}
</ul>
</div>
<div class="col-md-6">
<h6><i class="fas fa-lightbulb text-info me-2"></i>Benefits</h6>
<ul class="list-unstyled">
${info.benefits.map(benefit => `<li><i class="fas fa-arrow-right text-primary me-2"></i>${benefit}</li>`).join('')}
</ul>
</div>
</div>
<div class="alert alert-info mt-3">
<i class="fas fa-info-circle me-2"></i>
<strong>Pro Tip:</strong> Use this tool regularly to stay on top of your academic tasks and attendance.
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="openToolBtn">
<i class="fas fa-play me-2"></i> Open Tool
</button>
</div>
</div>
</div>
</div>
`;
// Remove existing modal if any
const existingModal = document.getElementById('toolInfoModal');
if (existingModal) {
existingModal.remove();
}
// Add new modal to body
document.body.insertAdjacentHTML('beforeend', modalHTML);
// Show modal
const modalEl = document.getElementById('toolInfoModal');
const modal = new bootstrap.Modal(modalEl);
modal.show();
// Wire Open Tool button to trigger the corresponding tool
const openButtonMap = { cgpa: 'openCgpaBtn', attendance: 'openAttendanceBtn', planner: 'openPlannerBtn' };
const openToolBtn = document.getElementById('openToolBtn');
if (openToolBtn) {
openToolBtn.addEventListener('click', () => {
modal.hide();
const targetBtnId = openButtonMap[toolId];
const targetBtn = document.getElementById(targetBtnId);
if (targetBtn) {
targetBtn.click();
trackToolUsage(toolId, 'open_from_info');
} else {
// Fallback: if no button exists, just log
console.warn('Open button for', toolId, 'not found');
}
});
}
}
// Expose to global scope for inline onclick handlers
window.showToolInfo = showToolInfo;
// Enhanced analytics for tool usage
function trackToolUsage(toolName, action) {
// Track tool usage for analytics
if (typeof gtag !== 'undefined') {
gtag('event', 'tool_interaction', {
'tool_name': toolName,
'action': action,
'page_location': window.location.href
});
}
console.log(`Tool Usage: ${toolName} - ${action}`);
}
// Floating Dashboard Button Functionality
const dashboardBtn = document.getElementById('dashboardBtn');
if (dashboardBtn) {
dashboardBtn.addEventListener('click', function() {
window.location.href = 'admin.html';
});
}
// Dashboard Settings Functionality
function loadDashboardSettings() {
// Load theme setting
const savedTheme = localStorage.getItem('dashboardTheme') || 'auto';
document.querySelector(`input[name="theme"][value="${savedTheme}"]`).checked = true;
// Load layout setting
const savedLayout = localStorage.getItem('dashboardLayout') || 'expanded';
document.querySelector(`input[name="layout"][value="${savedLayout}"]`).checked = true;
// Load quick access settings
const quickPyq = localStorage.getItem('quickPyq') === 'true';
const quickSyllabus = localStorage.getItem('quickSyllabus') === 'true';
const quickSearch = localStorage.getItem('quickSearch') === 'true';
const quickUpload = localStorage.getItem('quickUpload') === 'true';
document.getElementById('quickPyq').checked = quickPyq;
document.getElementById('quickSyllabus').checked = quickSyllabus;
document.getElementById('quickSearch').checked = quickSearch;
document.getElementById('quickUpload').checked = quickUpload;
}
function saveDashboardSettings() {
// Save theme setting
const selectedTheme = document.querySelector('input[name="theme"]:checked').value;
localStorage.setItem('dashboardTheme', selectedTheme);
applyTheme(selectedTheme);
// Save layout setting
const selectedLayout = document.querySelector('input[name="layout"]:checked').value;
localStorage.setItem('dashboardLayout', selectedLayout);
applyLayout(selectedLayout);
// Save quick access settings
const quickPyq = document.getElementById('quickPyq').checked;
const quickSyllabus = document.getElementById('quickSyllabus').checked;
const quickSearch = document.getElementById('quickSearch').checked;
const quickUpload = document.getElementById('quickUpload').checked;
localStorage.setItem('quickPyq', quickPyq);
localStorage.setItem('quickSyllabus', quickSyllabus);
localStorage.setItem('quickSearch', quickSearch);
localStorage.setItem('quickUpload', quickUpload);
applyQuickAccess({ quickPyq, quickSyllabus, quickSearch, quickUpload });
// Show success message
showSettingsSavedMessage();
}
function applyTheme(theme) {
const body = document.body;
body.classList.remove('theme-light', 'theme-dark', 'theme-auto');
if (theme === 'light') {
body.classList.add('theme-light');
} else if (theme === 'dark') {
body.classList.add('theme-dark');
} else {
body.classList.add('theme-auto');
// Apply system preference
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
body.classList.add('theme-dark');
} else {
body.classList.add('theme-light');
}
}
}
function applyLayout(layout) {
const body = document.body;
body.classList.remove('layout-compact', 'layout-expanded');
body.classList.add(`layout-${layout}`);
}
function applyQuickAccess(settings) {
// This could be extended to show/hide quick access elements
// For now, we'll just store the preferences
console.log('Quick access settings applied:', settings);
}
function showSettingsSavedMessage() {
// Create and show a temporary success message
const toast = document.createElement('div');
toast.className = 'toast align-items-center text-white bg-success border-0 position-fixed';
toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999;';
toast.innerHTML = `
<div class="d-flex">
<div class="toast-body">
<i class="fas fa-check-circle me-2"></i> Settings saved successfully!
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
</div>
`;
document.body.appendChild(toast);
const bsToast = new bootstrap.Toast(toast);
bsToast.show();
// Remove toast after it's hidden
toast.addEventListener('hidden.bs.toast', () => {
document.body.removeChild(toast);
});
}
// Save Settings Button Event Listener
const saveSettingsBtn = document.getElementById('saveDashboardSettings');
if (saveSettingsBtn) {
saveSettingsBtn.addEventListener('click', function() {
saveDashboardSettings();
dashboardModal.hide();
});
}
// Apply saved settings on page load
function applySavedSettings() {
const savedTheme = localStorage.getItem('dashboardTheme') || 'auto';
const savedLayout = localStorage.getItem('dashboardLayout') || 'expanded';
applyTheme(savedTheme);
applyLayout(savedLayout);