Spaces:
Runtime error
Runtime error
File size: 10,572 Bytes
83517c2 e53009c 83517c2 8566af4 83517c2 8566af4 83517c2 8566af4 83517c2 |
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 |
// Helper function to sanitize religion names for IDs
function sanitizeReligionName(name) {
return name.replace(/\s+/g, '-');
}
// ==================== AUTHENTICATION ====================
function authenticate() {
const username = document.getElementById('authUsername').value.trim();
const password = document.getElementById('authPassword').value;
if (!username || !password) {
document.getElementById('result').innerHTML =
'<p class="error-msg">⚠️ Please fill in all fields</p>';
return;
}
const endpoint = window.location.pathname === '/signup' ? '/signup' : '/login';
fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password})
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = '/';
} else {
document.getElementById('result').innerHTML =
`<p class="error-msg">${data.message}</p>`;
}
});
}
function switchAuth() {
const newPath = window.location.pathname === '/signup' ? '/login' : '/signup';
window.location.href = newPath;
}
// ==================== ASSESSMENT ====================
var currentQuestion = 1;
var maxQuestionReached = 1;
var assessmentDataEl = document.getElementById('assessmentData');
var totalQuestions = assessmentDataEl ? parseInt(assessmentDataEl.getAttribute('data-total')) : 0;
var questionIds = assessmentDataEl ? JSON.parse(assessmentDataEl.getAttribute('data-ids')) : [];
// Show first question on load
window.addEventListener('DOMContentLoaded', function() {
if (assessmentDataEl) {
showQuestion(1);
}
// Add Enter key listener for password field if it exists
const passwordField = document.getElementById('authPassword');
if (passwordField) {
passwordField.addEventListener('keypress', function(e) {
if (e.key === 'Enter') authenticate();
});
}
});
function showQuestion(questionIndex) {
if (questionIndex > maxQuestionReached + 1) return;
if (questionIndex > maxQuestionReached) maxQuestionReached = questionIndex;
document.querySelectorAll('.question-block').forEach(function(block) {
block.classList.remove('active');
var blockIndex = parseInt(block.getAttribute('data-question-index'));
if (blockIndex === questionIndex) block.classList.add('active');
});
currentQuestion = questionIndex;
document.getElementById('questionCounter').textContent = 'Question ' + questionIndex + ' of ' + totalQuestions;
document.getElementById('progressBar').style.width = (questionIndex / totalQuestions) * 100 + '%';
updateNavigationButtons();
}
function updateNavigationButtons() {
// Check if we're on the last question and it's answered
var currentQuestionId = questionIds[currentQuestion - 1];
var radioName = 'q' + currentQuestionId;
var isAnswered = document.querySelector('input[name="' + radioName + '"]:checked') !== null;
if (currentQuestion === totalQuestions && isAnswered) {
document.getElementById('submitBtn').style.display = 'block';
}
}
function handleAnswer(radioElement) {
var questionIndex = parseInt(radioElement.getAttribute('data-question-index'));
// Only process if this is the current question
if (questionIndex !== currentQuestion) {
return;
}
// Auto-advance to next question after selection
setTimeout(function() {
if (questionIndex < totalQuestions) {
showQuestion(questionIndex + 1);
} else {
// Last question - show submit button
document.getElementById('submitBtn').style.display = 'block';
}
}, 400);
}
function goToNext() {
if (currentQuestion < totalQuestions) {
showQuestion(currentQuestion + 1);
}
}
function goToPrev() {
if (currentQuestion > 1) {
showQuestion(currentQuestion - 1);
}
}
function submitAssessment() {
var form = document.getElementById('assessmentForm');
var answers = [];
questionIds.forEach(function(qId) {
var radioName = 'q' + qId;
var selectedRadio = form.querySelector('input[name="' + radioName + '"]:checked');
if (selectedRadio) {
answers.push({
question_id: qId,
answer: selectedRadio.value
});
}
});
if (answers.length !== totalQuestions) {
document.getElementById('errorMsg').innerHTML =
'<p class="error-msg">⚠️ Please answer all questions</p>';
return;
}
document.getElementById('submitBtn').disabled = true;
document.getElementById('submitBtn').textContent = '✨ Calculating...';
fetch('/submit_assessment', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({answers: answers})
})
.then(function(response) { return response.json(); })
.then(function(data) {
if (data.success) {
window.location.reload();
} else {
document.getElementById('errorMsg').innerHTML =
'<p class="error-msg">' + data.message + '</p>';
document.getElementById('submitBtn').disabled = false;
document.getElementById('submitBtn').textContent = '✨ Discover Your Path';
}
});
}
function resetAssessment() {
if (!confirm('Are you sure you want to retake the assessment? Your current results will be cleared.')) {
return;
}
fetch('/reset_assessment', {
method: 'POST',
headers: {'Content-Type': 'application/json'}
})
.then(function(response) { return response.json(); })
.then(function(data) {
if (data.success) {
window.location.reload();
}
});
}
// ==================== CHAT FUNCTIONALITY ====================
var chatHistories = {};
function formatBotResponse(text) {
var div = document.createElement('div');
div.textContent = text;
var escaped = div.innerHTML;
// Check for bullet points
if (escaped.match(/\*\s+/g) || escaped.match(/•\s+/g) || escaped.match(/^\s*-\s+/gm)) {
var lines = escaped.split(/(?:\*|•|\n-)\s+/);
if (lines.length > 1) {
var formatted = lines[0].trim() ? lines[0].trim() + '<br><br>' : '';
formatted += '<ul style="margin: 0; padding-left: 20px; line-height: 1.8;">';
for (var i = 1; i < lines.length; i++) {
if (lines[i].trim()) {
formatted += '<li style="margin-bottom: 6px;">' + lines[i].trim() + '</li>';
}
}
return formatted + '</ul>';
}
}
return escaped.replace(/\n/g, '<br>');
}
function toggleChat(religionName) {
var chatId = 'chat-' + sanitizeReligionName(religionName);
var chatWindow = document.getElementById(chatId);
if (chatWindow.classList.contains('open')) {
chatWindow.classList.remove('open');
} else {
chatWindow.classList.add('open');
var inputId = 'input-' + sanitizeReligionName(religionName);
setTimeout(function() {
document.getElementById(inputId).focus();
}, 300);
}
}
function sendMessage(religionName) {
var inputId = 'input-' + sanitizeReligionName(religionName);
var messagesId = 'messages-' + sanitizeReligionName(religionName);
var sendBtnId = 'send-' + sanitizeReligionName(religionName);
var inputEl = document.getElementById(inputId);
var messagesEl = document.getElementById(messagesId);
var sendBtn = document.getElementById(sendBtnId);
var message = inputEl.value.trim();
if (!message) return;
// Initialize chat history if not exists
if (!chatHistories[religionName]) {
chatHistories[religionName] = [];
}
// Add user message to UI
var userMsgDiv = document.createElement('div');
userMsgDiv.className = 'chat-message user';
userMsgDiv.textContent = message;
messagesEl.appendChild(userMsgDiv);
// Clear input and disable send button
inputEl.value = '';
sendBtn.disabled = true;
// Show typing indicator
var typingDiv = document.createElement('div');
typingDiv.className = 'chat-typing';
typingDiv.textContent = '💭 Thinking...';
messagesEl.appendChild(typingDiv);
// Scroll to bottom
messagesEl.scrollTop = messagesEl.scrollHeight;
// Add to chat history
chatHistories[religionName].push({
role: 'user',
content: message
});
// Send to backend
fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
message: message,
religion: religionName,
history: chatHistories[religionName]
})
})
.then(function(response) { return response.json(); })
.then(function(data) {
messagesEl.removeChild(typingDiv);
if (data.success) {
var botMsgDiv = document.createElement('div');
botMsgDiv.className = 'chat-message bot';
// Format the response with proper bullet points
var formattedResponse = formatBotResponse(data.response);
botMsgDiv.innerHTML = formattedResponse;
messagesEl.appendChild(botMsgDiv);
chatHistories[religionName].push({
role: 'assistant',
content: data.response
});
} else {
var errorMsgDiv = document.createElement('div');
errorMsgDiv.className = 'chat-message bot';
errorMsgDiv.style.color = '#EF4444';
errorMsgDiv.textContent = '❌ ' + data.message;
messagesEl.appendChild(errorMsgDiv);
}
sendBtn.disabled = false;
messagesEl.scrollTop = messagesEl.scrollHeight;
})
.catch(function(error) {
messagesEl.removeChild(typingDiv);
var errorMsgDiv = document.createElement('div');
errorMsgDiv.className = 'chat-message bot';
errorMsgDiv.style.color = '#EF4444';
errorMsgDiv.textContent = '❌ Connection error';
messagesEl.appendChild(errorMsgDiv);
sendBtn.disabled = false;
messagesEl.scrollTop = messagesEl.scrollHeight;
});
}
|