<script>
document.addEventListener('DOMContentLoaded', function () {
// DOM elements
const calendarElement = document.getElementById('calendar');
const selectedDatesElement = document.getElementById('selected-dates');
const showDatesButton = document.getElementById('show-dates');
const submitButton = document.getElementById('submit0');
const monthYearDisplay = document.getElementById('month-year');
const prevMonthButton = document.getElementById('prev-month');
const nextMonthButton = document.getElementById('next-month');
const prevYearButton = document.getElementById('prev-year');
const nextYearButton = document.getElementById('next-year');
// Variables for date selection and current date
let selectedStartDate = null;
let selectedEndDate = null;
let currentDate = new Date();
let allSelectedDates = [];
const variables = ["XX01_01", "XX01_02", "XX01_03", "XX01_04", "XX01_05", "XX01_06", "XX01_07", "XX01_08", "XX01_10", "XX01_11", "XX01_12"];
// Weekdays array
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
// Function to create the calendar for a given year and month
function createCalendar(year, month) {
calendarElement.innerHTML = '';
// Create weekday headers
weekdays.forEach(day => {
const dayElement = document.createElement('div');
dayElement.textContent = day;
dayElement.classList.add('weekday');
calendarElement.appendChild(dayElement);
});
// Calculate the first day of the month and total days in the month
const firstDayOfMonth = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
// Adjust start day to match the calendar's layout
const startDay = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1;
// Create placeholders for days before the first day of the month
for (let i = 0; i < startDay; i++) {
const placeholder = document.createElement('div');
calendarElement.appendChild(placeholder);
}
// Create day elements for each day in the month
for (let day = 1; day <= daysInMonth; day++) {
const dayElement = document.createElement('div');
dayElement.textContent = day;
const date = new Date(year, month, day);
if (date.getDay() === 6 || date.getDay() === 0) {
dayElement.classList.add('weekend');
} else {
dayElement.addEventListener('click', (event) => toggleDateSelection(date, event));
}
calendarElement.appendChild(dayElement);
}
// Update the calendar to show selected dates
updateCalendar();
}
// Function to handle date selection logic
function toggleDateSelection(date, event) {
if (date.getDay() === 6 || date.getDay() === 0) {
return;
}
// Check if Ctrl key is pressed for multi-select
if (event.ctrlKey) {
const range = { start: date, end: null };
allSelectedDates.push(range);
} else {
if (!selectedStartDate || (selectedStartDate && selectedEndDate)) {
selectedStartDate = date;
selectedEndDate = null;
} else if (date < selectedStartDate) {
selectedEndDate = selectedStartDate;
selectedStartDate = date;
} else {
selectedEndDate = date;
}
}
updateCalendar();
}
// Function to update the calendar display with selected dates
function updateCalendar() {
const dayElements = calendarElement.querySelectorAll('div:not(.weekday)');
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth();
dayElements.forEach(dayElement => {
const day = dayElement.textContent;
const date = new Date(currentYear, currentMonth, day);
dayElement.classList.remove('selected', 'in-range');
// Highlight all selected date ranges
allSelectedDates.forEach(range => {
if (!range.end && date.toDateString() === range.start.toDateString()) {
dayElement.classList.add('selected');
} else if (range.start && range.end && date >= range.start && date <= range.end) {
dayElement.classList.add('in-range');
}
});
// Highlight currently selected start and end dates
if (selectedStartDate && date.toDateString() === selectedStartDate.toDateString()) {
dayElement.classList.add('selected');
}
if (selectedEndDate && date.toDateString() === selectedEndDate.toDateString()) {
dayElement.classList.add('selected');
}
if (selectedStartDate && selectedEndDate && date > selectedStartDate && date < selectedEndDate) {
dayElement.classList.add('in-range');
}
});
// Display the current month and year
monthYearDisplay.textContent = `${currentDate.toLocaleString('default', { month: 'long' })} ${currentYear}`;
}
// Function to show selected date ranges
function showSelectedDates() {
if (selectedStartDate) {
const range = { start: selectedStartDate, end: selectedEndDate };
allSelectedDates.push(range);
selectedStartDate = null;
selectedEndDate = null;
}
displaySelectedDates();
updateCalendar();
}
// Function to display selected date ranges
function displaySelectedDates() {
selectedDatesElement.innerHTML = '';
allSelectedDates.forEach((range, index) => {
const rangeElement = document.createElement('div');
if (range.end) {
const startDateFormatted = formatDate(range.start);
const endDateFormatted = formatDate(range.end);
rangeElement.innerHTML = `<span>${startDateFormatted}</span> - <span> ${endDateFormatted}</span>`;
} else {
const startDateFormatted = formatDate(range.start);
rangeElement.innerHTML = `<span>${startDateFormatted}</span>`;
}
const deleteButton = document.createElement('button');
deleteButton.innerHTML = '🗑';
deleteButton.classList.add('delete-button');
deleteButton.addEventListener('click', () => deleteSelectedDate(index));
rangeElement.appendChild(deleteButton);
selectedDatesElement.appendChild(rangeElement);
});
}
// Function to delete a selected date range
function deleteSelectedDate(index) {
// Remove the selected date range from the list
allSelectedDates.splice(index, 1);
// Clear the form variables and shift remaining values
for (let i = index; i < variables.length - 1; i++) {
const currentElement = document.getElementById(variables[i]);
const nextElement = document.getElementById(variables[i + 1]);
if (currentElement && nextElement) {
currentElement.value = nextElement.value;
}
}
// Clear the last variable
const lastElement = document.getElementById(variables[allSelectedDates.length]);
if (lastElement) lastElement.value = '';
saveSelectedDates();
displaySelectedDates();
updateCalendar();
}
// Function to format dates as DD.MM.YYYY
function formatDate(date) {
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
return `${day}.${month}.${year}`;
}
// Function to change the current month
function changeMonth(offset) {
currentDate.setMonth(currentDate.getMonth() + offset);
createCalendar(currentDate.getFullYear(), currentDate.getMonth());
}
// Function to change the current year
function changeYear(offset) {
currentDate.setFullYear(currentDate.getFullYear() + offset);
createCalendar(currentDate.getFullYear(), currentDate.getMonth());
}
// Function to save selected dates to localStorage and form variables
function saveSelectedDates() {
try {
if (allSelectedDates.length > variables.length) {
throw new Error('Not enough variables to store all selected dates.');
}
for (let i = 0; i < variables.length; i++) {
const element = document.getElementById(variables[i]);
if (i < allSelectedDates.length) {
const range = allSelectedDates[i];
const startFormatted = formatDate(range.start);
const endFormatted = range.end ? formatDate(range.end) : '';
element.value = endFormatted ? `${startFormatted} - ${endFormatted}` : startFormatted;
} else {
element.value = '';
}
}
localStorage.setItem('selectedDates', JSON.stringify(allSelectedDates));
console.log('Saved dates:', allSelectedDates);
return true; // Return true on success
} catch (error) {
console.error('Error saving dates:', error);
return false; // Return false on failure
}
}
// Function to load selected dates from localStorage
function loadSelectedDates() {
const savedDates = localStorage.getItem('selectedDates');
if (savedDates) {
allSelectedDates = JSON.parse(savedDates).map(range => ({
start: new Date(range.start),
end: range.end ? new Date(range.end) : null
}));
displaySelectedDates();
updateCalendar();
}
}
// Initial setup
createCalendar(currentDate.getFullYear(), currentDate.getMonth());
loadSelectedDates();
// Event listeners for buttons
showDatesButton.addEventListener('click', showSelectedDates);
prevMonthButton.addEventListener('click', () => changeMonth(-1));
nextMonthButton.addEventListener('click', () => changeMonth(1));
prevYearButton.addEventListener('click', () => changeYear(-1));
nextYearButton.addEventListener('click', () => changeYear(1));
// Event listener for the submit button
submitButton.addEventListener('click', () => {
const success = saveSelectedDates();
if (success) {
alert('Dates have been saved successfully.');
} else {
alert('Ups, there was a problem, please contact the admin.');
}
});
});
</script>