// Установите здесь ваш реальный BACKEND_URL, полученный от cloudflared
window.BACKEND_URL = 'https://excellence-bibliographic-libraries-malta.trycloudflare.com'; // ЗАМЕНИТЕ ЭТОТ URL
document.addEventListener('DOMContentLoaded', () => {
const agreementCheckbox = document.getElementById('agreement');
const signaturePadDiv = document.getElementById('signaturePad');
const canvas = document.getElementById('signatureCanvas');
// Улучшаем качество подписи и решаем проблему с координатами
const signaturePad = new SignaturePad(canvas, {
penColor: 'rgb(0, 0, 0)'
});
function resizeCanvas() {
const ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
signaturePad.clear(); // Очищаем после изменения размера
}
window.addEventListener("resize", resizeCanvas);
resizeCanvas();
const clearSignatureButton = document.getElementById('clearSignature');
const companionPhone = document.getElementById('companionPhone');
const companionBirthDate = document.getElementById('companionBirthDate');
const addChildButton = document.getElementById('addChild');
const removeChildButton = document.getElementById('removeChild');
const childrenContainer = document.getElementById('childrenContainer');
const dateMask = {
alias: 'datetime',
inputFormat: 'dd.mm.yyyy',
placeholder: 'дд.мм.гггг',
showMaskOnHover: false,
showMaskOnFocus: true
};
Inputmask(dateMask).mask(companionBirthDate);
Inputmask({
mask: '+7 (999)-999-99-99',
placeholder: '_',
showMaskOnHover: false,
showMaskOnFocus: true
}).mask(companionPhone);
clearSignatureButton.style.display = 'none';
agreementCheckbox.addEventListener('change', () => {
if (agreementCheckbox.checked) {
signaturePadDiv.style.display = 'block';
// Принудительно пересчитываем размер холста после того, как он стал видимым
resizeCanvas();
} else {
signaturePadDiv.style.display = 'none';
}
signaturePad.clear();
clearSignatureButton.style.display = 'none';
});
clearSignatureButton.addEventListener('click', () => {
signaturePad.clear();
clearSignatureButton.style.display = 'none';
});
signaturePad.addEventListener('beginStroke', () => {
clearSignatureButton.style.display = 'block';
});
const updateButtons = () => {
const childCount = childrenContainer.children.length;
if (childCount > 1) {
removeChildButton.style.display = 'inline-block';
addChildButton.classList.add('ms-2'); // Добавляем отступ, когда есть кнопка "Удалить"
} else {
removeChildButton.style.display = 'none';
addChildButton.classList.remove('ms-2'); // Убираем отступ, когда кнопки "Удалить" нет
}
if (childCount <= 1) { // Используем <= 1, чтобы текст менялся правильно
addChildButton.textContent ='Добавить ребенка';
} else {
addChildButton.textContent = 'Добавить еще ребенка';
}
};
const addChild = () => {
const childCount = childrenContainer.children.length + 1;
const newChildEntry = document.createElement('div');
newChildEntry.className = 'child-entry';
newChildEntry.id = `childEntry${childCount}`;
const nameLabel = childCount > 1 ? `ФИО ребёнка ${childCount}` : 'ФИО ребёнка';
const dobLabel = childCount > 1 ? `Дата рождения ребёнка ${childCount}` : 'Дата рождения ребёнка';
newChildEntry.innerHTML = `
`;
childrenContainer.appendChild(newChildEntry);
Inputmask(dateMask).mask(document.getElementById(`childBirthDate${childCount}`));
updateButtons();
};
const removeChild = () => {
if (childrenContainer.children.length > 0) {
childrenContainer.lastChild.remove();
updateButtons();
}
};
addChildButton.addEventListener('click', addChild);
removeChildButton.addEventListener('click', removeChild);
const form = document.getElementById('registrationForm');
const welcomeOverlay = document.getElementById('welcomeOverlay');
welcomeOverlay.addEventListener('click', () => {
welcomeOverlay.style.display = 'none';
});
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
// Use BACKEND_URL for WebSocket connection as well
const ws = new WebSocket(`${wsProtocol}://${BACKEND_URL.replace(/(^https?:\\/\\/)|(\\/$)/g, '')}`);
ws.onopen = () => {
console.log('Connected to WebSocket');
};
ws.onmessage = event => {
const message = JSON.parse(event.data);
if (message.action === 'hideWelcome') {
welcomeOverlay.style.display = 'none';
} else if (message.action === 'showWelcome') {
welcomeOverlay.style.display = 'block';
}
};
// Проверяем, является ли хост "админским"
const isAdminHost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
if (isAdminHost) {
document.addEventListener('keydown', function(e) {
if (e.code === 'Space') {
welcomeOverlay.style.display = 'none';
}
});
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
// Проверка на заполнение всех основных полей
const companionPhone = document.getElementById('companionPhone').value.trim();
const representativeFullName = document.getElementById('representativeFullName').value.trim();
const relationship = document.getElementById('relationship').value.trim();
const companionBirthDate = document.getElementById('companionBirthDate').value.trim();
if (!companionPhone || !representativeFullName || !relationship || !companionBirthDate) {
alert('Пожалуйста, заполните все поля контактной информации и данных о представителе.');
return;
}
if (childrenContainer.children.length === 0) {
alert('Пожалуйста, добавьте хотя бы одного ребенка.');
return;
}
if (!agreementCheckbox.checked) {
alert('Пожалуйста, согласитесь с правилами.');
return;
}
if (signaturePad.isEmpty()) {
alert('Пожалуйста, поставьте подпись.');
return;
}
const companionBirthDateValue = document.getElementById('companionBirthDate').value;
if (companionBirthDateValue) {
const year = parseInt(companionBirthDateValue.split('.')[2], 10);
if (!isNaN(year) && year < 1900) {
alert('Год рождения сопровождающего не может быть ранее 1900 года.');
return;
}
}
const children = [];
const childEntries = childrenContainer.querySelectorAll('.child-entry');
for (const [index, entry] of Array.from(childEntries).entries()) {
const childId = index + 1;
const fullNameInput = entry.querySelector(`#childFullName${childId}`);
const birthDateInput = entry.querySelector(`#childBirthDate${childId}`);
if (!fullNameInput.value.trim() || !birthDateInput.value.trim()) {
alert(`Пожалуйста, заполните все данные для ребёнка ${childId}.`);
return;
}
if (fullNameInput && birthDateInput) {
const birthDateValue = birthDateInput.value;
if (birthDateValue) {
const year = parseInt(birthDateValue.split('.')[2], 10);
if (!isNaN(year) && year < 1900) {
alert(`Год рождения ребёнка ${childId} не может быть ранее 1900 года.`);
return;
}
}
children.push({
fullName: fullNameInput.value,
birthDate: birthDateInput.value
});
}
}
const data = {
children,
representativeFullName: document.getElementById('representativeFullName').value,
relationship: document.getElementById('relationship').value,
companionBirthDate: document.getElementById('companionBirthDate').value,
companionPhone: document.getElementById('companionPhone').value,
signature: signaturePad.toDataURL('image/png'),
source: 'lumiks' // Добавляем источник
};
try {
const response = await fetch(`${BACKEND_URL}/api/submit`, { // Обновляем URL
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (response.ok) {
const successModal = document.getElementById('successModal');
successModal.classList.add('show');
setTimeout(() => {
successModal.classList.remove('show');
form.reset();
signaturePad.clear();
agreementCheckbox.checked = false;
signaturePadDiv.style.display = 'none';
clearSignatureButton.style.display = 'none';
childrenContainer.innerHTML = '';
addChild(); // Добавляем обратно первое поле для ребенка
}, 2500); // Закрыть через 2.5 секунды
} else {
const error = await response.json();
alert(`Ошибка при отправке формы: ${error.error}`);
}
} catch (error) {
console.error('Error submitting form:', error);
alert('Произошла ошибка при отправке формы.');
}
});
addChild();
let inactivityTimer;
const showInactivityScreen = () => {
const welcomeOverlay = document.getElementById('welcomeOverlay');
// Update the image path to be absolute or relative to the Tilda page if it's hosted there
welcomeOverlay.style.backgroundImage = `url(\'${BACKEND_URL}/public/l-admin/img/image.png\')`; // Используем BACKEND_URL для изображения
welcomeOverlay.style.display = 'block';
};
const resetInactivityTimer = () => {
clearTimeout(inactivityTimer);
const welcomeOverlay = document.getElementById('welcomeOverlay');
if (welcomeOverlay.style.display === 'block') {
return;
}
inactivityTimer = setTimeout(showInactivityScreen, 60000);
};
['mousemove', 'mousedown', 'keypress', 'scroll', 'touchstart'].forEach(event => {
document.addEventListener(event, resetInactivityTimer);
});
resetInactivityTimer();
});