document.addEventListener("DOMContentLoaded", function () { const tapToBeginScreen = document.getElementById("tapToBegin"); const termsPage = document.getElementById("termsPage"); const liveCamScreen = document.getElementById("liveCam"); const resultsPage = document.getElementById("resultsPage"); const userInfoForm = document.getElementById("userInfoForm"); const endSessionButton = document.getElementById("endSessionButton"); const restartButton = document.getElementById("restartButton"); const thankYouPage = document.getElementById("thankYouPage"); const ethnicityForm = document.getElementById("ethnicityForm"); const submitButton = document.getElementById("submitButton"); const backButton2 = document.getElementById("backButton2"); // Tap to Begin screen if (tapToBeginScreen) { tapToBeginScreen.addEventListener("click", function () { window.location.href = "terms.html"; }); } // Terms and Conditions page if (termsPage) { const acceptButton = document.getElementById("acceptButton"); const declineButton = document.getElementById("declineButton"); if (acceptButton) { acceptButton.addEventListener("click", function () { window.location.href = "photo.html"; }); } if (declineButton) { declineButton.addEventListener("click", function () { window.location.href = "thankyou.html"; }); } } // Live Cam screen if (liveCamScreen) { const video = document.getElementById("videoFeed"); const canvas = document.getElementById("frameOverlay"); const captureButton = document.getElementById("captureButton"); const capturedImage = document.getElementById("capturedImage"); let stream; // Get user media navigator.mediaDevices.getUserMedia({ video: true }) .then(function (mediaStream) { stream = mediaStream; video.srcObject = mediaStream; video.onloadedmetadata = function () { video.play(); }; }) .catch(function (err) { console.log("An error occurred: " + err); alert("Camera access is required for this study. Please enable camera permissions."); }); // Capture photo if (captureButton) { captureButton.addEventListener("click", async function () { // Disable button to prevent double-clicks captureButton.disabled = true; captureButton.textContent = "Processing..."; // Capture the image canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height); const imageData = canvas.toDataURL("image/png"); capturedImage.src = imageData; // Stop the camera if (stream) { stream.getTracks().forEach(track => track.stop()); } try { // Send image to backend const response = await fetch('/upload', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ image: imageData }) }); const data = await response.json(); if (data.success) { // Store session ID and results sessionStorage.setItem('session_id', data.session_id); sessionStorage.setItem('model_results', JSON.stringify(data.results)); sessionStorage.setItem('captured_image', imageData); console.log('Results stored:', data.results); // Redirect to results page window.location.href = "results.html"; } else { alert('Error processing image: ' + (data.error || 'Unknown error')); captureButton.disabled = false; captureButton.textContent = "Capture Photo"; } } catch (error) { console.error('Error uploading image:', error); alert('Failed to process image. Please try again.'); captureButton.disabled = false; captureButton.textContent = "Capture Photo"; } }); } } // Results page if (resultsPage) { // Load and display AI results when page loads window.addEventListener('load', function() { const modelResults = sessionStorage.getItem('model_results'); const capturedImage = sessionStorage.getItem('captured_image'); if (!modelResults) { alert('No results found. Please start over.'); window.location.href = 'index.html'; return; } // Display the captured image if available const imgElement = document.getElementById('capturedImageDisplay'); if (imgElement && capturedImage) { imgElement.src = capturedImage; } // Parse and display the AI results try { const results = JSON.parse(modelResults); const aiResultsDiv = document.getElementById("aiResults"); if (aiResultsDiv) { // Format the results nicely aiResultsDiv.innerHTML = `
${JSON.stringify(results, null, 2)}
`;
}
} catch (error) {
console.error('Error parsing results:', error);
alert('Error displaying results. Please try again.');
}
});
// Handle user info form submission
if (userInfoForm) {
userInfoForm.addEventListener("submit", function (event) {
event.preventDefault();
const sessionId = sessionStorage.getItem('session_id');
const userAge = document.getElementById("userAge").value;
const userRace = Array.from(document.getElementById("userRace").selectedOptions).map(option => option.value);
const userGender = document.getElementById("userGender").value;
// Store user responses
sessionStorage.setItem('user_age', userAge);
sessionStorage.setItem('user_race', JSON.stringify(userRace));
sessionStorage.setItem('user_gender', userGender);
// Send to backend
fetch('/save_survey', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
age: userAge,
race: userRace,
gender: userGender
})
}).then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = "gender.html";
} else {
alert('Error saving data. Please try again.');
}
})
.catch(error => {
console.error('Error:', error);
alert('Error saving data. Please try again.');
});
});
}
}
// End Session button
if (endSessionButton) {
endSessionButton.addEventListener("click", function () {
window.location.href = "thankyou.html";
});
}
// Restart button
if (restartButton) {
restartButton.addEventListener("click", function () {
sessionStorage.clear(); // Clear session data
window.location.href = "index.html";
});
}
// Yes button (send results)
const yesButton = document.getElementById("yesButton");
if (yesButton) {
yesButton.addEventListener("click", async function () {
const sessionId = sessionStorage.getItem('session_id');
const contactMethod = document.getElementById('contactMethod')?.value || 'none';
const contactInfo = document.getElementById('contactInfo')?.value || '';
if (contactMethod !== 'none' && contactInfo) {
try {
const response = await fetch('/send_results', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
contact_method: contactMethod,
contact_info: contactInfo
})
});
const data = await response.json();
if (data.success) {
if (data.sent) {
alert('Results sent successfully!');
}
}
} catch (error) {
console.error('Error sending results:', error);
}
}
window.location.href = "thankyou.html";
});
}
// No button (skip sending results)
const noButton = document.getElementById("noButton");
if (noButton) {
noButton.addEventListener("click", function () {
window.location.href = "gender.html";
});
}
// Automatically restart session after 15 seconds on thank you page
if (thankYouPage) {
// Clear session storage
sessionStorage.clear();
setTimeout(function () {
window.location.href = "index.html";
}, 15000);
}
// Function to toggle visibility of subcategories and their text inputs
function toggleSubcategories(checkbox, subcategoryId, textInputId) {
const subcategories = document.getElementById(subcategoryId);
const textInput = document.getElementById(textInputId);
if (checkbox.checked) {
if (subcategories) subcategories.style.display = "block";
if (textInput) textInput.style.display = "block";
} else {
if (subcategories) subcategories.style.display = "none";
if (textInput) textInput.style.display = "none";
}
}
// Add event listeners to main category checkboxes
const mainCategories = document.querySelectorAll(".main-category input[type='checkbox']");
mainCategories.forEach(checkbox => {
checkbox.addEventListener("change", (event) => {
switch (event.target.id) {
case 'black':
toggleSubcategories(event.target, 'blackSubcategories', 'africanAmericanInput');
break;
case 'asian':
toggleSubcategories(event.target, 'asianSubcategories', 'asianInput');
break;
case 'native-american':
toggleSubcategories(event.target, 'nativeSubcategories', 'nativeAmericanInput');
break;
case 'native-hawaiian':
toggleSubcategories(event.target, 'hawaiianSubcategories', 'nativeHawaiianInput');
break;
case 'white':
toggleSubcategories(event.target, 'whiteSubcategories', 'whiteInput');
break;
case 'other':
toggleSubcategories(event.target, '', 'otherInput');
break;
default:
break;
}
});
});
// Initialize visibility based on current checked state
mainCategories.forEach(checkbox => {
switch (checkbox.id) {
case 'black':
toggleSubcategories(checkbox, 'blackSubcategories', 'africanAmericanInput');
break;
case 'asian':
toggleSubcategories(checkbox, 'asianSubcategories', 'asianInput');
break;
case 'native-american':
toggleSubcategories(checkbox, 'nativeSubcategories', 'nativeAmericanInput');
break;
case 'native-hawaiian':
toggleSubcategories(checkbox, 'hawaiianSubcategories', 'nativeHawaiianInput');
break;
case 'other':
toggleSubcategories(checkbox, '', 'otherInput');
break;
case 'white':
toggleSubcategories(checkbox, 'whiteSubcategories', 'whiteInput');
break;
default:
break;
}
});
// Add event listener for ethnicity form submission
if (ethnicityForm) {
ethnicityForm.addEventListener("submit", async function (event) {
event.preventDefault();
const sessionId = sessionStorage.getItem('session_id');
// Collect all checked ethnicities
const selectedEthnicities = [];
mainCategories.forEach(checkbox => {
if (checkbox.checked) {
selectedEthnicities.push(checkbox.value || checkbox.id);
}
});
// Save ethnicity data
try {
await fetch('/save_survey', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
race: selectedEthnicities
})
});
} catch (error) {
console.error('Error saving ethnicity:', error);
}
window.location.href = "thankyou.html";
});
}
// Submit button
if (submitButton) {
submitButton.addEventListener("click", async function () {
const sessionId = sessionStorage.getItem('session_id');
// Collect Hispanic/Latino data
const hispanicCheckboxes = document.querySelectorAll('input[name="hispanic"]:checked');
const hispanicValues = Array.from(hispanicCheckboxes).map(cb => cb.value);
// Collect race data
const raceCheckboxes = document.querySelectorAll('input[name="race"]:checked');
const raceValues = Array.from(raceCheckboxes).map(cb => cb.value);
// Collect all subcategories
const subcategoryCheckboxes = document.querySelectorAll('.subcategories input[type="checkbox"]:checked');
const subcategoryValues = Array.from(subcategoryCheckboxes).map(cb => cb.value);
// Combine all race/ethnicity data
const allRaceData = [...hispanicValues, ...raceValues, ...subcategoryValues];
if (allRaceData.length === 0) {
alert('Please select at least one option');
return;
}
// Save race data and send to Supabase
try {
const saveResponse = await fetch('/save_survey', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
race: allRaceData.join(', ')
})
});
const saveData = await saveResponse.json();
if (saveData.success) {
// ✅ NOW send everything to Supabase
const sendResponse = await fetch('/send_results', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
contact_method: 'none', // No contact info for now
contact_info: ''
})
});
const sendData = await sendResponse.json();
if (sendData.success) {
console.log('✅ Data saved to Supabase!');
window.location.href = "thankyou.html";
} else {
console.error('Error sending to Supabase:', sendData.error);
// Still redirect even if Supabase fails
window.location.href = "thankyou.html";
}
} else {
alert('Error saving data. Please try again.');
}
} catch (error) {
console.error('Error:', error);
alert('Error saving data. Please try again.');
}
});
}
// Continue button
const conButton = document.getElementById("conButton");
if (conButton) {
conButton.addEventListener("click", async function () {
const sessionId = sessionStorage.getItem('session_id');
// Collect selected genders
const selectedGenders = [];
const genderCheckboxes = document.querySelectorAll('input[name="gender"]:checked');
genderCheckboxes.forEach(checkbox => {
selectedGenders.push(checkbox.value);
});
if (selectedGenders.length === 0) {
alert('Please select at least one option');
return;
}
// Save gender data to backend
try {
await fetch('/save_survey', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: sessionId,
gender: selectedGenders.join(', ')
})
});
// Navigate to race page
window.location.href = "race.html";
} catch (error) {
console.error('Error saving gender:', error);
alert('Error saving data. Please try again.');
}
});
}
// Back buttons
const backButton = document.getElementById("backButton");
if (backButton) {
backButton.addEventListener("click", function () {
window.location.href = "results.html";
});
}
if (backButton2) {
backButton2.addEventListener("click", function () {
window.location.href = "gender.html";
});
}
});