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 = `
${uploadedFiles.map(url => `${url} `).join('')} `;
fileNameDisplay.classList.add('valid-file');
removeButton.style.display = 'inline';
} else {
fileNameDisplay.textContent = '';
removeButton.style.display = 'none';
}
}
// Удаление файлов из списка
removeButton.addEventListener('click', function () {
uploadedFiles = [];
updateFileList();
});
}
// Настройка загрузки для первого и второго блоков
setupFileUpload('resume1', 'upload-area1', 'file-name1', 'remove-file-btn1');
setupFileUpload('resume2', 'upload-area2', 'file-name2', 'remove-file-btn2');
// Handle form submission for the first form
document.getElementById('application-form').addEventListener('submit', function (event) {
if (this.submitting) return;
this.submitting = true;
event.preventDefault();
if (!validateLocation()) {
console.log('Location validation failed!');
this.submitting = false;
return;
}
const urlParams = new URLSearchParams(window.location.search);
const jobId = urlParams.get('job_id');
const formData = new FormData(event.target);
const dataTitleElement = document.getElementById('title-work-local');
const dataTitle = dataTitleElement ? dataTitleElement.textContent.trim() : null;
const uniqueKey = `locations_${dataTitle}`;
const selectedLocations = JSON.parse(localStorage.getItem(uniqueKey)) || [];
console.log('selectedLocations', selectedLocations)
if (!selectedLocations.length) {
console.log('No locations selected!');
this.submitting = false;
return;
}
let firstname = formData.get('firstname');
const email = formData.get('email');
const phone = formData.get('phone');
const nameParts = firstname.split(' ');
const lastname = nameParts.length > 1 ? nameParts.slice(1).join(' ') : '';
firstname = nameParts[0];
if (!firstname || !email || !phone) {
console.log('Missing required fields!');
this.submitting = false;
return;
}
const data = {
jobid: jobId,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
locations: selectedLocations,
language: localStorage.getItem('selectedLanguage'),
referrer: new URL(document.referrer).searchParams.get('utm_source') || 'Website'
};
fetch('https://recruiting01.god.de:5005/applications/first', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': '4cc98d781b76e3016f6c8d31896bac97bcca3f2f'
},
body: JSON.stringify(data)
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to submit the form');
}
})
.then(data => {
console.log('Success:', data);
const candidateId = data.data.candidateId;
document.getElementById('candidate-id').value = candidateId;
showStep(1);
})
.catch(error => {
console.error('Error:', error);
})
.finally(() => {
this.submitting = false;
});
});
// Handle form submission for the second form
document.getElementById('application-form2').addEventListener('submit', async function (event) {
event.preventDefault();
const submitButton = document.getElementById('submit-btn-form2');
submitButton.disabled = true;
const formData = new FormData(event.target);
const cvUrl = uploadedFiles.length > 0 ? uploadedFiles[0] : null;
const data = {
candidateId: formData.get('candidate-id'),
street: formData.get('street'),
zipcode: formData.get('postal_city').split(' ')[0],
city: formData.get('postal_city').split(' ')[1],
country: formData.get('country'),
website: formData.get('website'),
cv_url: cvUrl,
additional_files_url: uploadedFiles,
availability: formData.get('date')
};
try {
const response = await fetch('https://recruiting01.god.de:5005/applications/second', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': '4cc98d781b76e3016f6c8d31896bac97bcca3f2f'
},
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error('Failed to submit the form');
}
const responseData = await response.json();
window.location.href = '/thanks-for-your-application';
} catch (error) {
console.error('Error:', error);
submitButton.disabled = false;
}
});
document.getElementById('prev-step-page').addEventListener('click', function () {
window.history.back();
});
showStep(0);
});
document.getElementById('location')?.addEventListener('change', function () {
let storedLocations = JSON.parse(localStorage.getItem('selectedLocations')) || [];
const selectedOptions = Array.from(this.selectedOptions).map(option => option.value);
const index = selectedOptions.indexOf('start-location');
if (index > -1) {
selectedOptions.splice(index, 1);
}
selectedOptions.forEach(location => {
if (!storedLocations.includes(location)) {
storedLocations.push(location);
}
});
localStorage.setItem('selectedLocations', JSON.stringify(storedLocations));
updateSelectedLocationsDisplay(storedLocations);
});
document.addEventListener('DOMContentLoaded', async function () {
const locationList = document.getElementById('location');
const dataTitleElement = document.getElementById('title-work-local');
const dataTitle = dataTitleElement ? dataTitleElement.textContent.trim() : null;
const uniqueKey = `locations_${dataTitle}`;
const storedLocations = JSON.parse(localStorage.getItem(uniqueKey)) || [];
let selectedLocations = JSON.parse(localStorage.getItem(`selectedLocations_${uniqueKey}`)) || [];
if (storedLocations.length === 1) {
selectedLocations = [storedLocations[0]];
localStorage.setItem(`selectedLocations_${uniqueKey}`, JSON.stringify(selectedLocations));
}
function updateLocationList() {
// Сначала проверяем, что titleText уже получен и обновляем storedLocations
const titleElement = document.getElementById('title-work-local');
const titleText = titleElement ? titleElement.textContent.trim() : '';
// Обновляем storedLocations в зависимости от названия вакансии
if (titleText === 'Initiativbewerbung') {
console.log(titleText);
storedLocations.length = 0; // Очищаем массив
storedLocations.push(...[
'Berlin', 'Braunschweig', 'Breslau', 'Dortmund',
'Frankfurt am Main', 'Hamburg', 'Kaunas',
'Köln', 'München', 'Pune', 'Ratingen',
'Vilnius', 'Wolfsburg'
]);
}
console.log(storedLocations);
// Теперь отрисовываем список городов после обновления storedLocations
locationList.innerHTML = ''; // Очищаем старый список
storedLocations.forEach(location => {
const li = document.createElement('li');
li.textContent = location;
if (selectedLocations.includes(location)) {
li.classList.add('active-city');
}
li.addEventListener('click', function () {
toggleLocationSelection(location, li);
});
locationList.appendChild(li);
});
}
function toggleLocationSelection(location, element) {
if (selectedLocations.includes(location)) {
selectedLocations = selectedLocations.filter(loc => loc !== location);
element.classList.remove('active-city');
} else {
selectedLocations.push(location);
element.classList.add('active-city');
}
localStorage.setItem(`selectedLocations_${uniqueKey}`, JSON.stringify(selectedLocations));
}
const jobId = new URLSearchParams(window.location.search).get('job_id');
const titleElement = document.getElementById('title-work-local');
if (!jobId || !titleElement) {
if (titleElement) titleElement.textContent = 'Title not found';
return;
}
try {
const response = await fetch(`https://hyand.recruitee.com/api/offers/${jobId}`);
if (!response.ok) throw new Error('Ошибка при запросе');
const data = await response.json();
const siteLanguage = localStorage.getItem('selectedLanguage') || 'de';
const offerTitle = data?.offer?.translations?.[siteLanguage]?.sharing_title || 'Title not found';
// Записываем название в localStorage
localStorage.setItem('dataTitle', offerTitle);
// Отображаем название на странице
titleElement.textContent = offerTitle;
} catch (error) {
console.error(error);
titleElement.textContent = 'Title not found';
}
setTimeout(() => {
updateLocationList();
}, 1000);
});
_enterprise_development Archive - Hyand
Für unseren Kunden, ein international tätiges Logistikunternehmen, entwickelten wir ein individuelles Sales Planning Tool mit Low-Code in nur 5 Monaten.
Im Einzelhandel stellt die rechtssichere Auszeichnung von Warenpreisen gemäß der Preisangabenverordnung (PAngV) eine erhebliche Herausforderung dar...
Die Versandabteilung transportiert Fahrzeuge von einem Ort zum anderen. Um die Fahrzeuge zu identifizieren und zu lokalisieren, ...
Eines der größten deutschen Logistikzentren verwaltete sein Inventar manuell. Dies war eine sehr zeitaufwändige, fehleranfällige und ressourcenintensive Aufgabe.