/* Linguaforum shop search. Load only on focus. Keep this file small. Matching: fold + Cyrillic translit, prefix, Damerau-Levenshtein (1 for 4–7, 2 for 8+), synonym groups, multi-word AND, boost type+country. */ (function (root) { "use strict"; var CYR = { а:"a",б:"b",в:"v",г:"h",ґ:"g",д:"d",е:"e",ё:"e",є:"ye",ж:"zh",з:"z",и:"y",і:"i",ї:"yi",й:"y", к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",х:"kh",ц:"ts",ч:"ch", ш:"sh",щ:"shch",ъ:"",ы:"y",ь:"",э:"e",ю:"yu",я:"ya","і":"i" }; var STOP = { tlumaczenie:1,tlumaczenia:1,tlumaczyc:1,przysiegle:1,przysiegly:1,przysieglego:1, dokument:1,dokumenty:1,dokumentu:1,jezyk:1,jezyka:1,jezyku:1, the:1,of:1,and:1,a:1,an:1,to:1,for:1,in:1,on:1,at:1,from:1,into:1,pro:1,ob:1, na:1,z:1,do:1,po:1,od:1,we:1,w:1,o:1,u:1,i:1,oraz:1,albo:1,ten:1, co:1,jest:1,oznacza:1,online:1,sworn:1,certified:1,translation:1,translate:1, zamow:1,zamowienie:1,cena:1,pdf:1,jak:1,wyglada:1,wyglada:1 }; function fold(s) { s = (s == null ? "" : String(s)); var out = "", i, ch, low, mapped; for (i = 0; i < s.length; i++) { ch = s.charAt(i); low = ch.toLowerCase(); if (CYR[low] != null) { out += CYR[low]; continue; } out += low; } out = out.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); out = out.replace(/ł/g, "l").replace(/ß/g, "ss"); return out; } function tokens(s) { return fold(s).split(/[^a-z0-9]+/).filter(function (t) { return t.length >= 1 && !STOP[t]; }); } function damerau(a, b, max) { if (a === b) return 0; var la = a.length, lb = b.length, dlen = la - lb; if (dlen < 0) dlen = -dlen; if (dlen > max) return max + 1; if (!la) return lb; if (!lb) return la; var i, j, prev, prev2, cur, tmp, cost, row, prow, pprow; prow = new Array(lb + 1); pprow = new Array(lb + 1); for (j = 0; j <= lb; j++) prow[j] = j; for (i = 1; i <= la; i++) { cur = new Array(lb + 1); cur[0] = i; for (j = 1; j <= lb; j++) { cost = a.charAt(i - 1) === b.charAt(j - 1) ? 0 : 1; tmp = prow[j] + 1; if (cur[j - 1] + 1 < tmp) tmp = cur[j - 1] + 1; if (prow[j - 1] + cost < tmp) tmp = prow[j - 1] + cost; if (i > 1 && j > 1 && a.charAt(i - 1) === b.charAt(j - 2) && a.charAt(i - 2) === b.charAt(j - 1)) { if (pprow[j - 2] + 1 < tmp) tmp = pprow[j - 2] + 1; } cur[j] = tmp; } pprow = prow; prow = cur; } return prow[lb]; } function fuzzyMax(len) { if (len >= 8) return 2; if (len >= 4) return 1; return 0; } function tokenHit(q, hay) { if (!q || !hay) return 0; if (q === hay) return 5; var parts = hay.split(/[^a-z0-9]+/).filter(function (p) { return p.length; }); var best = 0, i, part, s; for (i = 0; i < (parts.length ? parts.length : 1); i++) { part = parts.length ? parts[i] : hay; if (q === part) s = 5; else if (part.length >= 3 && part.indexOf(q) === 0) s = 3.2; else if (q.length >= 3 && q.indexOf(part) === 0 && part.length >= 3) s = 2.6; else if (q.length >= 3 && part.indexOf(q) >= 0) s = 2.1; else { var mx = fuzzyMax(q.length < part.length ? part.length : q.length); s = (mx && damerau(q, part, mx) <= mx) ? (mx === 1 ? 1.8 : 1.4) : 0; } if (s > best) best = s; } return best; } function bestAgainstList(q, list) { var best = 0, i, s; for (i = 0; i < list.length; i++) { s = tokenHit(q, list[i]); if (s > best) best = s; } return best; } function prepare(index) { var syn = index.syn || [], implies = index.implies || {}, items = index.items || []; var groups = {}, i, g, t, folded, termToGroups = {}; for (i = 0; i < syn.length; i++) { g = syn[i]; folded = []; (g.t || g.terms || []).forEach(function (term) { var ft = fold(term); if (!ft) return; folded.push(ft); if (!termToGroups[ft]) termToGroups[ft] = []; if (termToGroups[ft].indexOf(g.id) < 0) termToGroups[ft].push(g.id); var ttoks = tokens(term); var GENERIC = {svidotstvo:1,svidoctvo:1,svidocztwo:1,svidetelstvo:1,swiadectwo:1,certificate:1,cert:1,akt:1,aktu:1,akcie:1,akty:1,urkunde:1,dokument:1,dokumenty:1,tlumaczenie:1,tlumaczenia:1,przysiegle:1,zaswiadczenie:1,wyciag:1,odpis:1,pro:1,o:1,of:1,the:1}; if (ttoks.length === 1) { var tok = ttoks[0]; if (tok.length < 2 && tok !== "de" && tok !== "nl" && tok !== "uk" && tok !== "us" && tok !== "ua" && tok !== "pl" && tok !== "fr") return; if (!termToGroups[tok]) termToGroups[tok] = []; if (termToGroups[tok].indexOf(g.id) < 0) termToGroups[tok].push(g.id); } else { ttoks.forEach(function (tok2) { if (GENERIC[tok2] || tok2.length < 4) return; if (!termToGroups[tok2]) termToGroups[tok2] = []; if (termToGroups[tok2].indexOf(g.id) < 0) termToGroups[tok2].push(g.id); }); } }); groups[g.id] = { id: g.id, kind: g.k || g.kind, terms: folded }; } var impl = {}; Object.keys(implies).forEach(function (k) { impl[fold(k)] = implies[k]; }); items.forEach(function (it) { if (!it._tok) it._tok = tokens((it.n || "") + " " + (it.t || "") + " " + (it.c || "") + " " + (it.x || "")); if (!it._g) it._g = it.g || []; if (!it._cs) it._cs = it.cs || []; }); var countriesById = {}; (index.countries || []).forEach(function (c) { if (c && c.id) countriesById[c.id] = c; }); return { groups: groups, termToGroups: termToGroups, implies: impl, also: index.also || {}, items: items, countriesById: countriesById }; } function matchGroups(tok, prep) { var hits = {}, keys = Object.keys(prep.termToGroups), i, k, s, j, gid, gids; for (i = 0; i < keys.length; i++) { k = keys[i]; if (k.indexOf(" ") >= 0) { if (tok === k) s = 5; else s = 0; } else { s = tokenHit(tok, k); } if (s >= 1.4) { gids = prep.termToGroups[k]; for (j = 0; j < gids.length; j++) { gid = gids[j]; if (!hits[gid] || hits[gid] < s) hits[gid] = s; } } } Object.keys(prep.implies).forEach(function (key) { var sc = (key.indexOf(" ") >= 0) ? (tok === key ? 5 : 0) : tokenHit(tok, key); if (sc >= 1.4) { (prep.implies[key] || []).forEach(function (id) { if (!hits[id] || hits[id] < sc) hits[id] = sc; }); } }); return hits; } function countryTermHit(ft, hay) { if (!ft) return false; if (ft.length <= 3) return hay.indexOf(" " + ft + " ") >= 0; var start = 0, i, prev, after; while ((i = hay.indexOf(ft, start)) >= 0) { prev = i ? hay.charAt(i - 1) : " "; if (prev === " ") { if (ft.length >= 5) return true; after = hay.charAt(i + ft.length); if (!after || after === " ") return true; } start = i + 1; } return false; } function itemHasCountry(item, cid, prep) { if (!cid) return true; var cs = item._cs || item.cs || []; if (cs.indexOf(cid) >= 0) return true; if ((item._g || item.g || []).indexOf(cid) >= 0) return true; var terms = [], cat = (prep.countriesById && prep.countriesById[cid]) || null; if (cat && cat.terms) terms = terms.concat(cat.terms); if (cat && cat.name) terms.push(cat.name); if (prep.groups[cid] && prep.groups[cid].terms) terms = terms.concat(prep.groups[cid].terms); var hay = " " + fold((item.n || "") + " " + (item.c || "")).replace(/[^a-z0-9]+/g, " ") + " "; var i, ft; for (i = 0; i < terms.length; i++) { ft = typeof terms[i] === "string" && terms[i].indexOf(" ") < 0 && /^[a-z0-9 ]+$/.test(terms[i]) && terms[i] === fold(terms[i]) ? terms[i] : fold(terms[i]); if (countryTermHit(ft, hay)) return true; } return false; } function stripFlagEmoji(s) { s = String(s || ""); // Regional-indicator pairs (flag emoji) and VS16 / ZWJ leftovers. s = s.replace(/[\uD83C][\uDDE6-\uDDFF][\uD83C][\uDDE6-\uDDFF]/g, " "); s = s.replace(/[\uFE0F\u200D]/g, ""); s = s.replace(/[\uD83C-\uDBFF][\uDC00-\uDFFF]/g, " "); s = s.replace(/[\u2600-\u27BF]/g, " "); return s.replace(/^\s+|\s+$/g, "").replace(/\s+/g, " "); } function flagsFromName(s) { s = String(s || ""); var out = [], i = 0, cp, next, a, b, cc; while (i < s.length) { cp = s.codePointAt(i); if (cp >= 0x1F1E6 && cp <= 0x1F1FF && i + 2 < s.length) { next = s.codePointAt(i + 2); if (next >= 0x1F1E6 && next <= 0x1F1FF) { a = cp - 0x1F1E6; b = next - 0x1F1E6; cc = String.fromCharCode(97 + a, 97 + b); if (out.indexOf(cc) < 0) out.push(cc); i += 4; continue; } } i += cp > 0xFFFF ? 2 : 1; } return out; } function flagUrl(base, cc, countriesById) { if (!cc) return ""; var file = cc; if (countriesById) { var id; for (id in countriesById) { if (countriesById[id] && (countriesById[id].cc === cc || countriesById[id].id === cc)) { file = countriesById[id].cc || cc; break; } } } if (file === "uk") file = "gb"; base = String(base || "flags/"); if (base.indexOf("{cc}") >= 0) return base.split("{cc}").join(file); return base.replace(/\/?$/, "/") + file + ".svg"; } function itemLangs(item) { if (item && item.ls && item.ls.length) return item.ls; var out = [], g = (item && (item._g || item.g)) || [], i, m; for (i = 0; i < g.length; i++) { m = String(g[i] || "").match(/^lang_([a-z]{2})$/); if (m && out.indexOf(m[1]) < 0) out.push(m[1]); } return out; } function itemHasLang(item, langs) { if (!langs || !langs.length) return true; var have = itemLangs(item), i; for (i = 0; i < langs.length; i++) if (have.indexOf(langs[i]) >= 0) return true; return false; } // Official languages of the issuing country. Mirrors the index builder. // "uk" as a *country* id is the United Kingdom (English); Ukrainian is country "ua". var COUNTRY_LANGS = { us: ["en"], uk: ["en"], au: ["en"], ie: ["en"], nz: ["en"], ph: ["en"], ca: ["en", "fr"], nl: ["nl"], be: ["nl", "fr"], ua: ["uk"], pl: ["pl"], de: ["de"], at: ["de"], li: ["de"], fr: ["fr"], ch: ["de", "fr", "it"], lu: ["fr", "de"], it: ["it"], es: ["es"], pt: ["pt"], ru: ["ru"], by: ["ru"], jp: ["ja"], kr: ["ko"], cn: ["zh"], vn: ["vi"], tr: ["tr"], ae: ["ar"], se: ["sv"], no: ["no"], dk: ["da"], fi: ["fi"], is: ["is"], cz: ["cs"], sk: ["sk"], si: ["sl"], hr: ["hr"], rs: ["sr"], ba: ["bs"], me: ["sr"], bg: ["bg"], ro: ["ro"], hu: ["hu"], lt: ["lt"], lv: ["lv"], ee: ["et"], gr: ["el"], ge: ["ka"], al: ["sq"], il: ["he"], idn: ["id"] }; function itemIssuingCountryIds(item) { var out = [], i, id; var cs = (item && (item._cs || item.cs)) || []; for (i = 0; i < cs.length; i++) { id = cs[i]; if (id && out.indexOf(id) < 0) out.push(id); } var g = (item && (item._g || item.g)) || []; for (i = 0; i < g.length; i++) { id = g[i]; if (!id || String(id).indexOf("lang_") === 0) continue; if (COUNTRY_LANGS[id] && out.indexOf(id) < 0) out.push(id); } return out; } function itemIssuedInLang(item, langs) { if (!langs || !langs.length) return false; var countries = itemIssuingCountryIds(item), i, j, official; for (i = 0; i < countries.length; i++) { official = COUNTRY_LANGS[countries[i]] || []; for (j = 0; j < langs.length; j++) { if (official.indexOf(langs[j]) >= 0) return true; } } return false; } function search(index, q, opts) { q = (q || "").trim(); opts = opts || {}; var forceTypes = opts.filterTypes || []; var forceCountries = opts.filterCountries || []; var forceLangs = opts.filterLangs || []; var prep = index._prep || (index._prep = prepare(index)); var qTok = tokens(q); if (!qTok.length && !forceTypes.length && !forceCountries.length) return []; var qGroups = {}, t, ghits, gid; for (t = 0; t < qTok.length; t++) { ghits = matchGroups(qTok[t], prep); for (gid in ghits) { if (!qGroups[gid] || qGroups[gid] < ghits[gid]) qGroups[gid] = ghits[gid]; } } var qTypes = [], qCountries = [], qCountriesImplied = []; for (gid in qGroups) { if (!prep.groups[gid]) continue; if (prep.groups[gid].kind === "type") qTypes.push(gid); if (prep.groups[gid].kind === "country") qCountries.push(gid); } var qHay = " " + fold(q).replace(/[^a-z0-9]+/g, " ") + " "; Object.keys(prep.countriesById || {}).forEach(function (cid) { var cat = prep.countriesById[cid] || {}; var terms = (cat.t || cat.terms || []).concat(cat.n || cat.name || []); var hi, term, ft; for (hi = 0; hi < terms.length; hi++) { ft = fold(terms[hi] || ""); if (countryTermHit(ft, qHay) && qCountries.indexOf(cid) < 0) { qCountries.push(cid); break; } } }); // countries that come only from implies (fahrzeugbrief→de), not typed by the user qTok.forEach(function (tok) { Object.keys(prep.implies).forEach(function (key) { if (tokenHit(tok, key) >= 1.4) { (prep.implies[key] || []).forEach(function (id) { if (prep.groups[id] && prep.groups[id].kind === "country" && qCountriesImplied.indexOf(id) < 0) qCountriesImplied.push(id); }); } }); }); var qCountriesExplicit = qCountries.filter(function (id) { return qCountriesImplied.indexOf(id) < 0 || qTok.some(function (tok) { return bestAgainstList(tok, (prep.groups[id] && prep.groups[id].terms) || []) >= 2.6; }); }); forceTypes.forEach(function (id) { if (qTypes.indexOf(id) < 0) qTypes.push(id); }); forceCountries.forEach(function (id) { if (qCountries.indexOf(id) < 0) qCountries.push(id); if (qCountriesExplicit.indexOf(id) < 0) qCountriesExplicit.push(id); }); var also = prep.also || {}; qTypes.forEach(function (id) { (also[id] || []).forEach(function (x) { if (qTypes.indexOf(x) < 0) qTypes.push(x); }); }); Object.keys(also).forEach(function (src) { (also[src] || []).forEach(function (dst) { if (qTypes.indexOf(dst) >= 0 && qTypes.indexOf(src) < 0) qTypes.push(src); }); }); var scored = [], i, item, s, tok, best, gset, hasType, hasCountry, all, miss; for (i = 0; i < prep.items.length; i++) { item = prep.items[i]; if (forceLangs.length && !itemHasLang(item, forceLangs)) continue; all = 0; miss = false; if (qTok.length) { for (t = 0; t < qTok.length; t++) { tok = qTok[t]; best = bestAgainstList(tok, item._tok); ghits = matchGroups(tok, prep); gset = item._g || []; for (gid in ghits) { if (gset.indexOf(gid) >= 0 && ghits[gid] + 0.8 > best) best = ghits[gid] + 0.8; } if (best <= 0) { if (!forceTypes.length && !forceCountries.length) { miss = true; break; } } else { all += best; } } if (miss) continue; } else if (forceTypes.length || forceCountries.length) { all += 2; } hasType = false; hasCountry = false; if (forceCountries.length) { var countryHit = false, fi; for (fi = 0; fi < forceCountries.length; fi++) { if (itemHasCountry(item, forceCountries[fi], prep)) countryHit = true; } if (!countryHit) continue; } if (qTypes.length) { var typeHit = false, ti; for (ti = 0; ti < qTypes.length; ti++) if ((item._g || []).indexOf(qTypes[ti]) >= 0) typeHit = true; if (!typeHit) continue; } for (t = 0; t < qTypes.length; t++) if ((item._g || []).indexOf(qTypes[t]) >= 0) hasType = true; for (t = 0; t < qCountries.length; t++) if ((item._g || []).indexOf(qCountries[t]) >= 0) hasCountry = true; if (hasType) all += 2.5; var hasExplicit = false, hasImplied = false, ci; for (ci = 0; ci < qCountriesExplicit.length; ci++) if ((item._g || []).indexOf(qCountriesExplicit[ci]) >= 0) hasExplicit = true; for (ci = 0; ci < qCountriesImplied.length; ci++) if ((item._g || []).indexOf(qCountriesImplied[ci]) >= 0) hasImplied = true; if (hasExplicit) { all += 3.5; hasCountry = true; } else if (hasImplied) { all += 1.4; hasCountry = true; } if (hasType && hasExplicit) all += 4; // exact query tokens in the product name beat synonym-only hits var nameTok = tokens(item.n || ""); var exact = 0; for (t = 0; t < qTok.length; t++) { if (nameTok.indexOf(qTok[t]) >= 0) exact += 4; else if (bestAgainstList(qTok[t], nameTok) >= 3) exact += 2.2; else if (bestAgainstList(qTok[t], nameTok) >= 1.4) exact += 0.8; } all += exact; var nm = fold(item.n || ""); var isPackage = /(^|[^a-z0-9])(pakiet|komplet|zestaw|bundle)([^a-z0-9]|$)/.test(nm); var qFold = fold(q); var packageWordInQ = /(pakiet|komplet|zestaw)/.test(qFold); var browsing = (forceTypes && forceTypes.length) || (forceCountries && forceCountries.length) || /(dokumenty\s+celne|dokumenty\s+samochod|odprawa\s+celn)/.test(qFold); if (isPackage && !packageWordInQ && !browsing) { var countryQuery = qCountriesExplicit && qCountriesExplicit.length && hasExplicit; all -= countryQuery ? 0.4 : 3.2; } var typFold = fold(item.t || ""); if (forceTypes && forceTypes.indexOf("celne") >= 0 && typFold.indexOf("dokumenty celne") >= 0 && !isPackage) { all += 2.6; } var FEATURED = { us: 1, ca: 1, jp: 1, kr: 1 }; if (isPackage) { var fcs = item.cs || item._cs || []; var fg = item._g || item.g || []; var fid, featured = false; for (fid in FEATURED) { if (fcs.indexOf(fid) >= 0 || fg.indexOf(fid) >= 0) { featured = true; break; } } if (featured) all += 2.2; } if (item.p != null && item.p !== "") all += 0.15; // On a language landing, documents issued in a country that uses that // language (e.g. Ukraine on the UA page) outrank Polish "Wybierz Język" variants. if (forceLangs.length && itemIssuedInLang(item, forceLangs)) all += 4; scored.push({ s: all, item: item }); } scored.sort(function (a, b) { if (b.s !== a.s) return b.s - a.s; return stripFlagEmoji(a.item.n || "").localeCompare(stripFlagEmoji(b.item.n || ""), "pl"); }); return scored; } function fmtPrice(p) { if (p == null || p === "") return null; var n = Number(p); if (!isFinite(n)) return null; return (Math.round(n) === n ? String(n) : n.toFixed(2).replace(".", ",")) + " zł"; } function bind(root, indexUrl) { if (!root) return; var input = root.querySelector("[data-lf-q]") || root.querySelector("#lf-shop-q"); var statusEl = root.querySelector("[data-lf-status]") || root.querySelector("#lf-shop-search-status"); var listEl = root.querySelector("[data-lf-results]") || root.querySelector("#lf-shop-search-results"); var emptyEl = root.querySelector("[data-lf-empty]") || root.querySelector("#lf-shop-search-empty"); if (!input || !listEl) return; function setStatus(t) { if (statusEl) statusEl.textContent = t || ""; } var countryRoot = root.querySelector(".lf-shop-country"); var countryBtn = root.querySelector("#lf-shop-country-btn"); var countryList = root.querySelector("#lf-shop-country-list"); var countryBtnText = root.querySelector("#lf-shop-country-btn-text"); var countryBtnFlag = root.querySelector(".lf-shop-country-btn-flag"); var data = null, loadPromise = null, WYCENA = "https://www.linguaforum.eu/wycena-tlumaczenia-online/"; var activeTypes = []; var activeCountries = []; var fixedLang = (root.getAttribute("data-lf-lang") || (root.closest && root.closest("[data-lf-lang]") && root.closest("[data-lf-lang]").getAttribute("data-lf-lang")) || "").trim().toLowerCase(); function currentQ() { return input ? input.value : ""; } function filtersOn() { return (activeTypes && activeTypes.length) || (activeCountries && activeCountries.length); } function render(rows, q) { listEl.innerHTML = ""; if (emptyEl) emptyEl.hidden = true; var showing = !!(rows && rows.length) || (rows && !rows.length); if (rows == null) showing = false; root.classList.toggle("is-showing-results", showing); listEl.hidden = !showing || !(rows && rows.length); if (rows == null) { var readyN = langItemCount(); setStatus(data ? (fixedLang ? ("Indeks gotowy — " + readyN + " tłumaczeń w tym języku. Wpisz frazę albo wybierz filtr.") : ("Indeks gotowy — " + (data.items || data).length + " produktów. Wpisz frazę albo wybierz filtr.")) : ""); return; } if (!rows.length) { setStatus(q ? (fixedLang ? ("Brak pozycji w tym języku dla „" + q + "”.") : ("Brak pozycji w sklepie dla „" + q + "”.")) : "Brak pozycji w sklepie dla wybranego filtra."); if (emptyEl) emptyEl.hidden = false; return; } setStatus("Pokazuję " + rows.length + " z dopasowanych wyników."); rows.forEach(function (r) { var it = r.item, li = document.createElement("li"); var a = document.createElement("a"); a.href = it.u; var title = document.createElement("span"); title.className = "t"; var flagBase = root.getAttribute("data-lf-flag-base") || (data && data.flagBase) || "flags/"; var ccs = flagsFromName(it.n); if (!ccs.length && it.cs && it.cs.length) { it.cs.forEach(function (cid) { var cat = (data && data._prep && data._prep.countriesById && data._prep.countriesById[cid]) || null; if (!cat && data && data.countries) { for (var ci = 0; ci < data.countries.length; ci++) if (data.countries[ci].id === cid) { cat = data.countries[ci]; break; } } var cc = cat && (cat.cc || cat.id); if (cc && ccs.indexOf(cc) < 0) ccs.push(cc); }); } if (ccs.length) { var flagWrap = document.createElement("span"); flagWrap.className = "lf-shop-result-flags"; ccs.forEach(function (cc) { var img = document.createElement("img"); img.className = "lf-shop-flag"; img.src = flagUrl(flagBase, cc, data && data._prep && data._prep.countriesById); img.alt = ""; img.width = 22; img.height = 16; img.loading = "lazy"; img.decoding = "async"; flagWrap.appendChild(img); }); title.appendChild(flagWrap); } var titleText = document.createElement("span"); titleText.className = "lf-shop-result-title"; titleText.textContent = stripFlagEmoji(it.n) || it.n; title.appendChild(titleText); var meta = document.createElement("span"); meta.className = "m"; meta.textContent = [it.t, it.c].filter(Boolean).join(" · "); var pr = document.createElement("span"); var fp = fmtPrice(it.p); if (fp) { pr.className = "price"; pr.textContent = fp; } else { pr.className = "wycena"; pr.textContent = "Indywidualna wycena"; } a.appendChild(title); if (meta.textContent) a.appendChild(meta); a.appendChild(pr); li.appendChild(a); listEl.appendChild(li); }); } function setActiveChip(btn) { root.querySelectorAll(".lf-shop-chip").forEach(function (c) { c.classList.remove("is-active"); c.setAttribute("aria-pressed", "false"); }); if (btn) { btn.classList.add("is-active"); btn.setAttribute("aria-pressed", "true"); } } function run(q, types, countries) { if (!data) return; q = (q || "").trim(); types = types || activeTypes || []; countries = countries || activeCountries || []; if (q.length < 2 && !types.length && !countries.length) { render(null, q); return; } var opts = { filterTypes: types, filterCountries: countries }; if (fixedLang) opts.filterLangs = [fixedLang]; render(search(data, q, opts).slice(0, 12), q); } function langItemCount() { if (!data) return 0; if (!fixedLang) return (data.items || []).length; var items = data.items || [], n = 0, i; for (i = 0; i < items.length; i++) if (itemHasLang(items[i], [fixedLang])) n++; return n; } function applyLangScope() { if (!data || !fixedLang) return; var items = data.items || []; var typeOk = {}, countryOk = {}, i, g, t, c; for (i = 0; i < items.length; i++) { if (!itemHasLang(items[i], [fixedLang])) continue; g = items[i].g || items[i]._g || []; for (t = 0; t < g.length; t++) typeOk[g[t]] = true; c = items[i].cs || []; for (t = 0; t < c.length; t++) countryOk[c[t]] = true; } root.querySelectorAll(".lf-shop-chip").forEach(function (btn) { var ids = (btn.getAttribute("data-types") || "").split(",").map(function (s) { return s.trim(); }).filter(Boolean); var ok = !ids.length || ids.some(function (id) { return typeOk[id]; }); btn.hidden = !ok; if (!ok) { btn.classList.remove("is-active"); btn.setAttribute("aria-pressed", "false"); } }); root.querySelectorAll(".lf-shop-country-option[data-country]").forEach(function (opt) { var id = opt.getAttribute("data-country") || ""; if (!id) { opt.hidden = false; return; } opt.hidden = !countryOk[id]; }); } function loadIndex() { if (loadPromise) return loadPromise; setStatus("Ładuję indeks produktów…"); loadPromise = fetch(indexUrl).then(function (r) { if (!r.ok) throw new Error("index " + r.status); return r.text().then(function (txt) { return JSON.parse(txt); }); }).then(function (json) { data = json.items ? json : { items: json, syn: [], implies: {} }; data._prep = prepare(data); applyLangScope(); setStatus(fixedLang ? ("Indeks gotowy — " + langItemCount() + " tłumaczeń w tym języku.") : ("Indeks gotowy — " + (data.items || []).length + " produktów.")); return data; }).catch(function () { setStatus("Nie udało się wczytać indeksu wyszukiwarki."); loadPromise = null; }); return loadPromise; } function onNeed() { loadIndex().then(function () { if (!data) return; if (currentQ().trim().length >= 2 || filtersOn()) run(currentQ()); }); } function closeCountry() { if (!countryBtn) return; countryBtn.setAttribute("aria-expanded", "false"); if (countryList) countryList.hidden = true; root.classList.remove("is-country-open"); } function openCountry() { if (!countryBtn || !countryList) return; countryBtn.setAttribute("aria-expanded", "true"); countryList.hidden = false; root.classList.add("is-country-open"); } function syncCountryButton() { var id = activeCountries[0] || ""; var opt = null; if (countryList) { countryList.querySelectorAll(".lf-shop-country-option").forEach(function (el) { var on = (el.getAttribute("data-country") || "") === id; el.classList.toggle("is-selected", on); el.setAttribute("aria-selected", on ? "true" : "false"); if (on) opt = el; }); } var label = "Wszystkie kraje"; var src = ""; if (opt) { var span = opt.querySelector("span"); label = ((span ? span.textContent : opt.textContent) || "").trim() || label; var img = opt.querySelector("img"); if (img) src = img.getAttribute("src") || ""; } if (countryBtnText) countryBtnText.textContent = label; if (countryBtnFlag) { if (src) { countryBtnFlag.src = src; countryBtnFlag.removeAttribute("hidden"); countryBtnFlag.hidden = false; countryBtnFlag.alt = ""; } else { countryBtnFlag.removeAttribute("src"); countryBtnFlag.hidden = true; countryBtnFlag.setAttribute("hidden", ""); } } } function setCountry(id) { activeCountries = id ? [id] : []; syncCountryButton(); closeCountry(); } function focusOption(el) { if (!el || !countryList) return; countryList.querySelectorAll(".lf-shop-country-option").forEach(function (o) { o.classList.remove("is-focused"); }); el.classList.add("is-focused"); if (el.focus) el.focus(); if (el.scrollIntoView) el.scrollIntoView({ block: "nearest" }); } if (countryBtn && countryList) { countryList.querySelectorAll(".lf-shop-country-option").forEach(function (opt) { if (!opt.hasAttribute("tabindex")) opt.setAttribute("tabindex", "-1"); }); countryBtn.addEventListener("click", function (ev) { ev.preventDefault(); var open = countryBtn.getAttribute("aria-expanded") === "true"; if (open) closeCountry(); else { onNeed(); openCountry(); } }); countryBtn.addEventListener("focus", onNeed); countryList.addEventListener("pointerdown", onNeed); countryList.addEventListener("click", function (ev) { var opt = ev.target.closest ? ev.target.closest(".lf-shop-country-option") : null; if (!opt || !countryList.contains(opt)) return; ev.preventDefault(); setCountry(opt.getAttribute("data-country") || ""); loadIndex().then(function () { if (data) run(currentQ()); }); countryBtn.focus(); }); countryList.addEventListener("keydown", function (ev) { var opts = Array.prototype.slice.call(countryList.querySelectorAll(".lf-shop-country-option")); var cur = (document.activeElement && countryList.contains(document.activeElement)) ? document.activeElement : (countryList.querySelector(".is-focused") || countryList.querySelector(".is-selected") || opts[0]); var i = opts.indexOf(cur); if (ev.key === "ArrowDown") { ev.preventDefault(); focusOption(opts[Math.min(opts.length - 1, Math.max(0, i) + 1)]); } else if (ev.key === "ArrowUp") { ev.preventDefault(); focusOption(opts[Math.max(0, i - 1)]); } else if (ev.key === "Home") { ev.preventDefault(); focusOption(opts[0]); } else if (ev.key === "End") { ev.preventDefault(); focusOption(opts[opts.length - 1]); } else if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); if (cur) { setCountry(cur.getAttribute("data-country") || ""); loadIndex().then(function () { if (data) run(currentQ()); }); countryBtn.focus(); } } else if (ev.key === "Escape") { ev.preventDefault(); closeCountry(); countryBtn.focus(); } }); document.addEventListener("click", function (ev) { if (!root.classList.contains("is-country-open")) return; if (countryRoot && countryRoot.contains(ev.target)) return; closeCountry(); }); document.addEventListener("keydown", function (ev) { if (ev.key === "Escape" && root.classList.contains("is-country-open")) closeCountry(); }); } if (input) { input.addEventListener("focus", onNeed); input.addEventListener("click", onNeed); input.addEventListener("input", function () { if (!data) { onNeed(); return; } run(input.value); }); input.addEventListener("keydown", function (ev) { if (ev.key === "Escape") { ev.preventDefault(); input.value = ""; listEl.innerHTML = ""; listEl.hidden = true; root.classList.remove("is-showing-results"); if (emptyEl) emptyEl.hidden = true; setStatus(""); input.focus(); return; } if (ev.key === "Enter") { var a = listEl.querySelector("a"); if (a && a.href) { ev.preventDefault(); location.href = a.href; } } }); } root.querySelectorAll(".lf-shop-chip").forEach(function (chip) { chip.addEventListener("click", function () { var types = (chip.getAttribute("data-types") || "").split(",").map(function (s) { return s.trim(); }).filter(Boolean); if (chip.classList.contains("is-active")) { activeTypes = []; setActiveChip(null); if (input && (chip.getAttribute("data-q") || "") && input.value === chip.getAttribute("data-q")) input.value = ""; } else { activeTypes = types; setActiveChip(chip); if (input && chip.getAttribute("data-q")) input.value = chip.getAttribute("data-q"); } loadIndex().then(function () { if (data) run(currentQ(), activeTypes); }); }); }); var params = new URLSearchParams(location.search); var demo = params.get("q") || ((location.hash || "").indexOf("#q=") === 0 ? location.hash.slice(3) : ""); if (demo) { if (input) input.value = demo; onNeed(); } enhanceClear(root); } function enhanceClear(rootEl) { if (!rootEl) return; var input = rootEl.querySelector("[data-lf-q]") || rootEl.querySelector("#lf-shop-q") || rootEl.querySelector("input[type=search]"); if (!input || input.getAttribute("data-lf-clear-bound")) return; var listEl = rootEl.querySelector("[data-lf-results]") || rootEl.querySelector("#lf-shop-search-results") || rootEl.querySelector(".lf-header-search-results, .lf-shop-search-results"); var emptyEl = rootEl.querySelector("[data-lf-empty]") || rootEl.querySelector("#lf-shop-search-empty"); var host = input.parentNode; if (!host) return; input.setAttribute("data-lf-clear-bound", "1"); rootEl.setAttribute("data-lf-clear-bound", "1"); var clearBtn = host.querySelector("[data-lf-clear]"); if (!clearBtn) { clearBtn = document.createElement("button"); clearBtn.type = "button"; clearBtn.setAttribute("data-lf-clear", "1"); clearBtn.className = "lf-search-clear"; clearBtn.setAttribute("aria-label", "Wyczyść"); clearBtn.textContent = "×"; host.appendChild(clearBtn); } function setFilled() { var has = !!(input.value && String(input.value).length); clearBtn.hidden = !has; rootEl.classList.toggle("is-filled", has); host.classList.toggle("is-filled", has); } function clearQuery() { input.value = ""; if (listEl) { listEl.innerHTML = ""; listEl.hidden = true; } rootEl.classList.remove("is-showing-results"); if (emptyEl) emptyEl.hidden = true; var statusEl = rootEl.querySelector("[data-lf-status]") || rootEl.querySelector("#lf-shop-search-status"); if (statusEl) statusEl.textContent = ""; setFilled(); input.focus(); } clearBtn.addEventListener("mousedown", function (ev) { ev.preventDefault(); }); clearBtn.addEventListener("click", function (ev) { ev.preventDefault(); ev.stopPropagation(); clearQuery(); }); input.addEventListener("input", setFilled); input.addEventListener("change", setFilled); input.addEventListener("keyup", setFilled); input.addEventListener("keydown", function (ev) { if (ev.key === "Escape") { ev.preventDefault(); clearQuery(); } }); rootEl.querySelectorAll(".lf-shop-chip").forEach(function (chip) { chip.addEventListener("click", function () { setTimeout(setFilled, 0); }); }); setFilled(); } function enhanceAll() { if (typeof document === "undefined") return; document.querySelectorAll("[data-lf-index], .lf-header-search, .lf-shop-search-field").forEach(enhanceClear); } function autoBind() { if (typeof document === "undefined") return; var nodes = document.querySelectorAll("[data-lf-index]"); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; if (el.getAttribute("data-lf-bound")) continue; var url = el.getAttribute("data-lf-index"); if (!url) continue; el.setAttribute("data-lf-bound", "1"); API.bind(el, url); } enhanceAll(); } var API = { fold: fold, tokens: tokens, damerau: damerau, search: search, prepare: prepare, bind: bind, fmtPrice: fmtPrice, autoBind: autoBind, enhanceClear: enhanceClear, enhanceAll: enhanceAll, stripFlagEmoji: stripFlagEmoji, flagsFromName: flagsFromName, flagUrl: flagUrl, itemLangs: itemLangs, itemHasLang: itemHasLang, itemIssuedInLang: itemIssuedInLang, itemIssuingCountryIds: itemIssuingCountryIds }; if (typeof module !== "undefined" && module.exports) module.exports = API; root.LFSklepSearch = API; if (typeof document !== "undefined") { if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", autoBind); else autoBind(); } })(typeof window !== "undefined" ? window : (typeof global !== "undefined" ? global : this));