/* DetoxBuy storefront behaviour: navigation, search suggestions, cart, product gallery/tabs, and the Stripe Payment Element checkout. */ (function () { // dbURL returns a storefront URL in the current language. The server injects // window.__DB.urls in layout.html so a scripted redirect never escapes the // language prefix (for example back to the Turkish order page). // T looks up a translated string injected by the server, so scripted // messages follow the page language instead of staying Turkish. function T(key, fallback) { var t = window.__DB && window.__DB.t; return (t && t[key]) || fallback || key; } function dbURL(name, fallback) { var u = window.__DB && window.__DB.urls && window.__DB.urls[name]; return u || fallback; } "use strict"; var $ = function (sel, root) { return (root || document).querySelector(sel); }; var $$ = function (sel, root) { return Array.prototype.slice.call((root || document).querySelectorAll(sel)); }; var on = function (el, ev, fn, opts) { if (el) el.addEventListener(ev, fn, opts); }; /* ---------- CSRF ---------- Every state-changing request must echo the double-submit token. Wrapping fetch once is safer than remembering to add it at every call site. */ function csrfToken() { var m = document.querySelector('meta[name="csrf-token"]'); return m ? m.getAttribute("content") : ""; } var nativeFetch = window.fetch ? window.fetch.bind(window) : null; if (nativeFetch) { window.fetch = function (input, init) { init = init || {}; var method = (init.method || (input && input.method) || "GET").toUpperCase(); if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") { var target = typeof input === "string" ? input : (input && input.url) || ""; if (!/^https?:\/\//i.test(target) || target.indexOf(window.location.origin) === 0) { var headers = new Headers(init.headers || (input && input.headers) || {}); if (!headers.has("X-CSRF-Token")) headers.set("X-CSRF-Token", csrfToken()); init.headers = headers; } } return nativeFetch(input, init); }; } /* ---------- image fallbacks ---------- CSP forbids inline onerror handlers, so the templates mark images with a data attribute and one delegated listener handles the error event. */ document.addEventListener("error", function (e) { var el = e.target; if (!el || el.tagName !== "IMG") return; if (el.hasAttribute("data-hide-on-error")) { el.style.display = "none"; } if (el.hasAttribute("data-reveal-on-error")) { el.style.display = "none"; var sib = el.nextElementSibling; if (sib) sib.style.display = "grid"; } }, true); /* ---------- mobile drawer ---------- */ var drawer = $("#mDrawer"); function openDrawer(open) { if (!drawer) return; drawer.classList.toggle("is-open", open); drawer.setAttribute("aria-hidden", open ? "false" : "true"); document.body.style.overflow = open ? "hidden" : ""; } $$("[data-drawer-open]").forEach(function (el) { on(el, "click", function (e) { e.preventDefault(); openDrawer(true); }); }); $$("[data-drawer-close]").forEach(function (el) { on(el, "click", function (e) { e.preventDefault(); openDrawer(false); }); }); var drawerCats = $("[data-drawer-cats]"), drawerCatList = $("[data-drawer-catlist]"); on(drawerCats, "click", function (e) { e.preventDefault(); if (drawerCatList) drawerCatList.style.display = drawerCatList.style.display === "none" ? "block" : "none"; }); /* ---------- hero showcase slider ---------- Desktop renders the cards as a static 4-column grid; on mobile the track becomes a horizontal snap scroller that advances every 3 seconds. Swiping is native: the track is a real overflow-x container with touch-action:pan-x pan-y, so the finger drags it and the page still scrolls vertically. What this code adds is everything around that: · mouse drag-to-scroll, so the same row works on a device without a touchscreen (and can be tested in a desktop browser), · auto-play that scans past cards, but yields the moment a finger or pointer lands and only resumes after the reader has settled, · dot state that follows the real scroll position. A card is a link, so a mouse drag must not navigate: once the pointer has travelled past a small threshold the click that follows is swallowed. */ (function () { var host = $("[data-showcase]"); if (!host) return; var track = $("[data-showcase-track]", host); var dots = $$("[data-showcase-dots] .dot", host); if (!track) return; var cards = $$(".hcard", track); if (cards.length < 2) return; var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; var interval = parseInt(host.getAttribute("data-interval"), 10) || 3000; // Auto-play stays out of the way until the reader has finished with the // row: a manual swipe buys this much quiet time before it moves again. var resumeDelay = 7000; /* Auto-advance is OFF by default, and the reason is measurable rather than aesthetic. A carousel that moves on its own keeps changing which element the browser considers the LCP: on the mobile report the reported LCP element was a card sitting at left:-231 — scrolled out of the viewport mid-measurement — and the phase timings read ~4.6 s for an image that had in fact downloaded in 165 ms. That is not a slow page, it is a page whose LCP never settles, and no amount of preloading can fix it. It is also a WCAG 2.2.2 problem: content that moves on its own for more than five seconds has to be pausable, and a hero row on a phone is exactly that. The row still scrolls — natively, with snap, by finger or mouse drag — so nothing is lost but the motion. An operator who wants the rotation can opt in with data-autoplay="1" on the showcase container. */ var autoplay = host.getAttribute("data-autoplay") === "1"; var index = 0; var timer = null; var visible = false; var interacting = false; var resumeAt = 0; function isSlider() { // Only the mobile layout scrolls horizontally. return track.scrollWidth > track.clientWidth + 4; } // Card left offset measured from the first card, so it never depends on // which ancestor happens to be the offset parent. function cardLeft(card) { return card.offsetLeft - cards[0].offsetLeft; } function go(i) { if (!isSlider()) return; index = (i + cards.length) % cards.length; var card = cards[index]; if (!card) return; track.scrollTo({ left: cardLeft(card), behavior: reduce ? "auto" : "smooth" }); syncDots(); } function syncDots() { for (var i = 0; i < dots.length; i++) dots[i].classList.toggle("is-active", i === index); } function nearestIndex() { var best = 0, bestDist = Infinity; for (var i = 0; i < cards.length; i++) { var d = Math.abs(cardLeft(cards[i]) - track.scrollLeft); if (d < bestDist) { bestDist = d; best = i; } } return best; } // hold() marks a manual interaction: the auto-advance goes quiet while it // lasts and for resumeDelay afterwards, so the row never slides out from // under a finger or a reader who just stopped to look. function hold() { interacting = true; resumeAt = Date.now() + resumeDelay; } function release() { interacting = false; resumeAt = Date.now() + resumeDelay; } function tick() { if (!visible || interacting || Date.now() < resumeAt) return; if (!isSlider()) return; go(index + 1); } function start() { if (!autoplay || reduce || timer) return; timer = setInterval(tick, interval); } function stop() { if (timer) { clearInterval(timer); timer = null; } } /* --- mouse drag-to-scroll ------------------------------------------- */ var drag = null; // Set when a drag ends and cleared by the very next click. A timer would be // wrong here: browsers deliver that click anywhere from now to a few hundred // milliseconds later, so the flag waits for it instead of racing it. var swallowNextClick = false; on(track, "pointerdown", function (e) { // A new press starts a new gesture, so any flag left over from a drag // whose click never arrived cannot eat this one. swallowNextClick = false; hold(); if (e.pointerType === "mouse" && e.button === 0 && isSlider()) { drag = { id: e.pointerId, x: e.clientX, left: track.scrollLeft, moved: false }; track.classList.add("is-dragging"); } }); on(track, "pointermove", function (e) { if (!drag || e.pointerId !== drag.id) return; var dx = e.clientX - drag.x; if (!drag.moved && Math.abs(dx) < 5) return; // still a click, not a drag if (!drag.moved) { drag.moved = true; try { track.setPointerCapture(e.pointerId); } catch (_) {} } e.preventDefault(); track.scrollLeft = drag.left - dx; }); function endDrag(e) { if (!drag) return; var moved = drag.moved; drag = null; // Dropping the class restores scroll-snap, so the row settles on a card. track.classList.remove("is-dragging"); try { track.releasePointerCapture(e.pointerId); } catch (_) {} if (moved) swallowNextClick = true; release(); } on(track, "pointerup", endDrag); on(track, "pointercancel", endDrag); // The cards are links: a drag must not also navigate to whichever card the // pointer happened to stop over. Capture phase, so it runs before the link. track.addEventListener("click", function (e) { if (!swallowNextClick) return; swallowNextClick = false; e.preventDefault(); e.stopPropagation(); }, true); // A drag inside the row must never start the browser's own image/link drag. on(track, "dragstart", function (e) { e.preventDefault(); }); /* --- touch: native scrolling, we only stand back -------------------- */ on(track, "touchstart", hold, { passive: true }); on(track, "touchend", function () { release(); settle(); }, { passive: true }); on(track, "touchcancel", function () { release(); settle(); }, { passive: true }); // syncDots reads the live scroll position rather than trusting a stored // index, so a manual swipe, a drag and the auto-advance all agree. function settle() { if (!isSlider()) return; index = nearestIndex(); syncDots(); } on(track, "scroll", settle, { passive: true }); // scroll fires asynchronously and is coalesced; also sample on the events // that bracket a gesture so the dots cannot lag behind the row. on(track, "pointerup", settle); on(track, "touchmove", settle, { passive: true }); if (window.IntersectionObserver) { new IntersectionObserver(function (entries) { entries.forEach(function (entry) { visible = entry.isIntersecting; if (visible) start(); else stop(); }); }, { threshold: 0.25 }).observe(host); } else { visible = true; start(); } syncDots(); })(); /* ---------- category panel ---------- */ var catToggle = $("[data-cat-toggle]"), catPanel = $("[data-cat-panel]"); on(catToggle, "click", function (e) { e.stopPropagation(); if (catPanel) catPanel.classList.toggle("is-open"); }); document.addEventListener("click", function (e) { if (catPanel && !e.target.closest("[data-cat-panel]") && !e.target.closest("[data-cat-toggle]")) { catPanel.classList.remove("is-open"); } }); // Sub-category accordion inside the browse panel. The caret only makes sense // if it actually expands something: previously nothing added .is-open, so the // nested links were unreachable. $$(".cat-panel .cat-item").forEach(function (item) { var link = item.querySelector(":scope > a"); var kids = item.querySelector(":scope > .cat-children"); if (!link || !kids) return; on(link, "click", function (e) { e.preventDefault(); var open = item.classList.contains("is-open"); $$(".cat-panel .cat-item.is-open").forEach(function (n) { n.classList.remove("is-open"); }); if (!open) item.classList.add("is-open"); }); }); /* ---------- language dropdown ---------- */ $$(".lang-btn").forEach(function (btn) { on(btn, "click", function (e) { e.preventDefault(); e.stopPropagation(); var host = btn.closest(".lang"); var wasOpen = host.classList.contains("is-open"); $$(".lang.is-open").forEach(function (n) { n.classList.remove("is-open"); }); if (!wasOpen) host.classList.add("is-open"); btn.setAttribute("aria-expanded", wasOpen ? "false" : "true"); }); }); document.addEventListener("click", function (e) { if (!e.target.closest(".lang")) { $$(".lang.is-open").forEach(function (n) { n.classList.remove("is-open"); }); } }); /* ---------- search suggestions ---------- */ var searchInput = $("[data-suggest]"), suggestPanel = $("[data-suggest-panel]"); var searchTimer = null; on(searchInput, "input", function () { var term = searchInput.value.trim(); clearTimeout(searchTimer); if (term.length < 2) { if (suggestPanel) suggestPanel.classList.remove("is-open"); return; } searchTimer = setTimeout(function () { fetch(window.dbWithLang("/api/arama?q=" + encodeURIComponent(term)), { headers: { Accept: "application/json" } }) .then(function (r) { return r.json(); }) .then(function (data) { if (!suggestPanel) return; if (!data.results || !data.results.length) { suggestPanel.classList.remove("is-open"); return; } // url and image are product-controlled (slug and image_url come from // the catalogue, which the WordPress import and the admin panel can // write). Concatenating them into innerHTML unescaped let a crafted // slug break out of the href attribute and run script for every // visitor who typed two characters into the search box. suggestPanel.innerHTML = data.results.map(function (r) { return '' + (r.image ? '' : '') + '' + escapeHtml(r.name) + '' + '' + escapeHtml(r.price) + ''; }).join(""); suggestPanel.classList.add("is-open"); }) .catch(function () {}); }, 220); }); document.addEventListener("click", function (e) { if (suggestPanel && !e.target.closest(".search-mini")) suggestPanel.classList.remove("is-open"); }); /* Keyboard navigation inside the suggestion list: arrows move, Enter opens. */ var suggestActive = -1; function suggestItems() { return suggestPanel ? Array.prototype.slice.call(suggestPanel.querySelectorAll("a")) : []; } function highlight(index) { var items = suggestItems(); if (!items.length) return; if (index < 0) index = items.length - 1; if (index >= items.length) index = 0; items.forEach(function (a) { a.classList.remove("is-active"); }); items[index].classList.add("is-active"); if (items[index].scrollIntoView) { items[index].scrollIntoView({ block: "nearest" }); } suggestActive = index; } on(searchInput, "keydown", function (e) { var items = suggestItems(); if (!items.length || !suggestPanel.classList.contains("is-open")) return; if (e.key === "ArrowDown") { e.preventDefault(); highlight(suggestActive + 1); } else if (e.key === "ArrowUp") { e.preventDefault(); highlight(suggestActive - 1); } else if (e.key === "Enter" && suggestActive >= 0) { e.preventDefault(); items[suggestActive].click(); } else if (e.key === "Escape") { suggestPanel.classList.remove("is-open"); suggestActive = -1; } }); on(searchInput, "input", function () { suggestActive = -1; }); /* ---------- mobile filter toggle ---------- */ var filterToggle = $("[data-filter-toggle]"), filters = $("[data-filters]"); on(filterToggle, "click", function () { if (!filters) return; var open = filters.classList.toggle("is-open"); filterToggle.textContent = open ? "Filtreyi Kapat" : "Filtrele"; }); /* ---------- product express checkout ---------- One-tap Apple Pay / Google Pay / Link from the product page. The element is mounted lazily when Stripe.js is present and the page carries a publishable key; otherwise the template already fell back to static badges. */ (function () { var host = $("#productExpressPay"); if (!host || !window.Stripe) return; var pkMeta = document.querySelector('meta[name="stripe-pk"]'); var pk = (window.STRIPE_PK || (pkMeta && pkMeta.getAttribute("content")) || "").trim(); if (!pk) return; var elementHost = $("#productExpressElement"); var errEl = host.querySelector("[data-express-error]"); if (!elementHost) return; var productID = host.getAttribute("data-product-id"); var productName = host.getAttribute("data-product-name") || ""; var price = parseInt(host.getAttribute("data-product-price"), 10) || 0; var currency = (host.getAttribute("data-currency") || "EUR").toLowerCase(); var quantity = 1; function fail(msg) { if (errEl) { errEl.textContent = msg; errEl.hidden = false; } } var stripe = window.Stripe(pk); var elements = stripe.elements({ mode: "payment", amount: price * quantity, currency: currency, paymentMethodCreation: "manual" }); var express = elements.create("expressCheckout", { buttonType: { applePay: "buy", googlePay: "buy", paypal: "buy" }, buttonHeight: 44 }); express.mount("#productExpressElement"); // Keep the element's amount in step with the quantity stepper. var stepperInput = document.querySelector(".qty-stepper input[name=qty]"); if (stepperInput) { on(stepperInput, "change", function () { var q = parseInt(stepperInput.value, 10) || 1; if (q === quantity) return; quantity = q; express.update({ amount: price * quantity }); }); } express.on("confirm", function (event) { if (errEl) errEl.hidden = true; // Create the PaymentIntent server-side from the cart so stock and totals // are reserved exactly like the normal checkout path. fetch("/api/odeme/express", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ product_id: parseInt(productID, 10), qty: quantity, email: (event.billingDetails && event.billingDetails.email) || "" }) }).then(function (r) { return r.json(); }).then(function (d) { if (!d.clientSecret) throw new Error(d.error || "Ödeme başlatılamadı."); return stripe.confirmPayment({ clientSecret: d.clientSecret, confirmParams: { return_url: window.location.origin + d.redirect } }); }).catch(function (e) { fail(e.message || "Ödeme tamamlanamadı."); }); }); })(); /* ---------- quantity steppers ---------- Binds to .qty-stepper (product page and cart). Two details matter: - preventDefault so a stray form submit cannot fire on the same click, - a change event after writing .value, otherwise form state (and any listener) keeps seeing the old number. */ function bindStepper(stepper) { var input = $("input[type=number]", stepper); if (!input) return; var min = parseInt(input.getAttribute("min"), 10); var max = parseInt(input.getAttribute("max"), 10); if (!isFinite(min) || min < 1) min = 1; if (!isFinite(max) || max <= min) max = 100; function setValue(next) { var val = parseInt(next, 10); if (!isFinite(val)) val = min; val = Math.max(min, Math.min(max, val)); input.value = String(val); // Notify listeners (cart line recalcs, validation) of the new quantity. input.dispatchEvent(new Event("change", { bubbles: true })); } $$("button[data-qty]", stepper).forEach(function (btn) { on(btn, "click", function (e) { e.preventDefault(); var delta = parseInt(btn.getAttribute("data-qty"), 10) || 0; var current = parseInt(input.value, 10); if (!isFinite(current)) current = min; setValue(current + delta); }); }); // Typing outside the range should snap back rather than submit "0". on(input, "change", function () { var v = parseInt(input.value, 10); if (!isFinite(v) || v < min) setValue(min); else if (v > max) setValue(max); }); } $$(".qty-stepper").forEach(bindStepper); /* ---------- product gallery ---------- */ var mainImage = $("#mainImage"); $$(".gallery-thumbs .thumb").forEach(function (thumb) { on(thumb, "click", function () { var src = thumb.getAttribute("data-src"); if (mainImage && src) { // The clicked thumb carries the original URL; drop the responsive set so // the browser does not keep serving the previously selected derivative. mainImage.removeAttribute("srcset"); mainImage.removeAttribute("sizes"); mainImage.src = src; mainImage.setAttribute("data-full", src); } $$(".gallery-thumbs .thumb").forEach(function (t) { t.classList.remove("is-active"); }); thumb.classList.add("is-active"); }); }); /* ---------- recent-purchase banner ---------- Rotates through real anonymised orders. Each item shows for six seconds with a four-second gap, so it reads as a hint rather than a nag. It stops for good once dismissed (localStorage), and the whole feature is skipped under prefers-reduced-motion. */ (function () { var host = $("[data-social-proof]"); var dataEl = $("[data-sp-data]"); if (!host || !dataEl) return; var items; try { items = JSON.parse(dataEl.textContent || "[]"); } catch (e) { return; } if (!Array.isArray(items) || !items.length) return; var KEY = "db_social_proof_off"; try { if (localStorage.getItem(KEY) === "1") return; } catch (e) {} var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; if (reduce) return; var buyerEl = host.querySelector("[data-sp-buyer]"); var productEl = host.querySelector("[data-sp-product]"); var metaEl = host.querySelector("[data-sp-meta]"); var thumbEl = host.querySelector("[data-sp-thumb]"); var closeBtn = host.querySelector("[data-sp-close]"); var idx = 0, timer = null, stopped = false; function minutesLabel(m) { if (m < 1) return T("sp.just_now", "just now"); if (m < 60) return m + " " + T("sp.minutes", "min ago"); var h = Math.round(m / 60); if (h < 24) return h + " " + T("sp.hours", "h ago"); return Math.round(h / 24) + " " + T("sp.days", "d ago"); } function render() { var it = items[idx % items.length]; idx++; if (!it || !it.buyer) { hide(); return; } buyerEl.textContent = it.buyer; productEl.textContent = it.product || ""; if (it.url) { // The text is a link when the product still exists. productEl.innerHTML = ""; var a = document.createElement("a"); a.href = it.url; a.textContent = it.product || ""; productEl.appendChild(a); } var bits = [minutesLabel(it.minutes || 0)]; if (it.city) bits.push(it.city); metaEl.textContent = bits.join(" · "); if (it.image) { thumbEl.style.backgroundImage = 'url("' + it.image + '")'; thumbEl.style.display = ""; } else { thumbEl.style.display = "none"; } host.removeAttribute("hidden"); host.classList.add("is-open"); timer = setTimeout(function () { host.classList.remove("is-open"); timer = setTimeout(render, 4000); }, 6000); } function hide() { host.setAttribute("hidden", ""); host.classList.remove("is-open"); if (timer) clearTimeout(timer); } if (closeBtn) { on(closeBtn, "click", function () { stopped = true; hide(); try { localStorage.setItem(KEY, "1"); } catch (e) {} }); } // Start after a short delay so the banner does not compete with page load. setTimeout(function () { if (!stopped) render(); }, 6000); })(); /* ---------- auth tab switcher ---------- Moves between the sign-in and create-account panels. Each form still posts to its own endpoint, so with JS off the server renders whichever tab the URL asked for (?tab=register) and both flows keep working. */ (function () { var tabs = $$("[data-auth-tab]"); var panels = $$("[data-auth-panel]"); if (!tabs.length || !panels.length) return; function activate(name) { tabs.forEach(function (t) { var on = t.getAttribute("data-auth-tab") === name; t.classList.toggle("is-active", on); t.setAttribute("aria-selected", on ? "true" : "false"); }); panels.forEach(function (p) { var on = p.getAttribute("data-auth-panel") === name; p.classList.toggle("is-active", on); if (on) { var input = p.querySelector("input:not([type=hidden])"); if (input) input.focus({ preventScroll: true }); } }); // Keep the URL honest so a refresh reopens the same tab. var url = new URL(window.location.href); if (name === "register") url.searchParams.set("tab", "register"); else url.searchParams.delete("tab"); window.history.replaceState({}, "", url); } tabs.forEach(function (t) { on(t, "click", function () { activate(t.getAttribute("data-auth-tab")); }); }); // Deep links such as the header's "Register" item carry ?tab=register. panels.forEach(function (p) { if (p.classList.contains("is-active")) return; }); })(); /* The description clamp and its "read more" toggle were removed: the product copy is now rendered in full. See product.html — the tab already keeps it away from the buy path, so hiding half the text behind a button only made the shopper tap twice for the thing they came to read. */ /* ---------- review helpfulness ---------- Anonymous, one vote per browser: the server keys the vote on IP plus user agent, so a repeat click comes back with changed=false and the counters do not move twice. The numbers are swapped in place, no reload. */ (function () { var buttons = $$("[data-review-vote]"); if (!buttons.length) return; function productSlug() { if (window.__DB && window.__DB.slug) return window.__DB.slug; var m = location.pathname.match(/\/product\/([^/]+)\//) || location.pathname.match(/\/urun\/([^/]+)\//) || location.pathname.match(/\/(?:produkt|produit|producto|prodotto|produto|produs|produkt|izdelek|proizvod)\/([^/]+)\//); return m ? decodeURIComponent(m[1]) : ""; } buttons.forEach(function (btn) { on(btn, "click", function () { var id = btn.getAttribute("data-review-vote"); var helpful = btn.getAttribute("data-helpful") === "1"; var slug = productSlug(); if (!slug || !id) return; btn.disabled = true; fetch("/urun/" + encodeURIComponent(slug) + "/yorum/" + encodeURIComponent(id) + "/oy", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "X-CSRF-Token": csrfHeader() }, body: JSON.stringify({ helpful: helpful }) }).then(function (r) { return r.json(); }).then(function (d) { btn.disabled = false; if (!d || !d.ok) return; var wrap = btn.closest(".review-vote"); if (!wrap) return; var yes = wrap.querySelector("[data-rv-yes]"); var no = wrap.querySelector("[data-rv-no]"); if (yes) yes.textContent = d.yes; if (no) no.textContent = d.no; wrap.classList.add("is-voted"); }).catch(function () { btn.disabled = false; }); }); }); })(); /* ---------- dialogs ---------- Opens the delivery/returns and ask-a-question panels. handles focus trapping and Escape natively, so this only wires the triggers. */ $$("[data-dialog-open]").forEach(function (btn) { on(btn, "click", function () { var d = document.getElementById(btn.getAttribute("data-dialog-open")); if (!d) return; if (typeof d.showModal === "function") d.showModal(); else d.setAttribute("open", ""); }); }); // Clicking the backdrop closes the dialog; a click on the panel itself must not. $$(".shop-dialog").forEach(function (d) { d.addEventListener("click", function (e) { if (e.target === d) d.close(); }); }); /* ---------- back to top ---------- Appears after the first viewport and scrolls up with the motion preference respected. Uses a passive listener and a rAF guard so the scroll handler never blocks the main thread. */ (function () { var btn = $("[data-back-to-top]"); if (!btn) return; var ticking = false; function update() { var show = window.pageYOffset > window.innerHeight * 0.9; if (show) btn.removeAttribute("hidden"); else btn.setAttribute("hidden", ""); ticking = false; } window.addEventListener("scroll", function () { if (ticking) return; ticking = true; window.requestAnimationFrame(update); }, { passive: true }); on(btn, "click", function () { var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches; window.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" }); }); update(); })(); /* ---------- sticky header shrink ---------- Past the top bar the header compacts so a long listing keeps more of the screen for products. Same rAF guard as the back-to-top handler: one fixed class toggle, no layout read per scroll event. */ (function () { var header = document.querySelector(".site-header"); if (!header) return; var stuck = false; var ticking = false; function update() { var next = window.pageYOffset > 90; if (next !== stuck) { stuck = next; header.classList.toggle("is-stuck", stuck); } ticking = false; } window.addEventListener("scroll", function () { if (ticking) return; ticking = true; window.requestAnimationFrame(update); }, { passive: true }); update(); })(); /* ---------- password visibility toggle ---------- Adds a button beside every password field, so a shopper can check what they typed before submitting a registration or reset form. */ $$('input[type="password"]').forEach(function (input) { if (input.dataset.pwToggle || input.closest(".pw-wrap")) return; var wrap = document.createElement("span"); wrap.className = "pw-wrap"; input.parentNode.insertBefore(wrap, input); wrap.appendChild(input); var btn = document.createElement("button"); btn.type = "button"; btn.className = "pw-toggle"; btn.setAttribute("aria-label", "Show password"); btn.setAttribute("aria-pressed", "false"); btn.innerHTML = ''; on(btn, "click", function () { var showing = input.type === "text"; input.type = showing ? "password" : "text"; btn.setAttribute("aria-pressed", showing ? "false" : "true"); btn.classList.toggle("is-on", !showing); }); wrap.appendChild(btn); input.dataset.pwToggle = "1"; }); /* ---------- product grid column switcher ---------- Writes data-cols on the grid and stores the choice in a cookie, so the next listing opens with the same density. CSS owns the breakpoints; this only sets the intent. */ (function () { var grid = $(".pgrid-catalog"); var buttons = $$("[data-view-cols]"); if (!grid || !buttons.length) return; var KEY = "db_grid_cols"; var read = function () { var m = document.cookie.match(/(?:^|;\s*)db_grid_cols=(\d+)/); return m ? parseInt(m[1], 10) : 3; }; var write = function (n) { document.cookie = KEY + "=" + n + ";path=/;max-age=" + (60 * 60 * 24 * 365) + ";samesite=lax"; }; function apply(n) { grid.setAttribute("data-cols", String(n)); buttons.forEach(function (b) { var on = parseInt(b.getAttribute("data-view-cols"), 10) === n; b.classList.toggle("is-active", on); b.setAttribute("aria-pressed", on ? "true" : "false"); }); } buttons.forEach(function (b) { on(b, "click", function () { var n = parseInt(b.getAttribute("data-view-cols"), 10) || 3; apply(n); write(n); }); }); apply(read()); })(); /* ---------- bundle selection ---------- Recomputes the preview total and the button label as cards are toggled. The server prices the selection itself; this only keeps the number honest while the shopper is still choosing. Two details matter here: · the selected card gets .is-on so the tick badge and border follow the real checkbox state, including when the shopper uses the keyboard; · the total is formatted with the page's own symbol and decimal separator, read from data-* on the form, instead of a hardcoded "€". */ (function () { var form = $("[data-bundle-form]"); if (!form) return; var totalEl = form.querySelector("[data-bundle-total]"); var countEl = form.querySelector("[data-bundle-count]"); var submit = form.querySelector("[data-bundle-submit]"); if (!totalEl) return; var symbol = form.getAttribute("data-money-symbol") || "€"; var decimal = form.getAttribute("data-money-decimal") || "."; var thousands = decimal === "," ? "." : ","; function money(cents) { var abs = Math.abs(Math.round(cents)); var whole = String(Math.floor(abs / 100)); var frac = String(abs % 100); if (frac.length < 2) frac = "0" + frac; if (whole.length > 3) whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousands); return (cents < 0 ? "-" : "") + symbol + whole + decimal + frac; } var checks = $$("input[name=bundle_ids][type=checkbox]", form); function recalc() { var cents = 0, n = 0; checks.forEach(function (c) { // Drive the card's visual state from the control, so keyboard toggles and // label clicks end up identical. var card = c.closest(".bundle-card"); if (card) card.classList.toggle("is-on", c.checked || c.disabled); if (!c.checked) return; cents += parseInt(c.getAttribute("data-price"), 10) || 0; n++; }); totalEl.textContent = money(cents); if (countEl) countEl.textContent = n; if (submit) submit.disabled = n === 0; } checks.forEach(function (c) { c.addEventListener("change", recalc); }); recalc(); })(); /* ---------- quick add from a tier ---------- Each pack size carries a "quick add" affordance. It posts the same form the main button uses but with that tier's quantity, so the server-side pricing path is identical and the drawer opens as usual. */ (function () { var box = $("[data-tier-box]"); if (!box) return; box.addEventListener("click", function (e) { var quick = e.target.closest("[data-tier-quick]"); if (!quick) return; // The quick add lives inside the tier button; stop the tier from also // being selected, otherwise the page would show two active options. e.preventDefault(); e.stopPropagation(); var qty = quick.getAttribute("data-tier-quick"); var form = document.querySelector(".add-form") || document.querySelector(".variation-form"); if (!form) return; var qtyInput = form.querySelector('input[name="qty"]'); if (qtyInput) qtyInput.value = qty; var btn = form.querySelector('button[type="submit"]'); if (btn) btn.click(); }); })(); /* ---------- copy product link ---------- */ (function () { var btn = $("[data-share-copy]"); if (!btn) return; var label = btn.getAttribute("title") || "Copy"; var copied = T("product.share_copied", "Copied"); on(btn, "click", function () { var url = btn.getAttribute("data-copy-url") || window.location.href; var done = function () { btn.classList.add("is-copied"); btn.setAttribute("title", copied); setTimeout(function () { btn.classList.remove("is-copied"); btn.setAttribute("title", label); }, 1800); }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(url).then(done, function () { window.prompt(label, url); }); } else { window.prompt(label, url); } }); })(); /* ---------- review list sorting ---------- Reviews are all in the DOM; sorting reorders the existing nodes instead of re-fetching, so the operation is instant and works with JS on but network off. The original order is the server's "most recent first". */ (function () { var select = $("[data-review-sort]"); var list = $("[data-review-list]"); if (!select || !list) return; var all = $$(".review", list); if (all.length < 2) return; var key = function (node) { var time = node.querySelector("time"); var stars = node.querySelector(".stars"); var rating = 0; if (stars) { // The stars helper renders ★/☆ pairs; counting filled stars recovers the // score without a data attribute on every node. rating = (stars.textContent.match(/★/g) || []).length; } return { node: node, date: time ? time.getAttribute("datetime") || time.textContent : "", rating: rating, }; }; var items = all.map(key); select.addEventListener("change", function () { var mode = select.value; var sorted = items.slice(); if (mode === "oldest") { sorted.sort(function (a, b) { return a.date < b.date ? -1 : a.date > b.date ? 1 : 0; }); } else if (mode === "high") { sorted.sort(function (a, b) { return b.rating - a.rating; }); } else if (mode === "low") { sorted.sort(function (a, b) { return a.rating - b.rating; }); } else { sorted.sort(function (a, b) { return a.date > b.date ? -1 : a.date < b.date ? 1 : 0; }); } var frag = document.createDocumentFragment(); sorted.forEach(function (it) { frag.appendChild(it.node); }); list.appendChild(frag); }); })(); /* ---------- live viewer counter ---------- Removed on purpose. The old code drifted the number every 9 seconds with Math.random(), so two tabs of the same product showed different figures and a reload could contradict what the shopper had just read. The figure now comes from the server once per page view (stable per product per day), and nothing touches it afterwards. A fake ticker costs more trust than it buys. */ /* ---------- product zoom + lightbox ---------- Two ways to inspect a photo: a lens follows the pointer over the main image (desktop only — a touch screen cannot hover), and a fullscreen viewer opens from the zoom button, a click on the image, or Enter on the button. CSP forbids inline handlers, so every binding goes through the delegated listeners here. The dialog keeps focus inside while open and restores it on close, and arrow keys page through the gallery. */ (function () { var host = $("#galleryMain"); var main = $("#mainImage"); var box = $("#productLightbox"); if (!host || !main) return; /* --- hover lens --- */ var lens = null; var canHover = window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches; if (canHover) { lens = document.createElement("div"); lens.className = "zoom-lens"; lens.setAttribute("aria-hidden", "true"); host.appendChild(lens); var zoom = function (e) { var r = main.getBoundingClientRect(); var full = main.getAttribute("data-full") || main.src; // Scale the lens by the ratio of natural to rendered width so the // magnified area matches what sits under the cursor. var scale = Math.max(1.6, (main.naturalWidth || r.width) / r.width); lens.style.backgroundImage = 'url("' + full + '")'; lens.style.backgroundSize = (r.width * scale) + "px " + (r.height * scale) + "px"; var x = e.clientX - r.left, y = e.clientY - r.top; lens.style.left = (x - lens.offsetWidth / 2) + "px"; lens.style.top = (y - lens.offsetHeight / 2) + "px"; var bgX = (x * scale) - lens.offsetWidth / 2; var bgY = (y * scale) - lens.offsetHeight / 2; lens.style.backgroundPosition = "-" + Math.max(0, bgX) + "px -" + Math.max(0, bgY) + "px"; // The lens is transparent until it has something to show. A class is used // rather than relying on the inline background-image, because mousemove // fires before the image finishes decoding and a style-based selector // would flash an empty white disc. lens.classList.add("is-on"); }; host.addEventListener("mousemove", zoom); host.addEventListener("mouseleave", function () { lens.classList.remove("is-on"); lens.style.backgroundImage = ""; }); } if (!box) return; /* --- lightbox --- */ var img = box.querySelector("[data-lightbox-img]"); var caption = box.querySelector("[data-lightbox-caption]"); var counter = box.querySelector("[data-lightbox-count]"); var lastFocus = null; function sources() { var out = []; var mainFull = main.getAttribute("data-full") || main.src; if (mainFull) out.push(mainFull); $$(".gallery-thumbs .thumb").forEach(function (t) { var s = t.getAttribute("data-src"); if (s && out.indexOf(s) === -1) out.push(s); }); return out; } var list = []; var index = 0; function render() { if (!list.length) return; img.src = list[index]; img.alt = main.alt || ""; if (caption) caption.textContent = main.alt || ""; if (counter) counter.textContent = (index + 1) + " / " + list.length; } function open(startAt) { list = sources(); index = Math.max(0, Math.min(startAt || 0, list.length - 1)); lastFocus = document.activeElement; box.hidden = false; box.setAttribute("aria-hidden", "false"); box.classList.add("is-open"); document.body.style.overflow = "hidden"; render(); var close = box.querySelector(".lightbox-close"); if (close) close.focus(); } function close() { box.classList.remove("is-open"); box.setAttribute("aria-hidden", "true"); box.hidden = true; document.body.style.overflow = ""; if (lastFocus && lastFocus.focus) lastFocus.focus(); } function step(delta) { if (!list.length) return; index = (index + delta + list.length) % list.length; render(); } function currentIndex() { var cur = main.getAttribute("data-full") || main.src; var i = list.indexOf(cur); return i < 0 ? 0 : i; } $$("[data-lightbox-open]").forEach(function (btn) { on(btn, "click", function (e) { e.preventDefault(); open(currentIndex()); }); }); // Clicking the photo itself opens the viewer; the lens already showed a // preview, so this is the natural next step rather than a surprise. on(main, "click", function () { open(currentIndex()); }); $$("[data-lightbox-close]").forEach(function (el) { on(el, "click", close); }); $$("[data-lightbox-prev]").forEach(function (el) { on(el, "click", function () { step(-1); }); }); $$("[data-lightbox-next]").forEach(function (el) { on(el, "click", function () { step(1); }); }); // Listen on document, not the dialog: the click that opened the viewer may // leave focus on the trigger, and a keydown bound to the panel would never // fire. Escape must always work while the viewer is open. document.addEventListener("keydown", function (e) { if (!box.classList.contains("is-open")) return; if (e.key === "Escape") { e.preventDefault(); close(); return; } if (e.key === "ArrowLeft") { e.preventDefault(); step(-1); return; } if (e.key === "ArrowRight") { e.preventDefault(); step(1); return; } if (e.key === "Tab") { // Keep focus inside the dialog while it is modal. var focusables = $$("button", box).filter(function (b) { return !b.disabled; }); if (!focusables.length) return; var first = focusables[0], last = focusables[focusables.length - 1]; if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } } }); // Swipe between photos on touch screens. var startX = null; box.addEventListener("touchstart", function (e) { if (e.touches.length === 1) startX = e.touches[0].clientX; }, { passive: true }); box.addEventListener("touchend", function (e) { if (startX === null) return; var dx = (e.changedTouches[0] || {}).clientX - startX; if (Math.abs(dx) > 50) step(dx < 0 ? 1 : -1); startX = null; }); })(); /* ---------- product tabs ---------- Description / specifications / reviews / Q&A, first tab open. Pieces worth noting: · All four panels are in the HTML with only the first open, so neither a crawler nor a visitor without JavaScript has to fetch anything to see the copy; the inactive ones are `hidden` in the markup, which is also what prevents a flash of all four before this script runs. · The underline is one element positioned from the button's own offset, re-measured on resize and on font load — a width-based border would jump when the fonts swap in. · Keyboard follows the ARIA tabs pattern: arrows move, Home/End jump, only the active tab is in the tab order. */ (function () { var root = $("[data-tabs]"); if (!root) return; var tabs = $$("[data-tab]", root); var panels = $$("[data-panel]", root); var ink = $(".tab-ink", root); var nav = $(".tab-nav", root); if (!tabs.length || !panels.length) return; var current = 0; function panelFor(tab) { return $('.tab-panel[data-panel="' + tab.getAttribute("data-tab") + '"]', root); } function moveInk(btn) { if (!ink || !btn) return; ink.style.width = btn.offsetWidth + "px"; ink.style.transform = "translateX(" + btn.offsetLeft + "px)"; } function select(index, opts) { if (index < 0) index = tabs.length - 1; if (index >= tabs.length) index = 0; current = index; tabs.forEach(function (tab, i) { var active = i === index; tab.classList.toggle("is-active", active); tab.setAttribute("aria-selected", active ? "true" : "false"); tab.setAttribute("tabindex", active ? "0" : "-1"); // `hidden` as well as the class: it keeps the inactive panels out of // the accessibility tree, not just out of view. var panel = panelFor(tab); if (panel) { panel.classList.toggle("is-active", active); if (active) panel.removeAttribute("hidden"); else panel.setAttribute("hidden", ""); } }); moveInk(tabs[index]); if (opts && opts.focus) { tabs[index].focus(); // Keep the active tab visible when the strip scrolls on a phone. var tr = tabs[index].getBoundingClientRect(); var nr = nav.getBoundingClientRect(); if (tr.left < nr.left) nav.scrollLeft -= (nr.left - tr.left) + 12; else if (tr.right > nr.right) nav.scrollLeft += (tr.right - nr.right) + 12; } } tabs.forEach(function (tab, i) { on(tab, "click", function () { select(i); }); // Arrow keys move selection and focus together, per the ARIA pattern. on(tab, "keydown", function (e) { var key = e.key; if (key === "ArrowRight" || key === "ArrowDown") { e.preventDefault(); select(i + 1, { focus: true }); } else if (key === "ArrowLeft" || key === "ArrowUp") { e.preventDefault(); select(i - 1, { focus: true }); } else if (key === "Home") { e.preventDefault(); select(0, { focus: true }); } else if (key === "End") { e.preventDefault(); select(tabs.length - 1, { focus: true }); } }); }); // Linking to #reviews (the review count in the summary, and any external // link) should open the matching tab instead of landing on a hidden panel. var hashMap = { "#reviews": "reviews", "#psec-reviews": "reviews", "#yorumlar": "reviews", "#psec-details": "details", "#psec-qa": "qa", "#soru-cevap": "qa" }; function applyHash() { var want = hashMap[location.hash]; if (!want) return false; for (var i = 0; i < tabs.length; i++) { if (tabs[i].getAttribute("data-tab") === want) { select(i); return true; } } return false; } on(window, "hashchange", applyHash); // Turned on only now: from here the CSS hides the inactive panels. select(0); root.classList.add("tabs-ready"); applyHash(); // Fonts change tab widths, so the underline has to be re-measured. on(window, "resize", function () { moveInk(tabs[current]); }, { passive: true }); if (document.fonts && document.fonts.ready) { document.fonts.ready.then(function () { moveInk(tabs[current]); }); } })(); /* ---------- add-to-cart ajax (progressive enhancement) ---------- One delegated listener covers every form that adds to the cart, on every page. Before this, only the catalogue card was wired up: the product page, the mobile sticky bar, quick view, the wishlist panel, the drawer's cross-sell strip, the compare table and the bundle form all did a full page POST, so the slide-out cart never appeared outside the grid pages. The form is recognised by its action pointing at the cart-add route, which the server exposes per language in window.__DB.urls.cartAdd. */ var cartAddURL = (window.__DB && window.__DB.urls && window.__DB.urls.cartAdd) || ""; var bundleURL = (window.__DB && window.__DB.urls && window.__DB.urls.cartBundle) || ""; // The route table emits decoded URLs for window.__DB but the browser stores // the form action percent-encoded (Arabic, Russian, Greek, Hebrew, Georgian), // so a raw string comparison misses every non-Latin locale. Compare both // forms through the URL parser instead. function samePath(a, b) { if (!a || !b) return false; try { return new URL(a, location.origin).pathname === new URL(b, location.origin).pathname; } catch (e) { return a === b; } } function isCartForm(form) { if (!form || form.tagName !== "FORM") return false; var action = form.getAttribute("action") || ""; if (cartAddURL && samePath(action, cartAddURL)) return true; if (bundleURL && samePath(action, bundleURL)) return true; // Fallback: the route always ends in /add/ or /paket/, whatever the locale. return /\/add\/?$/.test(action) || /\/paket\/?$/.test(action); } // The submit button that triggered the submit: "Sepete ekle" and "Hemen al" // both submit the same form, and buy-now must keep its redirect. var submitter = null; document.addEventListener("click", function (e) { var b = e.target.closest && e.target.closest("button[type=submit], input[type=submit]"); submitter = b || null; }, true); document.addEventListener("submit", function (e) { var form = e.target; if (!isCartForm(form)) return; if (!window.fetch) return; // no fetch: let the normal POST through // Buy now and bundle adds keep the full navigation: the first needs the // checkout redirect, the second is a single POST the API does not model. var clicked = submitter && form.contains(submitter) ? submitter : null; if (clicked && clicked.name === "buy_now") return; if (form.classList.contains("bundle-form")) return; e.preventDefault(); submitter = null; var btn = clicked || $("button[type=submit]", form); var original = btn ? btn.textContent : ""; if (btn) { btn.disabled = true; btn.textContent = "…"; } var fd = new FormData(form); // A variation form writes variation_id into a hidden field the variation // script keeps in sync with the selected attributes. var payload = { product_id: parseInt(fd.get("product_id"), 10) || 0, variation_id: parseInt(fd.get("variation_id"), 10) || 0, qty: parseInt(fd.get("qty"), 10) || 1 }; fetch(window.dbWithLang("/api/sepet/ekle"), { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(payload) }).then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); }).then(function (res) { var data = res.d || {}; if (btn) { btn.disabled = false; btn.textContent = original; } // A refusal (out of stock, unavailable product, stale variation) used to // be silent: the button simply snapped back and the shopper had no idea // why nothing was added. Show the server's own message. if (!res.ok || !data.ok) { showAddError(form, data.error || T("js.generic_error", "Bir hata oluştu.")); return; } updateCartCount(data.count); // Refresh the slide-out cart and open it, matching the live storefront: // the shopper sees the line item without leaving the page. refreshCartDrawer(true); if (btn) { btn.textContent = T("js.added", "✓ Eklendi"); btn.classList.add("is-done"); setTimeout(function () { btn.textContent = original; btn.classList.remove("is-done"); }, 1600); } }).catch(function () { if (btn) { btn.disabled = false; btn.textContent = original; } showAddError(form, T("js.connection_error", "Bağlantı hatası.")); }); }); // showAddError puts a short, dismissible note under the form's button. It is // created lazily so templates stay free of empty placeholders, and it is // replaced rather than stacked when the shopper retries. function showAddError(form, message) { if (!form || !message) return; var note = form.querySelector("[data-add-error]"); if (!note) { note = document.createElement("p"); note.className = "add-error"; note.setAttribute("data-add-error", ""); note.setAttribute("role", "alert"); form.appendChild(note); } note.textContent = message; clearTimeout(note._t); note._t = setTimeout(function () { if (note.parentNode) note.parentNode.removeChild(note); }, 6000); } // The panel endpoints live under /api/ and therefore have no language prefix; // without this they always answer in the default language, so a German page // used to receive a Turkish drawer. // // It is attached to window because the drawer, wishlist and quick-view panels // live in separate IIFEs: a plain function here is out of scope there, and the // resulting ReferenceError was swallowed by the .catch, so the panel simply // never refreshed. window.dbWithLang = function (url) { var lang = (window.__DB && window.__DB.lang) || ""; if (!lang) return url; return url + (url.indexOf("?") < 0 ? "?" : "&") + "lang=" + encodeURIComponent(lang); }; function updateCartCount(count) { $$("[data-cart-count]").forEach(function (el) { el.textContent = count > 0 ? count : ""; }); } /* ---------- newsletter (no backend endpoint yet: graceful fallback) ---------- */ $$("[data-newsletter]").forEach(function (form) { on(form, "submit", function (e) { e.preventDefault(); var input = $("input[type=email]", form); if (!input || !input.value) return; var btn = $("button", form); var email = input.value; if (btn) { btn.disabled = true; } fetch("/api/bulten", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body: "email=" + encodeURIComponent(email) }).then(function () { if (btn) { btn.textContent = "✓"; } input.value = ""; input.placeholder = T("js.thanks", "Thank you!"); }).catch(function () { if (btn) { btn.disabled = false; } }); }); }); /* ---------- checkout: address cascade ---------- These run before the Stripe block on purpose. They used to sit below an early `return` that fires when Stripe.js is absent, which silently killed the whole country -> state -> city cascade on any checkout page where the payment provider was not configured. The address form must work either way. */ /* ---------- checkout: Stripe Payment Element ---------- */ /* ---------- checkout mobile tabs ---------- The order summary sits above the form on mobile, which forces a long scroll before the payment fields. The tab bar switches between the two panels so the buyer reaches payment in one tap. */ (function () { var page = $(".co-page"); var tabs = $$(".co-tab"); if (!page || !tabs.length) return; tabs.forEach(function (tab) { on(tab, "click", function (e) { e.preventDefault(); var target = tab.getAttribute("data-co-tab"); page.setAttribute("data-tab", target); tabs.forEach(function (t) { var active = t === tab; t.classList.toggle("is-active", active); t.setAttribute("aria-selected", active ? "true" : "false"); }); // Switching to the summary should start at the top of it, not keep the // scroll offset from the form. window.scrollTo({ top: 0, behavior: "auto" }); }); }); page.setAttribute("data-tab", "pay"); })(); var checkoutForm = $("#checkoutForm"); var stripePk = document.body.getAttribute("data-stripe-pk") || window.STRIPE_PK || ""; var hasStripe = !!(checkoutForm && window.Stripe && stripePk); function initShipToggle() { if (!checkoutForm) return; var same = $('input[name="ship_same"]', checkoutForm); var shipFields = $(".ship-fields", checkoutForm); if (!same || !shipFields) return; var sync = function () { shipFields.hidden = same.checked; }; same.addEventListener("change", sync); sync(); } initShipToggle(); var stripe = null, elements = null, paymentElement = null, expressElement = null; var payButton = $("#payButton"); var messageEl = $("#paymentMessage"); var intentCreated = false; function setLoading(isLoading) { if (!payButton) return; payButton.disabled = isLoading; var label = $(".btn-label", payButton), spinner = $(".btn-spinner", payButton); if (label) label.hidden = isLoading; if (spinner) spinner.hidden = !isLoading; } function showMessage(msg) { if (messageEl) messageEl.textContent = msg || ""; } // --- Country / state / city cascade ----------------------------------- // The reference data is embedded in the server, so these calls are answered // from memory. States come first; a country without states skips straight to // the city list. function geoURL(kind, params) { var g = window.__GEO || {}; var qs = Object.keys(params).filter(function (k) { return params[k] !== "" && params[k] != null; }) .map(function (k) { return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]); }).join("&"); // The root comes from the server so the cache-busting token lives in one // place. A hardcoded copy here kept requesting the old, week-cached answers // after the subdivision rule changed. var root = g.root || "/api/geo"; return root + "/" + kind + (qs ? "?" + qs : ""); } function fillSelect(sel, items, placeholder, selected) { if (!sel) return; var html = placeholder ? '" : ""; items.forEach(function (it) { var value = it.value != null ? it.value : it.name || it; var label = it.name != null ? it.name : String(it); var isSel = selected && String(selected).toLowerCase() === String(label).toLowerCase(); html += '