-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1858 lines (1619 loc) · 64.8 KB
/
script.js
File metadata and controls
1858 lines (1619 loc) · 64.8 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
/**
* Biology Flashcards Application
* Main JavaScript file with all functionality
*/
// ============================================================================
// Card Manager Module
// ============================================================================
const CardManager = (function() {
// Default card dataset - 6 diverse biology organisms
const defaultCards = [
{
id: "elephant-african",
title: "African Elephant",
imageUrl: "https://images.unsplash.com/photo-1557050543-4d5f4e07ef46?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Animalia",
phylum: "Chordata",
class: "Mammalia"
},
details: {
description: "The African elephant is the largest land animal on Earth, characterized by its long trunk, large ears, and tusks (which are actually elongated incisors).",
habitat: "Savannas, grasslands, forests, and deserts across sub-Saharan Africa",
diet: "Herbivorous - primarily grasses, but also leaves, bark, fruits, and roots",
size: "Height: 3-4 meters (10-13 feet), Weight: 4,000-7,000 kg (8,800-15,400 lbs)",
distribution: "Eastern, Southern, and Western Africa",
conservation: "Vulnerable (IUCN Red List) - threatened by habitat loss and poaching",
funFact: "Elephants can communicate using infrasound below the range of human hearing, which allows them to communicate over distances of up to 10 kilometers."
},
categories: ["animal", "mammal", "herbivore", "endangered", "large"],
difficulty: "medium"
},
{
id: "butterfly-monarch",
title: "Monarch Butterfly",
imageUrl: "https://images.unsplash.com/photo-1551085254-e96b210db58a?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Animalia",
phylum: "Arthropoda",
class: "Insecta"
},
details: {
description: "The monarch butterfly is known for its striking orange and black pattern and its incredible multi-generational migration across North America.",
habitat: "Milkweed-rich fields, gardens, forests, and coastal areas",
diet: "Nectar from flowers; caterpillars feed exclusively on milkweed leaves",
size: "Wingspan: 8.9-10.2 cm (3.5-4 inches), Weight: 0.25-0.75 grams",
distribution: "North America, with migratory populations reaching Central Mexico",
conservation: "Near Threatened - population declines due to habitat loss and climate change",
funFact: "Monarchs complete a multi-generational migration of up to 4,800 km (3,000 miles) each year, with no single butterfly making the entire round trip."
},
categories: ["animal", "insect", "pollinator", "migratory"],
difficulty: "easy"
},
{
id: "tree-sequoia",
title: "Giant Sequoia",
imageUrl: "https://images.unsplash.com/photo-1503435980610-a51f3ddfee50?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Plantae",
phylum: "Tracheophyta",
class: "Pinopsida"
},
details: {
description: "The giant sequoia is the world's largest tree by volume, with some specimens over 3,000 years old and reaching heights of over 90 meters.",
habitat: "Moist, well-drained soils on the western slopes of the Sierra Nevada mountains",
diet: "Photosynthetic - converts sunlight, water, and carbon dioxide into energy",
size: "Height: up to 95 meters (312 feet), Diameter: up to 11 meters (36 feet)",
distribution: "Restricted to about 70 groves in the Sierra Nevada mountains of California",
conservation: "Endangered - threatened by climate change, drought, and increased wildfires",
funFact: "Giant sequoias have fire-resistant bark up to 60 cm (2 feet) thick and require periodic fires to open their cones and release seeds."
},
categories: ["plant", "tree", "conifer", "ancient", "large"],
difficulty: "medium"
},
{
id: "mushroom-amanita",
title: "Fly Agaric Mushroom",
imageUrl: "https://images.unsplash.com/photo-1572017932227-3c6c2c82b6e3?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Fungi",
phylum: "Basidiomycota",
class: "Agaricomycetes"
},
details: {
description: "The fly agaric is a iconic mushroom known for its bright red cap with white spots. It contains psychoactive compounds and has a long history in folklore.",
habitat: "Forest floors in symbiotic relationship with birch, pine, and spruce trees",
diet: "Mycorrhizal - forms symbiotic relationships with tree roots",
size: "Cap diameter: 8-20 cm (3-8 inches), Stem height: 15-20 cm (6-8 inches)",
distribution: "Temperate and boreal regions of the Northern Hemisphere",
conservation: "Least Concern - widespread and common",
funFact: "This mushroom is toxic and hallucinogenic. It was traditionally used by Siberian shamans and is famously depicted in fairy tales and video games (like Super Mario)."
},
categories: ["fungi", "mushroom", "toxic", "symbiotic"],
difficulty: "hard"
},
{
id: "shark-great-white",
title: "Great White Shark",
imageUrl: "https://images.unsplash.com/photo-1560279966-245c92c2ee91?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Animalia",
phylum: "Chordata",
class: "Chondrichthyes"
},
details: {
description: "The great white shark is a large predatory fish known for its size, power, and portrayal in popular culture. It has a streamlined body and rows of serrated teeth.",
habitat: "Coastal and offshore waters in temperate and subtropical oceans worldwide",
diet: "Carnivorous - primarily seals, sea lions, small whales, fish, and carrion",
size: "Length: 4-6 meters (13-20 feet), Weight: 680-1,100 kg (1,500-2,400 lbs)",
distribution: "Found in most coastal and offshore waters with temperatures between 12-24°C",
conservation: "Vulnerable - populations declining due to overfishing and bycatch",
funFact: "Great white sharks can detect a single drop of blood in 100 liters (25 gallons) of water and can sense the electromagnetic fields produced by living animals."
},
categories: ["animal", "fish", "predator", "marine", "endangered"],
difficulty: "medium"
},
{
id: "plant-venus-flytrap",
title: "Venus Flytrap",
imageUrl: "https://images.unsplash.com/photo-1598300042247-d088f8ab3a91?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80",
taxonomy: {
kingdom: "Plantae",
phylum: "Tracheophyta",
class: "Magnoliopsida"
},
details: {
description: "The Venus flytrap is a carnivorous plant famous for its unique trapping mechanism. Its leaves have hinged lobes with trigger hairs that snap shut when touched.",
habitat: "Nutrient-poor, acidic soils in subtropical wetlands of the Carolinas (USA)",
diet: "Carnivorous - insects and arachnids; also photosynthetic",
size: "Rosette diameter: 10-15 cm (4-6 inches), Trap size: 2.5-5 cm (1-2 inches)",
distribution: "Endemic to a small region in North and South Carolina, USA",
conservation: "Vulnerable - threatened by habitat loss, poaching, and fire suppression",
funFact: "The Venus flytrap's trapping mechanism is one of the fastest movements in the plant kingdom. It can close its trap in about 100 milliseconds when triggered twice within 20 seconds."
},
categories: ["plant", "carnivorous", "insectivorous", "endangered"],
difficulty: "easy"
}
];
// Current state
let cards = [];
let currentCardIndex = 0;
let filteredCards = [];
let activeFilters = {
kingdom: null,
phylum: null,
class: null,
search: ''
};
// Initialize - load cards from localStorage or use defaults
function init() {
const userCards = JSON.parse(localStorage.getItem('biologyCards_user') || '[]');
cards = [...defaultCards, ...userCards];
filteredCards = [...cards];
currentCardIndex = 0;
return cards;
}
// Get all cards (filtered if filters active)
function getCards() {
return filteredCards;
}
// Get current card
function getCurrentCard() {
return filteredCards[currentCardIndex] || null;
}
// Get card by index
function getCard(index) {
return filteredCards[index] || null;
}
// Get total number of cards
function getTotalCards() {
return filteredCards.length;
}
// Get current card index
function getCurrentIndex() {
return currentCardIndex;
}
// Navigate to next card
function nextCard() {
if (filteredCards.length === 0) return null;
currentCardIndex = (currentCardIndex + 1) % filteredCards.length;
return getCurrentCard();
}
// Navigate to previous card
function prevCard() {
if (filteredCards.length === 0) return null;
currentCardIndex = (currentCardIndex - 1 + filteredCards.length) % filteredCards.length;
return getCurrentCard();
}
// Jump to specific card index
function jumpToCard(index) {
if (index >= 0 && index < filteredCards.length) {
currentCardIndex = index;
return getCurrentCard();
}
return null;
}
// Shuffle cards
function shuffle() {
if (filteredCards.length === 0) return;
// Fisher-Yates shuffle algorithm
for (let i = filteredCards.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[filteredCards[i], filteredCards[j]] = [filteredCards[j], filteredCards[i]];
}
// Update current index to point to the same card if possible
const currentCard = getCurrentCard();
if (currentCard) {
const newIndex = filteredCards.findIndex(card => card.id === currentCard.id);
if (newIndex !== -1) {
currentCardIndex = newIndex;
} else {
currentCardIndex = 0;
}
} else {
currentCardIndex = 0;
}
return filteredCards;
}
// Reset to default order
function resetOrder() {
filteredCards = [...cards];
currentCardIndex = 0;
return filteredCards;
}
// Apply filters
function applyFilters(filters) {
activeFilters = { ...activeFilters, ...filters };
filteredCards = cards.filter(card => {
// Kingdom filter
if (activeFilters.kingdom && card.taxonomy.kingdom !== activeFilters.kingdom) {
return false;
}
// Phylum filter
if (activeFilters.phylum && card.taxonomy.phylum !== activeFilters.phylum) {
return false;
}
// Class filter
if (activeFilters.class && card.taxonomy.class !== activeFilters.class) {
return false;
}
// Search filter
if (activeFilters.search) {
const searchTerm = activeFilters.search.toLowerCase();
const searchableText = [
card.title,
card.taxonomy.kingdom,
card.taxonomy.phylum,
card.taxonomy.class,
card.details.description,
card.details.habitat,
card.details.diet,
...card.categories
].join(' ').toLowerCase();
if (!searchableText.includes(searchTerm)) {
return false;
}
}
return true;
});
// Reset to first card if current index is out of bounds
if (currentCardIndex >= filteredCards.length) {
currentCardIndex = filteredCards.length > 0 ? 0 : -1;
}
return filteredCards;
}
// Get available filter options
function getFilterOptions() {
const kingdoms = new Set();
const phyla = new Set();
const classes = new Set();
cards.forEach(card => {
kingdoms.add(card.taxonomy.kingdom);
phyla.add(card.taxonomy.phylum);
classes.add(card.taxonomy.class);
});
return {
kingdoms: Array.from(kingdoms),
phyla: Array.from(phyla),
classes: Array.from(classes)
};
}
// Add a new card (user-created)
function addUserCard(cardData) {
const newCard = {
...cardData,
id: `user-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
};
cards.push(newCard);
// Save to localStorage
const userCards = cards.filter(card => card.id.startsWith('user-'));
localStorage.setItem('biologyCards_user', JSON.stringify(userCards));
// Reapply filters
applyFilters(activeFilters);
return newCard;
}
// Get user cards
function getUserCards() {
return cards.filter(card => card.id.startsWith('user-'));
}
// Reset to default cards only
function resetToDefault() {
cards = [...defaultCards];
localStorage.removeItem('biologyCards_user');
applyFilters(activeFilters);
currentCardIndex = 0;
return cards;
}
// Export user cards as JSON
function exportUserCards() {
const userCards = getUserCards();
return JSON.stringify(userCards, null, 2);
}
// Import user cards from JSON
function importUserCards(jsonString) {
try {
const importedCards = JSON.parse(jsonString);
if (!Array.isArray(importedCards)) {
throw new Error('Invalid format: expected an array of cards');
}
// Add imported cards
importedCards.forEach(card => {
if (card.id && card.title && card.taxonomy) {
cards.push(card);
}
});
// Save to localStorage
const userCards = cards.filter(card => card.id.startsWith('user-'));
localStorage.setItem('biologyCards_user', JSON.stringify(userCards));
// Reapply filters
applyFilters(activeFilters);
return importedCards.length;
} catch (error) {
console.error('Failed to import cards:', error);
return 0;
}
}
// Public API
return {
init,
getCards,
getCurrentCard,
getCard,
getTotalCards,
getCurrentIndex,
nextCard,
prevCard,
jumpToCard,
shuffle,
resetOrder,
applyFilters,
getFilterOptions,
addUserCard,
getUserCards,
resetToDefault,
exportUserCards,
importUserCards
};
})();
// ============================================================================
// UI Controller Module
// ============================================================================
const UIController = (function() {
// DOM Elements
const elements = {
// Card display
card: document.getElementById('card'),
cardImage: document.getElementById('card-image'),
cardTitle: document.getElementById('card-title'),
tagKingdom: document.getElementById('tag-kingdom'),
tagPhylum: document.getElementById('tag-phylum'),
tagClass: document.getElementById('tag-class'),
// Card back
backTitle: document.getElementById('back-title'),
infoDescription: document.getElementById('info-description'),
infoHabitat: document.getElementById('info-habitat'),
infoDiet: document.getElementById('info-diet'),
infoSize: document.getElementById('info-size'),
infoDistribution: document.getElementById('info-distribution'),
infoConservation: document.getElementById('info-conservation'),
funFact: document.getElementById('fun-fact'),
// Controls
prevBtn: document.getElementById('prev-btn'),
nextBtn: document.getElementById('next-btn'),
flipBtn: document.getElementById('flip-btn'),
shuffleBtn: document.getElementById('shuffle-btn'),
resetBtn: document.getElementById('reset-btn'),
cardCounter: document.getElementById('card-counter'),
progressBar: document.getElementById('progress-bar'),
// Thumbnails
cardThumbnails: document.getElementById('card-thumbnails')
};
// Initialize UI
function init() {
// Check if all required elements exist
for (const [key, element] of Object.entries(elements)) {
if (!element) {
console.warn(`UI element not found: ${key}`);
}
}
// Set up event listeners (will be connected by main app)
console.log('UI Controller initialized');
}
// Update card display with current card data
function updateCardDisplay(card) {
if (!card) return;
// Front side
elements.cardTitle.textContent = card.title;
elements.tagKingdom.textContent = `Kingdom: ${card.taxonomy.kingdom}`;
elements.tagPhylum.textContent = `Phylum: ${card.taxonomy.phylum}`;
elements.tagClass.textContent = `Class: ${card.taxonomy.class}`;
// Update card image
elements.cardImage.innerHTML = '';
const img = document.createElement('img');
img.src = card.imageUrl;
img.alt = card.title;
img.loading = 'lazy';
img.onerror = function() {
// Fallback if image fails to load
this.parentElement.innerHTML = `
<div class="image-placeholder">
<i class="fas fa-seedling"></i>
<span>${card.title}</span>
</div>
`;
};
elements.cardImage.appendChild(img);
// Back side
elements.backTitle.textContent = card.title;
elements.infoDescription.textContent = card.details.description;
elements.infoHabitat.textContent = card.details.habitat;
elements.infoDiet.textContent = card.details.diet;
elements.infoSize.textContent = card.details.size;
elements.infoDistribution.textContent = card.details.distribution;
elements.infoConservation.textContent = card.details.conservation;
elements.funFact.textContent = card.details.funFact;
// Update counter and progress
const totalCards = CardManager.getTotalCards();
const currentIndex = CardManager.getCurrentIndex();
elements.cardCounter.textContent = `Card ${currentIndex + 1} of ${totalCards}`;
// Update progress bar
if (totalCards > 0) {
const progress = ((currentIndex + 1) / totalCards) * 100;
elements.progressBar.style.width = `${progress}%`;
}
}
// Flip card animation
function flipCard() {
elements.card.classList.toggle('flipped');
}
// Check if card is flipped
function isCardFlipped() {
return elements.card.classList.contains('flipped');
}
// Reset card to front side
function resetCardFlip() {
elements.card.classList.remove('flipped');
}
// Update thumbnail navigation
function updateThumbnails(cards, currentIndex) {
elements.cardThumbnails.innerHTML = '';
cards.forEach((card, index) => {
const thumbnail = document.createElement('div');
thumbnail.className = `thumbnail ${index === currentIndex ? 'active' : ''}`;
thumbnail.dataset.index = index;
thumbnail.innerHTML = `
<div class="thumbnail-img">
<img src="${card.imageUrl}" alt="${card.title}" loading="lazy">
</div>
<div class="thumbnail-content">
<div class="thumbnail-title">${card.title}</div>
<div class="thumbnail-kingdom">${card.taxonomy.kingdom}</div>
</div>
`;
thumbnail.addEventListener('click', () => {
// This will be handled by the main app
thumbnail.dispatchEvent(new CustomEvent('thumbnailClick', {
detail: { index },
bubbles: true
}));
});
elements.cardThumbnails.appendChild(thumbnail);
});
}
// Show notification message
function showNotification(message, type = 'info') {
// Create notification element
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.textContent = message;
// Add to page
document.body.appendChild(notification);
// Remove after 3 seconds
setTimeout(() => {
notification.classList.add('fade-out');
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
}
// Get DOM elements (for event listeners)
function getElements() {
return elements;
}
// Public API
return {
init,
updateCardDisplay,
flipCard,
isCardFlipped,
resetCardFlip,
updateThumbnails,
showNotification,
getElements
};
})();
// ============================================================================
// Filter Controller Module
// ============================================================================
const FilterController = (function() {
// DOM Elements
const elements = {
searchInput: document.getElementById('search-input'),
searchClear: document.getElementById('search-clear'),
kingdomFilter: document.getElementById('kingdom-filter'),
phylumFilter: document.getElementById('phylum-filter'),
classFilter: document.getElementById('class-filter'),
clearFiltersBtn: document.getElementById('clear-filters'),
activeFiltersContainer: document.getElementById('active-filters'),
addCardBtn: document.getElementById('add-card-btn'),
quizModeBtn: document.getElementById('quiz-mode-btn')
};
// Initialize filter controls
function init() {
populateFilterOptions();
setupEventListeners();
updateActiveFiltersDisplay();
console.log('Filter Controller initialized');
}
// Populate dropdowns with available options
function populateFilterOptions() {
const options = CardManager.getFilterOptions();
// Clear existing options (except first)
while (elements.kingdomFilter.options.length > 1) {
elements.kingdomFilter.remove(1);
}
while (elements.phylumFilter.options.length > 1) {
elements.phylumFilter.remove(1);
}
while (elements.classFilter.options.length > 1) {
elements.classFilter.remove(1);
}
// Add kingdom options
options.kingdoms.sort().forEach(kingdom => {
const option = document.createElement('option');
option.value = kingdom;
option.textContent = kingdom;
elements.kingdomFilter.appendChild(option);
});
// Add phylum options
options.phyla.sort().forEach(phylum => {
const option = document.createElement('option');
option.value = phylum;
option.textContent = phylum;
elements.phylumFilter.appendChild(option);
});
// Add class options
options.classes.sort().forEach(className => {
const option = document.createElement('option');
option.value = className;
option.textContent = className;
elements.classFilter.appendChild(option);
});
}
// Set up event listeners
function setupEventListeners() {
// Search input with debounce
let searchTimeout;
elements.searchInput.addEventListener('input', function() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
applyFilters();
}, 300);
});
// Search clear button
elements.searchClear.addEventListener('click', function() {
elements.searchInput.value = '';
applyFilters();
});
// Filter dropdowns
elements.kingdomFilter.addEventListener('change', applyFilters);
elements.phylumFilter.addEventListener('change', applyFilters);
elements.classFilter.addEventListener('change', applyFilters);
// Clear all filters button
elements.clearFiltersBtn.addEventListener('click', clearAllFilters);
// Add card button
elements.addCardBtn.addEventListener('click', function() {
CardCreation.openModal();
});
// Quiz mode button
elements.quizModeBtn.addEventListener('click', function() {
QuizEngine.startQuiz();
});
}
// Apply current filters
function applyFilters() {
const filters = {
kingdom: elements.kingdomFilter.value || null,
phylum: elements.phylumFilter.value || null,
class: elements.classFilter.value || null,
search: elements.searchInput.value.trim()
};
CardManager.applyFilters(filters);
updateActiveFiltersDisplay();
// Notify main app to reload card
if (typeof window.BiologyFlashcards !== 'undefined') {
window.BiologyFlashcards.loadCard();
}
}
// Clear all filters
function clearAllFilters() {
elements.searchInput.value = '';
elements.kingdomFilter.value = '';
elements.phylumFilter.value = '';
elements.classFilter.value = '';
applyFilters();
UIController.showNotification('All filters cleared', 'info');
}
// Update active filters display
function updateActiveFiltersDisplay() {
const filters = CardManager.applyFilters;
elements.activeFiltersContainer.innerHTML = '';
const activeFilters = [];
if (elements.searchInput.value.trim()) {
activeFilters.push({
type: 'search',
label: `Search: "${elements.searchInput.value.trim()}"`,
key: 'search'
});
}
if (elements.kingdomFilter.value) {
activeFilters.push({
type: 'kingdom',
label: `Kingdom: ${elements.kingdomFilter.value}`,
key: 'kingdom'
});
}
if (elements.phylumFilter.value) {
activeFilters.push({
type: 'phylum',
label: `Phylum: ${elements.phylumFilter.value}`,
key: 'phylum'
});
}
if (elements.classFilter.value) {
activeFilters.push({
type: 'class',
label: `Class: ${elements.classFilter.value}`,
key: 'class'
});
}
if (activeFilters.length === 0) {
const noFiltersMsg = document.createElement('div');
noFiltersMsg.textContent = 'No active filters';
noFiltersMsg.style.color = '#999';
noFiltersMsg.style.fontStyle = 'italic';
elements.activeFiltersContainer.appendChild(noFiltersMsg);
return;
}
activeFilters.forEach(filter => {
const filterTag = document.createElement('div');
filterTag.className = 'active-filter-tag';
const label = document.createElement('span');
label.textContent = filter.label;
const removeBtn = document.createElement('button');
removeBtn.className = 'remove-filter';
removeBtn.innerHTML = '<i class="fas fa-times"></i>';
removeBtn.title = `Remove ${filter.type} filter`;
removeBtn.addEventListener('click', () => {
removeFilter(filter.key);
});
filterTag.appendChild(label);
filterTag.appendChild(removeBtn);
elements.activeFiltersContainer.appendChild(filterTag);
});
}
// Remove specific filter
function removeFilter(filterKey) {
switch(filterKey) {
case 'search':
elements.searchInput.value = '';
break;
case 'kingdom':
elements.kingdomFilter.value = '';
break;
case 'phylum':
elements.phylumFilter.value = '';
break;
case 'class':
elements.classFilter.value = '';
break;
}
applyFilters();
}
// Get DOM elements (for other modules)
function getElements() {
return elements;
}
// Public API
return {
init,
applyFilters,
clearAllFilters,
updateActiveFiltersDisplay,
getElements
};
})();
// ============================================================================
// Card Creation Module
// ============================================================================
const CardCreation = (function() {
// DOM Elements
const elements = {
modal: document.getElementById('card-creation-modal'),
modalClose: document.getElementById('modal-close'),
modalCancel: document.getElementById('modal-cancel'),
form: document.getElementById('card-creation-form'),
titleInput: document.getElementById('card-title-input'),
imageUrlInput: document.getElementById('card-image-url'),
imagePreview: document.getElementById('image-preview'),
kingdomInput: document.getElementById('card-kingdom'),
phylumInput: document.getElementById('card-phylum'),
classInput: document.getElementById('card-class'),
descriptionInput: document.getElementById('card-description'),
habitatInput: document.getElementById('card-habitat'),
dietInput: document.getElementById('card-diet'),
sizeInput: document.getElementById('card-size'),
distributionInput: document.getElementById('card-distribution'),
conservationInput: document.getElementById('card-conservation'),
funFactInput: document.getElementById('card-fun-fact'),
categoriesInput: document.getElementById('card-categories'),
difficultySelect: document.getElementById('card-difficulty')
};
// Initialize module
function init() {
setupEventListeners();
console.log('Card Creation module initialized');
}
// Set up event listeners
function setupEventListeners() {
// Close modal buttons
elements.modalClose.addEventListener('click', closeModal);
elements.modalCancel.addEventListener('click', closeModal);
// Close modal when clicking outside
elements.modal.addEventListener('click', function(event) {
if (event.target === elements.modal) {
closeModal();
}
});
// Image URL preview
elements.imageUrlInput.addEventListener('input', updateImagePreview);
// Form submission
elements.form.addEventListener('submit', handleFormSubmit);
// Keyboard shortcuts
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape' && elements.modal.classList.contains('active')) {
closeModal();
}
});
}
// Open modal
function openModal() {
resetForm();
elements.modal.classList.add('active');
document.body.style.overflow = 'hidden';
elements.titleInput.focus();
}
// Close modal
function closeModal() {
elements.modal.classList.remove('active');
document.body.style.overflow = '';
}
// Reset form to default state
function resetForm() {
elements.form.reset();
elements.imagePreview.innerHTML = `
<div class="image-placeholder">
<i class="fas fa-image"></i>
<span>Image preview will appear here</span>
</div>
`;
elements.difficultySelect.value = 'medium';
}
// Update image preview
function updateImagePreview() {
const url = elements.imageUrlInput.value.trim();
if (!url) {
elements.imagePreview.innerHTML = `
<div class="image-placeholder">
<i class="fas fa-image"></i>
<span>Image preview will appear here</span>
</div>
`;
return;
}
// Create new image to test loading
const img = new Image();
img.onload = function() {
elements.imagePreview.innerHTML = '';
const previewImg = document.createElement('img');
previewImg.src = url;
previewImg.alt = 'Image preview';
elements.imagePreview.appendChild(previewImg);
};
img.onerror = function() {
elements.imagePreview.innerHTML = `
<div class="image-placeholder error">
<i class="fas fa-exclamation-triangle"></i>
<span>Unable to load image. Please check the URL.</span>
</div>
`;
};
img.src = url;
}
// Handle form submission
function handleFormSubmit(event) {
event.preventDefault();
if (!validateForm()) {
return;
}
// Gather form data
const cardData = {
title: elements.titleInput.value.trim(),
imageUrl: elements.imageUrlInput.value.trim(),
taxonomy: {
kingdom: elements.kingdomInput.value.trim(),
phylum: elements.phylumInput.value.trim(),
class: elements.classInput.value.trim()
},
details: {
description: elements.descriptionInput.value.trim(),
habitat: elements.habitatInput.value.trim() || 'Not specified',
diet: elements.dietInput.value.trim() || 'Not specified',
size: elements.sizeInput.value.trim() || 'Not specified',
distribution: elements.distributionInput.value.trim() || 'Not specified',
conservation: elements.conservationInput.value.trim() || 'Not specified',
funFact: elements.funFactInput.value.trim() || 'No fun fact available'
},
categories: elements.categoriesInput.value.trim()
? elements.categoriesInput.value.trim().split(',').map(cat => cat.trim()).filter(cat => cat)
: [],
difficulty: elements.difficultySelect.value
};
// Add card via CardManager
try {
const newCard = CardManager.addUserCard(cardData);
// Close modal
closeModal();
// Show success notification
UIController.showNotification(`Card "${newCard.title}" created successfully!`, 'success');
// Refresh UI
if (typeof window.BiologyFlashcards !== 'undefined') {
window.BiologyFlashcards.loadCard();
}
// Update filters dropdowns
FilterController.init?.();
} catch (error) {
console.error('Failed to create card:', error);
UIController.showNotification('Failed to create card. Please try again.', 'error');
}
}
// Validate form
function validateForm() {
const requiredFields = [
{ element: elements.titleInput, name: 'Organism Name' },