document.addEventListener('DOMContentLoaded', function () { const dateInput = document.getElementById('date'); const dateError = document.getElementById('dateError'); const calendarIcon = document.getElementById('calendar-icon'); // Set the minimum date to the current date const today = new Date().toISOString().split('T')[0]; if (dateInput) { dateInput.setAttribute('min', today); // Open the calendar when clicking on the icon calendarIcon.addEventListener('click', function () { dateInput.focus(); // Focus on the input first setTimeout(() => dateInput.showPicker(), 0); // Delay to ensure it's within a user gesture }); // Checking the selected date dateInput.addEventListener('input', function () { const selectedDate = new Date(dateInput.value); const todayDate = new Date(today); if (selectedDate < todayDate) { dateError.style.display = 'block'; } else { dateError.style.display = 'none'; } }); } const formSteps = document.querySelectorAll('.form-step'); const progressBarNum = document.getElementById('num'); const progressBar = document.getElementById('progress-bar-wrapper'); const progressBarFill = document.getElementById('progress-bar-fill'); const locationErrorStadt = document.getElementById('locationErrorStadt'); const locationStadt = document.getElementById('location'); const totalSteps = formSteps.length; let currentStep = 0; // Set the initial language based on URL parameter or localStorage const vacancyUrl = window.location.href; let selectedLanguage = localStorage.getItem('selectedLanguage'); if (!selectedLanguage) { selectedLanguage = vacancyUrl.includes('/en/') ? 'en' : 'de'; localStorage.setItem('selectedLanguage', selectedLanguage); } const languageContainer = document.getElementById('language'); if (languageContainer) { const languageBoxes = languageContainer.querySelectorAll('.language-box'); if(languageBoxes) { languageBoxes.forEach((box) => { if (box.dataset.language === selectedLanguage) { box.classList.add('active-language'); } else { box.classList.remove('active-language'); } box.addEventListener('click', () => { languageBoxes.forEach((b) => b.classList.remove('active-language')); box.classList.add('active-language'); localStorage.setItem('selectedLanguage', box.dataset.language); }); }); } } const savedTitle = localStorage.getItem('title'); const titleElement = document.getElementById('title-work-local'); if (titleElement) { titleElement.textContent = savedTitle || 'Title not found'; } else { console.warn("Element with ID 'title-work-local' not found on this page."); } function showStep(stepIndex) { formSteps.forEach((step, index) => { step.classList.toggle('active', index === stepIndex); }); updateProgressBar(stepIndex); currentStep = stepIndex; } function updateProgressBar(stepIndex) { progressBarNum.textContent = stepIndex + 1; if (stepIndex === 0) { progressBar.style.display = 'none'; } else { progressBar.style.display = 'flex'; progressBarFill.style.width = `${(stepIndex / (totalSteps - 1)) * 100}%`; } } function validateLocation() { if (locationStadt.value === 'start-location') { locationStadt.classList.remove('valid-location'); locationStadt.classList.add('invalid-location'); locationErrorStadt.style.display = 'block'; return false; } else { locationStadt.classList.remove('invalid-location'); locationStadt.classList.add('valid-location'); locationErrorStadt.style.display = 'none'; return true; } } // Navigation buttons for steps document.getElementById('next-step-1').addEventListener('click', function () { const firstname = document.getElementById('firstname'); const email = document.getElementById('email'); const phone = document.getElementById('phone'); const firstnameError = document.getElementById('nameError'); const emailError = document.getElementById('emailError'); const phoneError = document.getElementById('phoneError'); let isValid = true; if (!firstname.value.trim()) { firstnameError.style.display = 'flex'; firstnameError.textContent = 'Please enter your name.'; isValid = false; } else { firstnameError.style.display = 'none'; } const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!email.value.trim() || !emailPattern.test(email.value)) { emailError.style.display = 'flex'; emailError.textContent = 'Please enter a valid email address.'; isValid = false; } else { emailError.style.display = 'none'; } const phonePattern = /(\+?\d{1,4})?(\d{7,})/; if (!phone.value.trim() || !phonePattern.test(phone.value)) { phoneError.style.display = 'flex'; phoneError.textContent = 'Please enter a valid phone number.'; isValid = false; } else { phoneError.style.display = 'none'; } if (isValid && currentStep < totalSteps - 1) { showStep(currentStep + 1); } }); document.getElementById('prev-step-0').addEventListener('click', function () { if (currentStep > 0) { showStep(currentStep - 1); } }); document.getElementById('next-step-2').addEventListener('click', function () { if (currentStep < totalSteps - 1) { showStep(currentStep + 1); } }); document.getElementById('prev-step-1').addEventListener('click', function () { if (currentStep > 0) { showStep(currentStep - 1); } }); document.getElementById('next-step-3').addEventListener('click', function () { if (currentStep < totalSteps - 1) { showStep(currentStep + 1); } }); document.getElementById('prev-step-2').addEventListener('click', function () { if (currentStep > 0) { showStep(currentStep - 1); } }); // Функция загрузки файла на сервер function uploadFileToWordPress(file) { const formData = new FormData(); formData.append('file', file); formData.append('action', 'upload_file_to_wordpress'); formData.append('security', ajax_object.ajax_nonce); // Добавляем nonce для безопасности return fetch(ajax_object.ajax_url, { method: 'POST', body: formData, }) .then(response => { if (!response.ok) { throw new Error('Failed to upload file'); } return response.json(); }) .then(data => { if (data.success) { return data.data.url; // Возвращаем URL загруженного файла } else { throw new Error(data.data.error || 'File upload failed'); } }) .catch(error => { console.error("Upload error:", error); throw error; // Перебрасываем ошибку для дальнейшей обработки }); } let uploadedFiles = []; function setupFileUpload(fileInputId, uploadAreaId, fileNameDisplayId, removeButtonId) { const fileInput = document.getElementById(fileInputId); const uploadArea = document.getElementById(uploadAreaId); const fileNameDisplay = document.getElementById(fileNameDisplayId); const removeButton = document.getElementById(removeButtonId); // Массив загруженных файлов let isFileProcessing = false; // Флаг для защиты от параллельных загрузок // Проверяем существование всех элементов if (!fileInput || !uploadArea || !fileNameDisplay || !removeButton) { console.error("Missing required elements for file upload."); return; } // Обработчик на кнопку открытия диалога const triggerButton = document.querySelector(`[data-target="${fileInputId}"]`); if (!triggerButton) { console.error(`Trigger button for input #${fileInputId} is missing.`); return; } // **Защита от дублирующих обработчиков** if (!triggerButton.dataset.listenerAdded) { triggerButton.addEventListener('click', (event) => { event.preventDefault(); console.log("Opening file dialog..."); fileInput.click(); // Открываем диалог выбора файла }); triggerButton.dataset.listenerAdded = "true"; } // Обработчик выбора файла fileInput.addEventListener('change', async function () { if (isFileProcessing) { console.log("File processing is in progress, ignoring..."); return; } isFileProcessing = true; if (fileInput.files.length > 0) { try { await handleFiles(fileInput.files); } catch (error) { console.error("Error during file handling:", error); } } isFileProcessing = false; }); // Обработчик Drag & Drop uploadArea.addEventListener('drop', async function (event) { event.preventDefault(); if (isFileProcessing) { console.log("File processing is in progress, ignoring drop..."); return; } isFileProcessing = true; const files = event.dataTransfer.files; try { await handleFiles(files); } catch (error) { console.error("Error during file handling:", error); } isFileProcessing = false; }); // Предотвращение стандартного поведения при Drag & Drop ['dragenter', 'dragover', 'dragleave', 'drop'].forEach((eventName) => { uploadArea.addEventListener(eventName, preventDefaults, false); }); function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); } // Проверка формата файла и загрузка async function handleFiles(files) { const validExtensions = ['.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png']; for (let file of files) { const fileExtension = file.name.slice(((file.name.lastIndexOf('.') - 1) >>> 0) + 2).toLowerCase(); if (validExtensions.includes(`.${fileExtension}`)) { try { console.log("Uploading file:", file.name); const url = await uploadFileToWordPress(file); uploadedFiles.push(url); updateFileList(); } catch (error) { console.error(`Error uploading file "${file.name}":`, error.message); alert(`Ошибка загрузки файла "${file.name}": ${error.message}`); } } else { console.error(`Invalid file format: ${file.name}. Allowed formats: PDF, DOC, DOCX, JPG, JPEG, PNG.`); alert(`Недопустимый формат файла: ${file.name}. Разрешенные форматы: PDF, DOC, DOCX, JPG, JPEG, PNG.`); } } } // Обновление списка файлов function updateFileList() { if (uploadedFiles.length > 0) { fileNameDisplay.innerHTML = `