Spaces:
Sleeping
Sleeping
File size: 19,237 Bytes
894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 2b845ef 894ffa9 09af50b 2b845ef 09af50b 894ffa9 09af50b 2b845ef 894ffa9 2b845ef | 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 | 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 = `
<h3>AI Model Predictions:</h3>
<pre>${JSON.stringify(results, null, 2)}</pre>
`;
}
} 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";
});
}
}); |