drink-it-cold/web/assets/js/main.js

335 lines
12 KiB
JavaScript
Raw Normal View History

/* Drink it cold – Interaktionen
Kein Framework, kein Tracking. */
(function () {
'use strict';
var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* ---------- Jahr im Footer ---------- */
var year = document.getElementById('year');
if (year) year.textContent = new Date().getFullYear();
/* ---------- Header: Zustand beim Scrollen ---------- */
var header = document.getElementById('header');
var lastY = -1;
function onScroll() {
var y = window.scrollY;
if (y === lastY) return;
lastY = y;
header.classList.toggle('is-scrolled', y > 24);
}
onScroll();
window.addEventListener('scroll', onScroll, { passive: true });
/* ---------- Mobile Navigation ---------- */
var toggle = document.getElementById('navToggle');
var nav = document.getElementById('nav');
function setNav(open) {
header.classList.toggle('is-open', open);
toggle.setAttribute('aria-expanded', String(open));
toggle.setAttribute('aria-label', open ? 'Menü schließen' : 'Menü öffnen');
document.body.style.overflow = open && window.innerWidth <= 1200 ? 'hidden' : '';
}
if (toggle && nav) {
toggle.addEventListener('click', function () {
setNav(!header.classList.contains('is-open'));
});
nav.addEventListener('click', function (e) {
if (e.target.closest('a')) setNav(false);
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && header.classList.contains('is-open')) {
setNav(false);
toggle.focus();
}
});
document.addEventListener('click', function (e) {
if (!header.classList.contains('is-open')) return;
if (header.contains(e.target)) return;
setNav(false);
});
window.addEventListener('resize', function () {
if (window.innerWidth > 1200) setNav(false);
});
}
/* ---------- Einblenden beim Scrollen ---------- */
var revealItems = document.querySelectorAll('.reveal');
if (!reduceMotion && 'IntersectionObserver' in window) {
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (!entry.isIntersecting) return;
var el = entry.target;
var siblings = Array.prototype.slice.call(
el.parentElement ? el.parentElement.children : []
).filter(function (n) { return n.classList.contains('reveal'); });
var i = Math.max(0, siblings.indexOf(el));
el.style.transitionDelay = Math.min(i * 70, 350) + 'ms';
el.classList.add('is-visible');
io.unobserve(el);
});
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
revealItems.forEach(function (el) { io.observe(el); });
} else {
revealItems.forEach(function (el) { el.classList.add('is-visible'); });
}
/* ---------- Galerie-Lightbox ---------- */
var lightbox = document.getElementById('lightbox');
var lightboxImg = document.getElementById('lightboxImg');
var lightboxClose = document.getElementById('lightboxClose');
var lastFocus = null;
function openLightbox(img) {
lastFocus = document.activeElement;
lightboxImg.src = img.currentSrc || img.src;
lightboxImg.alt = img.alt || '';
lightbox.hidden = false;
document.body.style.overflow = 'hidden';
lightboxClose.focus();
}
function closeLightbox() {
lightbox.hidden = true;
lightboxImg.removeAttribute('src');
document.body.style.overflow = '';
if (lastFocus) lastFocus.focus();
}
document.querySelectorAll('#gallery figure').forEach(function (fig) {
var img = fig.querySelector('img');
if (!img) return;
fig.addEventListener('click', function () { openLightbox(img); });
fig.setAttribute('tabindex', '0');
fig.setAttribute('role', 'button');
fig.setAttribute('aria-label', 'Bild vergrößern: ' + (img.alt || ''));
fig.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openLightbox(img);
}
});
});
if (lightbox) {
lightboxClose.addEventListener('click', closeLightbox);
lightbox.addEventListener('click', function (e) {
if (e.target === lightbox) closeLightbox();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !lightbox.hidden) closeLightbox();
});
}
/* ---------- Anfrageformular ---------- */
var form = document.getElementById('requestForm');
var status = document.getElementById('formStatus');
var MAIL = 'drinkitcold@web.de';
function showStatus(message, isError) {
if (!status) return;
status.textContent = message;
status.classList.add('is-visible');
status.classList.toggle('is-error', !!isError);
}
if (form) {
var submitButton = form.querySelector('button[type="submit"]');
var phone = form.elements['phone'];
var dateFrom = form.elements['from'];
var dateTo = form.elements['to'];
// „Bis“ folgt „Von“: gleicher Tag als Vorschlag, frühere Tage sind gesperrt
// (so wie im Buchungsformular der App).
if (dateFrom && dateTo) {
var syncDates = function () {
if (!dateFrom.value) return;
dateTo.min = dateFrom.value;
if (!dateTo.value || dateTo.value < dateFrom.value) {
dateTo.value = dateFrom.value;
}
};
dateFrom.addEventListener('change', syncDates);
dateFrom.addEventListener('input', syncDates);
if (dateFrom.value) dateTo.min = dateFrom.value;
}
form.addEventListener('submit', function (e) {
e.preventDefault();
if (!form.checkValidity()) {
form.reportValidity();
return;
}
// Eigene Hinweise zuerst leeren: sonst blockiert eine alte Meldung
// (z. B. "Bitte eine erreichbare Telefonnummer angeben") auch nach der
// Korrektur noch jeden weiteren Versuch.
if (phone) phone.setCustomValidity('');
if (dateTo) dateTo.setCustomValidity('');
// Nur die Ziffern zählen – Schreibweisen wie 0172 6384350,
// +49 172 638 43 50 oder 0172/6384350 sind alle gültig.
if (phone && phone.value.replace(/[^0-9]/g, '').length < 6) {
phone.setCustomValidity('Bitte eine erreichbare Telefonnummer angeben.');
form.reportValidity();
return;
}
if (dateFrom && dateTo && dateFrom.value && dateTo.value && dateTo.value < dateFrom.value) {
dateTo.setCustomValidity('Das Ende der Miete muss nach dem Beginn liegen.');
form.reportValidity();
return;
}
if (submitButton) submitButton.disabled = true;
showStatus('Ihre Anfrage wird gesendet …', false);
fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: { 'X-Requested-With': 'fetch', 'Accept': 'application/json' },
credentials: 'omit'
})
.then(function (response) {
return response.json()
.catch(function () { return {}; })
.then(function (payload) {
return { ok: response.ok && payload.ok !== false, message: payload.message || '' };
});
})
.then(function (result) {
if (result.ok) {
form.reset();
showStatus(result.message || 'Vielen Dank! Ihre Anfrage ist bei uns eingegangen.', false);
} else {
showStatus(result.message || ('Die Anfrage konnte nicht gesendet werden. Bitte schreiben Sie uns an ' + MAIL + '.'), true);
}
})
.catch(function () {
showStatus('Die Anfrage konnte nicht gesendet werden – bitte prüfen Sie Ihre Verbindung oder schreiben Sie uns an ' + MAIL + '.', true);
})
.then(function () {
if (submitButton) submitButton.disabled = false;
});
});
}
/* ---------- Verfügbarkeitskalender (Ampel aus /verfuegbarkeit.json) ---------- */
var avail = document.querySelector('[data-avail]');
if (avail) {
var grid = avail.querySelector('[data-avail-grid]');
var label = avail.querySelector('[data-avail-label]');
var note = avail.querySelector('[data-avail-note]');
var prev = avail.querySelector('[data-avail-prev]');
var next = avail.querySelector('[data-avail-next]');
var months = []; // [{ key: '2026-06', days: { '2026-06-01': {...} } }]
var cursor = 0;
var weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
var monthNames = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli',
'August', 'September', 'Oktober', 'November', 'Dezember'];
var isoDate = function (date) {
return date.getFullYear() + '-' +
String(date.getMonth() + 1).padStart(2, '0') + '-' +
String(date.getDate()).padStart(2, '0');
};
var render = function () {
var month = months[cursor];
if (!month || !grid) return;
var parts = month.key.split('-');
var year = Number(parts[0]);
var monthIndex = Number(parts[1]) - 1;
var today = isoDate(new Date());
if (label) label.textContent = monthNames[monthIndex] + ' ' + year;
var first = new Date(year, monthIndex, 1);
var offset = (first.getDay() + 6) % 7; // Montag = 0
var daysInMonth = new Date(year, monthIndex + 1, 0).getDate();
var html = '';
var i;
for (i = 0; i < offset; i++) {
html += '<div class="avail__day avail__day--empty"></div>';
}
for (i = 1; i <= daysInMonth; i++) {
var iso = year + '-' + String(monthIndex + 1).padStart(2, '0') + '-' + String(i).padStart(2, '0');
var day = month.days[iso];
var level = day ? day.level : 'unknown';
var classes = 'avail__day avail__day--' + level;
if (iso < today) classes += ' avail__day--past';
if (iso === today) classes += ' is-today';
var hint = '';
if (day && level !== 'unknown') {
hint = '<small>' + (day.free > 0 ? day.free + ' frei' : 'ausgebucht') + '</small>';
}
var title = day
? (day.free > 0 ? day.free + ' von ' + (day.free + day.booked) + ' Anhängern frei' : 'ausgebucht')
: 'keine Angabe';
html += '<div class="' + classes + '" title="' + title + '">' + i + hint + '</div>';
}
grid.innerHTML = html;
if (prev) prev.disabled = cursor <= 0;
if (next) next.disabled = cursor >= months.length - 1;
var shown = month.key;
if (note) {
var freeDays = 0;
var bookedDays = 0;
Object.keys(month.days).forEach(function (key) {
if (month.days[key].level === 'full' && key >= today) bookedDays++;
if (month.days[key].level !== 'unknown' && month.days[key].free > 0 && key >= today) freeDays++;
});
note.textContent = bookedDays === 0
? 'In diesem Monat ist noch jeder Tag buchbar.'
: freeDays + ' Tage mit freien Anhängern, ' + bookedDays + ' Tage ausgebucht. '
+ 'Tagesaktueller Stand, keine Reservierung.';
}
void shown;
};
var fill = function (payload) {
if (!payload || payload.ok === false) throw new Error('unavailable');
var byMonth = {};
(payload.days || []).forEach(function (day) {
var key = String(day.date).slice(0, 7);
if (!byMonth[key]) byMonth[key] = {};
byMonth[key][day.date] = day;
});
months = Object.keys(byMonth).sort().map(function (key) {
return { key: key, days: byMonth[key] };
});
if (!months.length) throw new Error('unavailable');
var currentKey = isoDate(new Date()).slice(0, 7);
cursor = 0;
months.forEach(function (month, index) {
if (month.key === currentKey) cursor = index;
});
render();
};
if (prev) prev.addEventListener('click', function () { if (cursor > 0) { cursor--; render(); } });
if (next) next.addEventListener('click', function () { if (cursor < months.length - 1) { cursor++; render(); } });
var start = new Date();
var end = new Date();
end.setDate(end.getDate() + 75);
fetch('/verfuegbarkeit.json?from=' + isoDate(start) + '&to=' + isoDate(end), { headers: { Accept: 'application/json' } })
.then(function (response) { return response.json().catch(function () { return {}; }); })
.then(fill)
.catch(function () {
if (label) label.textContent = 'Verfügbarkeit gerade nicht abrufbar';
if (note) note.textContent = 'Bitte fragen Sie Ihren Wunschtermin direkt an – wir melden uns mit einer Rückmeldung.';
if (prev) prev.disabled = true;
if (next) next.disabled = true;
});
void weekdays;
}
})();