/* Be Their Someone · Christmas 2026 Static page. The only server it talks to is AL's existing donation backend (/php/*), which is why this page must be served from www.animalslebanon.org (same origin). */ (() => { 'use strict'; const IS_LOCAL = ['localhost', '127.0.0.1', ''].includes(location.hostname); const CONFIG = { campaign: 'xmas2026', minAmount: 10, currency: '840', // ISO 4217 USD, same as AL donate page (422 = LBP, not offered here) // AL backend endpoints. Root-relative on purpose, so they always hit the same host as this page. api: { forms: '/php/forms.php', countries: '/php/datasets.json.php?k=countries', paymentMonthly: '/php/payment_monthly.php?key=', }, countriesFallback: 'assets/countries.json', defaultCountry: 'lb', // Hidden-field values of AL's monthly page (/get-involved/monthly-giving-latest, served by donate.php). // TODO(AL dev): confirm whether `special` can carry a campaign tag (e.g. 'Christmas 2026') // without breaking reporting or payment_monthly.php. Until then we send the stock values. flow: { iam: 'monthly_giving_latest', special: 'Monthly New', steps: '3' }, // PayPal: the same hosted Donate button as AL's donate and monthly pages. It pays AL's partner // Animal People Forum (PayPal shows "ANIMAL PEOPLE INC"), with "Animals Lebanon" preselected as the purpose. // PayPal ignores a pre-filled amount, and "Make this a monthly donation" starts unticked, so the page // tells the donor what to enter and tick (the paypal hint in index.html). paypal: { url: 'https://givebutter.com/2026-holiday-season-campaign-4ho0bb' }, // Impact tiers: wording supplied for the campaign (2026-11-13). Adapted from AL's monthly giving page, // with vaccines at $20, $100 covering 6 months, and $250 "to an animal in need". // The line under the amount buttons uses the highest tier the chosen amount reaches. // Keep in sync with the "Your monthly gift of…" list in index.html. impact: [ [250, 'gives lifesaving emergency medical care to an animal in need'], [100, 'provides all the food and care for 6 months for a cat or dog'], [50, 'can spay or neuter a cat, preventing more homeless animals'], [20, 'can give the first vaccines to a rescued cat or dog'], ], // Used for amounts below the lowest tier (the $10 button, or a custom $10–19). // TODO(AL): confirm this wording, or supply a $10 line. impactBelow: 'helps give the first vaccines to a rescued cat or dog', // Locally there's no /php backend: simulate it so the UI flow can be tested. mock: IS_LOCAL, }; /* Slide IDs are the same numbers donate.js uses, because forms.php replies with "*" and the client compares that to the slide it is on. */ const SLIDE = { AMOUNT: 1, INFO: 2, PAY: 4, MONTHLY: 6 }; const PANEL_FOR = { [SLIDE.AMOUNT]: 'amount', [SLIDE.INFO]: 'info', [SLIDE.MONTHLY]: 'monthly', [SLIDE.PAY]: 'pay' }; const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; const $ = (s, el = document) => el.querySelector(s); const $$ = (s, el = document) => [...el.querySelectorAll(s)]; const form = $('#donate-form'); const card = $('#donate'); const F = name => form.elements[name]; // Mirrors donate.js globals: currentSlideID, nextSlideID, key, and the hidden "step" field. const st = { slide: 0, next: null, key: '', step: '1', busy: false }; /* ========================================================= Amount ========================================================= */ function getAmount() { const sel = $('input[name="preset"]:checked', form); if (!sel) return 0; if (sel.value === 'custom') return Math.floor(Number(F('custom_amount').value) || 0); return Number(sel.value); } F('custom_amount').addEventListener('focus', () => { $('input[name="preset"][value="custom"]').checked = true; onAmountChange(); }); F('custom_amount').addEventListener('input', () => { $('input[name="preset"][value="custom"]').checked = true; onAmountChange(); }); $$('input[name="preset"]', form).forEach(r => r.addEventListener('change', onAmountChange)); function onAmountChange() { clearErrors(); syncImpact(); } function syncImpact() { const el = $('[data-impact-text]', form); if (!el) return; const amt = getAmount(); const tier = CONFIG.impact.find(([min]) => amt >= min); const min = CONFIG.minAmount; el.textContent = tier ? `$${amt} a month ${tier[1]}.` : amt >= min ? `$${amt} a month ${CONFIG.impactBelow}.` : `Just $${min} a month ${CONFIG.impactBelow}.`; // Keep the PayPal instructions in step with the chosen amount. $$('[data-paypal-amount]', form).forEach(b => (b.textContent = amt >= CONFIG.minAmount ? `$${amt}` : 'your amount')); } /* ========================================================= Panels + progress ========================================================= */ function showPanel(name) { $$('.panel', form).forEach(p => (p.hidden = p.dataset.panel !== name)); const order = ['amount', 'info', 'monthly', 'pay']; const idx = order.indexOf(name); $$('.steps li').forEach(li => { const i = order.indexOf(li.dataset.step); li.classList.toggle('is-current', i === idx); li.classList.toggle('is-done', i < idx); }); const amt = getAmount(); $$('[data-summary]', form).forEach(el => (el.textContent = `$${amt} / month`)); $$('[data-summary-amount]', form).forEach(el => (el.textContent = `$${amt}`)); // Keep the card in view on mobile when the step changes. if (name !== 'amount' && card.getBoundingClientRect().top < 0) card.scrollIntoView({ block: 'start' }); const first = $(`[data-panel="${name}"] input:not([type=radio]), [data-panel="${name}"] select`, form); if (first && name !== 'amount') first.focus({ preventScroll: true }); } function goToAmount() { st.slide = 0; st.next = null; st.key = ''; st.step = '1'; showPanel('amount'); } $$('[data-back]', form).forEach(b => b.addEventListener('click', () => { if (st.slide === SLIDE.MONTHLY) { st.slide = SLIDE.INFO; st.next = SLIDE.MONTHLY; st.step = '2'; showPanel('info'); } else goToAmount(); })); /* ========================================================= Server protocol (port of donate.js: validateAmount / sendIt2 / nextStep / showNetCommerce) ========================================================= */ // Exactly the fields, order and formatting the original #donation_form serialises. function payload() { const amt = getAmount(); const custom = $('input[name="preset"]:checked', form)?.value === 'custom'; const f = CONFIG.flow; return new URLSearchParams([ ['other', custom ? `$ ${amt}` : ''], ['other2', ''], ['amount', String(amt)], ['currency', CONFIG.currency], ['first-name', F('first-name').value.trim()], ['last-name', F('last-name').value.trim()], ['address', F('address').value.trim()], ['city', F('city').value.trim()], ['country', F('country').value], ['email', F('email').value.trim()], ['mobile', F('mobile').value.trim()], ['dob_month', ''], ['dob_year', ''], ['last_month_contribution', F('last_month_contribution').value || '0'], ['q2', F('q2').value.trim()], ['iam', f.iam], ['special', f.special], ['step', st.step], ['steps', f.steps], ]); } async function post() { const body = payload(); if (CONFIG.mock) return mockForms(body); const res = await fetch(CONFIG.api.forms, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest' }, body, credentials: 'same-origin', }); if (!res.ok) throw new Error(`forms.php HTTP ${res.status}`); return (await res.text()).trim(); } // sendIt2(): post, then either flag a field on the current slide, or advance. async function send() { const btn = $(`[data-panel="${PANEL_FOR[st.slide] || 'amount'}"] button[type=submit]`, form); setBusy(btn, true); try { const data = await post(); const arr = data.split('*'); if (arr[0] !== 'ok') { if (String(arr[1]) === String(st.slide)) { showFieldError(arr[0]); // server says a field on THIS slide is invalid } else { nextStep(st.next); // the first invalid field is on a later slide, so move on } } else { st.key = data.substring(3); // "ok*" nextStep(st.next); } } catch (err) { console.error(err); showFormError(); } finally { setBusy(btn, false); } } // nextStep(which), with the same slide transitions as donate.js function nextStep(which) { st.slide = which; switch (which) { case SLIDE.INFO: st.next = SLIDE.MONTHLY; st.step = '2'; showPanel('info'); break; case SLIDE.MONTHLY: st.step = '3'; st.next = SLIDE.PAY; showPanel('monthly'); break; case SLIDE.PAY: // The original shows a "Clicking next opens NetCommerce" slide and waits for a click. // We skip that extra click and hand off straight away. if (!st.key) { showFormError(); st.slide = SLIDE.MONTHLY; return; } showPanel('pay'); goToNetCommerce(); break; } } function goToNetCommerce() { // Same rule as donate.js showNetCommerce(): iam=monthly_giving_latest goes to payment_monthly.php. const url = CONFIG.api.paymentMonthly + encodeURIComponent(st.key); $('[data-pay-link]').href = url; if (CONFIG.mock) { console.info('[mock] would redirect to', url); return; } window.location.href = url; } /* ---------- Submit: one handler, routed by current slide ---------- */ form.addEventListener('submit', e => { e.preventDefault(); if (st.busy) return; clearErrors(); if (st.slide === 0 || st.slide === SLIDE.AMOUNT) { // validateAmount() const amt = getAmount(); if (!(amt >= CONFIG.minAmount)) return showFieldError('amount', `Please choose an amount of at least $${CONFIG.minAmount}.`); st.slide = SLIDE.AMOUNT; st.next = SLIDE.INFO; st.step = '1'; return send(); } if (st.slide === SLIDE.INFO && !validateInfo()) return; send(); }); // Client-side check so most mistakes are caught before a round trip. The server still has the final say. function validateInfo() { const checks = [ ['first-name', v => v.trim() !== '', 'Please enter your first name.'], ['last-name', v => v.trim() !== '', 'Please enter your last name.'], ['email', v => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()), 'Please enter a valid email address.'], ['mobile', v => v.replace(/\D/g, '').length >= 6, 'Please enter your phone number.'], ['address', v => v.trim() !== '', 'Please enter your street address.'], ['city', v => v.trim() !== '', 'Please enter your city.'], ['country', v => v && v !== '0', 'Please select your country.'], ]; let firstBad = null; for (const [name, ok, msg] of checks) { if (!ok(F(name).value)) { markInvalid(name, msg); firstBad ||= F(name); } } if (firstBad) { firstBad.focus(); return false; } return true; } /* ---------- Errors / loading ---------- */ function markInvalid(name, msg) { const el = F(name); if (!el || !el.closest) return; el.setAttribute('aria-invalid', 'true'); const label = el.closest('.field'); if (label && !label.querySelector('.field-error')) { const p = document.createElement('p'); p.className = 'field-error'; p.id = `err-${name}`; p.textContent = msg; label.appendChild(p); el.setAttribute('aria-describedby', p.id); } } function showFieldError(name, msg) { if (name === 'amount' || name === 'other') { const p = $('[data-error-for="amount"]', form); p.textContent = msg || `Please choose an amount of at least $${CONFIG.minAmount}.`; p.hidden = false; return; } if (F(name)) { markInvalid(name, msg || 'Please check this field.'); F(name).focus(); } else showFormError(); // server named a field we don't render } function showFormError() { const p = $('[data-error-for="_form"]', form); p.innerHTML = 'Something went wrong on our side. Please try again, or use our main donation page.'; p.hidden = false; } function clearErrors() { $$('[aria-invalid]', form).forEach(el => { el.removeAttribute('aria-invalid'); el.removeAttribute('aria-describedby'); }); $$('.field .field-error', form).forEach(p => p.remove()); $$('[data-error-for]', form).forEach(p => (p.hidden = true)); } form.addEventListener('input', e => { if (e.target.getAttribute('aria-invalid')) { e.target.removeAttribute('aria-invalid'); e.target.closest('.field')?.querySelector('.field-error')?.remove(); } }); function setBusy(btn, on) { st.busy = on; btn?.classList.toggle('is-loading', on); } /* ========================================================= Select options (same values as forms_toolbox.js / donate.js) ========================================================= */ async function loadCountries() { const sel = F('country'); let list; try { const url = CONFIG.mock ? CONFIG.countriesFallback : CONFIG.api.countries; list = await fetch(url).then(r => r.json()); } catch (_) { list = await fetch(CONFIG.countriesFallback).then(r => r.json()).catch(() => []); } for (const c of list) sel.add(new Option(c.name, c.abrev)); if (list.some(c => c.abrev === CONFIG.defaultCountry)) sel.value = CONFIG.defaultCountry; } // fillMonthYear('last_month_contribution'): "0" = until the card expires, then 1..60 = months ahead. // (The original also lists the current month with value 0. That option is dropped here because it clashes with the default.) function fillLastContribution() { const sel = F('last_month_contribution'); sel.add(new Option('When my card expires', '0')); const d = new Date(); let m = d.getMonth(), y = d.getFullYear(); for (let i = 0; i < 61; i++) { if (i > 0) sel.add(new Option(`${MONTHS[m]} ${y}`, String(i))); if (++m > 11) { m = 0; y++; } } } /* ========================================================= PayPal ========================================================= */ // A plain link (href also set in index.html), so PayPal works even if this script fails. $('#paypal-btn').href = CONFIG.paypal.url; /* ========================================================= Local mock of forms.php (localhost only). Behaviour is inferred from donate.js; the real server's validation rules are unknown. ========================================================= */ async function mockForms(body) { await new Promise(r => setTimeout(r, 500)); const g = k => body.get(k) || ''; console.info('[mock] POST forms.php', Object.fromEntries(body)); if (!(Number(g('amount')) > 0)) return 'amount*1'; for (const k of ['first-name', 'last-name', 'address', 'city', 'country', 'email', 'mobile']) { if (!g(k) || g(k) === '0') return `${k}*2`; } if (g('steps') === '3' && g('step') !== '3') return 'last_month_contribution*6'; return 'ok*MOCKKEY123'; } /* ========================================================= Floating CTA: show as soon as the hero's own button has scrolled out of view. Hide again while the donation section is across the middle of the screen (the visitor is already there) and once the final CTA's button comes into view (it would sit right behind it). ========================================================= */ const sticky = $('#sticky-cta'); const heroBtn = $('.hero-ctas'); const donate = $('#sponsor'); const finalBtn = $('.final-cta .btn'); const headerH = () => $('.site-header').offsetHeight; const syncSticky = () => { const vh = innerHeight; const hero = heroBtn.getBoundingClientRect(); const d = donate.getBoundingClientRect(); const hide = hero.bottom > headerH() || // hero button still visible below the sticky header (d.top < vh / 2 && d.bottom > vh / 2) || // donation section is mid-screen finalBtn.getBoundingClientRect().top < vh; // final CTA button is on screen sticky.classList.toggle('is-hidden', hide); }; addEventListener('scroll', syncSticky, { passive: true }); addEventListener('resize', syncSticky); syncSticky(); /* ========================================================= Phone carousels: the swiping itself is CSS scroll-snap (styles.css). This only adds position dots under each [data-carousel] and makes it keyboard-scrollable on phones. ========================================================= */ const phone = matchMedia('(max-width: 599px)'); const A11Y = ['tabindex', 'role', 'aria-label']; $$('[data-carousel]').forEach(track => { const slides = [...track.children]; const dots = document.createElement('div'); dots.className = 'carousel-dots'; dots.setAttribute('aria-hidden', 'true'); dots.innerHTML = ''.repeat(slides.length); track.after(dots); let ticking = false; const update = () => { ticking = false; const atEnd = track.scrollLeft + track.clientWidth >= track.scrollWidth - 4; const step = slides[1] ? slides[1].offsetLeft - slides[0].offsetLeft : 1; const i = atEnd ? slides.length - 1 : Math.round(track.scrollLeft / step); [...dots.children].forEach((d, n) => d.classList.toggle('is-active', n === i)); }; track.addEventListener('scroll', () => { if (!ticking) { ticking = true; requestAnimationFrame(update); } }, { passive: true }); const setMode = () => { if (phone.matches) { const vals = ['0', 'region', track.dataset.carousel + ' (swipe for more)']; A11Y.forEach((a, n) => track.setAttribute(a, vals[n])); } else { A11Y.forEach(a => track.removeAttribute(a)); } update(); }; phone.addEventListener('change', setMode); setMode(); }); /* ---------- Init ---------- */ fillLastContribution(); loadCountries(); syncImpact(); goToAmount(); })();