PageSourceSearch

https://www.zangoo.it/assets/js/general-functions.js?1790903041

js zangoo.it collected 2026-10-02 01:04:11 UTC 108,768 bytes, 3,100 lines download raw bytes

1document.addEventListener('DOMContentLoaded', () => {})
2
3
4
5function riepilogo(cart_object) {
6    console.log(cart_object)
7    if (!cart_object.hasOwnProperty('servizi_extra')) {
8        cart_object['servizi_extra'] = {}
9    }
10
11    if (cart_object['peso_complessivo'] > 100) {
12        // se peso_complessivo > 30, mostra consegna_al_piano
13        var cp = document.getElementById("div_consegna_al_piano")
14        if (cp) {
15            document.getElementById("div_consegna_al_piano").classList.remove("d-none");
16            document.getElementById("div_consegna_al_piano").nextElementSibling.classList.remove("d-none");
17        }
18
19    }
20    var he = ''
21    cart_object['totale'] = cart_object['subtotale_articoli'] + cart_object['trasporto']
22    for (const [key, value] of Object.entries(cart_object['servizi_extra'])) {
23
24        cart_object['totale'] += parseFloat(value);
25        he += '<div class="d-flex justify-content-between"><p class="s_extra">' + replaceAll(key, '_', ' ') + ':</p><p class="prezzo" id="">&euro; ' + parseFloat(value).toFixed(2) + '</p></div>';
26
27    }
28
29    cart_object['iva'] = parseFloat(cart_object['totale'] * 0.22)
30
31    var riep_items = document.getElementById('items-riepilogo');
32    var riepilogo_ordine = document.getElementById('riepilogo-ordine');
33    var servizi_extra = document.getElementById('servizi_extra');
34    if (servizi_extra) {
35        servizi_extra.innerHTML = he
36    }
37
38
39    if (cart_object['lista_prodotti'].length == 0) {
40        riepilogo_ordine.setAttribute('style', 'display:none');
41        window.location.href = 'https://' + window.location.hostname
42        return ''
43    }
44
45    /*
46     */
47
48    var sr = document.getElementById('subtotale-riep');
49    var st = document.getElementById('trasporto-riep');
50    var tr = document.getElementById('totale-riep');
51    var ir = document.getElementById('iva-riep');
52    var sri = document.getElementById('spe-riep');
53
54    if (cart_object['trasporto'] == 0.00) {
55        st.innerHTML = 'Gratuite'
56    } else {
57        st.innerHTML = '&euro; ' + parseFloat(cart_object['trasporto']).toFixed(2)
58    }
59    sr.innerHTML = '&euro; ' + parseFloat(cart_object['subtotale_articoli']).toFixed(2)
60
61    if (!cart_object.hasOwnProperty('commissione_metodo_pagamento')) {
62        cart_object['commissione_metodo_pagamento'] = 0.00
63    } else {
64        cart_object['totale'] = parseFloat(cart_object['totale']) + cart_object['commissione_metodo_pagamento'];
65        cart_object['iva'] = parseFloat(cart_object['iva']) + parseFloat(cart_object['commissione_metodo_pagamento'] * 0.22)
66        if (cart_object['commissione_metodo_pagamento'] > 0.00) {
67            servizi_extra.innerHTML += '<div class="d-flex justify-content-between "><p class="s_extra">Servizio Contrassegno:</p><p class="prezzo" id="">&euro; ' + parseFloat(parseFloat(cart_object['commissione_metodo_pagamento'])).toFixed(2) + '</p></div>';
68        }
69    }
70
71    tr.innerHTML = '&euro; ' + parseFloat(cart_object['totale']).toFixed(2)
72    ir.innerHTML = '&euro; ' + parseFloat(cart_object['iva']).toFixed(2)
73        // sri.innerHTML = cart_object['tempo_consegna']
74    if (sri) {
75        sri.innerHTML = calcolaGiorno()
76    }
77
78
79    var h = '';
80
81    for (var i = 0; i < cart_object['lista_prodotti'].length; i++) {
82        var f = 'https://assets.zangoo.it/webp/not_found.webp'
83        if (cart_object['lista_prodotti'][i]['obj']['thumbs']['300x300'] != undefined) {
84            f = cart_object['lista_prodotti'][i]['obj']['thumbs']['300x300'][0]
85        }
86        var img = f
87        var nome = cart_object['lista_prodotti'][i]['obj']['nome']
88        var url = cart_object['lista_prodotti'][i]['obj']['url']
89        var sku = cart_object['lista_prodotti'][i]['obj']['sku']
90        var quantita = cart_object['lista_prodotti'][i]['quantita']
91        var prezzo = parseFloat(cart_object['lista_prodotti'][i]['prezzo']).toFixed(2)
92
93        h += `<div class="row">
94                                <div class="col-lg-3 mb-3">
95                                    <div class="d-flex justify-content-center">
96                                        <img class="img-fluid" src="` + img + `" alt="">
97                                    </div>
98                                </div>
99                                <div class="col-lg-9 mb-3">
100                                    <p class="nome-prodotto mb-3" data-url="` + url + `" data-title="` + nome + `" onclick="loadContent(this)" style="cursor:pointer">` + nome + `</p>
101                                    <div class="d-flex justify-content-between mb-3">
102                                        <p>Codice:  <strong>` + sku + `</strong></p>
103                                        <p>QUANTIT&Agrave;: <strong>` + quantita + `</strong></p>
104                                    </div>
105                                    <div class="d-flex justify-content-lg-end justify-content-end">
106                                        <p><strong>&euro; ` + prezzo + `</strong></p>
107                                    </div>
108                                </div>
109        </div>`;
110    }
111    if (riep_items) {
112        riep_items.innerHTML = h;
113    }
114
115
116
117
118}
119
120
121
122
123
124
125function convertion_event(ordine) {
126    try {
127        if (ordine['ordine'] !== undefined) {
128            ordine = ordine['ordine'];
129        }
130
131        let contenuto = [];
132        let imp = 0.0;
133
134        try {
135            imp = parseFloat(ordine.totale_ordine / 1.22).toFixed(2);
136
137            for (let i = 0; i < ordine.lineitems.length; i++) {
138                const item = ordine.lineitems[i];
139                contenuto.push({
140                    id: item.id_prodotto,
141                    item_id: item.id_prodotto,
142                    item_name: item.nome || item.id_prodotto,
143                    item_category: item.categoria || "generica",
144                    quantity: parseInt(item.quantita || 1),
145                    price: parseFloat(item.prezzo_lineitem || 0)
146                });
147            }
148        } catch (error) {
149            console.error("Errore nella costruzione contenuto:", error);
150        }
151
152        // --- Facebook Pixel ---
153        try {
154            fbq('track', 'Purchase', {
155                value: parseFloat(imp),
156                currency: 'EUR',
157                contents: contenuto.map(c => ({ id: c.item_id, quantity: c.quantity })),
158                content_type: 'product'
159            }, {
160                eventID: ordine.id
161            });
162        } catch (error) {
163            console.error("Errore Facebook Pixel Purchase:", error);
164        }
165
166        // --- GA4 Purchase ---
167        try {
168            gtag('event', 'purchase', {
169                transaction_id: ordine.id_timestamp || ordine.id,
170                value: parseFloat(ordine.totale_ordine || 0),
171                currency: 'EUR',
172                items: contenuto
173            });
174            console.log("GA4 Purchase inviato:", { id: ordine.id_timestamp, items: contenuto });
175        } catch (error) {
176            console.error("Errore GA4 Purchase:", error);
177        }
178
179        // --- dataLayer (mantieni compatibilità GTM e custom analytics) ---
180        try {
181            var infoA = {
182                event: 'acquisto_zangoo_event',
183                id_ordine: ordine.id_timestamp,
184                totale_ordine: ordine.totale_ordine,
185                email: hashValue(ordine.email),
186                telefono: hashValue(ordine.cellulare),
187                ecommerce: {
188                    purchase: {
189                        id_ordine: ordine.id_timestamp,
190                        totale_ordine: ordine.totale_ordine,
191                        products: contenuto,
192                        email: hashValue(ordine.email),
193                        telefono: hashValue(ordine.cellulare),
194                        value: ordine.totale_ordine,
195                        transaction_id: ordine.id,
196                        items: contenuto,
197                        currency: 'EUR'
198                    }
199                }
200            }
201            console.log('Acquisto')
202            console.warn(infoA)
203            dataLayer.push({ ecommerce: null });
204            dataLayer.push(infoA);
205            dataLayer.push({ ecommerce: null });
206            dataLayer.push({
207                event: "purchase",
208                ecommerce: {
209                    transaction_id: ordine.id_timestamp,
210                    value: parseFloat(ordine.totale_ordine || 0),
211                    currency: "EUR",
212                    items: contenuto
213                }
214            });
215            
216        } catch (error) {
217            console.error("Errore dataLayer purchase:", error);
218        }
219
220    } catch (error) {
221        console.error("Errore generale in convertion_event:", error);
222    }
223}
224
225
226function hashValue(value) {
227    if (!value) return null;
228
229    const normalized = value.toString().trim().toLowerCase();
230
231    function sha256(ascii) {
232        const rightRotate = (value, amount) => (value >>> amount) | (value << (32 - amount));
233
234        let mathPow = Math.pow;
235        let maxWord = mathPow(2, 32);
236        let lengthProperty = 'length';
237        let i, j;
238        let result = '';
239
240        let words = [];
241        let asciiBitLength = ascii[lengthProperty] * 8;
242
243        let hash = sha256.h = sha256.h || [];
244        let k = sha256.k = sha256.k || [];
245        let primeCounter = k[lengthProperty];
246
247        let isComposite = {};
248        for (let candidate = 2; primeCounter < 64; candidate++) {
249            if (!isComposite[candidate]) {
250                for (i = 0; i < 313; i += candidate) {
251                    isComposite[i] = candidate;
252                }
253                hash[primeCounter] = (mathPow(candidate, .5) * maxWord) | 0;
254                k[primeCounter++] = (mathPow(candidate, 1 / 3) * maxWord) | 0;
255            }
256        }
257        
258
259        ascii += '\x80';
260        while (ascii[lengthProperty] % 64 - 56) ascii += '\x00';
261        for (i = 0; i < ascii[lengthProperty]; i++) {
262            j = ascii.charCodeAt(i);
263            words[i >> 2] |= j << ((3 - i) % 4) * 8;
264        }
265
266        words[words[lengthProperty]] = (asciiBitLength / maxWord) | 0;
267        words[words[lengthProperty]] = asciiBitLength;
268
269        for (j = 0; j < words[lengthProperty];) {
270            let w = words.slice(j, j += 16);
271            let oldHash = hash;
272
273            hash = hash.slice(0, 8);
274
275            for (i = 0; i < 64; i++) {
276                let w15 = w[i - 15],
277                    w2 = w[i - 2];
278
279                let a = hash[0],
280                    e = hash[4];
281
282                let temp1 = hash[7] +
283                    (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) +
284                    ((e & hash[5]) ^ ((~e) & hash[6])) +
285                    k[i] +
286                    (w[i] = (i < 16) ? w[i] : (
287                        (w2 >>> 17 | w2 << 15) ^
288                        (w2 >>> 19 | w2 << 13) ^
289                        (w2 >>> 10)
290                    ) + w[i - 7] + (
291                        (w15 >>> 7 | w15 << 25) ^
292                        (w15 >>> 18 | w15 << 14) ^
293                        (w15 >>> 3)
294                    ) | 0);
295
296                let temp2 = (
297                    (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) +
298                    ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2]))
299                );
300
301                hash = [(temp1 + temp2) | 0].concat(hash);
302                hash[4] = (hash[4] + temp1) | 0;
303            }
304
305            for (i = 0; i < 8; i++) {
306                hash[i] = (hash[i] + oldHash[i]) | 0;
307            }
308        }
309
310        for (i = 0; i < 8; i++) {
311            for (j = 3; j + 1; j--) {
312                let b = (hash[i] >> (j * 8)) & 255;
313                result += ((b < 16) ? '0' : '') + b.toString(16);
314            }
315        }
316
317        return result;
318    }
319
320    return sha256(normalized);
321}
322
323
324
325
326
327
328function add_to_cart_event(id, qty, categoria = 'generica', subtotale = 0, sku = '', name = "") {
329
330    qty = Math.max(1, parseInt(qty) || 1);
331
332    // --- GA4 AddToCart ---
333    var name = ""
334    if(name == ""){
335       name = localStorage.getItem('prodotto_nome') || 'Prodotto:'+id
336    }
337    try {
338        gtag('event', 'add_to_cart', {
339            currency: 'EUR',
340            value: parseFloat(subtotale),
341            items: [{
342                item_id: sku || id,
343                item_name: name,
344                item_category: categoria,
345                quantity: qty,
346                price: parseFloat(subtotale)
347            }]
348        });
349    } catch (error) {
350        console.error('Errore GA4 add_to_cart:', error);
351    }
352
353    // --- dataLayer E-commerce (tuo codice originale) ---
354    try {
355        dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
356        dataLayer.push({
357            event: "add_to_cart",
358            ecommerce: {
359                currency: "EUR",
360                value: parseFloat(subtotale),
361                items: [{
362                    'id': id,
363                    'item_id' : id,
364                    'quantity': parseInt(qty), 
365                    'product' : name,
366                    'item_name' : name,
367                    'category': categoria,
368                    'item_category': categoria
369
370                }]
371            }
372        });
373
374        sku = sku.replace('B-', '');
375    } catch (error) {
376        console.error('Errore dataLayer add_to_cart:', error);
377    }
378
379    // --- Facebook Pixel ---
380    try {
381        fbq('track', 'AddToCart', {
382            'content_ids': [sku],
383            'content_type': 'product',
384            'currency': 'EUR'
385        });
386    } catch (error) {
387        console.error('Errore Facebook Pixel AddToCart:', error);
388    }
389
390    // --- Evento aggiunta carrello custom (resto invariato) ---
391    try {
392        dataLayer.push({ ecommerce: null });
393        dataLayer.push({
394            'event': 'aggiunta_carrello_prodotto_categoria_event',
395            'ecommerce': {
396                'add': {
397                    'products': [{
398                        'id': id,
399                        'category': categoria,
400                        'quantity': qty,
401                        'subtotale': subtotale,
402                        'productID': id,
403                        'name': name,
404                        'category': categoria || 'Generica',
405                    }]
406                }
407            }
408        });
409
410        // --- Criteo ---
411        if (sessionStorage.getItem('isCriteo') != undefined && sessionStorage.getItem('isCriteo') == true) {
412            dataLayer.push({
413                'event': 'addToCart',
414                'ecommerce': {
415                    'add': {
416                        'products': [{
417                            'id': id,
418                            'category': categoria,
419                            'quantity': qty,
420                            'price': subtotale,
421                            'productID': id
422                        }]
423                    }
424                }
425            });
426        }
427    } catch (error) {
428        console.error('Errore eventi add_to_cart custom:', error);
429    }
430}
431
432
433function tracking_view_eventOLD(prodotto = false, page = false) {
434
435    // --- Facebook Pixel ---
436    try {
437        fbq('track', 'PageView');
438    } catch (error) {
439        console.error('Errore Facebook Pixel:', error);
440    }
441
442    // --- Google Analytics 4 ---
443    try {
444        gtag('event', 'page_view', {
445            page_title: document.title,
446            page_path: window.location.pathname,
447            page_location: window.location.href
448        });
449    } catch (error) {
450        console.error('Errore GA4 page_view:', error);
451    }
452
453    // --- dataLayer E-commerce (lasciato invariato) ---
454    try {
455        if (prodotto) {
456            dataLayer.push({ ecommerce: null }); // Pulisce il precedente ecommerce object.
457
458            const push_data = {
459                'event': 'visualizzazione_prodotto_event',
460                'ecommerce': {
461                    'detail': {
462                        'products': [{
463                            'product_ID': prodotto['sku'],
464                            'productID': prodotto['id'],
465                            'name': localStorage.getItem('prodotto_nome'),
466                            'category': localStorage.getItem('categoria_name'),
467                            'price': prodotto['prezzo'],
468                            'qty': 1
469                        }]
470                    }
471                }
472            };
473
474            dataLayer.push(push_data);
475        }
476    } catch (error) {
477        console.error('Errore dataLayer E-commerce:', error);
478    }
479}
480
481
482function evento_iscrizione_zangoo(id = 0) {
483
484    try {
485        dataLayer.push({ ecommerce: null });
486        dataLayer.push({
487            'event': 'iscrizione_zangoo_event',
488            'id_user': id,
489        });
490    } catch (error) {
491        console.log(error)
492    }
493
494
495}
496
497
498function begin_checkout_event() {
499
500
501    //gtag('event', 'begin_checkout', {
502    //    'value': 100.00,
503    //    'currency': 'EUR', // Valuta del carrello
504    //    'items': [{
505    //            'id': 'SKU123', // ID univoco del prodotto
506    //            'name': 'Prodotto 1', // Nome del prodotto
507    //            'category': 'Categoria 1', // Categoria del prodotto
508    //            'quantity': 2, // Quantità nel carrello
509    //            'price': 50.00 // Prezzo unitario
510    //        },
511    //        {
512    //            'id': 'SKU456',
513    //            'name': 'Prodotto 2',
514    //            'category': 'Categoria 2',
515    //            'quantity': 1,
516    //            'price': 50.00
517    //        }
518    //    ]
519    //});
520    //
521    //fbq('track', 'InitiateCheckout', {
522    //    'value': 100.00, // Valore totale del carrello
523    //    'currency': 'USD', // Valuta del carrello
524    //    'content_type': 'product',
525    //    'content_ids': ['SKU123', 'SKU456'], // Array di ID univoci dei prodotti nel carrello
526    //    'content_name': ['Prodotto 1', 'Prodotto 2'], // Array di nomi dei prodotti nel carrello
527    //    'content_category': ['Categoria 1', 'Categoria 2'], // Array di categorie dei prodotti nel carrello
528    //    'content_quantity': [2, 1], // Array di quantità dei prodotti nel carrello
529    //    'content_price': [50.00, 50.00] // Array di prezzi unitari dei prodotti nel carrello
530    //});
531
532
533}
534
535
536function sign_up_tracking_event(email) {
537
538
539    try {
540        gtag('event', 'sign_up', {
541            'method': 'email',
542            'user_id': email // Unique user identifier
543        });
544
545        fbq('track', 'CompleteRegistration', {
546            'content_ids': [email] // Unique user identifier
547        });
548    } catch (error) {
549        console.log(error)
550    }
551
552
553}
554
555
556
557
558function get_cart(full = false) {
559    sessionStorage.setItem('totale-articoli-corrente', 0.00)
560    var mc = sessionStorage.getItem('importo_spedizione_gratuita')
561
562    var c = {};
563    var values = {
564        api: true,
565        act: 'get_cart'
566    };
567    if (full) {
568        // values['act'] = 'get_cart_full'
569    }
570    var req = $.ajax({
571        url: "index.php",
572        method: "post",
573        data: values,
574        async: true,
575        success: function(response) {
576            c = response
577            console.log(c)
578            if (c['totale'] !== undefined) {
579                if (c['totale'] !== null) {
580
581                    sessionStorage.setItem('totale-articoli-corrente', c['subtotale_articoli'])
582                    var msp = document.getElementsByClassName('mancante_sped_gratuita')
583                    var mancanti = mc - c['subtotale_articoli'];
584                    if (msp) {
585                        for (let index = 0; index < msp.length; index++) {
586                            const element = msp[index];
587                            if (parseFloat(c['subtotale_articoli']) == 0.00) {
588                                element.innerHTML = '<b>Spedizione GRATIS</b> sopra i  <b class=""> ' + mc + ' euro</b>'
589                                continue;
590                            }
591
592                            if (mancanti > 0) {
593                                element.innerHTML = 'Mancano solo <b>' + mancanti.toFixed(2) + '</b> euro per la tua <b>SPEDIZIONE GRATUITA</b>'
594                            } else {
595                                element.innerHTML = 'Completa il tuo ordine con <b>SPEDIZIONE GRATUITA</b>'
596                            }
597                        }
598                    }
599                }
600            }
601
602            var p = document.getElementById('carrello-page')
603            var pao = document.getElementById('carrello-page-ao')
604            var riepprodotti = document.getElementById('riepilogo-prodotti')
605            cart_object = c
606            if (riepprodotti) {
607                page_cart(cart_object)
608                calcolaDifferenzaOrario()
609            }
610            if (p) {
611                page_cart(cart_object)
612            }
613            if (pao) {
614                page_cart_ao(cart_object)
615            }
616            document.getElementById('prezzo-totale-mini').innerHTML = '0.00'
617            document.getElementById('numero-prodotti-acquistati').innerHTML = 0
618            document.getElementById('numero-prodotti-acquistati-mobile').innerHTML = 0
619            if (cart_object.hasOwnProperty('lista_prodotti')) {
620                if (cart_object['lista_prodotti'].length > 0) {
621                    document.getElementById('numero-prodotti-acquistati').innerHTML = cart_object['num_prodotti']
622                    document.getElementById('numero-prodotti-acquistati-mobile').innerHTML = cart_object['num_prodotti']
623                    document.getElementById('prezzo-totale-mini').innerHTML = parseFloat(cart_object['totale']).toFixed(2)
624                }
625            }
626
627            var cpp = document.getElementById('counter-prodotti')
628            if (cpp) {
629                var ppplabel = 'prodotti'
630                if (cart_object['num_prodotti'] == 1) {
631                    var ppplabel = 'prodotto'
632                }
633                cpp.innerHTML = cart_object['num_prodotti'] + ' ' + ppplabel
634            }
635            var nupa = document.getElementsByClassName('numero-prodotti-acquistati')
636            for (let index = 0; index < nupa.length; index++) {
637                let element = nupa[index];
638                element.innerHTML = cart_object['num_prodotti']
639            }
640            var cat_lat = document.getElementById('contenuto-car-lat');
641            var up = document.getElementById('car-lat-up');
642            var dsl = document.getElementById('dettagli-spedizione-lat');
643            var ocl = document.getElementById('opzioni-carrello-lat');
644            var rtl = document.getElementById('riepilogo-totale-lat');
645            var peso_complessivo = 0.00;
646            if (cat_lat) {
647                var h = ''
648                if (cart_object['lista_prodotti'] == undefined) {
649                    cart_object['lista_prodotti'] = []
650                }
651                if (cart_object['lista_prodotti'].length > 0) {
652
653                    var tc = cart_object['tempo_consegna'];
654                    if (tc == null) {
655                        tc = calcolaGiorno()
656                    }
657
658
659
660
661                    var spelat = document.getElementById('spe-lat');
662                    var teco = document.getElementById('tempi-lat');
663                    var tolat = document.getElementById('totale-lat');
664
665                    spelat.innerHTML = '€ ' + parseFloat(cart_object['trasporto']).toFixed(2) + '';
666                    tolat.innerHTML = '€ ' + parseFloat(cart_object['totale']).toFixed(2) + '';
667                    teco.innerHTML = tc
668
669                    for (var m = 0; m < cart_object['lista_prodotti'].length; m++) {
670
671                        var item = cart_object['lista_prodotti'][m]
672                        peso_complessivo += cart_object['lista_prodotti'][m]['peso_item']
673                        var id = cart_object['lista_prodotti'][m]['id'];
674                        var id_r = cart_object['id'] + '-' + cart_object['lista_prodotti'][m]['id'];
675                        var f = 'https://assets.zangoo.it/webp/not_found.webp'
676                        if (cart_object['lista_prodotti'][m]['obj']['thumbs'] != undefined) {
677                            f = cart_object['lista_prodotti'][m]['obj']['thumbs']['300x300'][0]
678                        } else {
679                            f = cart_object['lista_prodotti'][m]['obj']['foto'][0]
680                        }
681                        var img = f; //cart_object['lista_prodotti'][m]['obj']['foto'][0]
682                        var qty = cart_object['lista_prodotti'][m]['quantita']
683                        var url = cart_object['lista_prodotti'][m]['url']
684                        var prezzo = cart_object['lista_prodotti'][m]['prezzo']
685                        var subtotale = cart_object['lista_prodotti'][m]['subtotale']
686                        var name_trim = cart_object['lista_prodotti'][m]['obj']['nome'].substring(0, 16) + '...';
687                        var name = cart_object['lista_prodotti'][m]['obj']['nome'];
688                        var max = cart_object['lista_prodotti'][m]['obj'
688]['quantita'];
689                        var opts = '<option value="0">0 (Rimuovi)</option>';
690                        // var tempo_consegna = cart_object['lista_prodotti'][m]['tempo_consegna']
691                        var tempo_consegna = tc
692                        var slimit = 10;
693                        if (max >= 10) {
694
695                        }
696                        if (max >= 10 && qty >= 10) {
697                            visibile = 'qty-lat-input'
698                            visibile_rev = 'd-none'
699                        } else {
700                            visibile = 'd-none'
701                            visibile_rev = ''
702                        }
703                        var se = ''
704                        for (var o = 1; o < (slimit + 1); o++) {
705                            if (o == qty) {
706                                se = 'selected'
707                            } else {
708                                se = ''
709                            }
710                            opts += '<option value="' + o + '" ' + se + '>' + o + '</option>';
711                        }
712                        h += `<div id="` + id_r + `">
713                    <div class="dettagli-carrello mb-3" >
714                        <div class="row">
715                            <div class="col-3">
716                                <div class="position-relative">
717                                    <div class="numero-prodotti-acquistati item">` + qty + `</div>
718                                    <img class="ant-img" src="` + img + `">
719                                </div>
720                            </div>
721                            <div class="col-4">
722                                <div class="d-flex justify-content-center align-items-center h-100">
723                                    <p class="descrizione-prodotto">` + name_trim + `</p>
724                                </div>
725                            </div>
726                            <div class="col-5">
727                                <div class="d-flex justify-content-center align-items-center h-100">
728                                    <p class="prezzo-prodotto">€ ` + subtotale.toFixed(2) + `</p>
729                                    <i id="modifica-ordine-menu-lat-carrello" class="bi bi-pencil modifica-ordine" onclick="open_edit('` + id_r + `')"></i>
730                                </div>
731                            </div>
732                        </div>
733                    </div>
734                    <div class="modifica-carrello" >
735                        <p  data-url="` + url + `" data-title="` + name + `" onclick="loadContent(this)" style="cursor:pointer">` + name + `</p>
736                        <div class="row mb-2">
737                            <div class="col-6">
738                                <select data-id="` + id + `" class="form-select items-lat ` + visibile_rev + `" aria-label="" onchange="updateitemlat(this)">
739                                ` + opts + `
740                                </select>
741
742                                <input onchange="checkMaxQtyLat(this);updateitemlat(this)" type="number" data-id="` + id + `" class="items-lat ` + visibile + `" aria-label=""  min="0" max="` + (max) + `" value="` + qty + `">
743
744                            </div>
745                            <div class="col-4">
746                                <div class="d-flex justify-content-center align-items-center h-100">
747                                    <i class="bi bi-trash cancella"  onclick="open_modal_remove('` + id + `')" data-id="` + id + `"></i>
748                                </div>
749                            </div>
750                            <div class="col-2">
751                                <div class="d-flex justify-content-center align-items-center h-100">
752                                    <i id="conferma-modifica-ordine-menu-lat-carrello" class="bi bi-chevron-up nascondi" onclick="close_edit('` + id_r + `')"></i>
753                                </div>
754                            </div>
755                        </div>
756                        <div class="row mb-2">
757                            <div class="disponibilita">
758                                <!-- <p><b style="color: #36c1b8 !important;">Disponibilità ` + max + ` pezzi</b> - Spedito entro <el id="car-lat-tempo">` + tempo_consegna + `</el></p> -->
759                             <p><b style="color: #36c1b8 !important;">Disponibilità ` + max + ` pezzi</b><el class="d-none" id="car-lat-tempo">` + tempo_consegna + `</el></p>
760                            </div>
761                        </div>
762
763                    </div>
764                </div>`;
765
766                        if (up) {
767                            up.setAttribute('style', '');
768                        }
769                        dsl.setAttribute('style', '')
770                        ocl.setAttribute('style', '')
771                        rtl.setAttribute('style', '')
772
773                    }
774                } else {
775                    var h = `Nessun prodotto nel carrello`;
776                    dsl.setAttribute('style', 'display:none')
777                    ocl.setAttribute('style', 'display:none')
778                    rtl.setAttribute('style', 'display:none')
779                    if (up) {
780                        up.setAttribute('style', 'display:none');
781                    }
782                }
783
784
785                cat_lat.innerHTML = h
786
787
788            }
789
790            var r = document.getElementById('riepilogo-ordine')
791            if (r) {
792                riepilogo(cart_object)
793                var clt = document.getElementById('car-lat-tempo')
794                if (clt) {
795                    clt.innerHTML = tempo_consegna
796                }
797                var clt = document.getElementById('spe-riepilogo')
798                if (clt) {
799                    clt.innerHTML = calcolaGiorno()
800                }
801            }
802
803            var nupa = document.getElementsByClassName('numero-prodotti-acquistati')
804            for (let index = 0; index < nupa.length; index++) {
805                let element = nupa[index];
806                if (element.classList.contains('item')) {
807                    continue
808                }
809                element.innerHTML = cart_object['num_prodotti']
810            }
811            var nupa = document.getElementsByClassName('numero-prodotti-acquistati-mobile')
812            for (let index = 0; index < nupa.length; index++) {
813                let element = nupa[index];
814                if (element.classList.contains('item')) {
815                    continue
816                }
817                element.innerHTML = cart_object['num_prodotti']
818            }
819
820
821            var ath = document.getElementsByClassName('alert-top')
822            for (let index = 0; index < (ath.length); index++) {
823                const element = ath[index];
824                element.classList.add('visibile')
825            }
826
827
828            sessionStorage.setItem('peso_complessivo', peso_complessivo)
829            var cspe = document.getElementsByClassName('costo-spe')
830            for (let index = 0; index < cspe.length; index++) {
831                const element = cspe[index];
832                element.classList.add('visibile')
833                if (peso_complessivo != 0.00) {
834                    if (cart_object['trasporto'] == 0) {
835                        element.innerHTML = 'Gratuita'
836                    } else {
837                        element.innerHTML = ' &euro; ' + cart_object['trasporto'].toFixed(2)
838                    }
839
840                }
841
842            }
843
844            var ac = document.getElementById('aggiungi-prodotto')
845            var rac = document.getElementsByClassName('riga-aggiunta-carrello')
846            var inpq = document.getElementById('add-qty')
847            if (ac) {
848                var found = false
849                for (var m = 0; m < cart_object['lista_prodotti'].length; m++) {
850                    var e = cart_object['lista_prodotti'][m]
851                    if (ac.getAttribute('data-id') == e['id']) {
852                        var found = true
853                        var dreal = e['obj']['quantita']
854                        var dvirtuale = dreal - e['quantita']
855                        sessionStorage.setItem('current-max', dvirtuale)
856
857
858                        if (dvirtuale < 1) {
859                            inpq.setAttribute('max', dvirtuale)
860                            document.getElementById('aggiungi-prodotto').setAttribute('disabled', 'disabled')
861                            document.getElementById('aggiungi-prodotto').classList.add('disabled')
862                            for (let index = 0; index < rac.length; index++) {
863                                const element = rac[index];
864                                element.classList.add('disabled')
865                            }
866
867                        } else {
868                            document.getElementById('aggiungi-prodotto').removeAttribute('disabled')
869                            document.getElementById('aggiungi-prodotto').classList.remove('disabled')
870
871                            for (let index = 0; index < rac.length; index++) {
872                                const element = rac[index];
873                                element.classList.remove('disabled')
874                            }
875                            inpq.setAttribute('data-max', dvirtuale)
876                            inpq.setAttribute('max', dvirtuale)
877                        }
878
879                    }
880                }
881
882                if (cart_object['lista_prodotti'].length == 0 || found == false) {
883
884                    document.getElementById('aggiungi-prodotto').removeAttribute('disabled')
885                    document.getElementById('aggiungi-prodotto').classList.remove('disabled')
886                    for (let index = 0; index < rac.length; index++) {
887                        const element = rac[index];
888                        element.classList.remove('disabled')
889                    }
890                    inpq.setAttribute('max', sessionStorage.getItem('current-max'))
891                    inpq.setAttribute('data-max', sessionStorage.getItem('current-max'))
892
893                }
894
895
896            }
897
898        },
899        error: function(jqXHR, textStatus, errorThrown) {
900            console.log(textStatus, errorThrown);
901            return true
902        }
903
904    });
905    return c;
906}
907
908
909function update_cart_lat() {
910    var items = document.getElementsByClassName('items-lat');
911    for (let index = 0; index < items.length; index++) {
912
913        var el = items[index];
914        if (el.classList.contains('d-none') || el.style == 'dispaly:none') {
915            continue;
916        }
917        var id = el.getAttribute('data-id');
918        var q = el.value;
919        var values = {
920            api: true,
921            act: 'update_cart',
922            id_prodotto: id,
923            quantita: q
924        };
925        var req = $.ajax({
926            url: "index.php",
927            type: "post",
928            data: values,
929            async: true,
930            success: function(response) {
931                cart_composing()
932                var a = document.getElementById('car-lat-up');
933                a.setAttribute('onclick', '')
934                a.setAttribute('class', 'aggiorna-carrello disabled')
935            },
936            error: function(jqXHR, textStatus, errorThrown) {
937                console.log(textStatus, errorThrown);
938
939                return true
940            }
941        });
942    }
943
944
945}
946
947function open_modal_remove(id) {
948
949    var values = {
950        api: true,
951        act: 'get_prodotto',
952        id_prodotto: id
953    };
954    var req = $.ajax({
955        url: "index.php",
956        type: "post",
957        data: values,
958        async: false,
959        success: function(response) {
960            document.getElementById('elimina-btn-it').setAttribute('data-id', id)
961            var f = 'https://assets.zangoo.it/webp/not_found.webp'
962            if (response['thumbs']['300x300'] != undefined) {
963                f = response['thumbs']['300x300'][0]
964            }
965            document.getElementById('del-img').setAttribute('src', f)
966            document.getElementById('del-nome').innerHTML = response['nome']
967            document.getElementById('del-codice').innerHTML = response['sku']
968            $('#modal-delete-item').modal('show')
969        },
970        error: function(jqXHR, textStatus, errorThrown) {
971            console.log(textStatus, errorThrown);
972            return true
973        }
974    });
975
976
977}
978
979
980function setLang(el) {
981    var lang = el.value
982    var q = 0;
983    var values = {
984        api: true,
985        act: 'lang',
986        lang: lang
987    };
988    var request;
989    if (request != null) {
990        request.abort();
991        request = null;
992    }
993    var request = $.ajax({
994        url: "index.php",
995        type: "post",
996        data: values
997    });
998
999    request.done(function(response) {
1000        if (response == true) {
1001            window.location.reload();
1002        }
1003    })
1004
1005    request.fail(function(jqXHR, textStatus, errorThrown) {
1006        console.log(errorThrown)
1007    })
1008
1009
1010
1011
1012
1013}
1014
1015
1016function removeitemlat(el) {
1017    var id = el.getAttribute('data-id');
1018    var q = 0;
1019    var values = {
1020        api: true,
1021        act: 'update_cart',
1022        id_prodotto: id,
1023        quantita: q
1024    };
1025    var req = $.ajax({
1026        url: "index.php",
1027        type: "post",
1028        data: values,
1029        async: false,
1030        success: function(response) {
1031            if (response.hasOwnProperty('status') && response['status'] == true) {
1032                cart_composing()
1033                $('#modal-delete-item').modal('hide')
1034            } else {
1035
1036            }
1037
1038        },
1039        error: function(jqXHR, textStatus, errorThrown) {
1040            console.log(textStatus, errorThrown);
1041            return true
1042        }
1043    });
1044
1045}
1046
1047
1048function updateitemlat(el) {
1049
1050
1051    var id = el.getAttribute('data-id');
1052    var q = el.value;
1053    if (q == undefined) {
1054        q = 0
1055    } else {
1056        var a = document.getElementById('car-lat-up');
1057        a.setAttribute('onclick', 'update_cart_lat()')
1058        a.setAttribute('class', 'aggiorna-carrello')
1059        return '';
1060    }
1061
1062
1063    var values = {
1064        api: true,
1065        act: 'update_cart',
1066        id_prodotto: id,
1067        quantita: q
1068    };
1069    var req = $.ajax({
1070        url: "index.php",
1071        type: "post",
1072        data: values,
1073        async: true,
1074        success: function(response) {
1075            if (response.hasOwnProperty('status') && response['status'] == true) {
1076                 evento_aggiunta_carrello(id, q, null, null, null, response['cart'])
1077                cart_composing()
1078            } else {
1079
1080            }
1081        },
1082        error: function(jqXHR, textStatus, errorThrown) {
1083            console.log(textStatus, errorThrown);
1084            return true
1085        }
1086    });
1087
1088
1089}
1090
1091function sleep(time) {
1092    return new Promise((resolve) => setTimeout(resolve, time));
1093}
1094
1095function stream(url, id, pre = true) {
1096    if (pre) {
1097        var preloader = document.getElementById('preloader');
1098    }
1099
1100
1101    var req = $.ajax({
1102        url: url,
1103        type: "get",
1104        success: function(response) {
1105            var e = document.getElementById(id)
1106            e.innerHTML = response;
1107            if (pre) {
1108                sleep(1500).then(() => {
1109                    preloader.setAttribute('style', 'display:none !important');
1110                });
1111            }
1112        },
1113        error: function(jqXHR, textStatus, errorThrown) {
1114            console.log(textStatus, errorThrown);
1115            return true
1116        }
1117    });
1118}
1119
1120function hide(id) {
1121    var e = document.getElementById(id)
1122    if (e) {
1123        e.setAttribute('style', 'display:none;')
1124    }
1125}
1126
1127
1128
1129function page_cart(cart_object) {
1130    var h = ''
1131
1132    if (cart_object.hasOwnProperty('lista_prodotti')) {
1133        var items_c = document.getElementById('items-carrello');
1134        if (cart_object['lista_prodotti'].length > 0) {
1135            var cp = document.getElementById('carrello-page');
1136            if (cp) {
1137                cp.setAttribute('class', 'carrello-pieno')
1138                cp.setAttribute('style', '')
1139            }
1140
1141            for (let i = 0; i < cart_object['lista_prodotti'].length; i++) {
1142                var el = cart_object['lista_prodotti'][i];
1143
1144                var options = '';
1145                for (var o = 0; o < 10; o++) {
1146                    // var opt = array[o];
1147                    var sss = ''
1148                    if (el['quantita'] == o) {
1149                        sss = 'selected';
1150                    }
1151                    if (o <= el['obj']['quantita']) {
1152                        options += '<option value="' + o + '" ' + sss + '>
1152' + o + '</option>'
1153                    }
1154
1155                }
1156                if (el['obj']['quantita'] >= 10) {
1157                    // options += '<option value="10">10+</option>'
1158                }
1159
1160                var sq = 'none'
1161                var iq = 'none'
1162                if (el['quantita'] >= 10) {
1163                    iq = ''
1164                } else {
1165                    sq = ''
1166                }
1167                el['obj']['tempo_consegna'] = '1-2'
1168
1169                var f = 'https://assets.zangoo.it/webp/not_found.webp'
1170                if (el['obj']['thumbs']['300x300'] != undefined) {
1171                    f = el['obj']['thumbs']['300x300'][0]
1172                }
1173
1174                h += `
1175                <div class="carrello-sx" >
1176                <div class="row mb-3">
1177
1178                    <div class="col-lg-3 mb-3 col-3">
1179                        <div class="d-flex justify-content-center">
1180                        <a target="_blank" href="https://` + window.location.hostname + `/` + el['obj']['url'] + `"><img class="img-fluid" src="` + f + `" alt=""></a>
1181                        </div>
1182                    </div>
1183                    <div class="col-lg-6 mb-3 col-6">
1184                        <div class="carrello-flex-1">
1185                            <a target="_blank" href="https://` + window.location.hostname + `/` + el['obj']['url'] + `"><h3 class="nome-prodotto">` + el['obj']['nome'] + `</h3></a>
1186                            <div class="dettagli-prodotto">
1187                                <p>Codice: <strong>` + el['obj']['sku'] + `</strong></p>
1188                                <p class="tempi-spedizione"><b class="shipping_product"></b></p>
1189                                <p class="disponibilita">Disponibilità ` + el['obj']['quantita'] + ` pezzi</p>
1190                            </div>
1191                        </div>
1192                    </div>
1193                    <div class="col-lg-3 mb-3 col-3">
1194                        <div class="carrello-flex-2">
1195                            <h4 class="prezzo mb-3">` + parseFloat(el['prezzo']).toFixed(2) + `</h4>
1196                            <select style="display:` + sq + `" id="selectNumber-` + el['id'] + `" class="form-select mb-3 items" onchange="checkValue(this);aggiornaSingoloItem(this);" data-id="` + el['id'] + `" data-sku="` + el['obj']['sku'] + `">
1197                            ` + options + `
1198                            </select>
1199
1200
1201                        <div id="inputContainer-` + el['id'] + `" style="display:` + iq + `;" class="input-group inline-group avail riga-aggiunta-carrello new-inp">
1202                            <button class="input-group-prepend" onclick="incrementValue(-1, ` + el['id'] + `)">-</button>
1203                            <input onchange="checkInput(` + el['id'] + `)" class="form-control quantity items" type="number" id="numberInput-` + el['id'] + `" value="` + el['quantita'] + `" min="10" max="` + el['obj']['quantita'] + `"  data-id="` + el['id'] + `" data-sku="` + el['obj']['sku'] + `">
1204                            <button class="input-group-append" onclick="incrementValue(1, ` + el['id'] + `)">+</button>
1205                        </div>
1206
1207
1208                            </div>
1209                            <span class="rimuovi"><span class="link" onclick="openModalRemove(this)" data-titolo="` + (el['obj']['nome']).replace("'", "") + `"  data-sku="` + el['obj']['sku'] + `" data-id="` + el['id'] + `"  data-img="` + f + `" ><i class="bi bi-trash"></i> Rimuovi</span></span>
1210                        </div>
1211                    </div>
1212
1213                 </div>
1214                </div>`
1215            }
1216            items_c.innerHTML = h;
1217            var rs_sub = document.getElementById('riepilogo-sub');
1218            var rs_spe = document.getElementById('riepilogo-sped');
1219            var rs_tot = document.getElementById('riepilogo-tot');
1220            var rs_iva = document.getElementById('riepilogo-iva');
1221            var rs_time = document.getElementById('riepilogo-time');
1222
1223            if (rs_sub) {
1224                rs_sub.innerHTML = '&euro; ' + parseFloat(cart_object['subtotale_articoli']).toFixed(2)
1225            }
1226            if (rs_spe) {
1227                rs_spe.innerHTML = '&euro; ' + parseFloat(cart_object['trasporto']).toFixed(2)
1228                if (cart_object['trasporto'] == 0.00) {
1229                    rs_spe.innerHTML = 'Gratuite'
1230                } else {
1231                    rs_spe.innerHTML = '€ ' + parseFloat(cart_object['trasporto']).toFixed(2)
1232                }
1233            }
1234            if (rs_tot) {
1235                rs_tot.innerHTML = '&euro; ' + parseFloat(cart_object['totale']).toFixed(2)
1236            }
1237            if (rs_iva) {
1238                rs_iva.innerHTML = '&euro; ' + parseFloat(cart_object['iva']).toFixed(2)
1239            }
1240            if (rs_time) {
1241                rs_time.innerHTML = cart_object['tempo_consegna']
1242            }
1243            var spr = document.getElementById('spe-riepilogo');
1244            if (spr) {
1245                spr.innerHTML = calcolaGiorno()
1246            }
1247
1248        } else {
1249            var cart_not = document.getElementById('cart-notice');
1250            var riep = document.getElementById('riepilogo-carrello');
1251            var ts = document.getElementById('time-ship');
1252            var spr = document.getElementById('spe-riepilogo');
1253            var cont = document.getElementById('contenuto-carrello');
1254            var cp = document.getElementById('carrello-page');
1255            if(cp){
1256                cp.setAttribute('class', 'preferiti-vuota')
1257                cp.setAttribute('style', '')
1258            }
1259            if (ts) {
1260                ts.classList.add('d-none')
1261            }
1262
1263            if (spr) {
1264                spr.innerHTML = calcolaGiorno()
1265            }
1266            var h = `<div class="container"><div class="row"><div class="col-lg-12"><div class="d-flex flex-column align-items-center"><h2>Il mio carrello</h2><p>Il tuo carrello al momento è vuoto.</p><i class="bi bi-bag"></i><a href="https://` + window.location.hostname + `">Ritorna alla homepage</a></div></div></div></div>`;
1267            if(cart_not){
1268                cart_not.innerHTML = h;
1269                cart_not.classList.remove('d-none');
1270            }
1271            if(riep){
1272                riep.innerHTML = ''
1273            }
1274             if(cont){
1275                cont.innerHTML = ''
1276            }
1277        }
1278    }
1279}
1280
1281function suggeriti_carrello(elenco_new, size = 4) {
1282
1283    var elenco = []
1284    for (let index = 0; index < elenco_new.length; index++) {
1285        const element = elenco_new[index];
1286        if (element['visibile'] == true) {
1287            elenco.push(element)
1288        }
1289    }
1290
1291    var ss = document.getElementById('sezione-suggeriti')
1292    var rows = document.getElementById('suggeriti')
1293    if (elenco.length == 0) {
1294        ss.classList.add('d-none')
1295    } else {
1296        var h = ''
1297        var row = document.getElementById('slides_tutto_in_uno');
1298        var p = 1
1299        var limit = elenco.length
1300        if (limit > 20) {
1301            limit = 20
1302        }
1303        var number = 6
1304        if (window.innerWidth <= 768) {
1305            number = 2
1306        }
1307        for (let index = 0; index < limit; index++) {
1308            try {
1309
1310            } catch (error) {
1311
1312            }
1313            const prodotto = elenco[index];
1314            if (index % number == 0) {
1315                h += `<div class="swiper-slide"><div class="row">`;
1316            }
1317            h += print_prodotto(prodotto, 'col-6 col-md-2 ps-3 pe-3 mt-2');
1318            if ((index % number == (number - 1)) || (index == (limit - 1))) {
1319                h += `</div></div>`;
1320            }
1321
1322
1323
1324        }
1325        row.innerHTML = h
1326
1327        var swiper2 = new Swiper("#swiper_tutto_in_uno", {
1328            pagination: {
1329                el: '.swiper-pagination',
1330                type: 'custom',
1331                renderCustom: function(swiper, current, total) {
1332                    var string = 'Pagina ' + current + ' di ' + total;
1333                    if (current > 1) {
1334                        string += '<span class="fklink active">Pagina iniziale</span>';
1335                    } else {
1336                        string += '<span class="fklink disabled">Pagina iniziale</span>';
1337                    }
1338                    return string;
1339                }
1340            },
1341            navigation: {
1342                nextEl: ".swiper-button-next-sugg",
1343                prevEl: ".swiper-button-prev-sugg"
1344            }
1345        });
1346        ss.classList.remove('d-none')
1347            // Use event delegation for dynamically generated content
1348        $('body').on('click', '.fklink.active', function() {
1349            setTimeout(function() {
1350                swiper2.slideTo(0);
1351            }, 175);
1352        });
1353        if (typeof aos_init === 'function') {
1354            aos_init();
1355        }
1356
1357    }
1358
1359}
1360
1361
1362function page_cart_ao(cart_object) {
1363    var h = ''
1364    var suggeriti = []
1365    if (cart_object.hasOwnProperty('lista_prodotti')) {
1366        var items_c = document.getElementById('items-carrello');
1367        if (cart_object['lista_prodotti'].length > 0) {
1368            var cp = document.getElementById('carrello-page');
1369            if (cp) {
1370                cp.setAttribute('class', 'carrello-pieno')
1371                cp.setAttribute('style', '')
1372            }
1373
1374            for (let i = 0; i < cart_object['lista_prodotti'].length; i++) {
1375                var el = cart_object['lista_prodotti'][i];
1376
1377                var options = '';
1378                for (var o = 0; o < 10; o++) {
1379                    // var opt = array[o];
1380                    var sss = ''
1381                    if (el['quantita'] == o) {
1382                        sss = 'selected';
1383                    }
1384                    if (o <= el['obj']['quantita']) {
1385                        options += '<option value="' + o + '" ' + sss + '>' + o + '</option>'
1386                    }
1387
1388                }
1389                if (el['obj']['quantita'] >= 10) {
1390                    // options += '<option value="10">10+</option>'
1391                }
1392
1393                var sq = 'none'
1394                var iq = 'none'
1395                if (el['quantita'] >= 10) {
1396                    iq = ''
1397                } else {
1398                    sq = ''
1399                }
1400                el['obj']['tempo_consegna'] = '1-2'
1401
1402                var f = 'https://assets.zangoo.it/webp/not_found.webp'
1403                if (el['obj']['thumbs']['300x300'] != undefined) {
1404                    f = el['obj']['thumbs']['300x300'][0]
1405                }
1406
1407                h += `<div class="carrello-sx">
1408                <div class="row mb-3">
1409                    <div class="col-lg-4 mb-3 col-5">
1410                        <div class="d-flex justify-content-center">
1411                            <a target="_blank" href="https://` + window.location.hostname + `/` + el['obj']['url'] + `">
1412                                <img class="img-fluid" src="` + f + `" alt="">
1413                                <span class="infoDett"><i class="bi bi-eye me-2"></i> Dettagli</span>
1414                            </a>
1415                        </div>
1416                    </div>
1417                    <div class="col-lg-8 mb-3 col-7 pe-0 me-0">
1418                        <div class="col-md-12 col-12 row pe-0">
1419                            <div class="col-md-9 col-12">
1420                                <a target="_blank" href="https://` + window.location.hostname + `/` + el['obj']['url'] + `">
1421                                    <h3 class="nome-prodotto">` + el['obj']['nome'] + `</h3>
1422                                </a>
1423                                <div class="dettagli-prodotto">
1424                                    <p>Codice: <strong>` + el['obj']['sku'] + `</strong></p>
1425                                    <p class="tempi-spedizione">Tempi di spedizione: <b class="shipping_product">Acquista ora e ricevi tra 16/05 e 17/05</b></p>
1426                                    <p class="disponibilita d-none">Disponibilità ` + el['obj']['quantita'] + ` pezzi</p>
1427                                </div>
1428                            </div>
1429                            <div class="col-md-3 col-12">
1430                                <h4 class="prezzo mb-3">` + parseFloat(el['prezzo']).toFixed(2) + `</h4>
1431                            </div>
1432                            <div class="col-md-12 col-12 mb-3">
1433                                <div class="row">
1434                                    <div class="col-md-4" style="max-width:120px;">
1435                                    <select style="display:` + sq + `" id="selectNumber-` + el['id'] + `" class="form-select mb-3 items" onchange="checkValue(this);aggiornaSingoloItem(this);" data-id="` + el['id'] + `" data-sku="` + el['obj']['sku'] + `">
1436                                    ` + options + `
1437                                    </select>
1438                                <div id="inputContainer-` + el['id'] + `" style="display:` + iq + `;" class="input-group inline-group avail riga-aggiunta-carrello new-inp">
1439                                    <button class="input-group-prepend" onclick="incrementValue(-1, ` + el['id'] + `);">-</button>
1440                                    <input onchange="checkInput(` + el['id'] + `)" class="form-control quantity items" type="number" id="numberInput-` + el['id'] + `" value="` + el['quantita'] + `" min="10" max="` + el['obj']['quantita'] + `"  data-id="` + el['id'] + `" data-sku="` + el['obj']['sku'] + `">
1441                                    <button class="input-group-append" onclick="incrementValue(1, ` + el['id'] + `);">+</button>
1442                                </div>
1443                                    </div>
1444                                    <div class="col-md-8">
1445                                    <span style="" class="rimuovi">
1446                                    <span class="link" onclick="openModalRemove(this)" data-titolo="` + (el['obj']['nome']).replace("'", "") + `"  data-sku="` + el['obj']['sku'] + `" data-id="` + el['id'] + `"  data-img="` + f + `" >
1447                                        <i class="bi bi-trash"></i> <el>Rimuovi</el>
1448                                    </span>
1449                                </span>
1450                                    </div>
1451
1452
1453                                </div>
1454                            </div>
1455                        </div>
1456                    </div>
1457                </div>
1458            </div>`
1459
1460                if (el['obj']['suggeriti'] != undefined) {
1461                    var correlati = el['obj']['suggeriti']
1462                    for (let index = 0; index < correlati.length; index++) {
1463                        const element = correlati[index];
1464                        if (index < 6) {
1465                            suggeriti.push(element)
1466                        }
1467                    }
1468                }
1469
1470            }
1471            items_c.innerHTML = h;
1472            var rs_sub = document.getElementById('riepilogo-sub');
1473            var rs_spe = document.getElementById('riepilogo-sped');
1474            var rs_tot = document.getElementById('riepilogo-tot');
1475            var rs_iva = document.getElementById('riepilogo-iva');
1476            var rs_time = document.getElementById('riepilogo-time');
1477            if (rs_sub) {
1478                rs_sub.innerHTML = '&euro; ' + parseFloat(cart_object['subtotale_articoli']).toFixed(2)
1479            }
1480
1481            rs_spe.innerHTML = '&euro; ' + parseFloat(cart_object['trasporto']).toFixed(2)
1482            if (cart_object['trasporto'] == 0.00) {
1483                rs_spe.innerHTML = 'Gratuite'
1484            } else {
1485                rs_spe.innerHTML = '€ ' + parseFloat(cart_object['trasporto']).toFixed(2)
1486            }
1487            rs_tot.innerHTML = '&euro; ' + parseFloat(cart_object['totale']).toFixed(2)
1488            rs_iva.innerHTML = '&euro; ' + parseFloat(cart_object['iva']).toFixed(2)
1489            if (rs_time) {
1490                rs_time.innerHTML = cart_object['tempo_consegna']
1491            }
1492            var spr = document.getElementById('spe-riepilogo');
1493            if (spr) {
1494                spr.innerHTML = calcolaGiorno()
1495            }
1496            calcolaDifferenzaOrario()
1497            suggeriti_carrello(suggeriti)
1498        } else {
1499            var cart_not = document.getElementById('cart-notice');
1500            var riep = document.getElementById('riepilogo-carrello');
1501            var ts = document.getElementById('time-ship');
1502            var spr = document.getElementById('spe-riepilogo');
1503
1504            var cont = document.getElementById('contenuto-carrello');
1505            var cp = document.getElementById('carrello-page');
1506            cp.setAttribute('class', 'preferiti-vuota')
1507            cp.setAttribute('style', '')
1508            if (ts) {
1509                ts.classList.add('d-none')
1510            }
1511
1512            if (spr) {
1513                spr.innerHTML = calcolaGiorno()
1514            }
1515
1516
1517            var h = `<div class="container"><div class="row"><div class="col-lg-12"><div class="d-flex flex-column align-items-center"><h2>Il mio carrello</h2><p>Il tuo carrello al momento è vuoto.</p><i class="bi bi-bag"></i><a href="https://` + window.location.hostname + `">Ritorna alla homepage</a></div></div></div></div>`;
1518            cart_not.innerHTML = h;
1519            cart_not.classList.remove('d-none');
1520            riep.innerHTML = ''
1521            cont.innerHTML = ''
1522            calcolaDifferenzaOrario()
1523
1524
1525        }
1526    }
1527
1528
1529}
1530
1531function cart_composing() {
1532    var full = document.getElementById('carrello-page-ao')
1533    if (full) {
1534        full = true
1535    } else {
1536        full = false
1537    }
1538    get_cart(full)
1539    return
1540}
1541
1542
1543function addDaysExcludeWeekends(daysToAdd) {
1544    var currentDate = new Date();
1545    while (daysToAdd > 0) {
1546        currentDate.setDate(currentDate.getDate() + 1);
1547        var dayOfWeek = currentDate.getDay();
1548        if (dayOfWeek !== 0 && dayOfWeek !== 6) { // 0 = Domenica, 6 = Sabato
1549            daysToAdd--;
1550        }
1551    }
1552    return currentDate.toLocaleDateString('it-IT', {
1553        weekday: 'long',
1554        day: 'numeric',
1555        month: 'long'
1556    });
1557}
1558
1559function calcolaGiorno() {
1560
1561    var oraAttuale = new Date();
1562    var giornoSettimana = oraAttuale.getDay(); // 0 = Domenica, 1 = Lunedì, ..., 6 = Sabato
1563    var ora = oraAttuale.getHours();
1564    var limit_pome = 14
1565    var limit_mattina = 1
1566        // Da lunedì a venerdì (1-5), dalle 07:00 alle 14:00
1567    if (giornoSettimana >= 1 && giornoSettimana <= 5 && ora >= limit_mattina && ora < limit_pome) {
1568        return "Oggi";
1569    }
1570
1571    // Da lunedì a giovedì (1-4), dopo le 14:00 e prima delle 07:00 del giorno successivo
1572    if (giornoSettimana >= 1 && giornoSettimana <= 4 && ora >= limit_pome) {
1573        return "Domani";
1574    }
1575    if (giornoSettimana >= 1 && giornoSettimana < 4 && ora < 7) { // Gestisce il caso della mattina presto
1576        return "Oggi";
1577    }
1578    if (giornoSettimana === 4 && ora < 7) { // Giovedì mattina presto, ancora considerato "OGGI"
1579        return "Domani";
1580    }
1581
1582    // Venerdì (5) dopo le 14:00, si intende "2 GIORNI" per lunedì
1583    if (giornoSettimana === 5 && ora >= limit_pome) {
1584        return "Lunedì mattina";
1585    }
1586
1587    // Venerdì mattina presto, ancora considerato "OGGI"
1588    if (giornoSettimana === 5 && ora < 7) {
1589        return "Oggi";
1590    }
1591
1592    // Se è sabato (6) o domenica (0), o venerdì prima delle 07:00, si considera il prossimo "lavorativo" come "2 GIORNI" dopo
1593    if (giornoSettimana === 0 || giornoSettimana === 6) {
1594        return "2 giorni lavorativi";
1595    }
1596
1597    // Caso di default, se nessuna delle condizioni sopra è soddisfatta
1598    return "3 giorni lavorativi";
1599}
1600
1601
1602function calcolaDifferenzaOrario(param = false) {
1603
1604    var oraAttuale = new Date();
1605    var giornoSuccessivo = new Date();
1606    var inf = 2;
1607    var mints = document.getElementById('min-time-sped'); 
1608
1609    if (mints) {
1610        var dataValue = parseInt(mints.getAttribute('data-value'), 10); 
1611        if (dataValue > 0) {
1612            inf = dataValue; 
1613        }
1614    }
1615
1616    var orarioRiferimentoS = new Date(oraAttuale.getFullYear(), oraAttuale.getMonth(), oraAttuale.getDate(), 14, 0, 0);
1617
1618    if (oraAttuale < orarioRiferimentoS) {
1619        giornoSuccessivo.setDate(oraAttuale.getDate() + 0);
1620
1621    } else {
1622        inf += 1;
1623        giornoSuccessivo.setDate(oraAttuale.getDate() + 1);
1624    }
1625
1626    giornoSuccessivo.setHours(14, 0, 0, 0); // Imposta le 14:00
1627
1628    
1629    if (giornoSuccessivo.getDay() === 6) { // Sabato
1630        giornoSuccessivo.setDate(giornoSuccessivo.getDate() + 2);
1631        inf = 3;
1632    } else if (giornoSuccessivo.getDay() === 0) { // Domenica
1633        giornoSuccessivo.setDate(giornoSuccessivo.getDate() + 1);
1634        inf = 2;
1635    }
1636
1637    // Festività da escludere
1638    const festivita = [
1639        "2024-01-01", "2024-04-01", "2024-04-25", "2024-05-01", "2024-08-15", "2024-11-01", "2024-12-25", "2024-12-26"
1640    ];
1641
1642    function isFestivo(data) {
1643        const dataStringa = data.toISOString().split('T')[0];
1644        return festivita.includes(dataStringa);
1645    }
1646
1647    function addDaysExcludeWeekends(incremento) {
1648        let data = new Date(oraAttuale);
1649        while (incremento > 0) {
1650            data.setDate(data.getDate() + 1);
1651            if (data.getDay() !== 0 && data.getDay() !== 6 && !isFestivo(data)) {
1652                incremento--;
1653            }
1654        }
1655        return data.toLocaleDateString('it-IT', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
1656    }
1657
1658    var differenzaMs = giornoSuccessivo - oraAttuale;
1659    var ore = Math.floor(differenzaMs / 1000 / 60 / 60);
1660    var minuti = Math.floor((differenzaMs / 1000 / 60) % 60);
1661    var secondi = Math.floor((differenzaMs / 1000) % 60);
1662
1663    var normale = addDaysExcludeWeekends(inf + 1);
1664    var fast = addDaysExcludeWeekends(inf);
1665
1666    if (param == 'fast') {
1667        return fast;
1668    }
1669
1670    if (param == false) {
1671        var sc = document.getElementById('stima_consegna');
1672        if (sc) {
1673            sc.innerHTML = normale;
1674        }
1675        var cr = document.getElementById('consegna_rapida');
1676        if (cr) {
1677            cr.innerHTML = fast;
1678        }
1679        var oe = document.getElementById('ordina_entro');
1680        if (oe) {
1681            oe.innerHTML = ore + " ore e " + minuti + " minuti";
1682        }
1683    }
1684
1685    var bs = document.getElementsByClassName('shipping_product');
1686    for (let index = 0; index < bs.length; index++) {
1687        const element = bs[index];
1688        element.innerHTML = 'Acquista ora e ricevi tra <el>' + fast + '</el> e <el>' + normale + '</el>';
1689    }
1690
1691    return ore + " ore e " + minuti + " minuti";
1692}
1693
1694
1695
1696function generaStelle(rating) {
1697    const stelleArrotondate = Math.round(rating * 2) / 2;
1698
1699    const stellePiene = Math.floor(stelleArrotondate);
1700    const mezzaStella = stelleArrotondate % 1 !== 0;
1701    const stelleVuote = 5 - stellePiene - (mezzaStella ? 1 : 0);
1702
1703    let htmlStelle = '';
1704
1705    // Aggiungi le stelle piene
1706    for (let i = 0; i < stellePiene; i++) {
1707        htmlStelle += '<i class="bi bi-star-fill"></i>';
1708    }
1709
1710    if (mezzaStella) {
1711        htmlStelle += '<i class="bi bi-star-half"></i>';
1712    }
1713
1714    for (let i = 0; i < stelleVuote; i++) {
1715        htmlStelle += '<i class="bi bi-star"></i>';
1716    }
1717
1718
1719    return '<el style="zoom:0.9" class="star">' + htmlStelle + '</el>'
1720}
1721
1722
1723function makeReview() {
1724
1725    stream('/viste/risorse/make-review.html?d=5', 'make-review', false);
1726    sleep(500).then(() => {
1727        load()
1728        checkData()
1729        $("#modal-make-review").modal('show');
1730    });
1731
1732}
1733
1734function load() {
1735    document.getElementById('make-img').setAttribute('src', document.getElementById('img-prodotto').getAttribute('src'))
1736    document.getElementById('make-titolo').innerHTML = document.getElementById('titolo-prodotto').innerHTML
1737    document.getElementById('make-prezzo-attuale').innerHTML = document.getElementById('prezzo-attuale').innerHTML
1738    document.getElementById('lascia-recensione').setAttribute('data-id', document.getElementById('modal-make-review').getAttribute('data-id'))
1739
1740}
1741
1742
1743function checkData() {
1744
1745    var lr = document.getElementById('lascia-recensione')
1746    lr.classList.add('disabled')
1747    var score = document.querySelectorAll('.setScore.active')
1748    if (score.length == 0) {
1749        return ''
1750    }
1751    var titolo = document.getElementById('review-titolo')
1752    if (titolo == undefined) {
1753        return ''
1754    }
1755    var desc = document.getElementById('review-descrizione')
1756    if (desc == undefined) {
1757        return ''
1758    }
1759    if ((titolo.value).length < 5) {
1760        return ''
1761    }
1762    if ((desc.value).length < 10) {
1763        return ''
1764    }
1765
1766    lr.classList.remove('disabled')
1767
1768
1769}
1770
1771function setScore(score) {
1772
1773    var el = document.getElementsByClassName('setScore')
1774    var bif = '<i class="bi bi-star-fill"></i>'
1775    for (let index = 0; index < el.length; index++) {
1776        const element = el[index];
1777        element.innerHTML = bif
1778        element.classList = 'setScore'
1779        element.setAttribute('data-selezione', 0)
1780        if ((index + 1) == score) {
1781            element.classList = 'setScore active'
1782            element.setAttribute('data-selezione', score)
1783            bif = '<i class="bi bi-star"></i>'
1784        }
1785    }
1786
1787    checkData()
1788}
1789
1790
1791function uploaded(el) {
1792    var id = el.getAttribute('data-index')
1793    var files = el.files;
1794    if (files.length == 0) {
1795        return;
1796    }
1797
1798    var preview = document.getElementById('preview-items');
1799    var errorDiv = document.getElementById('error');
1800    errorDiv.textContent = ''; // Pulisce i messaggi di errore precedenti
1801
1802    for (var i = 0; i < files.length; i++) {
1803        var file = files[i];
1804
1805        const formData = new FormData();
1806        formData.append('files[]', files[i]);
1807        formData.append('api', true)
1808        formData.append('act', 'carica-file')
1809        caricareFileSuServer(formData, id)
1810
1811        if (file.size > 20971520 * 10) {
1812            errorDiv.textContent += `Il file ${file.name}
1812 supera il limite di 20MB. `;
1813            continue; // Salta questo file
1814        }
1815
1816        var container = document.createElement('div');
1817        container.classList.add('anteprima-container', 'col');
1818        container.setAttribute('id', 'c' + id);
1819        container.setAttribute('data-index', id);
1820
1821        if (file.type.startsWith('image/') || file.type.startsWith('video/')) {
1822            var media = document.createElement(file.type.startsWith('image/') ? 'img' : 'video');
1823            media.src = URL.createObjectURL(file);
1824            if (file.type.startsWith('video/')) {
1825                media.controls = false
1826                media.onloadeddata = function() {
1827                    URL.revokeObjectURL(this.src);
1828                };
1829            } else {
1830                media.onloadstart = media.onload = function() {
1831                    URL.revokeObjectURL(this.src);
1832                };
1833            }
1834            media.height = 100; // Altezza dell'anteprima
1835
1836            container.appendChild(media);
1837        } else {
1838            continue; // Salta file non immagine/video
1839        }
1840
1841        var rimuoviBtn = document.createElement('button');
1842        rimuoviBtn.textContent = 'X';
1843        rimuoviBtn.classList.add('rimuovi-anteprima');
1844        rimuoviBtn.setAttribute('data-index', id)
1845        rimuoviBtn.setAttribute('onclick', 'removeFileAtIndex(this)')
1846        rimuoviBtn.onclick = function() { removeFileAtIndex(this); };
1847        container.appendChild(rimuoviBtn);
1848
1849
1850
1851        preview.appendChild(container);
1852
1853    }
1854
1855    aggiungiNuovoInputFile(el.dataset.index);
1856}
1857
1858
1859function aggiungiNuovoInputFile(indiceCorrente) {
1860    var nuovoIndice = parseInt(indiceCorrente) + 1;
1861    var containerInput = document.getElementById('inputs');
1862
1863    // Crea il nuovo elemento input
1864    var nuovoInput = document.createElement('input');
1865    nuovoInput.setAttribute('id', `fileInput-${nuovoIndice}`);
1866    nuovoInput.setAttribute('style', 'width: 100%;');
1867    nuovoInput.setAttribute('type', 'file');
1868    nuovoInput.setAttribute('accept', 'image/*,video/*'); // Accetta sia immagini che video
1869    nuovoInput.classList.add('file-input');
1870    nuovoInput.setAttribute('data-index', nuovoIndice);
1871    nuovoInput.setAttribute('onchange', 'uploaded(this)');
1872
1873
1874    // Aggiungi il nuovo input al DOM
1875    containerInput.appendChild(nuovoInput);
1876
1877    // Aggiorna l'attributo 'for' del label di aggiunta per il nuovo input file
1878    var pulsanteAggiunta = document.getElementById('plus-file');
1879    if (pulsanteAggiunta.tagName.toLowerCase() === 'label') {
1880        pulsanteAggiunta.setAttribute('for', `fileInput-${nuovoIndice}`);
1881    }
1882}
1883
1884function removeFileAtIndex(el) {
1885
1886    var i = el.getAttribute('data-index')
1887    var index = document.getElementById('fileInput-' + i)
1888    if (index) {
1889        index.remove()
1890    }
1891    var input = document.getElementById('c' + i)
1892    if (input) {
1893        input.remove()
1894    }
1895
1896}
1897
1898function lasciaReview(el) {
1899
1900    el.setAttribute('onclick', '')
1901    var formData = new FormData();
1902    formData.append('api', true)
1903    formData.append('act', 'lascia-recensione')
1904    formData.append('id', el.getAttribute('data-id'))
1905        // Aggiungi il punteggio
1906    var score = document.querySelectorAll('.setScore.active')
1907    formData.append('score', score[0].getAttribute('data-selezione'));
1908
1909    // Aggiungi titolo e descrizione
1910    formData.append('titolo', $('#review-titolo').val());
1911    formData.append('descrizione', $('#review-descrizione').val());
1912
1913    // Aggiungi le immagini
1914    var files = document.getElementsByClassName('file-input')
1915    for (let index = 0; index < files.length; index++) {
1916        const element = files[index];
1917        if (element.files.length > 0) { // Controlla se c'è almeno un file
1918            if (element.getAttribute('data-ida') != undefined) {
1919                formData.append('ida[]', element.getAttribute('data-ida'));
1920            }
1921        }
1922    }
1923
1924
1925
1926    var request = $.ajax({
1927        url: 'index.php',
1928        type: 'POST',
1929        data: formData,
1930        contentType: false,
1931        processData: false
1932    });
1933
1934    request.done(function(response) {
1935        if (response['success'] == true) {
1936            window.location.href = window.location.href
1937        }
1938    })
1939    request.fail(function(jqXHR, textStatus) {
1940        el.setAttribute('onclick', 'lasciaReview(this)')
1941        console.log("Request failed: " + textStatus);
1942    })
1943
1944}
1945
1946
1947
1948function caricareFileSuServer(formData, index) {
1949    return new Promise((resolve, reject) => {
1950        const xhr = new XMLHttpRequest();
1951        xhr.upload.onprogress = function(event) {
1952            if (event.lengthComputable) {
1953                const percentCompleted = Math.round((event.loaded * 100) / event.total);
1954            }
1955        };
1956        xhr.onload = function() {
1957            if (xhr.status >= 200 && xhr.status < 300) {
1958                var r = JSON.parse(xhr.response)
1959                try {
1960                    document.getElementById('fileInput-' + index).setAttribute('data-ida', r['id'])
1961                } catch (error) {}
1962                resolve(xhr.response);
1963            } else {
1964                console.log('Errore nel caricamento del file');
1965                reject(xhr.statusText);
1966            }
1967        };
1968
1969        xhr.onerror = function() {
1970            console.error('Errore nella richiesta');
1971            reject(xhr.statusText);
1972        };
1973
1974        xhr.open('POST', 'index.php', true);
1975        xhr.send(formData);
1976    });
1977}
1978
1979function navigate(page) {
1980    window.location.href = page;
1981}
1982
1983
1984function loadContent(el, url = false, titolo = '') {
1985    event.preventDefault();
1986
1987    try {
1988        url = el.getAttribute('data-url')
1989        pagina = el.getAttribute('data-title')
1990    } catch {
1991        pagina = titolo
1992    }
1993
1994    try {
1995        $.ajax({
1996            url: url,
1997            async: true,
1998            method: 'GET',
1999
2000        }).done(function(data, textStatus, jqXHR) {
2001            document.documentElement.style.scrollBehavior = 'auto';
2002            document.body.scrollTop = 0;
2003            document.documentElement.scrollTop = 0;
2004
2005            navigate(url)
2006
2007            $("#main").html(data);
2008            $("#numero-preferiti").prev("i").removeClass("bi-heart bi-heart-pulse bi-heartbreak").addClass("bi-heart-pulse");
2009            $(".mobile-nav-close.d-block").click();
2010
2011            try {
2012                var crono = JSON.parse(sessionStorage.getItem('crono'))
2013
2014                if (crono[(crono.length - 1)] != url) {
2015                    crono.push(url)
2016                }
2017                sessionStorage.setItem('crono', JSON.stringify(crono))
2018            } catch (error) {
2019
2020            }
2021
2022            sessionStorage.setItem('previous', url)
2023
2024
2025            var nav = document.getElementsByClassName('ul_menu_level');
2026            for (let index = 0; index < nav.length; index++) {
2027                const element = nav[index];
2028                element.style = ""
2029            }
2030            cart_composing();
2031        }).fail(function(jqXHR, textStatus, errorThrown) {
2032            $("#numero-preferiti").prev("i").removeClass("bi-heart bi-heart-pulse bi-heartbreak").addClass("bi-heartbreak");
2033            console.err("textStatus: ", textStatus);
2034            console.err("errorThrown: ", errorThrown);
2035        });
2036    } catch {
2037
2038    }
2039}
2040
2041function loadLight(url) {
2042    try {
2043        $.ajax({
2044            url: url,
2045            async: true,
2046            method: 'GET',
2047        }).done(function(data, textStatus, jqXHR) {
2048            document.documentElement.style.scrollBehavior = 'auto';
2049            document.body.scrollTop = 0;
2050            document.documentElement.scrollTop = 0;
2051            // navigate(url)
2052            $("#main").html(data);
2053            $("#numero-preferiti").prev("i").removeClass("bi-heart bi-heart-pulse bi-heartbreak").addClass("bi-heart-pulse");
2054            $(".mobile-nav-close.d-block").click();
2055            var nav = document.getElementsByClassName('ul_menu_level');
2056            for (let index = 0; index < nav.length; index++) {
2057                const element = nav[index];
2058                element.style = ""
2059            }
2060
2061        }).fail(function(jqXHR, textStatus, errorThrown) {
2062            $("#numero-preferiti").prev("i").removeClass("bi-heart bi-heart-pulse bi-heartbreak").addClass("bi-heartbreak");
2063            console.err("textStatus: ", textStatus);
2064            console.err("errorThrown: ", errorThrown);
2065        });
2066    } catch {
2067
2068    }
2069}
2070
2071
2072
2073function evidenziaSottostringa(frase, daEvidenziare, tagName = '__aa-highlight__') {
2074    const regex = new RegExp(`(${daEvidenziare})`, 'gi');
2075    return frase.replace(regex, `${tagName}$1${tagName}`);
2076}
2077
2078
2079
2080function evidenziaConAlgoliaStyle(termineRicerca, testo) {
2081    // Escape dei caratteri speciali in RegExp
2082    const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2083
2084    // Creazione della RegExp per cercare il termine all'interno del testo
2085    const searchTermRegEx = new RegExp(escapeRegExp(termineRicerca), 'gi');
2086
2087    // Evidenziazione del termine nel testo
2088    const testoEvidenziato = testo.replace(searchTermRegEx, (match) => `__aa-highlight__${match}/aa-highlight__`);
2089
2090    // Creazione dell'oggetto di risposta simile ad Algolia
2091    const highlightResult = {
2092        query: {
2093            fullyHighlighted: false, // Imposta su true se tutto il testo è evidenziato
2094            matchLevel: "full",
2095            matchedWords: [termineRicerca],
2096            value: testoEvidenziato
2097        }
2098    };
2099
2100    return highlightResult;
2101}
2102
2103
2104
2105function crea_range(id, min, max, attributo) {
2106    if (id == 10000000) {
2107        var t = 'price'
2108    }
2109
2110    var h = `<div class="accordion-body">
2111       <div class="wrapper">
2112           <div class="position-relative">
2113               <div id="slider-track-` + id + `" class="slider-track" style="background: linear-gradient(to right, rgb(218, 218, 229) 0%, rgb(54, 192, 184) 0%, rgb(54, 192, 184) 100%, rgb(218, 218, 229) 100%);"></div>
2114               <input data-ranged="0" name="" type="range" min="` + min + `" max="` + max + `" value="` + min + `" id="slider-` + id + `-1" class="filter filter-range" data-attributo="` + attributo + `" data-type="min" data-id_attr="` + id + `" oninput="slideOne(` + id + `)">
2115               <input data-ranged="0" name="" type="range" min="` + min + `" max="` + max + `" value="` + max + `" id="slider-` + id + `-2" class="filter filter-range" data-attributo="` + attributo + `" data-type="max" data-id_attr="` + id + `" oninput="slideTwo(` + id + `)">
2116           </div>
2117       </div>
2118       <div class="values mb-3">
2119           <span>Min:</span>
2120           <span id="range-` + id + `-1">` + min + `</span>
2121           <span></span>
2122           <span> ‐ </span>
2123           <span>Max:</span>
2124           <span id="range-` + id + `-2">` + max + `</span>
2125           <span></span>
2126       </div>
2127       <button class="bottone" onclick="filterUp()">Filtra</button>
2128    </div>`
2129
2130    document.getElementById('filtro-range-' + id).innerHTML = h
2131    try {
2132        document.getElementById('values-' + id).setAttribute('data-loaded', 1)
2133    } catch (error) {
2134
2135    }
2136
2137    rangeCreator(id)
2138    rangeReload(id)
2139}
2140
2141function slideOne(id) {
2142    var minGap = 0;
2143    var sliderMinValue = document.getElementById("slider-" + id + "-1").min;
2144    var sliderMaxValue = document.getElementById("slider-" + id + "-2").max;
2145
2146    var sliderOne = document.getElementById("slider-" + id + "-1");
2147    var sliderTwo = document.getElementById("slider-" + id + "-2");
2148    var displayValOne = document.getElementById("range-" + id + "-1");
2149    if (parseInt(sliderTwo.value) - parseInt(sliderOne.value) <= minGap) {
2150        sliderOne.value = parseInt(sliderTwo.value) - minGap;
2151    }
2152    if (sliderOne.value != sliderMinValue || sliderTwo.value != sliderMaxValue) {
2153        sliderOne.setAttribute('data-ranged', 1)
2154    } else {
2155        sliderOne.setAttribute('data-ranged', 0)
2156    }
2157
2158    displayValOne.textContent = sliderOne.value;
2159    fillColor(id);
2160}
2161
2162function slideTwo(id) {
2163    var minGap = 0;
2164    var sliderMinValue = document.getElementById("slider-" + id + "-1").min;
2165    var sliderMaxValue = document.getElementById("slider-" + id + "-2").max;
2166    var sliderOne = document.getElementById("slider-" + id + "-1");
2167    var sliderTwo = document.getElementById("slider-" + id + "-2");
2168    var displayValTwo = document.getElementById("range-" + id + "-2");
2169    if (parseInt(sliderTwo.value) - parseInt(sliderOne.value) <= minGap) {
2170        sliderTwo.value = parseInt(sliderOne.value) + minGap;
2171    }
2172    displayValTwo.textContent = sliderTwo.value;
2173    if (sliderOne.value != sliderMinValue || sliderTwo.value != sliderMaxValue) {
2174        sliderTwo.setAttribute('data-ranged', 1)
2175    } else {
2176        sliderTwo.setAttribute('data-ranged', 0)
2177    }
2178
2179    fillColor(id);
2180}
2181
2182function fillColor(id, reset = false) {
2183
2184    var sliderMaxValue = document.getElementById("slider-" + id + "-1").max;
2185    var sliderOne = document.getElementById("slider-" + id + "-1");
2186    var sliderTwo = document.getElementById("slider-" + id + "-2");
2187    var sliderTrack = document.getElementById("slider-track-" + id);
2188    var sliderMinValueR = document.getElementById("slider-" + id + "-1").min;
2189    var sliderMaxValueR = document.getElementById("slider-" + id + "-2").max;
2190
2191
2192    percent1 = (sliderOne.value - sliderMinValueR) / (sliderMaxValue - sliderMinValueR) * 100;
2193    percent2 = (sliderTwo.value - sliderMinValueR) / (sliderMaxValue - sliderMinValueR) * 100;
2194
2195
2196    if (reset === true) {
2197        crea_range(id, sliderMinValueR, sliderMaxValueR)
2198    } else {
2199        sliderTrack.style.background = `linear-gradient(to right, #dadae5 ${percent1}% , #35c1b8 ${percent1}% , #35c1b8 ${percent2}%, #dadae5 ${percent2}%)`;
2200
2201    }
2202
2203}
2204
2205function rangeCreator(id) {
2206    slideOne(id);
2207    slideTwo(id);
2208}
2209
2210
2211function find_estremi(p) {
2212    Array.prototype.max = function() {
2213        return Math.max.apply(null, this);
2214    };
2215
2216    Array.prototype.min = function() {
2217        return Math.min.apply(null, this);
2218    };
2219    return [p.min(), p.max()]
2220
2221}
2222
2223function financial(x) {
2224    return Number.parseFloat(x).toFixed(0);
2225}
2226
2227
2228function get_address(tipo = 1) {
2229    var aggiungi = document.getElementById('aggiungi-action')
2230    aggiungi.setAttribute('onclick', 'open_add_address(' + tipo + ')')
2231    aggiungi.classList.remove('disabled')
2232
2233    var isu = document.getElementById('indirizzi_spe_utente');
2234    isu.innerHTML = ''
2235    var isuf = document.getElementById('indirizzi_fatt_utente');
2236    isuf.innerHTML = ''
2237    if (tipo == 1) {
2238        act = 'get_lista_indirizzi_spedizione'
2239        isu = isu
2240    } else {
2241        act = 'get_lista_indirizzi_fatturazione'
2242        isu = isuf
2243    }
2244    var c = {};
2245    var values = {
2246        api: true,
2247        act: act
2248    };
2249
2250    var req = $.ajax({
2251        url: "index.php",
2252        type: "post",
2253        data: values,
2254        async: false,
2255        success: function(response) {
2256
2257            var h = '';
2258
2259            if (response != null) {
2260
2261                for (var i = 0; i < response.length; i++) {
2262                    var a = response[i]['destinatario']
2263                    var b = response[i]['indirizzo']
2264                    var c = response[i]['provincia']
2265                    var d = response[i]['comune']
2266                    var e = response[i]['cap']
2267                    var t = response[i]['telefono']
2268                    var id = response[i]['id']
2269
2270                    h += `
2271                <div>
2272            <div class="d-flex justify-content-between">
2273                 <div class="dettagli-spedizione-utente">
2274                 <p>
2274` + a + `</p>
2275                 <p>` + b + ` , ` + e + ` ` + d + ` , ` + c + `</p>
2276                 <p>TEL. ` + t + `</p>
2277                </div>
2278                <div class="scegli-indirizzo">
2279                    <button type="button" id="" onclick="scegli_indirizzo('` + id + `')" class="btn">Scegli</button>
2280                </div>
2281            </div>
2282            <hr>
2283            </div>`
2284                }
2285
2286            } else {
2287
2288                var d = document.getElementById('blocco-indirizzi')
2289                d.innerHTML = `<div class="alert alert-warning"><i style="zoom:2; display:block; margin:auto" class="bi bi-exclamation-triangle"></i><p>Non hai completato il tuo profilo! Non sono presenti indirizzi di fatturazione e spedizione. <a href="https://www.zangoo.it/account?s=indirizzi">Completa il tuo account</a></p></div>`
2290            }
2291
2292
2293            isu.innerHTML = h
2294
2295
2296        },
2297        error: function(jqXHR, textStatus, errorThrown) {
2298            console.log(textStatus, errorThrown);
2299            return true
2300        }
2301    });
2302    return c;
2303}
2304
2305function forceUpdate(el) {
2306
2307    var a = document.getElementById('aggiorna-carrello')
2308    el.setAttribute('data-updated', 1)
2309    if (a.getAttribute('onclick') != '') {
2310        a.click();
2311    }
2312
2313}
2314
2315function checkValue(select) {
2316
2317    var value = select.value;
2318    var selectElement = document.getElementById('selectNumber-' + select.getAttribute('data-id'));
2319    var inputContainer = document.getElementById('inputContainer-' + select.getAttribute('data-id'));
2320    var numberInput = document.getElementById('numberInput-' + select.getAttribute('data-id'));
2321
2322    if (value === '10') {
2323        selectElement.style.display = 'none';
2324        inputContainer.style.display = '';
2325        numberInput.value = 10; // Reset the input to 10
2326        numberInput.focus();
2327        selectElement.classList.remove('items')
2328        numberInput.classList.add('items')
2329    } else {
2330        selectElement.style.display = '';
2331        inputContainer.style.display = 'none';
2332        selectElement.classList.add('items')
2333        numberInput.classList.remove('items')
2334            // updateitem(select)
2335
2336    }
2337    var a = document.getElementById('aggiorna-carrello')
2338    a.setAttribute('onclick', 'update_cart_global()')
2339    a.setAttribute('class', 'aggiorna-carrello')
2340}
2341
2342
2343function updateitem(el, ignore = false) {
2344
2345    if (el.value == "10") {
2346
2347    } else {
2348
2349    }
2350    if (ignore == false) {
2351        $('#rimuovi-item').modal('show')
2352        var mm = document.getElementById('messaggio-modale')
2353        var id = el.getAttribute('data-id');
2354        var name = el.getAttribute('data-titolo');
2355        var q = el.value;
2356        var sku = el.getAttribute('data-sku');
2357        if (q == undefined) {
2358            q = 0
2359        } else {
2360            if (q == 0) {
2361                mm.innerHTML = "Sei sicuro di voler rimuovere il prodotto dal carrello?";
2362            } else {
2363                mm.innerHTML = "Sei sicuro di voler cambiare la quantità del prodotto nel carrello?";
2364            }
2365            var a = document.getElementById('id-rimuovi-btn');
2366            a.setAttribute('onclick', 'updateitem(this, true)')
2367            a.setAttribute('data-id', id)
2368            a.setAttribute('data-value', q)
2369            document.getElementById('sku-rimuovi').innerHTML = sku
2370            return '';
2371        }
2372    } else {
2373        var a = document.getElementById('id-rimuovi-btn');
2374        var id = a.getAttribute('data-id')
2375        var q = a.getAttribute('data-value')
2376
2377    }
2378
2379
2380    var values = {
2381        api: true,
2382        act: 'update_cart',
2383        id_prodotto: id,
2384        quantita: q
2385    };
2386    var req = $.ajax({
2387        url: "index.php",
2388        type: "post",
2389        data: values,
2390        async: false,
2391        success: function(response) {
2392            if (response.hasOwnProperty('status') && response['status'] == true) {
2393                evento_aggiunta_carrello(id, q, null, null, null, response['cart'])
2394                cart_composing()
2395                $('#rimuovi-item').modal('hide')
2396            } else {
2397
2398            }
2399        },
2400        error: function(jqXHR, textStatus, errorThrown) {
2401            console.log(textStatus, errorThrown);
2402            // alert('Errore di visualizzazione dati, contatti il team IT');
2403            return true
2404        }
2405    });
2406
2407
2408}
2409
2410
2411function checkInput(id) {
2412    var numberInput = document.getElementById('numberInput-' + id);
2413    var selectElement = document.getElementById('selectNumber-' + id);
2414    var inputContainer = document.getElementById('inputContainer-' + id);
2415    var currentValue = parseInt(numberInput.value, 10);
2416
2417
2418    var maxValue = parseInt(numberInput.max, 10);
2419    if (parseInt(numberInput.value) > parseInt(maxValue)) {
2420        alertBlock('alert-login', 'Hai scelto una quantità maggiore di quella disponibile')
2421        numberInput.value = maxValue
2422    } else {
2423        var a = document.getElementById('aggiorna-carrello')
2424        a.setAttribute('onclick', 'update_cart_global()')
2425        a.setAttribute('class', 'aggiorna-carrello')
2426        aggiornaSingoloItem(numberInput);
2427    }
2428
2429
2430    return false
2431}
2432
2433function incrementValue(step, id) {
2434    var numberInput = document.getElementById('numberInput-' + id);
2435    var selectElement = document.getElementById('selectNumber-' + id);
2436    var inputContainer = document.getElementById('inputContainer-' + id);
2437    var currentValue = parseInt(numberInput.value, 10);
2438    var maxValue = parseInt(numberInput.max, 10);
2439
2440    currentValue += step;
2441
2442    if (currentValue < 10) {
2443        selectElement.value = currentValue;
2444        selectElement.style.display = '';
2445        inputContainer.style.display = 'none';
2446        numberInput.classList.remove('items')
2447        selectElement.classList.add('items')
2448
2449        var a = document.getElementById('aggiorna-carrello')
2450        a.setAttribute('onclick', 'update_cart_global()')
2451        a.setAttribute('class', 'aggiorna-carrello')
2452    } else if (currentValue <= maxValue) {
2453
2454        numberInput.value = currentValue;
2455        numberInput.style.display = '';
2456        numberInput.classList.add('items')
2457        selectElement.classList.remove('items')
2458        var a = document.getElementById('aggiorna-carrello')
2459        a.setAttribute('onclick', 'update_cart_global()')
2460        a.setAttribute('class', 'aggiorna-carrello')
2461    }
2462
2463
2464    if (parseInt(numberInput.value) > parseInt(maxValue)) {
2465        alertBlock('alert-login', 'Hai scelto una quantità maggiore di quella disponibile')
2466        numberInput.value = maxValue
2467    }
2468
2469
2470
2471}
2472
2473
2474function checkMaxQtyLat(e) {
2475    if (parseInt(e.value) > parseInt(e.getAttribute('max'))) {
2476
2477        alertBlock('alert-login', 'Hai scelto una quantità maggiore di quella disponibile')
2478        e.value = parseInt(e.getAttribute('max'))
2479    }
2480}
2481
2482function aggiornaSingoloItem(el) {
2483
2484    var id = el.getAttribute('data-id');
2485    var q = el.value;
2486    var values = {
2487        api: true,
2488        act: 'update_cart',
2489        id_prodotto: id,
2490        quantita: q
2491    };
2492
2493    var req = $.ajax({
2494        url: "index.php",
2495        type: "post",
2496        data: values,
2497        async: false,
2498        success: function(response) {
2499            evento_aggiunta_carrello(id, q, null, null, null, response['cart'])
2500            cart_composing()
2501        },
2502        error: function(jqXHR, textStatus, errorThrown) {
2503            console.log(textStatus, errorThrown);
2504            return true
2505        }
2506    });
2507
2508}
2509
2510/** GANALITICS function */
2511
2512function view_item_event(product, currency="EUR") {
2513    return "";
2514    /* try {
2515        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
2516        dataLayer.push({
2517            event: "view_item",
2518            ecommerce: {
2519                currency: currency,
2520                value: product['prezzo'],
2521                items: {
2522                    'item_id': product['id'],
2523                    'item_name': product['nome'],
2524                    'item_price' :  product['prezzo'],
2525                    'item_category' : product['cateogria'] || ""
2526                }
2527            }
2528        });
2529    } catch (err) {
2530        console.error(err)
2531    }
2532    // try {
2533    //     gtag('event', 'view_item', {
2534    //         'currency': currency,
2535    //         'value': product['prezzo'],
2536    //         'items': [{
2537    //             'item_id': product['id'],
2538    //             'item_name': product['nome']
2539    //         }]
2540    //     });
2541    // } catch (error) {
2542    //     console.log(error)
2543    // }
2544    */
2545}
2546
2547
2548function view_item_list_event(prodotti) {
2549    items = [];
2550    for (let i = 0; i < prodotti.length; i++) {
2551        var el = prodotti[i];
2552        item = {'item_id': el.id, 'item_name': el.nome}
2553        items.push(item);
2554    }
2555
2556    try {
2557        // gtag('event', 'view_item_list', {
2558        //     'items': items
2559        // });
2560        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
2561        dataLayer.push({
2562        event: "view_item_list",
2563        ecommerce: {
2564            items: items
2565        }
2566        });
2567
2568    } catch (error) {
2569        console.log(error)
2570    }
2571}
2572
2573
2574async function remove_from_cart_event(item_id, currency="EUR") {
2575    item_name = "";
2576    value = 0;
2577
2578    try {
2579        const cartData = await get_cart_ga();
2580        if(cartData){
2581            products = cartData.lista_prodotti;
2582            total = cartData.totale;
2583            let foundItem = products.find(el => el.obj.id == item_id);
2584
2585            if(foundItem) {
2586                item_id = foundItem.id;
2587                item_name = foundItem.obj.nome;
2588                value = foundItem.obj.prezzo;
2589            }
2590
2591        }
2592
2593    } catch (error) {
2594        console.error("Error to get cart:", error);
2595    }
2596
2597    try {
2598        if(item_id){
2599            dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
2600            dataLayer.push({
2601            event: "remove_from_cart",
2602            ecommerce: {
2603                currency: currency,
2604                value: value,
2605                items: [{
2606                    'item_id': item_id,
2607                    'item_name': item_name
2608                }]
2609            }
2610            });
2611            // gtag('event', 'remove_from_cart', {
2612            //     'currency': currency,
2613            //     'value': value,
2614            //     'items': [{
2615            //         'item_id': item_id,
2616            //         'item_name': item_name
2617            //     }]
2618            // });
2619        }
2620    } catch (error) {
2621        console.log(error)
2622    }
2623}
2624
2625
2626async function view_cart_event() {
2627    items = [];
2628    total = 0;
2629    try {
2630        const cartData = await get_cart_ga();
2631        if(cartData){
2632            products = cartData.lista_prodotti;
2633            total = cartData.totale;
2634            for (let i = 0; i < products.length; i++) {
2635                var el = products[i];
2636                el_obj = el['obj']
2637                // name = el_obj['nome'];
2638                item = {'item_id' :  el_obj['id'], 'item_name': el_obj['nome']}
2639                items.push(item)}
2640        }
2641
2642    } catch (error) {
2643        console.error("Error to get cart:", error);
2644    }
2645
2646    try {
2647        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
2648        dataLayer.push({
2649        event: "view_cart",
2650        ecommerce: {
2651            currency: "EUR",
2652            value: total,
2653            items: items
2654        }
2655        });
2656        // gtag('event', 'view_cart', {
2657        //     'currency': 'EUR',
2658        //     'value': total,
2659        //     'items': items
2660        // });
2661
2662    } catch (error) {
2663        console.log("Error to send data to ganalytics", error)
2664    }
2665}
2666
2667
2668
2669async function begin_checkout_ga_event(currency = "EUR") {
2670    let items = [];
2671    let total = 0;
2672
2673    try {
2674        const cartData = await get_cart_ga();
2675
2676        if (cartData && cartData.lista_prodotti && Array.isArray(cartData.lista_prodotti)) {
2677            const products = cartData.lista_prodotti;
2678            total = parseFloat(cartData.totale) || 0;
2679
2680            for (let i = 0; i < products.length; i++) {
2681                const el = products[i];
2682                const obj = el.obj;
2683
2684                const item = {
2685                    item_id: obj.id,
2686                    item_name: obj.nome,
2687                    item_brand: obj.marca || '',
2688                    item_category: obj.full_path_name ?
2689                        (obj.full_path_name.includes("/") ?
2690                            obj.full_path_name.split("/").pop().trim() :
2691                            obj.full_path_name.trim()) : '',
2692                    price: parseFloat(el.prezzo) || 0,
2693                    quantity: parseInt(el.quantita) || 1
2694                };
2695
2696                items.push(item);
2697            }
2698        }
2699    } catch (error) {
2700        console.error("Errore nel recupero del carrello:", error);
2701    }
2702
2703    try {
2704        const ecommerceData = {
2705            currency: currency,
2706            value: total,
2707            items: items
2708        };
2709
2710        dataLayer.push({ ecommerce: null });
2711        dataLayer.push({
2712            event: "begin_checkout",
2713            ecommerce: ecommerceData
2714        });
2715
2716        try {
2717            gtag('event', 'begin_checkout', ecommerceData);
2718        } catch (err) {
2719            console.error("Errore GA4 begin_checkout:", err);
2720        }
2721        console.info("Evento begin_checkout inviato:", ecommerceData);
2722    } catch (error) {
2723        console.error("Errore push begin_checkout:", error);
2724    }
2725}
2726
2727async function purchase_event(currency="EUR") {
2728    /*items = [];
2729    total = 0;
2730    try {
2731        const cartData = await get_cart_ga();
2732        if(cartData){
2733            products = cartData.lista_prodotti;
2734            total = cartData.totale;
2735            for (let i = 0; i < products.length; i++) {
2736                var el = products[i];
2737                el_obj = el['obj']
2738                name = el_obj['nome'];
2739                item = {'item_id' :  el_obj['id'], 'item_name': el_obj['nome']}
2740                items.push(item)}
2741        }
2742
2743    } catch (error) {
2744        console.error("Error to get cart:", error);
2745    }
2746
2747    try {
2748        gtag('event', 'purchase', {
2749            'currency': currency,
2750            'value': total,
2751            'items': items
2752        });
2753
2754    } catch (error) {
2755        console.log(error)
2756    }*/
2757    }
2758
2759
2760
2761async function add_shipping_info_event(currency="EUR") {
2762    items = [];
2763    total = 0;
2764    try {
2765        const cartData = await get_cart_ga();
2766        if(cartData){
2767            products = cartData.lista_prodotti;
2768            total = cartData.totale;
2769            for (let i = 0; i < products.length; i++) {
2770                var el = products[i];
2771                el_obj = el['obj']
2772                // name = el_obj['nome'];
2773                item = {'item_id' :  el_obj['id'], 'item_name': el_obj['nome']}
2774                items.push(item)
2775            }
2776        }
2777
2778    } catch (error) {
2779        console.error("Error to get cart:", error);
2780    }
2781
2782    try {
2783        // gtag('event', 'add_shipping_info', {
2784        //     'currency': currency,
2785        //     'value': total,
2786        //     'items': items
2787        // });
2788        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
2789        dataLayer.push({
2790            event: "add_shipping_info",
2791            ecommerce: {
2792                currency: currency,
2793                value: total,
2794                items: items
2795            }
2796        });
2797
2798    } catch (error) {
2799        console.log(error)
2800    }
2801}
2802
2803
2804
2805async function add_payment_info_event(payment_type = "Carta di credito", currency = "EUR") {
2806    let items = [];
2807    let total = 0;
2808
2809    try {
2810        const cartData = await get_cart_ga();
2811        if (cartData && cartData.lista_prodotti && Array.isArray(cartData.lista_prodotti)) {
2812            const products = cartData.lista_prodotti;
2813            total = parseFloat(cartData.totale) || 0;
2814
2815            for (let i = 0; i < products.length; i++) {
2816                const el = products[i];
2817                const obj = el.obj;
2818
2819                const item = {
2820                    item_id: obj.id,
2821                    item_name: obj.nome,
2822                    item_brand: obj.marca || '',
2823                    item_category: obj.full_path_name ?
2824                        (obj.full_path_name.includes("/") ?
2825                            obj.full_path_name.split("/").pop().trim() :
2826                            obj.full_path_name.trim()) : '',
2827                    price: parseFloat(el.prezzo) || 0,
2828                    quantity: parseInt(el.quantita) || 1
2829                };
2830
2831                items.push(item);
2832            }
2833        }
2834    } catch (error) {
2835        console.error("Errore nel recupero del carrello:", error);
2836    }
2837
2838    try {
2839        const ecommerceData = {
2840            currency: currency,
2841            value: total,
2842            payment_type: payment_type,
2843            items: items
2844        };
2845
2846        dataLayer.push({ ecommerce: null });
2847        dataLayer.push({
2848            event: "add_payment_info",
2849            ecommerce: ecommerceData
2850        });
2851
2852        try {
2853            gtag('event', 'add_payment_info', ecommerceData);
2854        } catch (err) {
2855            console.error("Errore GA4 add_payment_info:", err);
2856        }
2857
2858        console.info("Evento add_payment_info inviato:", ecommerceData);
2859    } catch (error) {
2860        console.error("Errore push add_payment_info:", error);
2861    }
2862}
2863
2864
2865function get_cart_ga(full = false) {
2866    var values = {
2867        api: true,
2868        act: 'get_cart'
2869    };
2870    if (full) {
2871        values['act'] = 'get_cart_full';
2872    }
2873    return new Promise(function(resolve, reject) {
2874        $.ajax({
2875            url: "index.php",
2876            method: "post",
2877            data: values,
2878            async: true,
2879            success: function(response) {
2880                if (response) {
2881                    resolve(response);
2882                } else {
2883                    reject("No response");
2884                }
2885            },
2886            error: function(jqXHR, textStatus, errorThrown) {
2887                console.log(textStatus, errorThrown);
2888                reject(errorThrown);
2889            }
2890        });
2891    });
2892}
2893
2894
2895
2896
2897
2898
2899function evento_aggiunta_carrello(id = null, quantita = 1, categoria = 'Generica', subtotale = 0, sku = '', carrello = null, prodotto = null) {
2900    quantita = Math.max(0, parseInt(quantita) || 0);
2901
2902    function ottieniProdottiTracciati() {
2903        return JSON.parse(sessionStorage.getItem('prodotti_tracciati_carrello') || '{}');
2904    }
2905
2906    function salvaProdottiTracciati(obj) {
2907        sessionStorage.setItem('prodotti_tracciati_carrello', JSON.stringify(obj));
2908    }
2909
2910    function inviaAggiuntaCarrello(item, quantita) {
2911        const p = item.obj || item;
2912        const dati = {
2913            event: 'add_to_cart',
2914            ecommerce: {
2915                currency: 'EUR',
2916                value: parseFloat(p.prezzo) * quantita,
2917                items: [{
2918                    item_id: p.id ? p.id.toString() : '',
2919                    item_name: p.nome,
2920                    item_brand: p.marca,
2921                    item_category: (p.full_path_name && typeof p.full_path_name === 'string') ?
2922                        (p.full_path_name.includes("/") ?
2923                            p.full_path_name.split("/").pop().trim() :
2924                            p.full_path_name.trim()) :
2925                        categoria.trim(),
2926                    price: parseFloat(p.prezzo) || 0,
2927                    quantity: quantita
2928                }]
2929            }
2930        };
2931        dataLayer.push({ ecommerce: null });
2932        dataLayer.push(dati);
2933        // gtag('event', 'add_to_cart', dati.ecommerce);
2934        console.info('Aggiunta tracciata:', p.nome, '(+' + quantita + ')');
2935    }
2936
2937    function inviaRimozioneCarrello(item, quantitaRimossa) {
2938        const p = item.obj || item;
2939        const dati = {
2940            event: 'remove_from_cart',
2941            ecommerce: {
2942                currency: 'EUR',
2943                items: [{
2944                    item_id: p.id ? p.id.toString() : '',
2945                    item_name: p.nome || ('Prodotto ' + (p.id || '')),
2946                    item_brand: p.marca || '',
2947                    item_category: (p.full_path_name && typeof p.full_path_name === 'string') ?
2948                        (p.full_path_name.includes("/") ?
2949                            p.full_path_name.split("/").pop().trim() :
2950                            p.full_path_name.trim()) :
2951                        (categoria ? categoria.trim() : 'Generica'),
2952                    price: parseFloat(p.prezzo) || 0,
2953                    quantity: quantitaRimossa
2954                }]
2955            }
2956        };
2957        dataLayer.push({ ecommerce: null });
2958        dataLayer.push(dati);
2959        // gtag('event', 'remove_from_cart', dati.ecommerce);
2960        console.info('Rimozione tracciata:', p.nome || p.id, '(-' 
2960+ quantitaRimossa + ')');
2961    }
2962
2963    try {
2964        const tracciati = ottieniProdottiTracciati();
2965        const stato_corrente = {};
2966
2967        if (carrello && carrello.lista_prodotti && Array.isArray(carrello.lista_prodotti)) {
2968            carrello.lista_prodotti.forEach(p => {
2969                stato_corrente[p.obj.id] = {
2970                    quantita: parseInt(p.quantita) || 0,
2971                    nome: p.obj.nome,
2972                    marca: p.obj.marca,
2973                    prezzo: parseFloat(p.prezzo),
2974                    full_path_name: p.obj.full_path_name
2975                };
2976            });
2977
2978            for (const idProdotto in stato_corrente) {
2979                const datiCorrenti = stato_corrente[idProdotto];
2980                const datiPrecedenti = tracciati[idProdotto];
2981                const nuovaQty = datiCorrenti.quantita;
2982                const precedenteQty = datiPrecedenti ? datiPrecedenti.quantita : 0;
2983
2984                if (nuovaQty > precedenteQty) {
2985                    inviaAggiuntaCarrello(carrello.lista_prodotti.find(p => p.obj.id == idProdotto), nuovaQty - precedenteQty);
2986                } else if (nuovaQty < precedenteQty) {
2987                    inviaRimozioneCarrello(carrello.lista_prodotti.find(p => p.obj.id == idProdotto), precedenteQty - nuovaQty);
2988                }
2989            }
2990
2991            for (const idTracciato in tracciati) {
2992                if (!(idTracciato in stato_corrente)) {
2993                    const datiRimossi = tracciati[idTracciato];
2994                    inviaRimozioneCarrello({ obj: datiRimossi }, datiRimossi.quantita);
2995                }
2996            }
2997
2998            salvaProdottiTracciati(stato_corrente);
2999        } else if (prodotto) {
3000            inviaAggiuntaCarrello({ obj: prodotto }, quantita);
3001            const nuovo = ottieniProdottiTracciati();
3002            nuovo[prodotto.id] = {
3003                quantita: (nuovo[prodotto.id] && nuovo[prodotto.id].quantita ? nuovo[prodotto.id].quantita : 0) + quantita,
3004                nome: prodotto.nome,
3005                marca: prodotto.marca,
3006                prezzo: prodotto.prezzo,
3007                full_path_name: prodotto.full_path_name
3008            };
3009            salvaProdottiTracciati(nuovo);
3010        } else if (id && subtotale) {
3011            const temp = { obj: { id: id, nome: 'Prodotto ' + id, prezzo: subtotale, full_path_name: categoria } };
3012            inviaAggiuntaCarrello(temp, quantita);
3013            const nuovo = ottieniProdottiTracciati();
3014            nuovo[id] = {
3015                quantita: (nuovo[id] && nuovo[id].quantita ? nuovo[id].quantita : 0) + quantita,
3016                nome: temp.obj.nome,
3017                marca: '',
3018                prezzo: temp.obj.prezzo,
3019                full_path_name: temp.obj.full_path_name
3020            };
3021            salvaProdottiTracciati(nuovo);
3022        }
3023    } catch (error) {
3024        console.error('Errore globale evento_aggiunta_carrello:', error);
3025    }
3026}
3027
3028
3029
3030
3031
3032function tracking_view_event(prodotto = false, page = false) {
3033
3034    // --- Facebook Pixel ---
3035    try {
3036        fbq('track', 'PageView');
3037    } catch (error) {
3038        console.error('Errore Facebook Pixel:', error);
3039    }
3040
3041    // --- Google Analytics 4 ---
3042    try {
3043        gtag('event', 'page_view', {
3044            page_title: document.title,
3045            page_path: window.location.pathname,
3046            page_location: window.location.href
3047        });
3048    } catch (error) {
3049        console.error('Errore GA4 page_view:', error);
3050    }
3051
3052    // --- dataLayer E-commerce (lasciato invariato) ---
3053    try {
3054        if (prodotto) {
3055            dataLayer.push({ ecommerce: null }); // Pulisce il precedente ecommerce object.
3056
3057            var push_data = {
3058                'event': 'visualizzazione_prodotto_event',
3059                'ecommerce': {
3060                    'detail': {
3061                        'products': [{
3062                            'product_ID': prodotto['sku'],
3063                            'productID': prodotto['id'],
3064                            'name': localStorage.getItem('prodotto_nome'),
3065                            'category': localStorage.getItem('categoria_name'),
3066                            'price': prodotto['prezzo'],
3067                            'qty': 1
3068                        }]
3069                    }
3070                }
3071            };
3072            dataLayer.push(push_data);
3073            var push_data = {
3074                'event': 'view_item',
3075                'ecommerce': {
3076                    'value': prodotto['prezzo'],
3077                    'currency': 'EUR',
3078                    'items': [{
3079                        'item_name': prodotto['nome'],
3080                        'item_id': prodotto['id'],
3081                        'price': prodotto['prezzo'],
3082                        'item_brand': prodotto['marca'],
3083                        'item_category': prodotto['full_path_name'].includes("/") ? prodotto['full_path_name'].split("/").pop().trim() : prodotto['full_path_name'].trim(),
3084                        'quantity': 1
3085                    }]
3086                }
3087            }
3088
3089
3090            console.info('Tracciamento prodotto:', push_data);
3091            dataLayer.push(push_data);
3092
3093        }
3094    } catch (error) {
3095        console.error('Errore dataLayer E-commerce:', error);
3096    }
3097}
3098
3099
3100

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.