let enabledFilters=['category','brand'];
let traduzioni = {};
var VisualizzaRibbonSconto = false;
function initializeSearchContainer() {
document.getElementById("osw-search-container").classList.add("active");
document.getElementsByClassName("ais-SearchBox-input")[0].focus();
}
function closeOswSearch() {
document.getElementById("osw-search-container").classList.remove("active");
document.getElementsByClassName("ais-ClearRefinements-button")[0].click();
}
function cerca(text) {
var searchBox = document.querySelector('.ais-SearchBox-input');
if (searchBox) {
searchBox.value = '';
for (let i = 0; i < text.length; i++) {
var inputEvent = new InputEvent('input', {
bubbles: true
});
searchBox.value += text[i];
}
searchBox.dispatchEvent(inputEvent);
} else {
console.error('Elemento non trovato');
}
}
// Funzione di attesa
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var searchBodyTemplate = `
`
const {
connectHits
} = instantsearch.connectors;
const renderHits = (renderOptions, isFirstRender) => {
if (isFirstRender == false) {
const category = renderOptions.results.categoryresults;
const {
hits,
widgetParams
} = renderOptions;
if (category === undefined || category == null) {
document.getElementById("category-results").innerHTML="";
return;
}
var risultato;
widgetParams.container.innerHTML = `
${category.map(
item =>
widgetParams.templates.item.replaceAll('{{Image}}',item["Image"]).replaceAll('{{Name}}',item["Name"]).replaceAll('{{Link}}',item["Link"])
)
.join('')}
`;
}
};
// 2. Create the custom widget
const customHits = connectHits(
renderHits
);
//BRAND
const {
connectBrandHits
} = instantsearch.connectors;
const renderBrandHits = (renderOptions, isFirstRender) => {
if (isFirstRender == false) {
const sugg = renderOptions.results.brandresults;
const {
hits,
widgetParams
} = renderOptions;
if (sugg === undefined || sugg == null) {
document.getElementById("brand-results").innerHTML = "";
return;
}
widgetParams.container.innerHTML = `
${sugg.map(
item =>
widgetParams.templates.item.replaceAll('{{Image}}', item["Image"]).replaceAll('{{Name}}', item["Name"]).replaceAll('{{Link}}', item["Link"])
)
.join('')}
`;
}
};
const BrandHits = connectHits(
renderBrandHits
);
//FINE BRAND
//suggerimenti script
const {
connectSuggestionsHits
} = instantsearch.connectors;
const renderSuggestionsHits = (renderOptions, isFirstRender) => {
if (isFirstRender == false) {
const sugg = renderOptions.results.suggestionsresults;
const {
hits,
widgetParams
} = renderOptions;
if (sugg === undefined || sugg == null) {
document.getElementById("suggerimenti").innerHTML="";
return;
}
widgetParams.container.innerHTML = `
${sugg.map(
item =>
widgetParams.templates.item.replaceAll('{{Name}}',item["Name"])
)
.join('')}
`;
}
};
const SuggestionsHits = connectHits(
renderSuggestionsHits
);
//fine suggerimenti script
function initiateSearch(apiKey, searchBoxIdentifier, languageId) {
document.getElementById(searchBoxIdentifier).onclick = function () {
initializeSearchContainer()
};
document.body.insertAdjacentHTML('beforeend', searchBodyTemplate);
const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
server: {
apiKey: apiKey, // Be sure to use an API key that only allows searches, in production
nodes: [{
host: "www.hunty.it",
port: "",
protocol: "https",
}, ],
},
additionalSearchParameters: {
"ln": languageId,
},
});
const searchClient = typesenseInstantsearchAdapter.searchClient;
const search = instantsearch({
searchClient,
indexName: "products",
routing: true,
searchFunction: function (helper) {
if (helper.state.query === '') {
return;
}
helper.search();
}
});
search.addWidgets([
customHits({
container: document.querySelector("#category-results"),
escapeHTML: true,
escapeHTML: true,
templates: {
item: `
`,
},
cssClasses: {
list: "osw-search_category-results-ontainer",
item: "osw-search_category-result-box",
},
}),
//SUGGERIMENTI
SuggestionsHits({
container: document.querySelector("#suggerimenti"),
escapeHTML: true,
escapeHTML: true,
templates: {
item: `
{{Name}}
`,
},
}),
//FINE-SUGGERIMENTI
//Brand
BrandHits({
container: document.querySelector("#brand-results"),
escapeHTML: true,
escapeHTML: true,
templates: {
itemx: `
`,
item: `
`,
},
cssClasses: {
// list: "osw-search_brand-results-ontainer",
// item: "osw-search_brand-result-box",
},
}),
//fine brand
instantsearch.widgets.searchBox({
container: "#searchbox",
showSubmit: false,
showReset: true,
placeholder: "Cerca un prodotto... ",
autofocus: false,
cssClasses: {
input: "osw-search_keyword-input",
loadingIcon: "osw-stroke-primary",
},
}),
instantsearch.widgets.pagination({
container: "#pagination",
cssClasses: {
list: "osw-search_pagination",
item: "osw-search_pagination-item",
disabledItem: "osw-search_pagination-disabled",
selectedItem: "osw-search_pagination-selected",
},
}),
//prodotti
instantsearch.widgets.hits({
container: "#hits",
escapeHTML: true,
templates: {
item: `
{{ribbon}}
{{availability}}
{{#helpers.highlight}}{ "attribute": "title" }{{/helpers.highlight}}
\{{price}} \{{prezzovecchio}}
{{sku}}
`,
empty: `
Non è stato trovato alcun prodotto per la ricerca {{ query }} Prova a cercare con meno parole o con termini diversi.
`,
},
transformItems(items) {
return items.map(entry => {
entry.prezzovecchio = oldpricevalorized(entry['price'], entry['old-price-value'], entry['price-withoutDiscount-value']),
entry.ribbon = discountribbon(entry['price'], entry['old-price-value'], entry['price-withoutDiscount-value']),
entry.ribboncss = discountribbonclass(entry['price'], entry['old-price-value'], entry['price-withoutDiscount-value']),
entry.price = '€ ' + (entry.price * 1.22).toFixed(2), entry.test = dispoclass(entry.availability),
entry.availability = dispo(entry.availability)
return entry
})
},
cssClasses: {
list: "osw-search_product-box-container",
item: "osw-search_product-box",
},
}),
instantsearch.widgets.stats({
container: "#stats",
templates: {
text: `
{{#hasNoResults}}Non è stato trovato alcun prodotto per la ricerca {{/hasNoResults}}
{{#hasOneResult}}1 prodotto{{/hasOneResult}}
{{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} prodotti{{/hasManyResults}}
trovati in {{processingTimeMS}}ms
`,
},
cssClasses: {
text: "small",
},
}),
instantsearch.widgets.clearRefinements({
templates: {
resetLabel: `Cancella Filtri`
},
container: "#clear-refinements",
}),
instantsearch.widgets.currentRefinements({
container: "#current-refinements",
}),
]);
const {
connectPoweredBy
} = instantsearch.connectors;
// Create the render function
const renderPoweredBy = (renderOptions, isFirstRender) => {
const {
url,
widgetParams
} = renderOptions;
widgetParams.container.innerHTML = `
Powered by Open Software
`;
};
// Create the custom widget
const customPoweredBy = connectPoweredBy(
renderPoweredBy
);
// Instantiate the custom widget
search.addWidgets([
customPoweredBy({
container: document.querySelector('#powewdby'),
})
]);
//additional filters attribute
if (enabledFilters != null && enabledFilters != undefined && enabledFilters != '') {
enabledFilters.forEach(function (item, index) {
var attributeHtml = `Filtra per ` + getTranslation(traduzioni, item) + `
`
document.getElementById("osw-actual-filters").insertAdjacentHTML('beforeend', attributeHtml);
search.addWidgets([
instantsearch.widgets.refinementList({
limit: 5,
showMoreLimit: 50,
container: "#" + item,
attribute: item,
searchable: true,
searchablePlaceholder: "Filtra per " + getTranslation(traduzioni, item) ,
showMore: true,
templates: {
showMoreText: `
{{#isShowingMore}}
Mostra meno
{{/isShowingMore}}
{{^isShowingMore}}
Mostra altri
{{/isShowingMore}}
`,
},
sortBy: ["name:asc", "count:desc"],
}),
]);
});
}
search.start();
}
function dispo(testo) {
if (testo.toLowerCase() === "in stock") {
return 'DISPONIBILE';
} else {
return 'NON DISPONIBILE';
}
}
function dispoclass(testo) {
if (testo.toLowerCase() == "in stock") {
return 'c-pill--success';
} else {
return 'c-pill--danger';
}
}
function oldpricevalorized(prezzo,vecchioprezzo,priceWithoutDiscount) {
var maxmumPrice= Math.max(vecchioprezzo, priceWithoutDiscount)
if (prezzo == vecchioprezzo || vecchioprezzo<=0 || vecchioprezzo==undefined ) {
return '';
} else {
return 'EUR ' + vecchioprezzo;
}
}
function discountribbonclass(prezzo,vecchioprezzo,priceWithoutDiscount) {
var maxmumPrice= Math.max(vecchioprezzo, priceWithoutDiscount)
if (prezzo == maxmumPrice || maxmumPrice<=0|| isNaN(maxmumPrice) || VisualizzaRibbonSconto == false) {
return '';
} else {
return 'ribbon ribbon-top-right';
// return '-'+calcPercentage(prezzo,vecchioprezzo)+'
';
}
}
function discountribbon(prezzo,vecchioprezzo,priceWithoutDiscount) {
var maxmumPrice= Math.max(vecchioprezzo, priceWithoutDiscount)
if (prezzo == maxmumPrice || maxmumPrice<=0 || isNaN(maxmumPrice)|| VisualizzaRibbonSconto == false) {
return '';
} else {
return '-'+calcPercentage(prezzo,maxmumPrice);
}
}
function calcPercentage(x, y, fixed = 0) {
const percent = ((y - x) / y) * 100;
if(!isNaN(percent)){
return percent.toFixed(fixed) + '%';
}else{
return '';
}
}
function oswToggle(e) {
e.classList.toggle("active");
var panel = e.nextElementSibling;
if (panel.style.display === "block" || panel.style.display==="") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
};
function getTranslation(jsonObj, key) {
if (jsonObj.hasOwnProperty(key)) {
// Se la chiave esiste, restituisci il suo valore
return jsonObj[key];
} else {
// Se la chiave non esiste, restituisci il nome della chiave mancante
return `${key}`;
}
}