-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1504 lines (1349 loc) Β· 62.9 KB
/
script.js
File metadata and controls
1504 lines (1349 loc) Β· 62.9 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
// Navigation active link handling
document.addEventListener('DOMContentLoaded', function() {
// Set active navigation link based on current page
const currentPage = window.location.pathname.split('/').pop() || 'index.html';
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
const linkHref = link.getAttribute('href');
if (linkHref === currentPage || (currentPage === '' && linkHref === 'index.html')) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
// Mobile menu toggle
const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
const navLinksContainer = document.querySelector('.nav-links');
if (mobileMenuToggle && navLinksContainer) {
mobileMenuToggle.addEventListener('click', function() {
this.classList.toggle('active');
navLinksContainer.classList.toggle('active');
});
// Close menu when clicking on a link
navLinks.forEach(link => {
link.addEventListener('click', function() {
mobileMenuToggle.classList.remove('active');
navLinksContainer.classList.remove('active');
});
});
// Close menu when clicking outside
document.addEventListener('click', function(e) {
if (!mobileMenuToggle.contains(e.target) && !navLinksContainer.contains(e.target)) {
mobileMenuToggle.classList.remove('active');
navLinksContainer.classList.remove('active');
}
});
}
// Handle notification icon click
const notificationIcon = document.querySelector('.notification-icon');
if (notificationIcon) {
notificationIcon.addEventListener('click', function() {
showNotification('No new notifications');
});
}
// Handle profile click - redirect to dashboard if logged in
const userProfile = document.querySelector('.user-profile');
if (userProfile) {
userProfile.addEventListener('click', function() {
const token = localStorage.getItem('token');
if (token) {
window.location.href = 'dashboard.html';
} else {
window.location.href = 'login.html';
}
});
}
// Check authentication and update UI
updateAuthUI();
// Register Page Functionality (Animal Registration only)
// Only initialize on animal registration page, not user registration page
const currentPage = window.location.pathname.split('/').pop() || 'index.html';
// Check if this is NOT the user registration page
if (document.getElementById('registerForm') &&
currentPage === 'register.html' &&
!window.USER_REGISTRATION_PAGE) {
initRegisterPage();
}
// Identify Page Functionality
// Use setTimeout to ensure auth-guard has finished
if (document.getElementById('identifyBtn')) {
setTimeout(() => {
// Check if still on identify page (not redirected by auth)
if (window.location.pathname.includes('identify.html')) {
initIdentifyPage();
}
}, 100);
}
// Animals List Page Functionality
if (document.getElementById('animalsGrid')) {
initAnimalsListPage();
}
});
// Authentication Helper Functions
function updateAuthUI() {
let user = null;
if (window.localStorageAPI) {
user = window.localStorageAPI.getCurrentUser();
} else {
// Fallback
const userJson = localStorage.getItem('scanimal_current_user');
user = userJson ? JSON.parse(userJson) : null;
}
const authButtons = document.getElementById('authButtons');
const userMenu = document.getElementById('userMenu');
const userNameDisplay = document.getElementById('userNameDisplay');
if (user) {
// User is logged in
if (authButtons) authButtons.style.display = 'none';
if (userMenu) userMenu.style.display = 'flex';
if (userNameDisplay) userNameDisplay.textContent = user.name;
} else {
// User is not logged in
if (authButtons) authButtons.style.display = 'flex';
if (userMenu) userMenu.style.display = 'none';
}
}
function getAuthToken() {
if (window.localStorageAPI) {
return localStorage.getItem('scanimal_token');
}
return localStorage.getItem('token');
}
function checkAuth() {
if (window.localStorageAPI) {
if (!window.localStorageAPI.isAuthenticated()) {
const currentPage = window.location.pathname.split('/').pop();
localStorage.setItem('redirectAfterLogin', currentPage);
window.location.href = 'login.html';
return false;
}
return true;
}
// Fallback
const token = getAuthToken();
if (!token) {
const currentPage = window.location.pathname.split('/').pop();
localStorage.setItem('redirectAfterLogin', currentPage);
window.location.href = 'login.html';
return false;
}
return true;
}
// Register Page Functions (Animal Registration)
function initRegisterPage() {
// Check authentication - this is for animal registration page
if (!checkAuth()) {
return;
}
const form = document.getElementById('registerForm');
if (!form) {
console.error('Register form not found');
return;
}
const photoInputs = document.querySelectorAll('.photo-input');
if (photoInputs.length === 0) {
console.error('Photo inputs not found');
return;
}
// Handle photo uploads and previews
photoInputs.forEach(input => {
input.addEventListener('change', function(e) {
const file = e.target.files[0];
const photoNum = this.getAttribute('data-photo');
const preview = document.getElementById(`preview${photoNum}`);
if (file && preview) {
// Validate file type
if (!file.type.startsWith('image/')) {
alert('Please select an image file');
this.value = ''; // Clear input
return;
}
const reader = new FileReader();
reader.onload = function(e) {
if (preview) {
const imageData = e.target.result;
preview.src = imageData;
preview.classList.add('active');
preview.style.display = 'block';
preview.style.zIndex = '10';
preview.style.position = 'absolute';
preview.style.top = '0';
preview.style.left = '0';
preview.style.width = '100%';
preview.style.height = '100%';
preview.style.objectFit = 'cover';
preview.style.borderRadius = '8px';
preview.style.background = 'white';
// Hide upload icon and text
const label = preview.parentElement;
if (label) {
const uploadIcon = label.querySelector('.upload-icon');
const uploadText = label.querySelector('.upload-text');
if (uploadIcon) {
uploadIcon.style.display = 'none';
}
if (uploadText) {
uploadText.style.display = 'none';
}
}
// Force reflow to ensure display
void preview.offsetHeight;
console.log('Image preview displayed for photo', photoNum);
} else {
console.error('Preview element not found for photo', photoNum);
}
};
reader.onerror = function() {
console.error('Error reading file');
alert('Error reading image file. Please try again.');
};
reader.readAsDataURL(file);
}
});
});
// Handle form submission
form.addEventListener('submit', async function(e) {
e.preventDefault();
// Check authentication
const token = getAuthToken();
if (!token) {
alert('Please login to register an animal.');
window.location.href = 'login.html';
return;
}
// Validate photos
const photos = [];
photoInputs.forEach(input => {
if (input.files.length > 0) {
photos.push(input.files[0]);
}
});
if (photos.length < 1) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = 'Please upload at least 1 photo of the animal.';
errorDiv.style.cssText = 'display: block; padding: 15px; margin-bottom: 20px; background-color: #ffebee; color: #c62828; border-radius: 5px; border-left: 4px solid #c62828;';
form.insertBefore(errorDiv, form.firstChild);
setTimeout(() => errorDiv.remove(), 5000);
submitBtn.disabled = false;
submitBtn.textContent = originalText;
return;
}
// Show processing message
const submitBtn = form.querySelector('.btn-generate');
const originalText = submitBtn.textContent;
submitBtn.disabled = true;
submitBtn.textContent = 'Registering animal...';
// Convert photos to base64
if (!window.localStorageAPI || !window.localStorageAPI.filesToBase64) {
alert('System error. Please refresh the page.');
submitBtn.disabled = false;
submitBtn.textContent = originalText;
return;
}
window.localStorageAPI.filesToBase64(photos).then((base64Images) => {
// Prepare animal data
const animalTypeEl = document.getElementById('animalType');
const genderEl = document.getElementById('gender');
const colorEl = document.getElementById('color');
if (!animalTypeEl || !genderEl || !colorEl) {
alert('Form error. Please refresh the page.');
submitBtn.disabled = false;
submitBtn.textContent = originalText;
return;
}
const animalData = {
animalType: animalTypeEl.value,
breed: document.getElementById('breed')?.value || '',
gender: genderEl.value,
color: colorEl.value,
markings: document.getElementById('markings')?.value || '',
description: document.getElementById('description')?.value || '',
images: base64Images
};
// Validate required fields
if (!animalData.animalType || !animalData.gender || !animalData.color) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = 'Please fill in all required fields (Animal Type, Gender, Color).';
errorDiv.style.cssText = 'display: block; padding: 15px; margin-bottom: 20px; background-color: #ffebee; color: #c62828; border-radius: 5px; border-left: 4px solid #c62828;';
form.insertBefore(errorDiv, form.firstChild);
setTimeout(() => errorDiv.remove(), 5000);
submitBtn.disabled = false;
submitBtn.textContent = originalText;
return;
}
// Register animal using localStorage API
if (!window.localStorageAPI.registerAnimal) {
alert('System error. Please refresh the page.');
submitBtn.disabled = false;
submitBtn.textContent = originalText;
return;
}
const result = window.localStorageAPI.registerAnimal(animalData);
if (result.success) {
// Reset button
submitBtn.disabled = false;
submitBtn.textContent = originalText;
// Show success popup with animal details
showRegistrationSuccessPopup(result.animal, animalData);
// Reset form
form.reset();
photoInputs.forEach(input => {
const photoNum = input.getAttribute('data-photo');
const preview = document.getElementById(`preview${photoNum}`);
if (preview) {
preview.src = '';
preview.classList.remove('active');
preview.style.display = 'none';
const label = preview.parentElement;
if (label) {
const uploadIcon = label.querySelector('.upload-icon');
const uploadText = label.querySelector('.upload-text');
if (uploadIcon) uploadIcon.style.display = 'block';
if (uploadText) uploadText.style.display = 'block';
}
}
});
} else {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = result.message || 'Failed to register animal. Please try again.';
errorDiv.style.cssText = 'display: block; padding: 15px; margin-bottom: 20px; background-color: #ffebee; color: #c62828; border-radius: 5px; border-left: 4px solid #c62828;';
form.insertBefore(errorDiv, form.firstChild);
setTimeout(() => errorDiv.remove(), 5000);
submitBtn.disabled = false;
submitBtn.textContent = originalText;
}
}).catch((error) => {
console.error('Error processing images:', error);
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.textContent = 'Error processing images. Please try again.';
errorDiv.style.cssText = 'display: block; padding: 15px; margin-bottom: 20px; background-color: #ffebee; color: #c62828; border-radius: 5px; border-left: 4px solid #c62828;';
form.insertBefore(errorDiv, form.firstChild);
setTimeout(() => errorDiv.remove(), 5000);
submitBtn.disabled = false;
submitBtn.textContent = originalText;
});
});
}
function generateAnimalID(animalType) {
const prefix = {
'cow': 'PK-C',
'buffalo': 'PK-B',
'goat': 'PK-G'
}[animalType] || 'PK-A';
const year = new Date().getFullYear();
const count = JSON.parse(localStorage.getItem('animals') || '[]').length + 1;
const idNum = String(count).padStart(4, '0');
return `${prefix}-${idNum}-${year}`;
}
// Extract image features for pattern matching
function extractImageFeatures(imageData, file) {
// In a real application, this would use AI/ML to extract unique patterns
// For demo purposes, we'll create a simplified feature vector
return {
size: file.size,
type: file.type,
timestamp: Date.now(),
hash: simpleHash(imageData) // Simple hash for pattern matching
};
}
// Simple hash function for pattern matching
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(16);
}
// Compare image features for pattern matching
function compareImageFeatures(features1, features2) {
// In real app, this would use advanced AI/ML algorithms
// For demo, we use simplified comparison
const sizeSimilarity = Math.abs(features1.size - features2.size) / Math.max(features1.size, features2.size);
const hashSimilarity = features1.hash === features2.hash ? 1 :
(features1.hash.substring(0, 8) === features2.hash.substring(0, 8) ? 0.7 : 0);
// Combined similarity score (0-1)
return (hashSimilarity * 0.8) + ((1 - sizeSimilarity) * 0.2);
}
// Identify Page Functions
function initIdentifyPage() {
console.log('Initializing identify page...');
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const startCameraBtn = document.getElementById('startCamera');
const capturePhotoBtn = document.getElementById('capturePhoto');
const stopCameraBtn = document.getElementById('stopCamera');
const uploadImageBtn = document.getElementById('uploadImage');
const fileInput = document.getElementById('fileInput');
const clearImageBtn = document.getElementById('clearImage');
const identifyBtn = document.getElementById('identifyBtn');
const statusText = document.getElementById('statusText');
const resultsSection = document.getElementById('resultsSection');
const previewImg = document.getElementById('previewImg');
const uploadedPreview = document.getElementById('uploadedImagePreview');
// Check if all required elements exist
if (!video || !canvas || !startCameraBtn || !uploadImageBtn || !identifyBtn) {
console.error('Required elements not found on identify page', {
video: !!video,
canvas: !!canvas,
startCameraBtn: !!startCameraBtn,
uploadImageBtn: !!uploadImageBtn,
identifyBtn: !!identifyBtn
});
return;
}
console.log('All required elements found, setting up event listeners...');
let stream = null;
let currentImageData = null;
let currentImageFeatures = null;
const ctx = canvas.getContext('2d');
// Start camera - works on all devices (desktop, mobile, tablet)
if (startCameraBtn) {
startCameraBtn.addEventListener('click', async function() {
console.log('Start camera clicked');
if (statusText) {
statusText.textContent = 'Requesting camera access...';
statusText.style.color = '';
}
try {
// First try with back camera preference (for mobile)
let constraints = {
video: {
facingMode: { ideal: 'environment' }
}
};
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
} catch (err1) {
// If that fails, try with any camera (for desktop)
console.log('Trying with any camera...');
constraints = { video: true };
stream = await navigator.mediaDevices.getUserMedia(constraints);
}
if (stream) {
video.srcObject = stream;
video.style.display = 'block';
video.play();
canvas.style.display = 'none';
if (uploadedPreview) uploadedPreview.style.display = 'none';
startCameraBtn.style.display = 'none';
if (capturePhotoBtn) capturePhotoBtn.style.display = 'inline-block';
if (stopCameraBtn) stopCameraBtn.style.display = 'inline-block';
identifyBtn.disabled = true;
if (statusText) {
statusText.textContent = 'Camera active - Position animal in frame and click Capture Photo';
statusText.style.color = '#4CAF50';
}
}
} catch (err) {
// If camera fails, suggest using upload (works on all devices)
if (statusText) {
statusText.textContent = 'Camera not available. Please use the "Upload Picture" button instead.';
statusText.style.color = '#c62828';
}
console.error('Camera error:', err);
alert('Camera access denied or not available. Please use the "Upload Picture" button to upload an image from your device.');
// Upload button remains available - it works on all devices
}
});
}
// Capture photo from camera
if (capturePhotoBtn) {
capturePhotoBtn.addEventListener('click', function() {
if (video && video.videoWidth > 0 && video.videoHeight > 0) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Clear background image
canvas.style.backgroundImage = 'none';
ctx.drawImage(video, 0, 0);
// Convert canvas to image data
currentImageData = canvas.toDataURL('image/jpeg');
// Create a file-like object for feature extraction
const blob = dataURLtoBlob(currentImageData);
const file = new File([blob], 'captured-photo.jpg', { type: 'image/jpeg' });
currentImageFeatures = extractImageFeatures(currentImageData, file);
// Display captured image
if (previewImg) previewImg.src = currentImageData;
if (uploadedPreview) uploadedPreview.style.display = 'block';
if (video) video.style.display = 'none';
if (canvas) canvas.style.display = 'none';
// Enable identify button
identifyBtn.disabled = false;
if (clearImageBtn) clearImageBtn.style.display = 'inline-block';
capturePhotoBtn.style.display = 'none';
if (statusText) {
statusText.textContent = 'Photo captured - Ready to identify';
statusText.style.color = '';
}
}
});
}
// Helper function to convert data URL to blob
function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
// Stop camera
if (stopCameraBtn) {
stopCameraBtn.addEventListener('click', function() {
if (stream) {
stream.getTracks().forEach(track => track.stop());
stream = null;
}
if (video) video.style.display = 'none';
if (canvas) {
canvas.style.display = 'block';
canvas.style.backgroundImage = "url('/assets/pattern-img.png')";
canvas.style.backgroundSize = 'cover';
canvas.style.backgroundPosition = 'center';
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
if (uploadedPreview) uploadedPreview.style.display = 'none';
if (startCameraBtn) startCameraBtn.style.display = 'inline-block';
if (capturePhotoBtn) capturePhotoBtn.style.display = 'none';
stopCameraBtn.style.display = 'none';
identifyBtn.disabled = true;
if (statusText) {
statusText.textContent = 'Upload or capture an image to begin identification...';
statusText.style.color = '';
}
});
}
// Upload image
if (uploadImageBtn && fileInput) {
uploadImageBtn.addEventListener('click', function() {
console.log('Upload image clicked');
fileInput.click();
});
}
fileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
// Validate file type
if (!file.type.startsWith('image/')) {
if (statusText) {
statusText.textContent = 'Please select an image file (jpg, png, etc.)';
statusText.style.color = '#c62828';
}
fileInput.value = ''; // Clear input
return;
}
// Validate file size (max 10MB)
if (file.size > 10 * 1024 * 1024) {
if (statusText) {
statusText.textContent = 'Image file is too large. Please use an image smaller than 10MB.';
statusText.style.color = '#c62828';
}
fileInput.value = ''; // Clear input
return;
}
const reader = new FileReader();
reader.onload = function(e) {
currentImageData = e.target.result;
currentImageFeatures = extractImageFeatures(currentImageData, file);
// Display image
if (previewImg) previewImg.src = currentImageData;
if (uploadedPreview) uploadedPreview.style.display = 'block';
if (canvas) {
canvas.style.display = 'none';
canvas.style.backgroundImage = 'none';
}
if (video) video.style.display = 'none';
// Stop camera if running
if (stream) {
stream.getTracks().forEach(track => track.stop());
stream = null;
}
// Enable identify button
identifyBtn.disabled = false;
if (clearImageBtn) clearImageBtn.style.display = 'inline-block';
if (statusText) {
statusText.textContent = 'Image loaded - Ready to identify';
statusText.style.color = '';
}
};
reader.onerror = function() {
if (statusText) {
statusText.textContent = 'Error reading image file. Please try again.';
statusText.style.color = '#c62828';
}
};
reader.readAsDataURL(file);
}
});
// Clear image
// Clear image button
if (clearImageBtn) {
clearImageBtn.addEventListener('click', function() {
currentImageData = null;
currentImageFeatures = null;
if (previewImg) previewImg.src = '';
if (uploadedPreview) uploadedPreview.style.display = 'none';
if (canvas) {
canvas.style.display = 'block';
canvas.style.backgroundImage = "url('/assets/pattern-img.png')";
canvas.style.backgroundSize = 'cover';
canvas.style.backgroundPosition = 'center';
// Clear canvas content
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
identifyBtn.disabled = true;
clearImageBtn.style.display = 'none';
if (resultsSection) resultsSection.style.display = 'none';
if (statusText) {
statusText.textContent = 'Upload or capture an image to begin identification...';
statusText.style.color = '';
}
if (fileInput) fileInput.value = '';
});
}
// Identify animal using pattern matching
if (identifyBtn) {
identifyBtn.addEventListener('click', async function() {
console.log('Identify button clicked');
if (!currentImageFeatures) {
if (statusText) {
statusText.textContent = 'Please upload or capture an image first.';
statusText.style.color = '#c62828';
}
return;
}
identifyBtn.disabled = true;
if (statusText) statusText.textContent = 'Analyzing image patterns...';
// Pattern matching process using localStorage API
setTimeout(() => {
if (!window.localStorageAPI) {
showNoMatchResults('System error. Please refresh the page.');
identifyBtn.disabled = false;
return;
}
const animals = window.localStorageAPI.getAnimals();
if (animals.length === 0) {
showNoMatchResults('No animals registered in database. Please register animals first.');
identifyBtn.disabled = false;
return;
}
// Pattern matching: Compare uploaded image with registered animal photos
let bestMatch = null;
let bestMatchScore = 0;
const matchThreshold = 0.5; // 50% similarity threshold (lowered for better matching)
animals.forEach(animal => {
if (animal.images && animal.images.length > 0) {
// Compare with each image
animal.images.forEach(imageData => {
try {
// Extract features from stored base64 image
const file = new File([], 'stored-image.jpg', { type: 'image/jpeg' });
const storedFeatures = extractImageFeatures(imageData, file);
const similarity = compareImageFeatures(currentImageFeatures, storedFeatures);
if (similarity > bestMatchScore) {
bestMatchScore = similarity;
bestMatch = animal;
}
} catch (error) {
console.error('Error comparing images:', error);
}
});
}
});
// Check if match is above threshold
if (bestMatch && bestMatchScore >= matchThreshold) {
showMatchResults(bestMatch, bestMatchScore);
} else {
showNoMatchResults(null, bestMatchScore);
}
identifyBtn.disabled = false;
}, 1500);
});
function showMatchResults(animal, confidence) {
if (!statusText || !resultsSection) {
console.error('Status text or results section not found');
return;
}
statusText.textContent = `Animal identified! (${Math.round(confidence * 100)}% confidence)`;
statusText.style.color = '#4CAF50';
resultsSection.style.display = 'block';
// Get animal image (use first image if available - base64 from localStorage)
const animalImage = animal.images && animal.images.length > 0 ? animal.images[0] : '';
const imageDisplay = animalImage ?
`<img src="${animalImage}" alt="Animal photo" class="match-animal-image" style="max-width: 100%; border-radius: 10px; border: 3px solid #4CAF50;">` :
`<div class="match-animal-placeholder">${getEmojiForType(animal.animalType)}</div>`;
resultsSection.innerHTML = `
<div class="match-result-container">
<div style="background: #e8f5e9; padding: 20px; border-radius: 10px; margin-bottom: 20px; text-align: center;">
<h3 style="color: #4CAF50; margin-bottom: 10px;">Your Animal Details Are Here</h3>
<p style="color: #666;">Animal ID: <strong style="color: #4CAF50; font-size: 18px;">${animal.animalId || animal._id}</strong></p>
</div>
<div class="match-result-header">
<h2 class="match-found-title">β
Match Found!</h2>
<span class="confidence-badge">${Math.round(confidence * 100)}% Match</span>
</div>
<div class="match-result-card">
<div class="match-animal-image-container">
${imageDisplay}
</div>
<div class="match-status-banner">
<span class="match-status-text">Match Found!</span>
</div>
<div class="match-details-grid">
<div class="match-detail-item">
<span class="detail-label">Animal ID</span>
<span class="detail-value">${animal.animalId || animal._id}</span>
</div>
<div class="match-detail-item">
<span class="detail-label">Type</span>
<span class="detail-value">${animal.animalType.charAt(0).toUpperCase() + animal.animalType.slice(1)}</span>
</div>
<div class="match-detail-item">
<span class="detail-label">Gender</span>
<span class="detail-value">${animal.gender.charAt(0).toUpperCase() + animal.gender.slice(1)}</span>
</div>
${animal.breed ? `
<div class="match-detail-item">
<span class="detail-label">Breed</span>
<span class="detail-value">${animal.breed}</span>
</div>
` : ''}
${animal.color ? `
<div class="match-detail-item">
<span class="detail-label">Color</span>
<span class="detail-value">${animal.color}</span>
</div>
` : ''}
<div class="match-detail-item">
<span class="detail-label">Owner</span>
<span class="detail-value">${animal.ownerId?.name || 'Unknown'}</span>
</div>
${animal.markings ? `
<div class="match-detail-item" style="grid-column: 1 / -1;">
<span class="detail-label">Markings</span>
<span class="detail-value">${animal.markings}</span>
</div>
` : ''}
<div class="match-detail-item">
<span class="detail-label">Registered</span>
<span class="detail-value">${new Date(animal.registeredAt).toLocaleDateString()}</span>
</div>
</div>
<div class="verification-status">
<svg class="verified-icon" viewBox="0 0 24 24" fill="none">
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z" fill="currentColor"/>
</svg>
<span>Owner Verified</span>
</div>
<div class="match-action-button">
<button onclick="window.searchAnimalById('${animal.animalId || animal._id}')" class="btn btn-primary btn-view-profile">View Full Details</button>
</div>
</div>
<div class="match-result-actions">
<button onclick="if(document.getElementById('clearImage')) document.getElementById('clearImage').click()" class="btn btn-secondary">Identify Another</button>
</div>
</div>
`;
identifyBtn.disabled = false;
}
function getEmojiForType(type) {
const emojis = {
'cow': 'π',
'buffalo': 'π',
'goat': 'π'
};
return emojis[type] || 'πΎ';
}
function showNoMatchResults(customMessage, confidence) {
statusText.textContent = 'No match found';
resultsSection.style.display = 'block';
let message = customMessage || 'No matching animal found in the database.';
if (confidence !== undefined && confidence > 0) {
message += ` Best match confidence was only ${Math.round(confidence * 100)}% (requires 60%+).`;
}
resultsSection.innerHTML = `
<h2>β Animal Not Identified</h2>
<div class="no-match-results">
<div class="no-match-icon">β οΈ</div>
<p class="no-match-message">${message}</p>
<div class="guidance-box">
<h3>What to do next:</h3>
<ul class="guidance-list">
<li>Ensure the photo is clear and shows the animal's face/nose clearly</li>
<li>Check that the animal is registered in the system</li>
<li>Try taking the photo from a different angle or with better lighting</li>
<li>Make sure there are no obstructions blocking the animal's face</li>
<li>If this is a new animal, <a href="register.html">register it first</a></li>
</ul>
</div>
<div class="photo-tips-box">
<h3>Photo Quality Tips:</h3>
<div class="tips-grid">
<div class="tip-item">
<strong>β Good:</strong> Clear, well-lit, focused on face
</div>
<div class="tip-item">
<strong>β Avoid:</strong> Blurry, too far, poor lighting
</div>
<div class="tip-item">
<strong>β Good:</strong> Face fills most of the frame
</div>
<div class="tip-item">
<strong>β Avoid:</strong> Obstructions, other animals in frame
</div>
</div>
</div>
<div class="no-match-actions">
<a href="register.html" class="btn btn-primary">Register New Animal</a>
<button onclick="document.getElementById('clearImage').click()" class="btn btn-secondary">Try Again</button>
</div>
</div>
`;
identifyBtn.disabled = false;
});
}
// Search by Animal ID functionality
const searchAnimalIdInput = document.getElementById('searchAnimalId');
const searchByIdBtn = document.getElementById('searchByIdBtn');
if (searchByIdBtn && searchAnimalIdInput) {
searchByIdBtn.addEventListener('click', function() {
const animalId = searchAnimalIdInput.value.trim();
if (animalId) {
window.searchAnimalById(animalId);
} else {
if (statusText) {
statusText.textContent = 'Please enter an Animal ID';
statusText.style.color = '#c62828';
}
}
});
// Allow Enter key to search
searchAnimalIdInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
searchByIdBtn.click();
}
});
}
console.log('Identify page initialized successfully');
}
// Animals List Page Functions
function initAnimalsListPage() {
const searchInput = document.getElementById('searchInput');
const filterSelect = document.getElementById('filterType');
const animalsGrid = document.getElementById('animalsGrid');
const emptyState = document.getElementById('emptyState');
if (!animalsGrid) {
console.error('Animals grid not found');
return;
}
let allAnimals = [];
// Load animals from localStorage
function loadAnimals() {
if (window.localStorageAPI) {
allAnimals = window.localStorageAPI.getAnimals();
console.log('Loaded animals from localStorage:', allAnimals.length);
if (allAnimals.length === 0) {
console.log('No animals found in localStorage');
showEmptyState();
} else {
displayAnimals();
}
} else {
console.error('localStorage API not loaded');
showEmptyState();
}
}
// Display animals with filters
function displayAnimals() {
const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
const filterType = filterSelect ? filterSelect.value : '';
let filteredAnimals = [...allAnimals];
// Filter by search term
if (searchTerm) {
filteredAnimals = filteredAnimals.filter(animal => {
const animalId = animal.animalId || animal._id;
const ownerName = animal.ownerId?.name || '';
return animalId.toLowerCase().includes(searchTerm) ||
ownerName.toLowerCase().includes(searchTerm) ||
(animal.animalType && animal.animalType.toLowerCase().includes(searchTerm));
});
}
// Filter by type
if (filterType) {
filteredAnimals = filteredAnimals.filter(animal => animal.animalType === filterType);
}
// Display animals
if (filteredAnimals.length === 0) {
showEmptyState();
} else {
if (animalsGrid) {
animalsGrid.style.display = 'grid';
animalsGrid.innerHTML = filteredAnimals.map(animal => createAnimalCard(animal)).join('');