PageSourceSearch

https://cannaprovisions.com/wp-content/plugins/leafbridge/public/j…?ver=2026.10.08.09.09.46

js cannaprovisions.com collected 2026-10-08 21:10:34 UTC 279,364 bytes, 6,421 lines download raw bytes

1(function ($) {
2  "use strict";
3
4  function build_nearby_locations_urls(passed_url, urlattribute, attrvalue) {
5    let url_pattern = /^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(:[0-9]+)?(\/[\w-]*)*(\?.*)?(#.*)?$/i;
6
7    if (url_pattern.test(passed_url)) {
8      const location_page_url = new URL(passed_url.includes("http") ? passed_url : `https://${passed_url}`);
9      location_page_url.searchParams.set(urlattribute, attrvalue);
10      return location_page_url.toString();
11    }
12    else {
13      return '';
14    }
15
16  }
17  //nearby retailer locations
18  function gmaps_store_locator_func() {
19    $('.leafbridge-address-input').each(function () {
20      const $input = $(this);
21      const autocomplete = new google.maps.places.Autocomplete(this, {
22        fields: ['formatted_address', 'geometry']
23      });
24  
25      function showNoRetailersMessage(message = 'No retailers found for this location.') {
26        $('.leafbridge-address-output').html(`<p class="no-retailers-message">${message}</p>`);
27      }
28  
29      function handleRetailerDisplay(latitude = null, longitude = null, searchedZipCode = '') {
30        $('.leafbridge-address-output').html('<p>Searching for retailers...</p>');
31  
32        $.ajax({
33          url: leafbridge_public_ajax_obj.ajaxurl,
34          dataType: "json",
35          cache: false,
36          type: "POST",
37          processData: true,
38          data: {
39            action: 'leafbridge_nearby_retailers',
40            latitude: latitude,
41            longitude: longitude,
42          },
43          success: function (response) {
44            let nearbyRetailers = [];
45            let retailer_pages = {};
46  
47            if (response.success && (response.data.retailer_pages != false)) {
48              var display_retailer_names = response.data.retailer_custom_names;
49
50              // Always use synced retailers as a base
51              nearbyRetailers = Object.values(response.data.synced_retailers)
52                .sort((a, b) => a.name.localeCompare(b.name))
53                .map(retailer => ({
54                  retailer: retailer
55                }));
56  
57              // If coordinates were provided but no nearby retailers found
58              if (latitude && longitude && (!response.data.nearby_retailers || response.data.nearby_retailers.length === 0)) {
59                showNoRetailersMessage();
60                return;
61              }
62  
63              // If nearby retailers are present, replace the list
64              if (response.data.nearby_retailers) {
65                nearbyRetailers = response.data.nearby_retailers.map(item => ({
66                  retailer: item.retailer
67                }));
68              }
69  
70              retailer_pages = response.data.retailer_pages || {};
71            } else {
72              showNoRetailersMessage();
73              return;
74            }
75  
76            // Filter retailers based on fulfillment options
77            const pickupRetailers = nearbyRetailers.filter(
78              item => item.retailer.fulfillmentOptions.pickup
79            );
80  
81            const deliveryRetailers = nearbyRetailers.filter(item => {
82              const retailer = item.retailer;
83              const hasDelivery = retailer.fulfillmentOptions.delivery;
84              
85              if (!hasDelivery) return false;
86            
87              if (!searchedZipCode || !retailer.deliverySettings?.postalCodes?.length) {
88                return true;
89              }
90            
91              const deliveryZipCodes = retailer.deliverySettings.postalCodes;
92              return deliveryZipCodes.some(zipObj => zipObj.postalCode === searchedZipCode);
93            });
94  
95            // If no retailers found in either category after filtering
96            if (pickupRetailers.length === 0 && deliveryRetailers.length === 0) {
97              showNoRetailersMessage();
98              return;
99            }
100  
101            // tabs container
102            let tabsHtml = `
103              <div class="retailers-tabs">
104                <div class="tab-buttons">
105                  <button class="tab-btn active" data-tab="pickup">
106                    Pickup (${pickupRetailers.length})
107                  </button>
108                  <button class="tab-btn" data-tab="delivery">
109                    Delivery (${deliveryRetailers.length})
110                  </button>
111                </div>
112                <div class="tab-content">
113                  <div class="tab-pane pickup active"></div>
114                  <div class="tab-pane delivery"></div>
115                </div>
116              </div>
117            `;
118  
119            $('.leafbridge-address-output').html(tabsHtml);
120
121            // retailer HTML
122            const generateRetailerHtml = (retailers, col_type) => {
123              if (retailers.length === 0) {
124                return '<p>No retailers available for this option.</p>';
125              }
126
127              let retailerHtml = '<div class="retailers-list">';
128
129              retailers.forEach(item => {
130                const retailer = item.retailer;
131                const menuTypes = retailer.menuTypes;
132
133                let menuButtonsHtml = '';
134
135                // let med_ret_page = build_nearby_locations_urls(retailer_pages[retailer.id]['med'], 'collection_type', col_type);
136                // let rec_ret_page = build_nearby_locations_urls(retailer_pages[retailer.id]['rec'], 'collection_type', col_type);
137
138                let med_ret_page_dl = (typeof retailer_pages[retailer.id]['medDelivery'] != 'undefined') ? retailer_pages[retailer.id]['medDelivery'] : '';
139                let med_ret_page_pk = (typeof retailer_pages[retailer.id]['medPickup'] != 'undefined') ? retailer_pages[retailer.id]['medPickup'] : '';
140                let rec_ret_page_dl = (typeof retailer_pages[retailer.id]['recDelivery'] != 'undefined') ? retailer_pages[retailer.id]['recDelivery'] : '';
141                let rec_ret_page_pk = (typeof retailer_pages[retailer.id]['recPickup'] != 'undefined') ? retailer_pages[retailer.id]['recPickup'] : '';
142                let info_ret_page = (typeof retailer_pages[retailer.id]['info-page'] != 'undefined') ? retailer_pages[retailer.id]['info-page'] : '';
143
144                let med_ret_page = (col_type == 'DELIVERY') ? med_ret_page_dl : med_ret_page_pk;
145                let rec_ret_page = (col_type == 'DELIVERY') ? rec_ret_page_dl : rec_ret_page_pk;
146
147                if (menuTypes.includes('MEDICAL') && menuTypes.includes('RECREATIONAL')) {
148                  menuButtonsHtml = `
149                    <button class="shop-now-btn medical-btn" data-menu-type="MEDICAL" data-retailer-id="${retailer.id}"  data_link_a="${med_ret_page}"><a href="${med_ret_page}">Shop Medical</a></button>
150                    <button class="shop-now-btn recreational-btn" data-menu-type="RECREATIONAL" data-retailer-id="${retailer.id}"  data_link_a="${rec_ret_page}"><a href="${rec_ret_page}">Shop Recreational</a></button>
151                  `;
152                } else if (menuTypes.includes('MEDICAL')) {
153                  menuButtonsHtml = `
154                    <button class="shop-now-btn medical-btn" data-menu-type="MEDICAL" data-retailer-id="${retailer.id}"  data_link_a="${med_ret_page}"><a href="${med_ret_page}">Shop Medical</a></button>
155                  `;
156                } else if (menuTypes.includes('RECREATIONAL')) {
157                  menuButtonsHtml = `
158                    <button class="shop-now-btn recreational-btn" data-menu-type="RECREATIONAL" data-retailer-id="${retailer.id}"  data_link_a="${rec_ret_page}"><a href="${rec_ret_page}">Shop Recreational</a></button>
159                  `;
160                }
161
162                var display_name = ((display_retailer_names[retailer.id]) || (display_retailer_names[retailer.id] != '')) ? display_retailer_names[retailer.id] : retailer.name;
163              
164                retailerHtml += `
165                  <div class="retailer-item">
166                    <h3 class="retailer-name">${display_name}</h3>
167                    <div class="retailer-address">${retailer.address}</div>
168                    <div class="retailer-phone">${retailer.phone}</div>
169                    <div class="retailer-actions">
170                      ${menuButtonsHtml}
171                      <button class="store-info-btn" data-retailer-id="${retailer.id}" data_link_a="${info_ret_page}"><a href="${info_ret_page}">Store Info</a></button>
172                    </div>
173                  </div>
174                `;
175              });
176
177              return retailerHtml + '</div>';
178            };
179
180            // content for each tab
181            $('.pickup').html(generateRetailerHtml(pickupRetailers, 'PICKUP'));
182            $('.delivery').html(generateRetailerHtml(deliveryRetailers, 'DELIVERY'));
183          },
184          error: function (error) {
185            console.error('API Error:', error);
186            showNoRetailersMessage('Error searching for retailers. Please try again.');
187          }
188        });
189      }
190
191      // Initial load of all retailers
192      handleRetailerDisplay();
193
194      // Reset to all retailers if input is cleared
195      $input.on('input', function () {
196        if ($(this).val().trim() === '') {
197          handleRetailerDisplay();
198        }
199      });
200
201  // Handle location autocomplete
202  autocomplete.addListener('place_changed', function () {
203    const place = autocomplete.getPlace();
204
205    if (!place.geometry?.location) {
206      showNoRetailersMessage('Invalid location selected. Please try again.');
207      return;
208    }
209
210    const latitude = place.geometry.location.lat();
211    const longitude = place.geometry.location.lng();
212
213    const geocoder = new google.maps.Geocoder();
214    geocoder.geocode({ location: { lat: latitude, lng: longitude } }, function (results, status) {
215      if (status === 'OK' && results[0]) {
216        let zipCode = '';
217        results[0].address_components.forEach(component => {
218          if (component.types.includes('postal_code')) {
219            zipCode = component.long_name;
220          }
221        });
222        handleRetailerDisplay(latitude, longitude, zipCode);
223      } else {
224        // console.error('Geocoding failed:', status);
225        handleRetailerDisplay(latitude, longitude);
226      }
227    });
228  });
229  });
230  }
231
232  function render_retailer_banner_content(){
233
234  }
235
236  // Tab switching
237  $(document).on('click', '.leafbridge-address-output .tab-btn', function () {
238    $('.tab-btn').removeClass('active');
239    $('.tab-pane').removeClass('active');
240    $(this).addClass('active');
241    const tabClass = $(this).data('tab');
242    $(`.${tabClass}`).addClass('active');
243  });
244
245
246  /*
247   * Selecting retailer and update the next step based on retailer selection.
248   */
249  $(document).on("click", ".wizardbox_retailer_box button", function () {
250    var menu_type = $(".wizardbox_tab_head.leaf_bridge_btn.active_btn").attr("data_menu_type");
251    var data_retailer_id = $(this).attr("data_retailer_id");
252
253    $(".selected_retailer").removeClass("selected_retailer");
254    $(this).closest(".wizardbox_retailer_box").addClass("selected_retailer");
255
256    $(this).closest(".leafbridge_shop_wizard_step").find('.leaf_bridge_btn[data_direction="#leafbridge_shop_wizard_set_delivery"]').fadeIn("250");
257
258    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
259
260    if (leafbridge_wizard_data == null) {
261      var leafbridge_wizard_data = {
262        age_confirm: true,
263        created_time: new Date(),
264        collection_method: $(this).val(),
265        retailer_id: data_retailer_id,
266        menu_type: menu_type,
267      };
268    } else {
269      leafbridge_wizard_data.collection_method = $(this).val();
270      leafbridge_wizard_data.retailer_id = data_retailer_id;
271      leafbridge_wizard_data.menu_type = menu_type;
272    }
273    localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
274    set_delivery_pickup(data_retailer_id);
275  });
276
277  // ajax function associated with checking if retailer has pickup or deliver or both and
278  // make the ui depending the retailer
279  function set_delivery_pickup(retailer_id) {
280    var data = {
281      action: "show_delivery_pickup_ajax",
282      retailer_id: retailer_id,
283      nonce_ajax: leafbridge_public_ajax_obj.nonce,
284    };
285
286    $.ajax({
287      url: leafbridge_public_ajax_obj.ajaxurl,
288      dataType: "json",
289      cache: false,
290      data: data,
291      type: "POST",
292      proccessData: false,
293      success: function (json) {
294        var capturehtml = json.data.returnHTML;
295        $(".product_collection").html(capturehtml);
296      },
297      error: function (json) {
298        $("#leafbridge_shop_wizard_set_location").find('button[data_direction="#leafbridge_shop_wizard_set_delivery"]').hide();
299        console.error("set_delivery_pickup err", json);
300      },
301      complete: function (json) { },
302    });
303  }
304
305  /*
306   * Validate ZIP CODE
307   */
308  $(document).on("click", "#wizardbox_zipcode_validation", function (event) {
309    event.preventDefault();
310    var wizardbox_zipcode = $("#wizardbox_zipcode").val();
311
312    var data = {
313      action: "delivery_validate_zip_code",
314      zipcode: wizardbox_zipcode,
315      nonce_ajax: leafbridge_public_ajax_obj.nonce,
316    };
317
318    $.ajax({
319      url: leafbridge_public_ajax_obj.ajaxurl,
320      dataType: "json",
321      cache: false,
322      data: data,
323      type: "POST",
324      proccessData: false,
325      success: function (json) { },
326      error: function (json) {
327        $(".error_zip_validation").fadeIn();
328      },
329      complete: function (json) { },
330    });
331  });
332
333  // Recently viewed items click events
334  $(document).on("click", ".leafbridge_product_modal_add_to_cart button, .open_prod_modal, .product_popup_enabled", function (e) {
335    e.preventDefault();
336    e.stopPropagation();
337
338    if (!$(this).hasClass('prod_page_add_to_cart')) {
339      var productCard = e.target.closest('.leafbridge_product_card');
340    }
341    else {
342      var productCard = e.target.closest('.lb_prod_single_add_to_cart');
343    }
344
345    var filterData = null;
346    try {
347      filterData = productCard.getAttribute('filter_data');
348    }
349    catch (err) {
350      console.error('trying to add product to recents from popup',err);
351      var temp_prod_id = $(this).closest('.leafbridge_product_modal_add_to_cart').attr('data_product_id');
352      var temp_productCard = $('.leafbridge_product_card[data_product_id="' + temp_prod_id + '"]').html();
353
354      productCard = document.createElement('div');
355      productCard.innerHTML = temp_productCard;
356      filterData = $('.leafbridge_product_card[data_product_id="' + temp_prod_id + '"]').attr('filter_data');
357    }
358
359    const productData = JSON.parse(filterData);
360    const name = productData.item_name;
361    const brand = productData.brand_name;
362
363    if (!$(this).hasClass('prod_page_add_to_cart')) {
364      var image = productCard.querySelector('.lb_prod_card_thumb').src;
365      var productLink = productCard.querySelector('.leafbridge_product_name a').href;
366    }
367    else {
368      var image = $('.lb_prod_single_img').find('.swiper-slide.swiper-slide-active img').attr('src');
369      var productLink = window.location.href;
370    }
371
372    const retailerId = productCard.getAttribute('data_retailer_id');
373    const productId = productCard.getAttribute('data_product_id');
374
375    const variants = productData.variants;
376
377    const variantDetails = variants.map(variant => ({
378      priceMed: variant.priceMed,
379      priceRec: variant.priceRec,
380      specialPriceMed: variant.specialPriceMed,
381      specialPriceRec: variant.specialPriceRec,
382      quantity: variant.quantity
383    }));
384
385    // Create a product object to store in localStorage
386    const viewedProduct = {
387      retailerId: retailerId,
388      productId: productId,
389      image: image,
390      name: name,
391      brand: brand,
392      productLink: productLink,
393      variants: variantDetails
394    };
395
396    var recentlyViewed = JSON.parse(localStorage.getItem("recently_viewed_products")) || {};
397
398    if (!recentlyViewed[viewedProduct.retailerId]) {
399      recentlyViewed[viewedProduct.retailerId] = [];
400    }
401
402    var existingProductIndex = recentlyViewed[viewedProduct.retailerId].findIndex(p => p.productId === viewedProduct.productId);
403
404    if (existingProductIndex !== -1) {
405      var existingProduct = recentlyViewed[viewedProduct.retailerId].splice(existingProductIndex, 1)[0];
406      recentlyViewed[viewedProduct.retailerId].push(existingProduct);
407    } else {
408      if (recentlyViewed[viewedProduct.retailerId].length >= 10) {
409        recentlyViewed[viewedProduct.retailerId].shift();
410      }
411      recentlyViewed[viewedProduct.retailerId].push(viewedProduct);
412    }
413
414    localStorage.setItem("recently_viewed_products", JSON.stringify(recentlyViewed));
415  });
416
417  // show pre filtered products
418  function show_prefiltered_products() {
419    var $wizardWrapper = $('.leafbridge_shop_wizard_wrapper');
420    var categoryFromShortcode = $wizardWrapper.attr('data-category');
421    var subcategoryFromShortcode = $wizardWrapper.data('subcategory');
422    var effectFromShortcode = $wizardWrapper.data('effect');
423    var brandFromShortcode = $wizardWrapper.data('brand');
424    var tagFromShortcode = $wizardWrapper.data('tag');
425    var strainTypeFromShortcode = $wizardWrapper.data('straintype');
426    var menuSectionFiltereFromShortcode = $wizardWrapper.data('menusectionfilter');
427
428    function capitalizeWords(string) {
429      return string.replace(/_/g, ' ').toLowerCase().split(' ').map(function (word) {
430        return word.charAt(0).toUpperCase() + word.slice(1);
431      }).join(' ');
432    }
433
434    // Function to apply filter
435    function applyFilter(filterType, filterValue) {
436      if (filterValue) {
437        var filterSelector = ".lb_prod_filter_attr_box[filter_attr='" + filterType + "'] ul li[attr_value='" + filterValue.toUpperCase() + "']";
438        $(filterSelector).trigger('click').addClass('selected');
439        $(".lb_prod_filter_attr_box[filter_attr='" + filterType + "']").addClass('attr_set');
440      }
441    }
442
443    // Apply filters from shortcode
444    applyFilter('effects', effectFromShortcode);
445    applyFilter('strainType', strainTypeFromShortcode);
446    applyFilter('MenuSectionFilter', menuSectionFiltereFromShortcode);
447
448    // if (brandFromShortcode) {
449    //   var brand = capitalizeWords(brandFromShortcode);
450
451    //   $(".lb_prod_filter_attr_box[filter_attr='brands'] ul li")
452    //     .find('span:contains("' + brand + '")')
453    //     .closest('li')
454    //     .trigger('click')
455    //     .addClass('selected');
456    //   $(".lb_prod_filter_attr_box[filter_attr='brands']").addClass('attr_set');
457    // } 
458
459    // Retrieve retailer_id from local storage
460    var retailerId = JSON.parse(localStorage.getItem('leafbridge_wizard_data'))?.retailer_id;
461
462    // Apply brand filter if provided
463    if (brandFromShortcode && retailerId) {
464      var brand = capitalizeWords(brandFromShortcode);
465
466      // Filter for the exact brand and retailer_id
467      $(".lb_prod_filter_attr_box[filter_attr='brands'] ul li").filter(function () {
468          return $(this).find('span').text().trim() === brand &&
469            $(this).attr('brand_retailer') === retailerId;
470       }).trigger('click')
471      $(".lb_prod_filter_attr_box[filter_attr='brands']").addClass('attr_set');
472    }
473
474    if (categoryFromShortcode) {
475      try {
476          var categoriesArray = JSON.parse(categoryFromShortcode);
477          categoriesArray.forEach(function (category) {
478              applyFilter('categories', category.trim().toUpperCase());
479          });
480      } catch (e) {
481          console.error("Error parsing category data:", e);
482      }
483    }
484
485      if (subcategoryFromShortcode) {
486        $(".lb_prod_filter_attr_box[filter_attr='subcategory']").removeClass('hidden-filter');
487        applyFilter('subcategory', subcategoryFromShortcode);
488    }
489
490    if (tagFromShortcode) {
491      var tag = capitalizeWords(tagFromShortcode);
492      var filterSelector = ".lb_prod_filter_attr_box[filter_attr='POS_Tags'] ul li[attr_value='" + tag + "']";
493      $(filterSelector).trigger('click').addClass('selected');
494      $(".lb_prod_filter_attr_box[filter_attr='POS_Tags']").addClass('attr_set');
495    }
496  }
497
498  // new show products on store page
499  function show_products_from_filter() {
500    $("#leafbridge_shop_wizard_view_products").show();
501    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
502
503    // override leafbridge_wizard_data if it's empty or in retailer_based_store
504    if ($("div").hasClass("retailer_based_store")) {
505      leafbridge_wizard_data = {
506        retailer_id: $(".retailer_based_store").attr("retailer_id"),
507        menu_type: $(".retailer_based_store").attr("menu_type"),
508        collection_method: $(".retailer_based_store").attr("order_type"),
509      };
510    }
511    var force_wizard = $("div").hasClass("retailer_based_store") ? $(".retailer_based_store").attr("force_wizard") : $(".retailer_based_store").attr("force_wizard") ? "off" : "off";
512
513    // var selected_retailer = (leafbridge_wizard_data) ? leafbridge_wizard_data.retailer_id : false;
514    var selected_retailer = $("div").hasClass("retailer_based_store") ? $(".retailer_based_store").attr("retailer_id") : leafbridge_wizard_data ? leafbridge_wizard_data.retailer_id : false;
515    var selected_menu_type = $("div").hasClass("retailer_based_store") ? $(".retailer_based_store").attr("menu_type") : leafbridge_wizard_data ? leafbridge_wizard_data.menu_type : false;
516
517    selected_menu_type = selected_menu_type == "" ? leafbridge_wizard_data.menu_type : selected_menu_type;
518
519    if (selected_retailer) {
520      //  hide brands from other retailers
521      $("ul#prods_brands li").hide();
522      $("ul#prods_brands li").removeClass("show_brand");
523      $("ul#prods_brands li[brand_retailer=" + selected_retailer + "]").show();
524      $("ul#prods_brands li[brand_retailer=" + selected_retailer + "]").addClass("show_brand");
525
526      // hide weight from other retailers
527      // $(".weight_retailer").hide();
528      $('li.shop_filter_weights').hide();
529      if (selected_menu_type) {
530        $('li.shop_filter_weights').each(function(index,el){
531          var this_li = $(this);
532          var weight_cats = JSON.parse(this_li.attr('data_weight_cats'));
533          var weight_retailers = JSON.parse(this_li.attr('data_weight_retailers'));
534          var weight_menu_type = JSON.parse(this_li.attr('data_weight_menu_type'));
535
536          // selected_menu_type
537          // selected_retailer
538
539          // if( weight_retailers.includes(selected_retailer) && weight_menu_type.includes(selected_menu_type)){
540          //   this_li.show();
541          // }
542          if( weight_retailers.includes(selected_retailer) && weight_menu_type.includes(selected_menu_type)){
543            this_li.show();
544          }
545        })
546      }
547
548      // hide pos cats from other retailers
549      $("ul#prods_POS_cats li").hide();
550      $("ul#prods_POS_cats li").removeClass("show_brand");
551      $("ul#prods_POS_cats li[tag_retailer=" + selected_retailer + "]").show();
552      $("ul#prods_POS_cats li[tag_retailer=" + selected_retailer + "]").addClass("show_brand");
553
554      // hide pos tags from other retailers
555      $("ul#prods_POS_Tags li").hide();
556      $("ul#prods_POS_Tags li").removeClass("show_brand");
557      $("ul#prods_POS_Tags li[tag_retailer=" + selected_retailer + "]").show();
558      $("ul#prods_POS_Tags li[tag_retailer=" + selected_retailer + "]").addClass("show_brand");
559    }
560
561    var searchParams = new URLSearchParams(window.location.search);
562    var pagination = searchParams.get("pagination") ? parseInt(searchParams.get("pagination")) : 1;
563    var params_counter = 0;
564
565    searchParams.forEach((value, key) => {
566      params_counter++;
567    });
568
569    $("#leafbridge_products_sort_by").val() == null ? $("#leafbridge_products_sort_by").val("NAME_ASC") : "";
570
571    if (leafbridge_wizard_data) {
572      searchParams.forEach((search_attr_val, search_attr) => {
573
574        if (search_attr == "brands") {
575          var selected_brands_array = search_attr_val.split(",").map((item) => item.replace(/["\\]/g, ""));
576
577          selected_brands_array.forEach((item, index) => {
578            var li_slctd = $(".lb_prod_filter_attr_box[filter_attr=" + search_attr + "] ul").find('li[attr_value="' + item + '"][brand_retailer="' + leafbridge_wizard_data.retailer_id + '"]');
579            li_slctd.trigger("click");
580            li_slctd.addClass("selected");
581          });
582
583          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]").addClass("attr_set");
584        }
585        else if (search_attr == "categories" || search_attr == "subcategory" || search_attr == "strainType" || search_attr == "effects" || search_attr == "POS_Tags" || search_attr == "POS_Categories" || search_attr == "MenuSectionFilter") {
586          var selected_brands_array = search_attr_val.split(",").map((item) => item.replace(/["\\]/g, ""));
587
588          selected_brands_array.forEach((item, index) => {
589            var li_slctd = $(".lb_prod_filter_attr_box[filter_attr=" + search_attr + "] ul").find('li[attr_value="' + item + '"]');
590            li_slctd.trigger("click");
591            li_slctd.addClass("selected");
592          });
593          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]").addClass("attr_set");
594        }
595
596        // set potency_cbd
597        else if (search_attr == "potency_cbd") {
598          var split_search_attr_val = search_attr_val.split("_");
599          var metric = split_search_attr_val[2] == "%" ? "percentage" : split_search_attr_val[2];
600
601          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]")
602            .find("select")
603            .val(split_search_attr_val[2])
604            .trigger("change"); //selects metric dropdown
605          $("#prods_cbd_" + metric + "_min")
606            .val(split_search_attr_val[0])
607            .trigger("input"); //set min value
608          $("#prods_cbd_" + metric + "_max")
609            .val(split_search_attr_val[1])
610            .trigger("input"); //set max value
611
612          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]").addClass("attr_set");
613        }
614
615        // set potency_thc
616        else if (search_attr == "potency_thc") {
617          var split_search_attr_val = search_attr_val.split("_");
618          var metric = split_search_attr_val[2] == "%" ? "percentage" : split_search_attr_val[2];
619          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]")
620            .find("select")
621            .val(split_search_attr_val[2])
622            .trigger("change"); //selects metric dropdown
623          $("#prods_thc_" + metric + "_min")
624            .val(split_search_attr_val[0])
625            .trigger("input"); //set min value
626          $("#prods_thc_" + metric + "_max")
627            .val(split_search_attr_val[1])
628            .trigger("input"); //set max value
629
630          $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]").addClass("attr_set");
631        }
632
633        // set search keyword
634        else if (search_attr == "products_search") {
635          $("#products_search_input").val(search_attr_val).trigger("input");
636        }
637
638        // set filter weight
639        else if (search_attr == "weight") {
640          $('.shop_filter_weights[attr_value="'+search_attr_val+'"]').trigger('click');
641        }
642        else if (search_attr == "sort") {
643          
644        }
645        else {
646          if (search_attr != "brands") {
647            //temp fix for triggering brands here
648            $(".lb_prod_filter_attr_box[filter_attr=" + search_attr + "] ul").find('li[attr_value="' + search_attr_val + '"]');
649            // .trigger("click");
650            $(".lb_prod_filter_attr_box[filter_attr=" + search_attr + "] ul")
651              .find('li[attr_value="' + search_attr_val + '"]')
652              .addClass("selected");
653            $(".lb_prod_filter_attr_box[filter_attr=" + search_attr.toLowerCase() + "]").addClass("attr_set");
654
655            if (search_attr == "POS_Categories") {
656              $(".lb_prod_filter_attr_box[filter_attr=prods_POS_cats]").addClass("attr_set");
657            }
658            if (search_attr == "POS_Tags") {
659              $(".lb_prod_filter_attr_box[filter_attr=prods_POS_Tags]").addClass("attr_set");
660            }
661          }
662        }
663
664      });
665
666      if (pagination == 1) {
667        $(".wizard_category_products_pagination button.prev").hide();
668        $(".wizard_category_products_pagination button.next").show();
669      }
670      else {
671        $(".wizard_category_products_pagination button.prev").show();
672        $(".wizard_category_products_pagination button.next").show();
673      }
674      $(".wizard_category_products_pagination button.next").attr("data_page", pagination + 1);
675      $(".wizard_category_products_pagination button.prev").attr("data_page", pagination - 1);
676
677      setTimeout(function () {
678        $(".lb_prod_filter_btn").first().trigger("click");
679      }, 100);
680    }
681    else {
682      // $('.leafbridge_shop_wizard_wrapper').html('<p>You are required to select retailer, Menutype and Collection opiton</p>');
683    }
684
685    hide_if_no_retailer_brands();
686  }
687
688  function hide_if_no_retailer_brands() {
689    // if ($("ul#prods_brands li.show_brand").length == 0) {
690    //   $('.lb_prod_filter_attr_box[filter_attr="brands"]').hide();
691    // }
692
693    // if ($("ul#prods_POS_Tags li.show_brand").length == 0) {
694    //   $('.lb_prod_filter_attr_box[filter_attr="POS_Tags"]').hide();
695    // }
696
697    // if ($("ul#prods_POS_cats li.show_brand").length == 0) {
698    //   $('.lb_prod_filter_attr_box[filter_attr="POS_Categories"]').hide();
699    // }
700  }
701
702  /*
703   * show products based on retailer selection - ajax
704   */
705  $(document).on("click", "#wizard_show_products", function () {
706    const urlParams = new URLSearchParams(window.location.search);
707    const param_pagination = parseInt(urlParams.get("pagination"));
708    const page_number = param_pagination ? param_pagination : 0;
709    const trigger_event = param_pagination ? "" : "initial";
710
711    var item_list_element = $(this);
712
713    if ($("div").hasClass("show_products_based_on_retailer")) {
714      show_products_from_filter();
715      location.reload();
716    }
717    get_featured_products_ajax();
718    single_prod_page_fetch();
719    show_category_products(item_list_element);
720    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
721  });
722
723  /*
724   * Show filtered results - Phase 2 function ! - start
725   */
726
727  // for selecting attributes
728  $(document).on("click", ".lb_prod_filter_attr_box ul li", function (event) {
729    var target_attr = $(this).closest(".lb_prod_filter_attr_box");
730    var attribute_val = $(this).attr("attr_value");
731    var ul_filter = $(this).closest("ul").attr("id");
732
733    if (ul_filter == "prods_brands" || ul_filter == "prods_categories" || ul_filter == "prods_strainType") {
734      if ($(this).hasClass("selected")) {
735        $(this).removeClass("selected");
736      } else {
737        $(this).addClass("selected");
738      }
739
740      var closest_ul = $(this).closest("ul");
741      var temp_values = "";
742      closest_ul.find("li.selected").each(function (item) {
743        var each_sLi = $(this);
744        var each_value = each_sLi.attr("attr_value");
745        temp_values += ul_filter == "prods_brands" ? '"' + each_value + '",' : each_value + ",";
746      });
747      target_attr.attr("filter_selected_val", temp_values);
748    } else {
749      $(this).siblings("li").removeClass("selected");
750      if ($(this).hasClass("selected")) {
751        $(this).removeClass("selected");
752        target_attr.attr("filter_selected_val", "");
753        target_attr.removeClass("attr_set");
754      } else {
755        $(this).addClass("selected");
756        target_attr.attr("filter_selected_val", attribute_val);
757        target_attr.addClass("attr_set");
758      }
759    }
760
761    $(this).closest(".lb_prod_filter_attr_box").addClass("attr_set");
762
763    updateSelectedAttributesDisplay();
764
765    setTimeout(function (attribute_val) {
766      $(".lb_prod_filter_btn").first().trigger("click");
767    }, 500);
768  });
769
770
771  // for typing attributes - multiple textboxes
772  $(document).on("input change keypress", ".lb_prod_filter_attr_range input", function (event) {
773    var target_attr = $(this).closest(".lb_prod_filter_attr_box");
774    var input_val = parseFloat($(this).val());
775    var sibling_val = parseFloat($(this).val());
776    var input_wrapper = $(this).closest(".lb_prod_filter_attr_range");
777    var prod_filter_ul_wrapper = $(this).closest(".prod_filter_ul_wrapper");
778    var this_input_id = $(this).attr("id");
779    var this_min = parseFloat($(this).attr("min"));
780    var this_max = parseFloat($(this).attr("max"));
781
782    var this_sibling_val = parseFloat($(this).siblings("input").val());
783
784    var step = parseFloat($(this).attr("step"));
785
786    // set default min max values if one field is not entered by mistake
787    if (!input_wrapper.attr("max_val")) {
788      input_wrapper.attr("max_val", $(this).attr("max"));
789    }
790    if (!input_wrapper.attr("min_val")) {
791      input_wrapper.attr("min_val", $(this).attr("min"));
792    }
793
794    // prepaer min max values to be sent to graphql and url params
795    if ($(this).attr("id").includes("min")) {
796      input_wrapper.attr("min_val", input_val);
797
798      if (input_val >= this_sibling_val) {
799        lb_range_error_label(prod_filter_ul_wrapper);
800      } else {
801        $(".lb_range_error_label").remove();
802      }
803    }
804
805    if ($(this).attr("id").includes("max")) {
806      input_wrapper.attr("max_val", input_val);
807      // do not entering value less than min amount
808      if (input_val <= this_sibling_val) {
809        lb_range_error_label(prod_filter_ul_wrapper);
810      } else {
811        $(".lb_range_error_label").remove();
812      }
813    }
814
815    if (input_val > this_max || input_val < this_min) {
816      lb_range_error_label(prod_filter_ul_wrapper);
817    } else {
818      // $(this).removeClass('lb_error');
819      $(".lb_range_error_label").remove();
820    }
821
822    var min_val = input_wrapper.attr("min_val");
823    var max_val = input_wrapper.attr("max_val");
824    var metric_ref = input_wrapper.attr("metric_ref");
825
826    $(this)
827      .closest(".lb_prod_filter_attr_box")
828      .attr("filter_selected_val", min_val + "_" + max_val + "_" + metric_ref);
829    $(this).closest(".lb_prod_filter_attr_box").addClass("attr_set");
830
831    setTimeout(function () {
832      $(".lb_prod_filter_btn").first().trigger("click");
833    }, 100);
834  });
835
836  $(document).on("click", ".set_filter_attr_range", function () {
837    setTimeout(function () {
838      $("#products_search_button").trigger("click"), 100;
839    });
840  });
841
842  // for typing attributes - single textbox
843  $(document).on("input change keypress", ".lb_prod_filter_attr_input input", function (e) {
844    var this_val = $(this).val();
845    this_val = this_val.replace("/", "%2F");
846    $(this).closest(".lb_prod_filter_attr_box").attr("filter_selected_val", this_val);
847    $(this).closest(".lb_prod_filter_attr_box").addClass("attr_set");
848
849    // trigger auto filter
850    setTimeout(function () {
851      $(".lb_prod_filter_btn").first().trigger("click");
852    }, 100);
853  });
854
855  function updateSelectedAttributesDisplay() {
856    var selectedAttributes = [];
857
858    $(".lb_prod_filter_attr_box").each(function () {
859      var selectedElements = $(this).find("li.selected");
860      var filterAttr = $(this).attr("filter_attr");
861
862      selectedElements.each(function () {
863        var spanText = $(this).find(".prod_cat_select_lable span").text().trim();
864        if (spanText) {
865          var displayText = spanText;
866          if (filterAttr === "potency_cbd") {
867            displayText = "CBD: " + spanText;
868          } else if (filterAttr === "potency_thc") {
869            displayText = "THC: " + spanText;
870          } else if (filterAttr === "weight") {
871            displayText = "Weight: " + spanText;
872          }
873          var isDuplicate = selectedAttributes.some(function (attr) {
874            return attr.text === displayText && attr.filterAttr === filterAttr;
875          });
876
877          if (!isDuplicate) {
878            selectedAttributes.push({
879              text: displayText,
880              element: $(this),
881              filterAttr: filterAttr
882            });
883          }
884        }
885      });
886    });
887
888    var displayDiv = $("#selectedAttributesDisplay");
889    displayDiv.empty();
890
891    selectedAttributes.forEach(function (item) {
892      displayDiv.append('<div class="selected-attribute-item" data-span-text="' + item.text + '">' + item.text + '<span class="filter-cross-icon">&#10006;</span></div>');
893    });
894  }
895
896  // Handle click event on the displayed selected attributes
897  $(document).on("click", ".selected-attribute-item .filter-cross-icon", function (event) {
898    event.stopPropagation(); // Prevent event from bubbling up to parent elements
899
900    //var spanText = $(this).closest(".selected-attribute-item").data("span-text");
901    var spanText = String($(this).closest(".selected-attribute-item").data("span-text"));
902
903    // Find the corresponding li element and remove the selected class
904    $(".lb_prod_filter_attr_box li.selected").each(function () {
905      var itemSpanText = $(this).find(".prod_cat_select_lable span").text().trim();
906      if (spanText.includes(itemSpanText)) {
907        $(this).trigger('click');
908        // $(this).removeClass('selected').trigger('click');
909        // var target_attr = $(this).closest(".lb_prod_filter_attr_box");
910        // var temp_values = "";
911        // target_attr.find("li.selected").each(function () {
912        //   var each_sLi = $(this);
913        //   var each_value = each_sLi.attr("attr_value");
914        //   temp_values += each_value + ",";
915        // });
916        // target_attr.attr("filter_selected_val", temp_values);
917        // if (!temp_values) {
918        //   target_attr.removeClass("attr_set");
919        // }
920      }
921    });
922
923    // Remove the clicked attribute from the display
924    $(this).closest(".selected-attribute-item").remove();
925
926    // Trigger the filter button click to apply changes
927    // setTimeout(function () {
928    //   $(".lb_prod_filter_btn").first().trigger("click");
929    // }, 500);
930  });
931
932
933  // for clearing multiple filter selections
934  $(document).on("click", ".lb_filter_reset", function (e) {
935    e.preventDefault();
936    var target_attr_box = $(this).closest(".lb_prod_filter_attr_box");
937    target_attr_box.attr("filter_selected_val", "");
938    target_attr_box.removeClass("attr_set");
939    target_attr_box.find("ul.prod_filter_ul li").removeClass("selected");
940    // Remove corresponding filter values from the display div
941    target_attr_box.find("ul.prod_filter_ul li").each(function () {
942      var spanText = $(this).find(".prod_cat_select_lable span").text().trim();
943      $("#selectedAttributesDisplay .selected-attribute-item").each(function () {
944        if ($(this).data("span-text").includes(spanText)) {
945          $(this).remove();
946        }
947      });
948    });
949
950    setTimeout(function () {
951      $("#products_search_button").trigger("click");
952    }, 400);
953  });
954
955  function lb_range_error_label(prod_filter_ul_wrapper) {
956    // (!$('span').hasClass('lb_range_error_label')) ? $('.lb_prod_filter_attrs').append('<span class="lb_range_error_label">min < max</span>') : '';
957    // $('.lb_prod_filter_attrs').append('<span class="lb_range_error_label">min < max</span>');
958  }
959
960  // clear typing attribute inputs
961  $(document).on("click", ".clear_filter_attr_range", function () {
962    $(this).siblings("input").val("");
963    $(this).closest(".lb_prod_filter_attr_range").attr("min_val", "");
964    $(this).closest(".lb_prod_filter_attr_range").attr("max_val", "");
965    $(this).closest(".lb_prod_filter_attr_box").attr("filter_selected_val", "");
966    $(this).closest(".lb_prod_filter_attr_box").removeClass("attr_set");
967    update_page_url(1);
968  });
969
970  // function to update the url based on attribute selection
971  function update_page_url(page_number) {
972    var page_url = window.location.href;
973    var url = new URL(page_url);
974    var params = new URLSearchParams(url.search);
975    var updated_url = "";
976
977    page_number = page_number != null ? parseInt(page_number) : 1;
978    params.delete("products_search");
979    params.set("pagination", page_number);
980    params.set("sort", $("#leafbridge_products_sort_by").val());
981
982    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
983
984    if (leafbridge_wizard_data != null) {
985      var selected_retailer = leafbridge_wizard_data.retailer_id;
986      var menu_type = leafbridge_wizard_data.menu_type;
987      var collection_type = leafbridge_wizard_data.collection_method;
988
989      !params.get("retailer_id") ? params.append("retailer_id", selected_retailer) : "";
990      !params.get("menu_type") ? params.append("menu_type", menu_type) : "";
991      !params.get("collection_type") ? params.append("collection_type", collection_type) : "";
992    }
993    $("#products_search_input").val() ? params.append("products_search", $("#products_search_input").val()) : "";
994
995    $(".lb_prod_filter_attrs .lb_prod_filter_attr_box").each(function (index, el) {
996      var this_attr = $(this).attr("filter_attr");
997      var this_attr_val = $(this).attr("filter_selected_val");
998      if (this_attr_val) {
999        params.delete(this_attr);
1000        params.append(this_attr, this_attr_val);
1001      } else {
1002        params.delete(this_attr);
1003      }
1004    });
1005
1006    updated_url = url.origin + url.pathname + "?" + params.toString();
1007    window.history.pushState({}, "", updated_url);
1008
1009    // update page number in the paginations
1010    $(".wizard_category_products_pagination button.prev").attr("data_page", page_number - 1);
1011    $(".wizard_category_products_pagination button.next").attr("data_page", page_number + 1);
1012
1013    page_number == 1 ? $(".wizard_category_products_pagination button.prev").hide() : $(".wizard_category_products_pagination button.prev").show();
1014    $('.pagination-link[data-page="' + page_number + '"]').addClass('current-page');
1015  }
1016
1017  /*
1018   * call the ajax function to filter on filter button click
1019   */
1020
1021  var initialContent = $(".wizard_category_products_showcase").html();
1022
1023  $(document).on("click", ".lb_prod_filter_btn", function () {
1024    var item_list_element = $(this);
1025    $(".wizard_category_products_showcase").html(initialContent);
1026    lb_prod_filter(true,item_list_element);
1027  });
1028
1029  $(document).on("change", "#leafbridge_products_sort_by", function () {
1030    // update local storage with selected sorting. this selected sorting will be set when page is being loaded
1031    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1032    var item_list_element = $(this);
1033    leafbridge_wizard_data.sort = $(this).val();
1034    localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
1035    lb_prod_filter(true,item_list_element);
1036  });
1037
1038  function lb_prod_filter(triggered_from_sort,item_list_element) {
1039    $('body').css('pointer-events', 'none');
1040    var get_urlPgNo = ($('.wizard_prods_categories').attr('data_event') == 'justlanded') ? true : false;
1041    var default_sorting = "POPULAR_DESC";
1042    //get pagination number
1043    var page_url = window.location.href;
1044    var url = new URL(page_url);
1045    var params = new URLSearchParams(url.search);
1046    var page_number = params.get("pagination") ? params.get("pagination") : 1;
1047    page_number = triggered_from_sort ? ((get_urlPgNo) ? page_number : 1) : page_number;
1048
1049    var leafbridge_wizard_data = localStorage.getItem("leafbridge_wizard_data") ? JSON.parse(localStorage.getItem("leafbridge_wizard_data")) : { sort: null };
1050
1051    // get retailer default sorting
1052    var data_stores_sorting = JSON.parse($('.leafbridge_shop_wizard_wrapper[data_stores_sorting]').attr('data_stores_sorting'));
1053    var local_sorting = leafbridge_wizard_data.sort;
1054
1055    default_sorting = (local_sorting == null) ? (data_stores_sorting[leafbridge_wizard_data.retailer_id] ? data_stores_sorting[leafbridge_wizard_data.retailer_id] : default_sorting) : default_sorting;
1056
1057    // get all filter attributes
1058    var filter_attributes = {};
1059    filter_attributes.search_key_word = $("#products_search_input").val();
1060    filter_attributes.sort_order = leafbridge_wizard_data.sort != null ? leafbridge_wizard_data.sort : default_sorting;
1061    // filter_attributes.prods_pageNumber = page_number;
1062
1063    $(".lb_prod_filter_attrs .lb_prod_filter_attr_box").each(function (index, el) {
1064      var this_filter_attr = $(this).attr("filter_attr");
1065      var this_filter_attr_val = $(this).attr("filter_selected_val");
1066      this_filter_attr_val ? (filter_attributes[this_filter_attr] = this_filter_attr_val) : "";
1067    });
1068
1069    // update_page_url(page_number);
1070    promise_get_products_ajax(filter_attributes, "", page_number)
1071      .then(function (json) {
1072        update_page_url(page_number);
1073        filter_attributes.sort_order == default_sorting ? $("#leafbridge_products_sort_by").val(default_sorting) : "";
1074        $('body').css('pointer-events', 'auto');
1075        dl_view_item_list(item_list_element,json);
1076      })
1077      .catch(function (err) {
1078        console.error("get_products_ajax", err);
1079      });
1080  }
1081  /*
1082   * Show filtered results - Phase 2 function ! - End
1083   */
1084
1085  /*
1086   * Product Category pages search
1087   */
1088  $(document).on("click", "#products_category_search_button", function (event) {
1089    var item_list_element = $(this);
1090    $("#products_clear_search_button").fadeIn();
1091    var get_category = $(this).closest(".wizard_product_section").attr("data_category");
1092    promise_get_products_ajax(get_category, "", 1)
1093      .then(function (json) { 
1094        dl_view_item_list(item_list_element,json);
1095      })
1096      .catch(function (err) {
1097        console.error("products_category_search_button : get_products_ajax", err);
1098      });
1099  });
1100
1101  /*
1102   * Clear Product Category pages search
1103   */
1104  $(document).on("click", "#products_clear_search_button", function (event) {
1105    $("#products_search_input").val("");
1106    $("#products_search_button").trigger("click");
1107    $("#products_category_search_button").trigger("click");
1108  });
1109
1110  // ajax function promise to load products
1111  function promise_get_products_ajax(category, triggering_event, prods_pageNumber) {
1112    return new Promise(function (resolve, reject) {
1113      // if it's retailer location page, it will not pass wizard data . instead it will only send the retailer id.
1114      var get_leafbridge_wizard_data = {};
1115      var retailer_based_store = false;
1116      var localStorage_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1117      var retailer_name = $(".retailer_based_store").attr("retailer_name");
1118
1119      try {
1120        var lb_prod_prefixes = ($('meta[name="lb_prod_prefixes"]').length > 0) ? JSON.parse($('meta[name="lb_prod_prefixes"]').attr('content')) : '';
1121      }
1122      catch (err) {
1123        var lb_prod_prefixes = '';
1124      }
1125
1126      get_leafbridge_wizard_data = localStorage_wizard_data;
1127      get_leafbridge_wizard_data.prod_prefix = (lb_prod_prefixes != '') ? lb_prod_prefixes[get_leafbridge_wizard_data.retailer_id] : null;
1128
1129      if (triggering_event == "initial") {
1130        
1131        $("#wizard_prods_view").show();
1132        var data = {
1133          action: "wizard_show_products",
1134          wizard_data: get_leafbridge_wizard_data,
1135          nonce_ajax: leafbridge_public_ajax_obj.nonce,
1136          prods_pageNumber: prods_pageNumber,
1137          prod_categories: "all",
1138          search_key_word: $("#products_search_input").val(),
1139          filter_attributes: JSON.stringify(category),
1140        };
1141
1142        $.ajax({
1143          url: leafbridge_public_ajax_obj.ajaxurl,
1144          dataType: "json",
1145          cache: false,
1146          data: data,
1147          type: "POST",
1148          proccessData: false,
1149          beforeSend: function () {
1150            $(".lb_prod_filter_btn").css("pointer-events", "none");
1151          },
1152          success: function (json) {
1153            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all .wizard_category_products_showcase").html(json.data.products_html);
1154            //hide_null_filter_attrs_shop(json.data.products_html);
1155            hide_null_filter_attrs_shop(json.data.available_filters);
1156            // $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all").fadeIn("250");
1157            location_pages_addtocart(retailer_based_store, localStorage_wizard_data, retailer_name);
1158            // $('.wizard_category_products_showcase').css('display','inline-grid');
1159            setTimeout(function () {
1160              $(".leafbridge_shop_wizard_wrapper .leafbridge_shop_wizard_container").css("opacity", "1");
1161              $(".leafbridge_shop_wizard_wrapper").addClass("loaded");
1162            }, 500);
1163           
1164            resolve(json);
1165          },
1166          error: function (json) {
1167            show_system_error(json.data);
1168            reject(json);
1169          },
1170          complete: function (json) {
1171            
1172            $(".lb_prod_filter_btn").css("pointer-events", "all");
1173            $(".select2_init").select2();
1174            $("#wizard_prods_view").hide();
1175            $("#prods_categories li.selected").each(function (index, el) {
1176              $(this).removeClass("selected");
1177            });
1178          },
1179        });
1180      } 
1181      else {
1182        // $("#wizard_prods_view").show();
1183        var data = {
1184          action: "wizard_show_products",
1185          wizard_data: get_leafbridge_wizard_data,
1186          nonce_ajax: leafbridge_public_ajax_obj.nonce,
1187          prods_pageNumber: prods_pageNumber,
1188          prod_categories: category,
1189          search_key_word: $("#products_search_input").val(),
1190          filter_attributes: category,
1191        };
1192
1193        $.ajax({
1194          url: leafbridge_public_ajax_obj.ajaxurl,
1195          dataType: "json",
1196          cache: false,
1197          data: data,
1198          type: "POST",
1199          proccessData: false,
1200          beforeSend: function () {
1201            $(".lb_prod_filter_btn").css("pointer-events", "none");
1202          },
1203          success: function (json) {
1204            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view section.wizard_product_section").hide();
1205            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all .wizard_category_products_showcase").html(json.data.products_html);
1206            //hide_null_filter_attrs_shop(json.data.products_html);
1207            hide_null_filter_attrs_shop(json.data.available_filters);
1208            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all").show();
1209
1210            // show / hide pagination next button
1211            $("#pagination_text").text(json.data.pagination_show_current_page_text);
1212
1213            if (json.data.pagination_show_current_page_with_no) {
1214              var paginationText = "";
1215              var pageNumbers = json.data.pagination_show_current_page_with_no.split(" ");
1216
1217              var currentPageNumber = prods_pageNumber;
1218
1219              if (pageNumbers[pageNumbers.length - 1] === pageNumbers[pageNumbers.length - 2]) {
1220                pageNumbers.pop();
1221              }
1222
1223              for (var i = 0; i < pageNumbers.length; i++) {
1224                if (pageNumbers[i] === "...") {
1225                  paginationText += "<span>" + pageNumbers[i] + "</span>"; // Keep ellipsis as span (non-clickable)
1226                } else {
1227                  // Check if the current page number matches the current page being iterated
1228                  if (parseInt(pageNumbers[i]) === currentPageNumber) {
1229                    paginationText += '<a href="#" class="pagination-link current-page" data-page="' + pageNumbers[i] + '">' + pageNumbers[i] + "</a>";
1230                  } else {
1231                    paginationText += '<a href="#" class="pagination-link" data-page="' + pageNumbers[i] + '">' + pageNumbers[i] + "</a>";
1232                  }
1233                }
1234              }
1235
1236              $("#pagination_text_with_no").html(paginationText);
1237              $("#pagination_text_with_no").show();
1238              // Store the current category and triggering_event as data attributes
1239              $("#product_collection")
1240              .data("category", category)
1241              .data("trigger", triggering_event);
1242            }
1243            else {
1244              $("#pagination_text_with_no").hide();
1245            }
1246
1247            var paginationStyle = json.data.pagination_style;
1248
1249            $(".wizard_category_products_pagination.allow_pages").hide();
1250
1251            // Show the appropriate pagination container based on pagination_style
1252            if (paginationStyle === "next_prev") {
1253              $(".wizard_category_products_pagination.allow_pages:first").show();
1254            } else if (paginationStyle === "next_prev_with_page_buttons") {
1255              $(".wizard_category_products_pagination.allow_pages:last").show();
1256            }
1257
1258            // Update the data_page attribute for next and previous buttons
1259            $(".wizard_category_products_pagination .prev").attr("data_page", prods_pageNumber - 1);
1260            $(".wizard_category_products_pagination .next").attr("data_page", prods_pageNumber + 1);
1261
1262
1263            if (parseInt(json.data.current_products_set) - parseInt(json.data.products_count) < 0) {
1264              $(".wizard_category_products_pagination button.next").show();
1265            } else {
1266              $(".wizard_category_products_pagination button.next").hide();
1267            }
1268
1269            // show/hide pagination prev button
1270            if (json.data.current_products_set == json.data.prods_per_page) {
1271              $(".wizard_category_products_pagination button.prev").hide();
1272            } else {
1273              $(".wizard_category_products_pagination button.prev").show();
1274            }
1275            location_pages_addtocart(retailer_based_store, localStorage_wizard_data, retailer_name);
1276            setTimeout(function () {
1277              $(".leafbridge_shop_wizard_wrapper .leafbridge_shop_wizard_container").css("opacity", "1");
1278              $(".leafbridge_shop_wizard_wrapper").addClass("loaded");
1279            }, 500);
1280
1281            // if(json.data.filter_rules){
1282            //   if(json.data.filter_rules.hide_pagination){
1283            //     $('.pagination-container').hide();
1284            //   }
1285            // }
1286            resolve(json);
1287          },
1288          error: function (json) {
1289            show_system_error(json.data);
1290            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all").hide();
1291            $("#leafbridge_shop_wizard_view_products .wizard_box_container #product_collection .wizard_prods_view #prod_show_cat_all").show();
1292            reject(json);
1293          },
1294          complete: function (json) {
1295            $(".lb_prod_filter_btn").css("pointer-events", "all");
1296            $(".select2_init").select2();
1297            $("#prods_categories").css("opacity", "1");
1298            $("#prods_categories").css("pointer-events", "auto");
1299            $("#wizard_prods_view").hide();
1300          },
1301        });
1302      }
1303    });
1304  }
1305
1306  function location_pages_addtocart(retailer_based_store, localStorage_wizard_data, retailer_name) {
1307    if (retailer_based_store && localStorage_wizard_data && $(".retailer_based_store").attr("force_wizard") == "off") {
1308      var location_retailer_id = $(".retailer_based_store").attr("retailer_id");
1309      if (location_retailer_id != localStorage_wizard_data.retailer_id) {
1310        $(".leafbridge_product_card").each(function (index, el) {
1311          $(this).find(".leafbridge_product_modal_add_to_cart").css("display", "block");
1312          $(this).find(".leafbridge_product_modal_add_to_cart").css("width", "100%");
1313          $(this).find(".leafbridge_product_modal_add_to_cart").html('<div class="add_to_cart_warning"><i class="fa-sharp fa-solid fa-triangle-exclamation"></i><p style="font-size:12px;">To add this item to your cart, please change your location using the options at the top of the page.</div>');
1314        });
1315      }
1316    }
1317  }
1318
1319  // Attach click event handlers to the pagination links
1320  $(document).on("click", ".pagination-link", function(e) {
1321    e.preventDefault();
1322    var item_list_element = $(this);
1323    var pageNumber = $(this).data("page");
1324    // Get the current category and triggering_event from data attributes
1325    var category = $("#product_collection").data("category");
1326    var triggering_event = $("#product_collection").data("trigger");
1327
1328    $(".pagination-link").removeClass("current_page");
1329    $(this).addClass("current_page");
1330    
1331    // Trigger AJAX request with the selected page number
1332    promise_get_products_ajax(category, triggering_event, pageNumber)
1333      .then(function (json) {
1334        $("html, body").animate({ scrollTop: $("#product_collection").offset().top }, 750);
1335        update_page_url(pageNumber);
1336        dl_view_item_list(item_list_element,json);
1337      })
1338      .catch(function (error) {
1339        // Handle error
1340      });
1341  });
1342
1343  // product sections pagination
1344  $(document).on("click", ".wizard_category_products_pagination button", function () {
1345    $("html, body").animate({ scrollTop: $("#product_collection").offset().top }, 750);
1346    var item_list_element = $(this).closest(".wizard_category_products_pagination");
1347    // extract any filter attributes
1348    var get_category = $(this).closest(".wizard_product_section").attr("data_category");
1349    var filter_attributes = {};
1350    filter_attributes.search_key_word = $("#products_search_input").val();
1351    filter_attributes.sort_order = $("#leafbridge_products_sort_by").val();
1352
1353    $(".lb_prod_filter_attrs .lb_prod_filter_attr_box").each(function (index, el) {
1354      var this_filter_attr = $(this).attr("filter_attr");
1355      var this_filter_attr_val = $(this).attr("filter_selected_val");
1356      this_filter_attr_val ? (filter_attributes[this_filter_attr] = this_filter_attr_val) : "";
1357    });
1358    get_category = filter_attributes;
1359    var get_page = parseInt($(this).attr("data_page"));
1360    update_page_url(get_page);
1361    promise_get_products_ajax(get_category, "", get_page)
1362      .then(function (json) { 
1363        dl_view_item_list(item_list_element,json);
1364      })
1365      .catch(function (err) {
1366        console.error("get_products_ajax", err);
1367      });
1368  });
1369
1370  // ajax function to view featured products
1371  function get_featured_products_ajax() {
1372    $("#leafbridge_featured_products_wrapper").fadeIn("250");
1373    var wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1374
1375    try {
1376      var lb_prod_prefixes = ($('meta[name="lb_prod_prefixes"]').length > 0) ? JSON.parse($('meta[name="lb_prod_prefixes"]').attr('content')) : '';
1377    }
1378    catch (err) {
1379      var lb_prod_prefixes = '';
1380    }
1381    wizard_data.prod_prefix = lb_prod_prefixes[wizard_data.retailer_id];
1382
1383    var data = {
1384      action: "show_featured_products_func",
1385      wizard_data: wizard_data,
1386      nonce_ajax: leafbridge_public_ajax_obj.nonce,
1387      prod_categories: "all",
1388      product_count: $("#leafbridge_featured_products_wrapper").attr("data_product_count"),
1389    };
1390    $.ajax({
1391      url: leafbridge_public_ajax_obj.ajaxurl,
1392      dataType: "json",
1393      cache: false,
1394      data: data,
1395      type: "POST",
1396      proccessData: false,
1397      success: function (json) {
1398        $("#leafbridge_featured_products_wrapper").addClass("has_prods");
1399        $("#leafbridge_featured_products_wrapper .leafbridge_featured_products_inner").html(json.data.products_html);
1400        $("#leafbridge_featured_products_wrapper").fadeIn("250");
1401      },
1402      error: function (json) {
1403        show_system_error(json.data);
1404        $("#leafbridge_featured_products_wrapper .leafbridge_featured_products_inner").html("error fetching products");
1405      },
1406      complete: function (json) {
1407        $(".select2_init").select2();
1408        $("#wizard_prods_view").hide();
1409        $("#prods_categories li.selected").each(function (index, el) {
1410          $(this).removeClass("selected");
1411        });
1412      },
1413    });
1414  }
1415
1416  // opening product modals
1417  $(document).on("click", ".open_prod_modal", function (event) {
1418    event.preventDefault();
1419    var data_modal_id = $(this).attr("data_modal_id");
1420    var capture_modal = $("#" + data_modal_id).html();
1421    // $('#'+data_modal_id).fadeIn('250');
1422    $("#popup_container").addClass("open_popup");
1423    $("#popup_container").html(capture_modal);
1424
1425    // pushing image url 
1426    var prod_card = $(this).closest(".leafbridge_product_card");
1427    var prod_thumb_url = prod_card.find('.lb_prod_card_thumb').attr('src');
1428    prod_thumb_url = prod_thumb_url.replace("w=200", "w=500");
1429    prod_thumb_url = prod_thumb_url.replace("h=200", "h=500");
1430
1431    $("#popup_container").find('.leafbridge_product_modal_image img').attr('src', prod_thumb_url);
1432
1433    //GTM view_item push to data layer - START
1434    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1435    var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
1436
1437    var json = {};
1438    var item_data = null;
1439    item_data = JSON.parse(prod_card.attr("filter_data"));
1440
1441    var cart_prod = {
1442      product_id: item_data.product_id,
1443      variation: item_data.variants[0].option,
1444      prod_count: 1,
1445      prod_name: item_data.item_name,
1446    };
1447
1448    if (item_data != null) {
1449      json.moreDataLayerPush = {
1450        item_data: item_data,
1451        cart_prod: cart_prod,
1452        location_id: leafbridge_wizard_data.retailer_id,
1453        location_name: leafbridge_recent_location.retailer_name,
1454        menu_type: leafbridge_wizard_data.menu_type,
1455      };
1456      gtm_push_single_item_data(json, "LB_ViewItem");
1457    }
1458    //GTM view_item push to data layer - END
1459  });
1460
1461  $(document).on('click','.add_to_cart_variant',function(e){
1462    e.preventDefault();
1463    if($(this).closest('.leafbridge_product_card').hasClass('product_popup_enabled')){
1464      e.stopPropagation();
1465    }
1466  })
1467
1468  // change limit of add to cart per variant
1469  $(document).on("change", ".add_to_cart_variant", function (event) {
1470    var variation_qty_list = $(this).closest(".leafbridge_product_modal_add_to_cart").attr("quantities");
1471    var variations_qty_obj = JSON.parse(variation_qty_list);
1472    var selected_variation = $(this).val();
1473    $(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_count").attr("max", variations_qty_obj[selected_variation]);
1474    $(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_count").val(1);
1475
1476    //GTM view_item push to data layer - START
1477    var variation_type = $(this).val();
1478    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1479    var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
1480
1481    var json = {};
1482    var item_data = null;
1483
1484    if ($(this).hasClass("variant_prod_box")) {
1485      var prod_card = $(this).closest(".leafbridge_product_card");
1486      item_data = JSON.parse(prod_card.attr("filter_data"));
1487      item_data = null;
1488    } else if ($(this).hasClass("variant_prod_modal")) {
1489      var modal_prod_id = $(this).closest(".leafbridge_product_modal_add_to_cart").attr("data_product_id");
1490      var prod_card = $(".leafbridge_product_card[data_product_id=" + modal_prod_id + "]");
1491      item_data = JSON.parse(prod_card.attr("filter_data"));
1492    } else if ($(this).hasClass("variant_prod_page")) {
1493      item_data = JSON.parse($(".lb_prod_single_add_to_cart").attr("filter_data"));
1494    }
1495
1496    var cart_prod = {
1497      product_id: item_data.product_id,
1498      variation: variation_type,
1499      prod_count: 1,
1500      prod_name: item_data.item_name,
1501    };
1502
1503    if (item_data != null) {
1504      json.moreDataLayerPush = {
1505        item_data: item_data,
1506        cart_prod: cart_prod,
1507        location_id: leafbridge_wizard_data.retailer_id,
1508        location_name: leafbridge_recent_location.retailer_name,
1509        menu_type: leafbridge_wizard_data.menu_type,
1510      };
1511      gtm_push_single_item_data(json, "LB_ViewItem");
1512    }
1513    //GTM view_item push to data layer - END
1514  });
1515
1516  // popup add product to cart
1517  $(document).on("click", ".leafbridge_product_modal_add_to_cart button", function (event) {
1518    
1519    if($(this).closest('.leafbridge_product_card').hasClass('product_popup_enabled')){
1520      event.stopPropagation();
1521    }
1522
1523    var this_button = $(this);
1524    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1525    var preserve_leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1526    var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
1527    var force_leafbridge_wizard_data = {};
1528    var retailer_based_store = $("div").hasClass("retailer_based_store") ? true : false;
1529
1530    var cart_creation_utc = new Date().toUTCString();
1531
1532    if ($("div").hasClass("retailer_based_store")) {
1533      if ($(".retailer_based_store").attr("force_wizard") == "on") {
1534        force_leafbridge_wizard_data = {
1535          retailer_id: $(".retailer_based_store").attr("retailer_id"),
1536          menu_type: $(".retailer_based_store").attr("menu_type"),
1537          collection_method: $(".retailer_based_store").attr("order_type"),
1538        };
1539      }
1540    }
1541
1542    if (!localStorage.getItem("leafbridge_wizard_data")) {
1543      leafbridge_wizard_data = {
1544        age_confirm: true,
1545        collection_method: $(".retailer_based_store").attr("order_type"),
1546        created_time: new Date(),
1547        default_set: true,
1548        event: "EMPTY CART",
1549        menu_type: $(".retailer_based_store").attr("menu_type"),
1550        retailer_id: $(".retailer_based_store").attr("retailer_id"),
1551      };
1552    }
1553    else {
1554      leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1555
1556      if ($("div").hasClass("retailer_based_store")) {
1557        if ($(".retailer_based_store").attr("force_wizard") == "on") {
1558          // inside retailer based store page, check if there's already wizard data and cart data is in local storage
1559          if (localStorage.getItem("leafbridge_cart_data")) {
1560            var check_leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1561            if (check_leafbridge_cart_data.retailer_id != force_leafbridge_wizard_data.retailer_id || check_leafbridge_cart_data.menutype != force_leafbridge_wizard_data.menu_type) {
1562              leafbridge_toast({
1563                heading: translations.errorHeading,
1564                text: translations.setLocationText + " " + $(".retailer_based_store").attr("retailer_name"),
1565                showHideTransition: "slide",
1566                position: "top-right",
1567                icon: "error",
1568                bgColor: "#fd3c51",
1569                textColor: "white",
1570                hideAfter: 2000,
1571              });
1572
1573              return null;
1574            }
1575          }
1576        }
1577      }
1578    }
1579
1580    var leafbridge_cart_data = localStorage.getItem("leafbridge_cart_data") !== null ? JSON.parse(localStorage.getItem("leafbridge_cart_data")) : [];
1581
1582    // again check if cart is mutated before adding products to cart in shop
1583    var flag_reset_cart = localStorage.getItem("leafbridge_cart_data") ? false : true;
1584
1585    if (localStorage.getItem("leafbridge_cart_data")) {
1586      if (leafbridge_cart_data.retailer_id != leafbridge_wizard_data.retailer_id || leafbridge_cart_data.menutype != leafbridge_wizard_data.menu_type) {
1587        var confirm_change_cart = confirm("There are products from another retailer / menutype so adding this product will reset your current cart. Proceed?");
1588
1589        if (confirm_change_cart == true) {
1590          flag_reset_cart = true;
1591          localStorage.removeItem("leafbridge_cart_data");
1592        }
1593      }
1594    }
1595
1596    var prod_name = $(this).closest(".leafbridge_product_modal_descr_inner").find(".leafbridge_product_name").text();
1597    var product_id = $(this).closest(".leafbridge_product_modal_add_to_cart").attr("data_product_id");
1598    var checkout_id = typeof leafbridge_cart_data.new_checkout_id != "undefined" ? leafbridge_cart_data.new_checkout_id : 0;
1599    var variation = $(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_variant").length > 0 ? $(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_variant").val() : "N/A";
1600    var prod_count = $(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_count").val();
1601    var prod_available_amount = parseInt($(this).closest(".leafbridge_product_modal_add_to_cart").find(".add_to_cart_count").attr("max"));
1602
1603    var retailer_id = retailer_based_store ? force_leafbridge_wizard_data.retailer_id : leafbridge_wizard_data.retailer_id;
1604    var menutype = retailer_based_store ? force_leafbridge_wizard_data.menu_type : leafbridge_wizard_data.menu_type;
1605    var collection_type = retailer_based_store ? force_leafbridge_wizard_data.collection_method : leafbridge_wizard_data.collection_method;
1606
1607    leafbridge_wizard_data.created_time = new Date();
1608
1609    var cart_prod = {
1610      product_id: product_id,
1611      variation: variation,
1612      prod_count: prod_count,
1613      prod_name: prod_name,
1614    };
1615
1616    if (flag_reset_cart) {
1617      leafbridge_cart_data = {
1618        retailer_id: retailer_id,
1619        menutype: menutype,
1620        collection_type: collection_type,
1621        // products_count : [],
1622        products: [],
1623        cart_creation_utc: cart_creation_utc,
1624      };
1625    }
1626
1627    leafbridge_cart_data.products.push(cart_prod);
1628
1629    $(this).prop("disabled", false);
1630
1631    // true if more than available quantity is added.
1632    if (check_prod_count(product_id, prod_count, prod_available_amount)) {
1633      ajax_add_to_cart(retailer_id, checkout_id, menutype, collection_type, cart_prod)
1634        .then(function (json) {
1635          //GTM add to cart push to data layer - START
1636          var capture_prod_id = this_button.closest(".leafbridge_product_modal_add_to_cart").attr("data_product_id");
1637          var item_data = null;
1638
1639          if ($(".leafbridge_product_card[data_product_id=" + capture_prod_id + "]").length != 0) {
1640            item_data = JSON.parse($(".leafbridge_product_card[data_product_id=" + capture_prod_id + "]").attr("filter_data"));
1641          }
1642          else {
1643            if (item_data == null && $("div").hasClass("lb_prod_single_add_to_cart")) {
1644              item_data = JSON.parse($(".lb_prod_single_add_to_cart").attr("filter_data"));
1645            } else {
1646              item_data = null;
1647            }
1648          }
1649
1650          var recent_location_name = leafbridge_recent_location ? (leafbridge_recent_location.retailer_name ? leafbridge_recent_location.retailer_name : "") : "";
1651          if (item_data != null) {
1652            json.moreDataLayerPush = {
1653              item_data: item_data,
1654              cart_prod: cart_prod,
1655              location_id: retailer_id,
1656              location_name: recent_location_name,
1657              menu_type: menutype,
1658            };
1659            gtm_push_single_item_data(json, "LB_AddToCart");
1660          }
1661          //GTM add to cart push to data layer - END
1662          if (json.success && !json.data.add_to_cart_error) {
1663            localStorage.setItem("leafbridge_cart_data", JSON.stringify(leafbridge_cart_data));
1664            var checkout_2nd_attempt = json.data.checkout_2nd_attempt;
1665
1666            if (checkout_id == 0) {
1667              var leafbridge_cart_data_2 = localStorage.getItem("leafbridge_cart_data") !== null ? JSON.parse(localStorage.getItem("leafbridge_cart_data")) : [];
1668              leafbridge_cart_data_2.new_checkout_id = json.data.new_checkout_id;
1669              localStorage.setItem("leafbridge_cart_data", JSON.stringify(leafbridge_cart_data_2));
1670            }
1671
1672            if (checkout_2nd_attempt) {
1673              leafbridge_toast({
1674                heading: 'Expired Cart',
1675                text: 'A new cart will be created',
1676                showHideTransition: "slide",
1677                position: "top-right",
1678                icon: "",
1679                bgColor: "#4292a9",
1680                textColor: "white",
1681                hideAfter: hide_after,
1682              });
1683
1684              var leafbridge_cart_data_3 = leafbridge_cart_data;
1685              leafbridge_cart_data_3.new_checkout_id = json.data.new_checkout_id;
1686              localStorage.removeItem('leafbridge_cart_data');
1687              localStorage.setItem("leafbridge_cart_data", JSON.stringify(leafbridge_cart_data_3));
1688            }
1689
1690            if (json.data.cart_html) {
1691              leafbridge_toast({
1692                heading: translations.successHeading,
1693                text: translations.addToCartText,
1694                showHideTransition: "slide",
1695                position: "top-right",
1696                icon: "success",
1697              });
1698            }
1699            else {
1700              if (json.data.add_to_cart_error) {
1701                var hide_after = 20000;
1702                if (json.data.add_to_cart_error == "Not Found") {
1703                  // this_button.trigger('click');
1704                  hide_after = 3000;
1705                  json.data.add_to_cart_error = "Could not add to cart. retrying..";
1706                  localStorage.removeItem("leafbridge_cart_data");
1707                }
1708                leafbridge_toast({
1709                  heading: translations.errorAddToCartHeading,
1710                  text: json.data.add_to_cart_error,
1711                  showHideTransition: "slide",
1712                  position: "top-right",
1713                  icon: "error",
1714                  bgColor: "#fd3c51",
1715                  textColor: "white",
1716                  hideAfter: hide_after,
1717                });
1718                // alert("json.data.add_to_cart_error");
1719              }
1720              else {
1721                leafbridge_toast({
1722                  heading: translations.errorHeading,
1723                  text: translations.errorAddToCartText,
1724                  showHideTransition: "slide",
1725                  position: "top-right",
1726                  icon: "error",
1727                  bgColor: "#fd3c51",
1728                  textColor: "white",
1729                  hideAfter: 20000,
1730                });
1731              }
1732            }
1733          }
1734          else {
1735            leafbridge_toast({
1736              heading: translations.errorAddToCartHeading,
1737              text: json.data.add_to_cart_error,
1738              showHideTransition: "slide",
1739              position: "top-right",
1740              icon: "error",
1741              bgColor: "#fd3c51",
1742              textColor: "white",
1743              hideAfter: 20000,
1744            });
1745          }
1746          set_cart_prod_count(json.data.update_cart.items);
1747          render_cart(json.data);
1748        })
1749        .catch(function (err) {
1750          console.error("add to cart error", err);
1751        });
1752    }
1753  });
1754
1755
1756  function set_cart_prod_count(cart_items) {
1757    var get_local_cart = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1758    get_local_cart.cart_items_count = cart_items;
1759    localStorage.setItem("leafbridge_cart_data", JSON.stringify(get_local_cart));
1760  }
1761
1762  function check_prod_count(prod_id, prod_count, prod_available_amount) {
1763    var flag_over_packed = true;
1764    var get_local_cart = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1765
1766    if (get_local_cart) {
1767      var cart_items_count = get_local_cart.cart_items_count;
1768      if (cart_items_count) {
1769        for (let cic_index = 0; cic_index < cart_items_count.length; cic_index++) {
1770          var cart_item = cart_items_count[cic_index];
1771          var attempting_qty = parseInt(cart_item.quantity) + parseInt(prod_count);
1772          if (cart_item.productId == prod_id && attempting_qty > prod_available_amount) {
1773            flag_over_packed = false;
1774          }
1775        }
1776      }
1777
1778      if (!flag_over_packed) {
1779        leafbridge_toast({
1780          heading: translations.errorHeading,
1781          text: translations.quantityExceedText,
1782          showHideTransition: "slide",
1783          position: "top-right",
1784          icon: "error",
1785          bgColor: "#fd3c51",
1786          textColor: "white",
1787          hideAfter: 20000,
1788        });
1789      }
1790    }
1791    else {
1792      flag_over_packed = true;
1793    }
1794    return flag_over_packed;
1795  }
1796
1797  // ajax fuction to add products to cart
1798  function ajax_add_to_cart(retailerId, checkoutId, menutype, collection_type, products_list) {
1799    return new Promise(function (resolve, reject) {
1800      var data = {
1801        retailerId: retailerId,
1802        checkoutId: checkoutId,
1803        collection_type: collection_type,
1804        pricingType: menutype,
1805        products_list: products_list,
1806        init_cart_data: JSON.parse(localStorage.getItem("leafbridge_cart_data")),
1807        nonce_ajax: leafbridge_public_ajax_obj.nonce,
1808        action: "leafbridge_shop_add_products_to_cart",
1809      };
1810      $.ajax({
1811        url: leafbridge_public_ajax_obj.ajaxurl,
1812        dataType: "json",
1813        cache: false,
1814        data: data,
1815        type: "POST",
1816        proccessData: false,
1817        beforeSend: function () {
1818          $(".leafbridge_product_modal_add_to_cart button").prop("disabled", true);
1819          $(".leafbridge_product_modal_add_to_cart").css("opacity", "0.5");
1820        },
1821        success: function (json) {
1822          $(".leafbridge_product_modal_add_to_cart button").prop("disabled", false);
1823          $(".leafbridge_product_modal_add_to_cart").css("opacity", "1");
1824
1825          if (json.data.cart_slide_status === "on") {
1826            $("#open_the_cart").trigger("click");
1827          } else {
1828            //
1829          }
1830          resolve(json);
1831        },
1832        error: function (json) {
1833          show_system_error(json.data);
1834          reject(json);
1835        },
1836        complete: function (json) { },
1837      });
1838    });
1839  }
1840
1841  // check and prepare cart items on page load
1842  function check_and_prepare_cart_items() {
1843    if (localStorage.getItem("leafbridge_cart_data")) {
1844      var leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1845      var retailer_id = leafbridge_cart_data.retailer_id;
1846      var new_checkout_id = leafbridge_cart_data.new_checkout_id;
1847      var item_id = leafbridge_cart_data.products[0].product_id;
1848      var item_quantity = leafbridge_cart_data.products[0].prod_count;
1849
1850      ajax_get_cart(retailer_id, new_checkout_id, item_id, item_quantity)
1851        .then(function (json) {
1852          render_cart(json.data);
1853        })
1854        .catch(function (err) {
1855          console.error("ajax get cart error ", err);
1856        });
1857    } else {
1858      render_empty_cart();
1859    }
1860  }
1861
1862  // ajax function to send a product count update and retrieve the updated cart details
1863  function ajax_get_cart(retailer_id, new_checkout_id, item_id, item_quantity) {
1864    return new Promise(function (resolve, reject) {
1865      var data = {
1866        action: "leafbridge_get_cart_items",
1867        retailer_id: retailer_id,
1868        new_checkout_id: new_checkout_id,
1869        item_id: item_id,
1870        item_quantity: item_quantity,
1871        nonce_ajax: leafbridge_public_ajax_obj.nonce,
1872      };
1873      $.ajax({
1874        url: leafbridge_public_ajax_obj.ajaxurl,
1875        dataType: "json",
1876        cache: false,
1877        data: data,
1878        type: "POST",
1879        proccessData: false,
1880        beforeSend: function () { },
1881        success: function (json) {
1882          resolve(json);
1883        },
1884        error: function (json) {
1885          show_system_error(json.data);
1886          reject(json);
1887        },
1888        complete: function (json) {
1889          // jQuery('.floating_cart_items_inner').slimScroll({
1890          // 	height: '65vh'
1891          // });
1892        },
1893      });
1894    });
1895  }
1896
1897  // remove items from the cart
1898  $(document).on("click", ".remove_cart_item", function () {
1899    var leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1900    var gtm_data = JSON.parse($(this).closest(".floating_cart_item_box").attr("gtm_prod_data"));
1901    var item_key = $(this).closest(".floating_cart_item_box").attr("cart_item_id");
1902    var retailerId = leafbridge_cart_data.retailer_id;
1903    var checkoutId = leafbridge_cart_data.new_checkout_id;
1904    var cartItem_qty = parseInt($(this).closest(".floating_cart_item_box").find(".cart_item_count_val").val());
1905    ajax_remove_item_from_cart(item_key, retailerId, checkoutId)
1906      .then(function (json) {
1907        render_cart(json.data);
1908        //GTM view_item push to data layer - START
1909        var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1910        var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
1911
1912        var item_data = {
1913          item_name: gtm_data.product.name,
1914          item_id: gtm_data.product.id,
1915          category: gtm_data.product.category,
1916          subcategory: gtm_data.product.subcategory,
1917          brand_name: gtm_data.product.brand ? gtm_data.product.brand.name : null,
1918          brand: gtm_data.product.brand ? gtm_data.product.brand.id : null,
1919          potencyCbd: gtm_data.product.potencyCbd != null ? gtm_data.product.potencyCbd.formatted : null,
1920          potencyThc: gtm_data.product.potencyThc != null ? gtm_data.product.potencyThc.formatted : null,
1921          strainType: gtm_data.product.strainType,
1922          variants: gtm_data.product.variants,
1923        };
1924
1925        var cart_prod = {
1926          product_id: gtm_data.productId,
1927          variation: gtm_data.option,
1928          prod_count: cartItem_qty,
1929          prod_name: item_data.item_name,
1930        };
1931
1932        var recent_location_name = leafbridge_recent_location ? (leafbridge_recent_location.retailer_name ? leafbridge_recent_location.retailer_name : "") : "";
1933
1934        if (item_data != null) {
1935          json.moreDataLayerPush = {
1936            item_data: item_data,
1937            cart_prod: cart_prod,
1938            location_id: leafbridge_wizard_data.retailer_id,
1939            location_name: recent_location_name,
1940            menu_type: leafbridge_wizard_data.menu_type,
1941          };
1942          gtm_push_single_item_data(json, "LB_RemoveCartItem");
1943        }
1944        //GTM view_item push to data layer - END
1945      })
1946      .catch(function (err) {
1947        console.error("remove cart item err", err);
1948      });
1949  });
1950
1951  $(document).on("click", ".floating_cart_footer a", function (e) {
1952    e.preventDefault();
1953    var lb_checkout_link = $(this).attr("href");
1954
1955    // LB_BeingCheckout for GTM - Start
1956    var GTM_leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
1957    var GTM_leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
1958    var GTM_leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
1959    var gtm_retailer_id = GTM_leafbridge_cart_data.retailer_id;
1960    var gtm_new_checkout_id = GTM_leafbridge_cart_data.new_checkout_id;
1961    var gtm_item_id = GTM_leafbridge_cart_data.products[0].product_id;
1962    var gtm_item_quantity = GTM_leafbridge_cart_data.products[0].prod_count;
1963
1964    var extracted_JSON = JSON.parse($("#floating_cart").attr("cart_data"));
1965    var wrapperJSON = {};
1966    wrapperJSON.data = extracted_JSON;
1967    var order_details = wrapperJSON.data.update_cart;
1968    wrapperJSON.data.order_details = wrapperJSON.data.update_cart;
1969
1970    var recent_location_name = GTM_leafbridge_recent_location ? (GTM_leafbridge_recent_location.retailer_name ? GTM_leafbridge_recent_location.retailer_name : gtm_retailer_id) : gtm_retailer_id;
1971
1972    if (order_details != null) {
1973      wrapperJSON.moreDataLayerPush = {
1974        order_details: order_details,
1975        location_id: GTM_leafbridge_wizard_data.retailer_id,
1976        location_name: recent_location_name,
1977        menu_type: GTM_leafbridge_wizard_data.menu_type,
1978      };
1979      gtm_push_items_data(wrapperJSON, "LB_BeginCheckout");
1980    } else {
1981      console.error("LB_UpdateCart failed");
1982    }
1983    // LB_BeingCheckout for GTM - End
1984    setTimeout(function () {
1985      window.location.href = lb_checkout_link;
1986    }, 1500);
1987  });
1988
1989  // ajax function to remove items from the cart
1990  function ajax_remove_item_from_cart(item_key, retailerId, checkoutId) {
1991    return new Promise(function (resolve, reject) {
1992      var data = {
1993        action: "leafbridge_remove_cart_item",
1994        item_key: item_key,
1995        retailerId: retailerId,
1996        checkoutId: checkoutId,
1997        nonce_ajax: leafbridge_public_ajax_obj.nonce,
1998      };
1999      $.ajax({
2000        url: leafbridge_public_ajax_obj.ajaxurl,
2001        dataType: "json",
2002        cache: false,
2003        data: data,
2004        type: "POST",
2005        proccessData: false,
2006        beforeSend: function () { },
2007        success: function (json) {
2008          resolve(json);
2009          leafbridge_toast({
2010            heading: translations.successHeading,
2011            text: translations.successRemoveCartText,
2012            showHideTransition: "slide",
2013            position: "top-right",
2014            icon: "success",
2015          });
2016        },
2017        error: function (json) {
2018          show_system_error(json.data);
2019          reject(json);
2020        },
2021        complete: function (json) { },
2022      });
2023    });
2024  }
2025
2026  //edit cart item quantity - single cart item button
2027  $(document).on("click", "#update_cart_qts", function () {
2028    $(".floating_cart_wrapper .floating_cart_items_wrapper .floating_cart_items_inner").addClass("updating_cart");
2029
2030    var gtm_cart_items = [];
2031    var floating_cart_items_count = $(".floating_cart_wrapper .floating_cart_items_wrapper .floating_cart_items_inner .floating_cart_item_box").length;
2032    $(".floating_cart_wrapper .floating_cart_items_wrapper .floating_cart_items_inner .floating_cart_item_box").each(function (index, el) {
2033      var leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
2034      var leafbridge_cart_data_prods = leafbridge_cart_data.products;
2035      var retailerId = leafbridge_cart_data.retailer_id;
2036      var checkoutId = leafbridge_cart_data.new_checkout_id;
2037      var itemId = $(this).attr("cart_item_id");
2038      var prod_id = $(this).attr("prod_id");
2039      var quantity = $(this).find(".cart_item_count").find(".cart_item_count_val").val();
2040
2041      gtm_cart_items[prod_id] = JSON.parse($(this).attr("gtm_prod_data"));
2042      ajax_update_cart_item_qunatity(retailerId, checkoutId, itemId, quantity)
2043        .then(function (json) {
2044          if (json.data.cart_html) {
2045            render_cart(json.data);
2046
2047            // limit to success toast to once
2048            if (floating_cart_items_count - 1 == index) {
2049              leafbridge_toast({
2050                heading: translations.successHeading,
2051                text: translations.cartUpdateText,
2052                showHideTransition: "slide",
2053                position: "top-right",
2054                icon: "success",
2055              });
2056            }
2057
2058            // Get checkout for GTM - Start
2059            var GTM_leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
2060            var gtm_retailer_id = GTM_leafbridge_cart_data.retailer_id;
2061            var gtm_new_checkout_id = GTM_leafbridge_cart_data.new_checkout_id;
2062            var gtm_item_id = GTM_leafbridge_cart_data.products[0].product_id;
2063            var gtm_item_quantity = GTM_leafbridge_cart_data.products[0].prod_count;
2064
2065            ajax_get_cart(gtm_retailer_id, gtm_new_checkout_id, gtm_item_id, gtm_item_quantity)
2066              .then(function (json) {
2067                //GTM view_item push to data layer - START
2068                var GTM_leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2069                var GTM_leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
2070
2071                var order_details = json.data.update_cart;
2072                json.data.order_details = json.data.update_cart;
2073
2074                var recent_location_name = GTM_leafbridge_recent_location ? (GTM_leafbridge_recent_location.retailer_name ? GTM_leafbridge_recent_location.retailer_name : "") : "";
2075
2076                if (order_details != null) {
2077                  json.moreDataLayerPush = {
2078                    order_details: order_details,
2079                    location_id: GTM_leafbridge_wizard_data.retailer_id,
2080                    location_name: recent_location_name,
2081                    menu_type: GTM_leafbridge_wizard_data.menu_type,
2082                  };
2083                  gtm_push_items_data(json, "LB_UpdateCart");
2084                } else {
2085                  console.error("LB_UpdateCart failed");
2086                }
2087                //GTM view_item push to data layer - END
2088              })
2089              .catch(function (err) {
2090                console.error("ajax get cart error ", err);
2091              });
2092            // Get checkout for GTM - End
2093          } else if (json.data.update_cart_error) {
2094            leafbridge_toast({
2095              heading: translations.errorHeading,
2096              text: json.data.update_cart_error,
2097              showHideTransition: "slide",
2098              position: "top-right",
2099              icon: "error",
2100              bgColor: "#fd3c51",
2101              textColor: "white",
2102              hideAfter: 20000,
2103            });
2104            // alert("json.data.add_to_cart_error");
2105          } else {
2106            leafbridge_toast({
2107              heading: translations.errorHeading,
2108              text: translations.cartUpdateFailText,
2109              showHideTransition: "slide",
2110              position: "top-right",
2111              icon: "error",
2112              bgColor: "#fd3c51",
2113              textColor: "white",
2114              hideAfter: 20000,
2115            });
2116          }
2117        })
2118        .catch(function (err) {
2119          console.error("ajax_update_cart_item_qunatity err", err);
2120        });
2121    });
2122
2123    setTimeout(function () {
2124      $(".floating_cart_wrapper .floating_cart_items_wrapper .floating_cart_items_inner").removeClass("updating_cart");
2125    }, 3000);
2126  });
2127
2128  //edit cart item quantity - single cart item button
2129  $(document).on("click", ".floating_cart_item_box .cart_item_count .cart_item_count_val_save", function () {
2130    var leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
2131    var retailerId = leafbridge_cart_data.retailer_id;
2132    var checkoutId = leafbridge_cart_data.new_checkout_id;
2133    var itemId = $(this).closest(".floating_cart_item_box").attr("cart_item_id");
2134    var quantity = $(this).closest(".cart_item_count").find(".cart_item_count_val").val();
2135
2136    ajax_update_cart_item_qunatity(retailerId, checkoutId, itemId, quantity)
2137      .then(function (json) {
2138        if (json.data.cart_html) {
2139          render_cart(json.data);
2140          leafbridge_toast({
2141            heading: translations.successHeading,
2142            text: translations.cartUpdateText,
2143            showHideTransition: "slide",
2144            position: "top-right",
2145            icon: "success",
2146          });
2147        } else if (json.data.update_cart_error) {
2148          leafbridge_toast({
2149            heading: translations.errorHeading,
2150            text: json.data.update_cart_error,
2151            showHideTransition: "slide",
2152            position: "top-right",
2153            icon: "error",
2154            bgColor: "#fd3c51",
2155            textColor: "white",
2156            hideAfter: 20000,
2157          });
2158          // alert("json.data.add_to_cart_error");
2159        } else {
2160          leafbridge_toast({
2161            heading: translations.errorHeading,
2162            text: translations.cartUpdateFailText,
2163            showHideTransition: "slide",
2164            position: "top-right",
2165            icon: "error",
2166            bgColor: "#fd3c51",
2167            textColor: "white",
2168            hideAfte
2168r: 20000,
2169          });
2170        }
2171      })
2172      .catch(function (err) {
2173        console.error("ajax_update_cart_item_qunatity err", err);
2174      });
2175  });
2176
2177  // Update cart automatically when clicking +,- buttons
2178  $(document).on('click', '.cart_item_count .changecount', function (e) {
2179    e.preventDefault();
2180
2181    var current_count = $(this).closest('.cart_item_count').find('.cart_item_count_val');
2182    var current_count_val = parseInt(current_count.val());
2183    var current_min = parseInt(current_count.attr('min'));
2184    var current_max = parseInt(current_count.attr('max'));
2185
2186    var new_value = ($(this).hasClass('cart_count_down')) ? current_count_val - 1 : current_count_val + 1;
2187    new_value = (new_value > current_max) ? current_max : new_value;
2188    new_value = (new_value < current_min) ? current_min : new_value;
2189
2190    current_count.val(new_value);
2191
2192    var itemBox = $(this).closest('.floating_cart_item_box');
2193    var itemId = itemBox.attr("cart_item_id");
2194    var quantity = new_value;
2195    var leafbridge_cart_data = JSON.parse(localStorage.getItem("leafbridge_cart_data"));
2196    var retailerId = leafbridge_cart_data.retailer_id;
2197    var checkoutId = leafbridge_cart_data.new_checkout_id;
2198
2199    // Call the AJAX function to update the cart
2200    ajax_update_cart_item_qunatity(retailerId, checkoutId, itemId, quantity)
2201      .then(function (json) {
2202        if (json.data.cart_html) {
2203          render_cart(json.data);
2204        } else if (json.data.update_cart_error) {
2205          leafbridge_toast({
2206            heading: translations.errorHeading,
2207            text: json.data.update_cart_error,
2208            showHideTransition: "slide",
2209            position: "top-right",
2210            icon: "error",
2211            bgColor: "#fd3c51",
2212            textColor: "white",
2213            hideAfter: 20000,
2214          });
2215        }
2216      })
2217      .catch(function (err) {
2218        console.error("ajax_update_cart_item_qunatity error", err);
2219      });
2220  });
2221
2222  // $(document).on('click', '.cart_item_count .changecount', function (e) {
2223  //   e.preventDefault();
2224  //   var current_count = $(this).closest('.cart_item_count').find('.cart_item_count_val');
2225  //   var current_count_val = parseInt(current_count.val());
2226  //   var current_min = parseInt(current_count.attr('min'));
2227  //   var current_max = parseInt(current_count.attr('max'));
2228  //   var new_value = ($(this).hasClass('cart_count_down')) ? current_count_val - 1 : current_count_val + 1;
2229  //   new_value = (new_value > current_max) ? current_max : new_value;
2230  //   new_value = (new_value < current_min) ? current_min : new_value;
2231  //   $(this).closest('.cart_item_count').find('.cart_item_count_val').val(new_value);
2232  // })
2233
2234  $(document).on('click', '.dominant_terp_node', function (e) {
2235    var target_terp_descr = $(this).attr('target_id');
2236    $('.active_terp_label').removeClass('active_terp_label');
2237    $(this).addClass('active_terp_label');
2238
2239    $('.terp_description_card').removeClass('show_terp_descriotion');
2240    $('#' + target_terp_descr).toggleClass('show_terp_descriotion');
2241  })
2242
2243  //ajax function to edit cart item qunantity
2244  function ajax_update_cart_item_qunatity(retailerId, checkoutId, itemId, quantity) {
2245    return new Promise(function (resolve, reject) {
2246      var data = {
2247        action: "leafbridge_update_cart_item_quantity",
2248        retailerId: retailerId,
2249        checkoutId: checkoutId,
2250        itemId: itemId,
2251        quantity: quantity,
2252        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2253      };
2254
2255      $.ajax({
2256        url: leafbridge_public_ajax_obj.ajaxurl,
2257        dataType: "json",
2258        cache: false,
2259        data: data,
2260        type: "POST",
2261        proccessData: false,
2262        beforeSend: function () { },
2263        success: function (json) {
2264          resolve(json);
2265          set_cart_prod_count(json.data.update_cart.items);
2266        },
2267        error: function (json) {
2268          show_system_error(json.data);
2269          reject(json);
2270        },
2271        complete: function (json) { },
2272      });
2273    });
2274  }
2275
2276  //Reset reatiler , menu type and delivery selection
2277  // AKA reset checkout
2278  // reset selection
2279  $(document).on("click", "#leafbridge_shop_wizard_reset_selection_confirm .wizard_reset", function (e) {
2280    var wizard_reset = $(this).val();
2281    if (wizard_reset == "no") {
2282      $("#leafbridge_shop_wizard_popup").hide();
2283    } else {
2284      e.preventDefault();
2285      // var leafbridge_wizard_data = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
2286      // leafbridge_wizard_data.reset_flag = true;
2287      // localStorage.setItem('leafbridge_wizard_data',JSON.stringify(leafbridge_wizard_data));
2288
2289      // remove local storage items so it will create new checkout when adding first product to chekcout
2290      // localStorage.removeItem("leafbridge_wizard_data");
2291      localStorage.removeItem("leafbridge_cart_data");
2292      render_empty_cart();
2293      // location.reload();
2294      // $('#leafbridge_shop_wizard_set_location button[data_direction="#leafbridge_shop_wizard_set_age"]').hide();
2295    }
2296  });
2297
2298  // ajax function to reset checkout
2299  function ajax_reset_checkout(wizard_data) {
2300    return new Promise(function (resolve, reject) {
2301      var data = {
2302        action: "leafbridge_reset_checkout",
2303        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2304        wizard_data: wizard_data,
2305      };
2306
2307      $.ajax({
2308        url: leafbridge_public_ajax_obj.ajaxurl,
2309        dataType: "json",
2310        cache: false,
2311        data: data,
2312        type: "POST",
2313        proccessData: false,
2314        beforeSend: function () { },
2315        success: function (json) {
2316          resolve(json);
2317        },
2318        error: function (json) {
2319          reject(json);
2320        },
2321        complete: function (json) { },
2322      });
2323    });
2324  }
2325
2326  // function to render the cartitems
2327  function render_cart(cart_data) {
2328    $("#floating_cart").attr("cart_data", JSON.stringify(cart_data));
2329    $("#floating_cart .floating_cart_footer_wrapper").fadeIn();
2330    $("#floating_cart .floating_cart_items_inner").html(cart_data.cart_html);
2331
2332    if (cart_data.update_cart.redirectUrl) {
2333      var checkout_url = cart_data.update_cart.redirectUrl;
2334      checkout_url += "?r=" + cart_data.order_details_url;
2335      $("#floating_cart .floating_cart_footer a").attr("href", checkout_url);
2336    }
2337
2338    var subtotal = convert_and_format_numbers(cart_data.update_cart.priceSummary.subtotal);
2339    var discounts = convert_and_format_numbers(cart_data.update_cart.priceSummary.discounts);
2340    var fees = convert_and_format_numbers(cart_data.update_cart.priceSummary.fees);
2341    var mixAndMatch = convert_and_format_numbers(cart_data.update_cart.priceSummary.mixAndMatch);
2342    var rewards = convert_and_format_numbers(cart_data.update_cart.priceSummary.rewards);
2343    var taxes = convert_and_format_numbers(cart_data.update_cart.priceSummary.taxes);
2344    var total = convert_and_format_numbers(cart_data.update_cart.priceSummary.total);
2345
2346    // show cart expenses
2347    var cart_total_html = "";
2348    cart_total_html += cart_data.update_cart.priceSummary.subtotal > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.subtotal + '</span><span class="cart_amnt_val"> $' + subtotal + "</span></span>" : "";
2349    cart_total_html += cart_data.update_cart.priceSummary.discounts >= 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.discounts + '</span><span class="cart_amnt_val"> ($' + discounts + ")</span></span>" : "";
2350    cart_total_html += cart_data.update_cart.priceSummary.fees > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.fees + '</span><span class="cart_amnt_val"> $' + fees + "</span></span>" : "";
2351    cart_total_html += cart_data.update_cart.priceSummary.mixAndMatch > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.mixAndMatch + '</span><span class="cart_amnt_val"> $' + mixAndMatch + "</span></span>" : "";
2352    cart_total_html += cart_data.update_cart.priceSummary.rewards > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.rewards + '</span><span class="cart_amnt_val"> $' + rewards + "</span></span>" : "";
2353    cart_total_html += cart_data.update_cart.priceSummary.taxes > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.taxes + '</span><span class="cart_amnt_val"> $' + taxes + "</span></span>" : "";
2354    cart_total_html += cart_data.update_cart.priceSummary.total > 0 ? '<span class="cart_amnt_parent"><span class="cart_amnt_label">' + translations.total + '</span><span class="cart_amnt_val"> $' + total + "</span></span>" : "";
2355
2356    $(".floating_cart_notes").html(cart_total_html);
2357    $("#floating_cart .floating_cart_footer a span.cart_total").html(" - $" + total);
2358
2359    // show cart quantity
2360    var cart_quantity = 0;
2361    var cart_items = cart_data.update_cart.items;
2362    for (const [key, value] of Object.entries(cart_items)) {
2363      cart_quantity = cart_quantity + value.quantity;
2364    }
2365
2366    if (cart_quantity > 0) {
2367      $(".cart_count").text(cart_quantity);
2368      $(".open_the_cart_button_icon").find(".cart_count").length == 0 ? $(".open_the_cart_button_icon").append('<span class="cart_count otcbi">' + cart_quantity + "</span>") : "";
2369    } else {
2370      render_empty_cart();
2371    }
2372  }
2373
2374  function render_empty_cart() {
2375    $("#floating_cart .floating_cart_items_inner").html('<p style="text-align:center;width:100%">' + translations.emptyCart + "</p>");
2376    $("#floating_cart .floating_cart_footer_wrapper").hide();
2377    $(".cart_count").text("");
2378  }
2379
2380  function convert_and_format_numbers(number) {
2381    var float_number_in_cents = parseFloat(number);
2382    var float_number_in_usd = float_number_in_cents / 100;
2383    var float_number_in_decimals = float_number_in_usd.toFixed(2);
2384    var float_number_formatted = float_number_in_decimals.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
2385    return float_number_formatted;
2386  }
2387
2388  // ajax function to load oder details
2389  function ajax_get_order_details() {
2390    return new Promise(function (resolve, reject) {
2391      var url_string = window.location.href;
2392      var url = new URL(url_string);
2393      var orderNumber = url.searchParams.get("orderNumber");
2394
2395      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2396      var retailer_id = leafbridge_wizard_data.retailer_id;
2397
2398      var data = {
2399        retailerId: retailer_id,
2400        orderId: orderNumber,
2401        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2402        action: "leafbridge_order_details",
2403      };
2404
2405      $.ajax({
2406        url: leafbridge_public_ajax_obj.ajaxurl,
2407        dataType: "json",
2408        cache: false,
2409        data: data,
2410        type: "POST",
2411        proccessData: true,
2412        beforeSend: function () {
2413          //$('#lb_order_preloader').fadeIn();
2414        },
2415        success: function (json) {
2416          //$('#lb_order_preloader').fadeOut();
2417          resolve(json);
2418          //$('.lb-order-inner').fadeIn();
2419        },
2420        error: function (json) {
2421          //$('#lb_order_preloader').fadeOut();
2422          show_system_error(json.data);
2423          reject(json);
2424          //$('.lb-order-inner').fadeIn();
2425        },
2426        complete: function (json) {
2427          //$('#lb_order_preloader').fadeOut();
2428          //$('.lb-order-inner').fadeIn();
2429        },
2430      });
2431    });
2432  }
2433
2434  function single_prod_page_fetch() {
2435    if ($("div").hasClass("lb_single_prod_page_wrapper")) {
2436      var error_add_to_cart = "This Item is not available with the selected retailer. Please reset the selection if you wish to buy this item.";
2437      ajax_get_product_page()
2438        .then(function (json) {
2439          $(".lb_prod_single_add_to_cart.lb_prod_single_section").html(json.data.render_html);
2440          var passing_ret_id = JSON.parse(localStorage.getItem('leafbridge_wizard_data')).retailer_id;
2441          var get_menu_type = JSON.parse(localStorage.getItem('leafbridge_wizard_data')).menu_type;
2442
2443          if (json.data.render_html.includes("prod_real_retailer")) {
2444            ajax_get_retailer_details(passing_ret_id)
2445              .then(function (json) {
2446                $("#prod_real_retailer").html(json.data.lb_retailer_custom_name);
2447              })
2448              .catch(function (json) {
2449                console.error("single_prod_page_fetch err", json);
2450              });
2451          }
2452
2453          if (json.data.product_node.tags) {
2454            var product_tags = json.data.product_node.tags ? json.data.product_node.tags : false;
2455            var product_pos_cats = json.data.product_node.posMetaData.category ? json.data.product_node.posMetaData.category : false;
2456
2457            $("#tags_locator").html('<div class="pos_tags_view"></div>');
2458
2459            if (product_pos_cats) {
2460              $("#tags_locator .pos_tags_view").append('<span class="pos_cat_name">' + product_pos_cats + "</span>");
2461            }
2462
2463            if (product_tags) {
2464              for (const [key, value] of Object.entries(product_tags)) {
2465                $("#tags_locator .pos_tags_view").append('<span class="pos_tag_name">' + value + "</span>");
2466              }
2467            }
2468          }
2469
2470          prod_page_show_relevant_retailer();
2471
2472          // showing COA dynamic link
2473          if (json.data.labResultUrl) {
2474            $('.coa_link_section').removeClass('hide_coa_link');
2475            $('.coa_link_section').find('a.coa_link_a').attr('href', json.data.labResultUrl);
2476          }
2477          else {
2478            $('.coa_link_section').remove();
2479          }
2480
2481          // filtering prod available retailers 
2482          if (json.data.synced_retailers) {
2483            var synced_retailers = json.data.synced_retailers;
2484            $('.available-retailer-name').each(function (el, i) {
2485              var current_avai_ret = $(this);
2486              var check_retid = current_avai_ret.attr('data-retailer-id');
2487              if (!synced_retailers.hasOwnProperty(check_retid)) {
2488                current_avai_ret.remove();
2489              }
2490            })
2491          }
2492
2493          //GTM view_item push to data layer - START
2494          var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2495          var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
2496
2497          var json = {};
2498          var item_data = null;
2499          item_data = JSON.parse($(".lb_prod_single_add_to_cart").attr("filter_data"));
2500
2501          var cart_prod = {
2502            product_id: item_data.product_id,
2503            variation: item_data.variants[0].option,
2504            prod_count: 1,
2505            prod_name: item_data.item_name,
2506          };
2507
2508          if (item_data != null && leafbridge_recent_location != null) {
2509            json.moreDataLayerPush = {
2510              item_data: item_data,
2511              cart_prod: cart_prod,
2512              location_id: leafbridge_wizard_data.retailer_id,
2513              location_name: leafbridge_recent_location.retailer_name,
2514              menu_type: leafbridge_wizard_data.menu_type,
2515            };
2516            gtm_push_single_item_data(json, "LB_ViewItem");
2517          }
2518          //GTM view_item push to data layer - END
2519          prod_page_get_specials();
2520
2521          $('#available_locations .available-retailer-name').each(function (el) {
2522            try{
2523              $(this).attr('data_menu_type', get_menu_type);
2524              var old_url = $(this).find('.retailer-link').attr('href');
2525              var old_url_obj = new URL(old_url);
2526              var old_url_params = new URLSearchParams(old_url_obj.search);
2527              old_url_params.set('menu_type', get_menu_type);
2528              old_url_obj.search = old_url_params.toString();
2529              var update_url = old_url_obj.toString();
2530              $(this).find('.retailer-link').attr('href', update_url);
2531  
2532              $(this).find('.OR_toggle').attr('data_menu_type', get_menu_type);
2533            }
2534            catch(error){
2535               console.error(error);
2536            }
2537          });
2538        })
2539        .catch(function (json) {
2540          console.error("ajax-get_product_page err", json);
2541          $(".lb_prod_single_add_to_cart.lb_prod_single_section").html(error_add_to_cart);
2542        });
2543    }
2544  }
2545
2546  function prod_page_get_specials() {
2547    var prod_page_specials_list = []; // to record the specials details where the current product belongs to
2548    var specials_id = null;
2549    var specials_name = null;
2550    var specials_desc = null;
2551
2552    var specialConditionIds = $('#lb_prod_single_offers').attr('specialConditionIds');
2553    var specialRewardIds = $('#lb_prod_single_offers').attr('specialRewardIds');
2554
2555    specialConditionIds = specialConditionIds != '' ? JSON.parse(specialConditionIds) : [];
2556    specialRewardIds = specialRewardIds != '' ? JSON.parse(specialRewardIds) : [];
2557
2558    ajax_get_retailer_specials()
2559      .then(function (json) {
2560        var ret_specials = json.data.getSpecials; //getting 4 specials
2561        var ret_specials_size = Object.keys(ret_specials).length;
2562        const ret_specials_sorted = ret_specials.reduce((acc, item) => {
2563          acc[item.id] = item;
2564          return acc;
2565        }, {});
2566
2567
2568        specialConditionIds.forEach(spConditionId => {
2569          var temp_sp = ret_specials_sorted[spConditionId];
2570          if (temp_sp) {
2571            var get_specials_id = temp_sp.id;
2572            var get_specials_name = temp_sp.menuDisplayConfiguration.name;
2573            var get_specials_desc = temp_sp.menuDisplayConfiguration.description;
2574
2575            get_specials_name = (get_specials_name != null) ? get_specials_name : '';
2576            get_specials_desc = (get_specials_desc != null) ? get_specials_desc : '';
2577            get_specials_id = (get_specials_id != null) ? get_specials_id : '';
2578
2579            $("#offers_overlay").fadeOut();
2580            $("#offers_stack_div").fadeIn();
2581            $("#offers_stack").append('<div class="offer_box"><div class="offer_title_div"><span class="spec_name_span">' + get_specials_name + '</span><span class="spec_desc_span">' + get_specials_desc + '</span></div><div class="offer_desc_div">
2581<a class="shop_offer" href="/specials/?specials_id=' + get_specials_id + '">Shop offer</a></div></div>');
2582          }
2583        });
2584        specialRewardIds.forEach(spRewardId => {
2585          var temp_sp = ret_specials_sorted[spRewardId];
2586          if (temp_sp) {
2587            var get_specials_id = temp_sp.id;
2588            var get_specials_name = temp_sp.menuDisplayConfiguration.name;
2589            var get_specials_desc = temp_sp.menuDisplayConfiguration.description;
2590
2591            get_specials_name = (get_specials_name != null) ? get_specials_name : '';
2592            get_specials_desc = (get_specials_desc != null) ? get_specials_desc : '';
2593            get_specials_id = (get_specials_id != null) ? get_specials_id : '';
2594
2595            $("#offers_overlay").fadeOut();
2596            $("#offers_stack_div").fadeIn();
2597            $("#offers_stack").append('<div class="offer_box"><div class="offer_title_div"><span class="spec_name_span">' + get_specials_name + '</span><span class="spec_desc_span">' + get_specials_desc + '</span></div><div class="offer_desc_div"><a class="shop_offer" href="/specials/?specials_id=' + get_specials_id + '">Shop offer</a></div></div>');
2598
2599          }
2600        });
2601
2602        specialConditionIds
2603        specialRewardIds
2604        // get product page product id
2605        // var prod_id = $(".single-product .lb_single_prod_page_wrapper").attr("data_product_id");
2606
2607        // // loop through specials
2608        // for (var i = 0; i < specials_array.length; i++) {
2609        //   specials_id = specials_array[i]["id"]; // or either try var specials_id = specials_array[i].id
2610        //   specials_name = specials_array[i]["name"];
2611        //   specials_desc = specials_array[i]["menuDisplayConfiguration"]["description"];
2612
2613        //   // call the promise to get specials products
2614        //   // var specials_products = get_specials_products(specials_id);
2615
2616        //   get_specials_products(specials_id, specials_name, specials_desc)
2617        //     .then(function (json) {
2618        //       var get_specials_id = json.specials_id;
2619        //       var get_specials_name = json.specials_name;
2620        //       var get_specials_desc = json.specials_desc;
2621
2622        //       // getting all products under each special menu.
2623        //       var specials_products = json.data.products_list;
2624
2625        //       // loop again through specials_products and find if any product ID matches with current product page's product id
2626        //       for (var j = 0; j < specials_products.length; j++) {
2627        //         if (prod_id == specials_products[j]["id"]) {
2628        //           $("#offers_overlay").fadeOut();
2629        //           $("#offers_stack_div").fadeIn();
2630        //           $("#offers_stack").append('<div class="offer_box"><div class="offer_title_div"><span class="spec_name_span">' + get_specials_name + '</span><span class="spec_desc_span">' + get_specials_desc + '</span></div><div class="offer_desc_div"><a class="shop_offer" href="/specials/?specials_id=' + get_specials_id + '">Shop offer</a></div></div>');
2631        //         }
2632        //       }
2633        //     })
2634        //     // .then(function(json){})
2635        //     .catch(function (json) {
2636        //       console.error("error #@ get_specials_products promise call", json);
2637        //     });
2638        // }
2639      })
2640      .catch(function (json) {
2641        console.error(json);
2642      });
2643  }
2644
2645  function get_specials_products(specials_id, specials_name, specials_desc) {
2646    return new Promise(function (resolve, reject) {
2647      var filter_attributes = {};
2648      filter_attributes.MenuSectionFilter = "SPECIALS";
2649      filter_attributes.special_id = specials_id;
2650      filter_attributes.sort_order = "NAME_ASC";
2651      filter_attributes.search_key_word = "";
2652
2653      // var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2654      var leafbridge_wizard_data = {};
2655      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2656
2657      ajax_get_filtered_products(filter_attributes)
2658        .then(function (json) {
2659          json.specials_id = specials_id;
2660          json.specials_name = specials_name;
2661          json.specials_desc = specials_desc;
2662          resolve(json);
2663        })
2664        .catch(function (json) {
2665          // console.error("get filtered prods ", json);
2666          reject(json);
2667          // return null;
2668        });
2669    });
2670  }
2671
2672  // ajax promise to load retailer details by passing retalier id
2673  function ajax_get_retailer_details(retailer_id) {
2674    return new Promise(function (resolve, reject) {
2675      var data = {
2676        action: "load_retailer_name",
2677        retailer_id: retailer_id,
2678        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2679      };
2680      $.ajax({
2681        type: "POST",
2682        dataType: "json",
2683        cache: false,
2684        proccessData: false,
2685        url: leafbridge_public_ajax_obj.ajaxurl,
2686        data: data,
2687        success: function (json) {
2688          if(json.data.dynamic_data){
2689            localStorage.setItem("dl_lb_lc_details", JSON.stringify(json.data.dynamic_data));
2690          }
2691          resolve(json);
2692        },
2693        error: function (json) {
2694          show_system_error(json.data);
2695          reject(json);
2696        },
2697        complete: function (json) { },
2698      });
2699    });
2700  }
2701
2702  // ajax function to load product detail on single product page
2703  function ajax_get_product_page() {
2704    return new Promise(function (resolve, reject) {
2705      var unavailable_product = false;
2706      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2707      var retailer_id = leafbridge_wizard_data.retailer_id;
2708      var menu_type = leafbridge_wizard_data.menu_type;
2709      
2710      var product_id = $(".lb_single_prod_page_wrapper").attr("data_real_product_id");
2711      
2712      var data = {
2713        unavailable_product: unavailable_product,
2714        retailerId: retailer_id,
2715        product_id: product_id,
2716        menu_type: menu_type,
2717        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2718        page_url: window.location.href,
2719        action: "leafbridge_single_product",
2720      };
2721
2722      $.ajax({
2723        url: leafbridge_public_ajax_obj.ajaxurl,
2724        dataType: "json",
2725        cache: false,
2726        data: data,
2727        type: "POST",
2728        proccessData: false,
2729        beforeSend: function () {
2730          var svg_animation = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: none; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid"> <circle cx="50" cy="50" fill="none" stroke="#c8c8c8" stroke-width="10" r="35" stroke-dasharray="164.93361431346415 56.97787143782138"> <animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform> </circle> </svg>';
2731          $(".lb_prod_single_add_to_cart.lb_prod_single_section").html(svg_animation);
2732        },
2733        success: function (json) {
2734          resolve(json);
2735          var product = json.data.product_node;
2736          var category = product.category || "";
2737          
2738          var viewedProduct = {
2739            retailerId: json.data.retailerId,
2740            productId: product.id,
2741            name: product.name,
2742            brand: (product.brand) ? product.brand.name : '',
2743            image: product.image,
2744            variants: product.variants.map(function (variant) {
2745              return {
2746                priceMed: variant.priceMed || '',
2747                priceRec: variant.priceRec || '',
2748                specialPriceMed: variant.specialPriceMed || '',
2749                specialPriceRec: variant.specialPriceRec || '',
2750                quantity: variant.quantity || ''
2751              };
2752            }),
2753            productLink: json.data.page_url
2754          };
2755
2756          var recentlyViewed = JSON.parse(localStorage.getItem("recently_viewed_products")) || {};
2757
2758          if (!recentlyViewed[viewedProduct.retailerId]) {
2759            recentlyViewed[viewedProduct.retailerId] = [];
2760          }
2761
2762          var existingProductIndex = recentlyViewed[viewedProduct.retailerId].findIndex(p => p.productId === viewedProduct.productId);
2763
2764          if (existingProductIndex !== -1) {
2765            var existingProduct = recentlyViewed[viewedProduct.retailerId].splice(existingProductIndex, 1)[0];
2766            recentlyViewed[viewedProduct.retailerId].push(existingProduct);
2767          } else {
2768            if (recentlyViewed[viewedProduct.retailerId].length >= 10) {
2769              recentlyViewed[viewedProduct.retailerId].shift();
2770            }
2771            recentlyViewed[viewedProduct.retailerId].push(viewedProduct);
2772          }
2773
2774          update_featured_brand_carousel(category);
2775
2776          localStorage.setItem("recently_viewed_products", JSON.stringify(recentlyViewed));
2777
2778          $(".lb_prod_single_add_to_cart.lb_prod_single_section").html(json.data.render_html);
2779          $('#moodidays_product_reveiw_wrapper').html('');
2780          $('#moodidays_product_reveiw_wrapper').append('<div id="moodi-day-widget" data-productid="' + product.id + '"></div>');
2781
2782        },
2783        error: function (json) {
2784          show_system_error(json.data);
2785          reject(json);
2786        },
2787        complete: function (json) { },
2788      });
2789    });
2790  }
2791
2792  function show_category_products(item_list_element) {
2793    // function to show category pages
2794    setTimeout(function () {
2795      if ($("div").hasClass("lb_categories_wrapper")) {
2796        const urlParams = new URLSearchParams(window.location.search);
2797        const param_pagination = parseInt(urlParams.get("pagination"));
2798
2799        if (param_pagination) {
2800          $(".wizard_category_products_pagination button.next").attr("data_page", param_pagination - 1);
2801          $(".wizard_category_products_pagination button.next").trigger("click");
2802          $(".wizard_category_products_pagination button.next").attr("data_page", param_pagination);
2803          $(".wizard_category_products_pagination button.prev").attr("data_page", param_pagination - 2);
2804        } else {
2805          ajax_get_category_products()
2806            .then(function (json) {
2807              $(".wizard_category_products_showcase").html(json.data.products_html);
2808              $("#wizard_prods_view").fadeOut();
2809              dl_view_item_list(item_list_element,json);
2810            })
2811            .catch(function (json) {
2812              console.error("ajax get category products err", json);
2813              $(".wizard_category_products_showcase").html("<p>No Available Products</p>");
2814              $("#wizard_prods_view").fadeOut();
2815              // $('.wizard_category_products_pagination').fadeOut();
2816            });
2817        }
2818      }
2819    }, 200);
2820  }
2821
2822  // ajax function to load category products
2823  function ajax_get_category_products() {
2824    return new Promise(function (resolve, reject) {
2825      var this_category = $(".lb_categories_wrapper").attr("data_category");
2826
2827      var data = {
2828        action: "wizard_show_products",
2829        wizard_data: JSON.parse(localStorage.getItem("leafbridge_wizard_data")),
2830        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2831        prod_categories: this_category,
2832      };
2833      $.ajax({
2834        url: leafbridge_public_ajax_obj.ajaxurl,
2835        dataType: "json",
2836        cache: false,
2837        data: data,
2838        type: "POST",
2839        proccessData: false,
2840        success: function (json) {
2841          resolve(json);
2842        },
2843        error: function (json) {
2844          reject(json);
2845        },
2846        complete: function (json) { },
2847      });
2848    });
2849  }
2850
2851  function ajax_get_retailer_pages(){
2852    return new Promise(function(resolve,reject){
2853      var data = {
2854        nonce_ajax : leafbridge_public_ajax_obj.nonce
2855      }
2856
2857      $.ajax({
2858        url : leafbridge_public_ajax_obj.ajax_url,
2859        dataType : 'json',
2860        cache : false,
2861        data : data,
2862        type : 'POST',
2863        proccessData: false,
2864        success: function (json) {
2865          resolve(json);
2866        },
2867        error: function (json) {
2868          reject(json);
2869        },
2870        complete: function (json) { },
2871      })
2872    });
2873  }
2874  /*
2875   * new sticky wizard functionalities
2876   */
2877  // select store and show store's menu type selector
2878  $(document).on("change", "#select_store_sticky_wizard", function (event) {
2879    var this_val = $(this).val();
2880
2881    $("#select_collection_type_sticky_wizard").prop("disabled", true);
2882    $("#select_collection_type_sticky_wizard option").remove();
2883    $("#select_collection_type_sticky_wizard").append('<option value="">Please Select</option>');
2884
2885    if (this_val !== "") {
2886      // show the menutype dropdown depending on retailer selection
2887      var target_menutype_selector_wrapper = $(".menu_type_selector[retailer_id=" + this_val + "]");
2888      target_menutype_selector_wrapper.siblings(".menu_type_selector").hide();
2889      target_menutype_selector_wrapper.find("select").prop("disabled", true);
2890      target_menutype_selector_wrapper.show();
2891      target_menutype_selector_wrapper.find("select").prop("disabled", false);
2892    } else {
2893      $(".menu_type_selector select").prop("disabled", true);
2894      $("#set_floating_wizard_data").prop("disabled", true);
2895    }
2896    reset_cart();
2897  });
2898
2899  // select menu type after selecting the retailer
2900  $(document).on("change", ".menu_type_selector select", function () {
2901    $("#set_floating_wizard_data").prop("disabled", true);
2902    $(this).closest("#menu_types_selector_wrapper").attr("selected_menu_type", $(this).val());
2903    var retailer_id = $(this).closest(".menu_type_selector").attr("retailer_id");
2904    populate_delivery_pickup_dropdown(retailer_id, "");
2905    reset_cart();
2906  });
2907
2908  function populate_delivery_pickup_dropdown(retailer_id, collection_method) {
2909    if (collection_method == "") {
2910      // var url_string  = window.location.href;
2911      // var url = new URL(url_string);
2912      // var leafbridge_wizard_data = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
2913      // collection_method = (url.searchParams.get("collection_type")) ? url.searchParams.get("collection_type") : leafbridge_wizard_data.collection_method;
2914    }
2915
2916    $(".loading_collection_methods").addClass("show");
2917    get_delivery_pickup(retailer_id)
2918      .then(function (json) {
2919        if ($("div").hasClass("retailer_based_store")) {
2920          var disp_order_type_e = $(".retailer_based_store").attr("order_type");
2921          var disp_order_type = disp_order_type_e.toLowerCase();
2922          $(".header_stiky_wizard_inner select").prop("disabled", "disabled");
2923          $("#select_collection_type_sticky_wizard").html('<option value="' + disp_order_type_e + '" >' + disp_order_type.charAt(0).toUpperCase() + disp_order_type.slice(1) + "</option>");
2924          $("#select_collection_type_sticky_wizard").val(disp_order_type_e);
2925          $("#select_collection_type_sticky_wizard").prop("disabled", true);
2926        } else {
2927          $("#select_collection_type_sticky_wizard").prop("disabled", false);
2928          if (json.data.data) {
2929            json.data.data.fulfillmentOptions.delivery ? ($('#select_collection_type_sticky_wizard option[value="DELIVERY"]').length == 0 ? $("#select_collection_type_sticky_wizard").append('<option value="DELIVERY">' + translations.delivery + "</option>") : "") : "";
2930            json.data.data.fulfillmentOptions.pickup ? ($('#select_collection_type_sticky_wizard option[value="PICKUP"]').length == 0 ? $("#select_collection_type_sticky_wizard").append('<option value="PICKUP">
2930' + translations.pickup + "</option>") : "") : "";
2931            json.data.data.fulfillmentOptions.curbsidePickup ? ($('#select_collection_type_sticky_wizard option[value="curbsidePickup"]').length == 0 ? $("#select_collection_type_sticky_wizard").append('<option value="curbsidePickup">' + translations.curbside + "</option>") : "") : "";
2932            json.data.data.fulfillmentOptions.driveThruPickup ? ($('#select_collection_type_sticky_wizard option[value="driveThruPickup"]').length == 0 ? $("#select_collection_type_sticky_wizard").append('<option value="driveThruPickup">' + translations.driveThru + "</option>") : "") : "";
2933          }
2934        }
2935
2936        // set collection type
2937        // $('#select_collection_type_sticky_wizard').val(collection_method.toUpperCase());
2938        $("#select_collection_type_sticky_wizard").val(collection_method);
2939        $(".loading_collection_methods").removeClass("show");
2940      })
2941      .catch(function (json) {
2942        console.error("get_delivery_pickup error", json);
2943      });
2944  }
2945
2946  // get raw data for pickup / delivery depending on retailer
2947  function get_delivery_pickup(retailer_id) {
2948    return new Promise(function (resolve, reject) {
2949      var data = {
2950        action: "show_delivery_pickup_ajax",
2951        retailer_id: retailer_id,
2952        nonce_ajax: leafbridge_public_ajax_obj.nonce,
2953      };
2954
2955      var return_data = null;
2956      $.ajax({
2957        url: leafbridge_public_ajax_obj.ajaxurl,
2958        dataType: "json",
2959        cache: false,
2960        data: data,
2961        type: "POST",
2962        proccessData: false,
2963        success: function (json) {
2964          resolve(json);
2965        },
2966        error: function (json) {
2967          reject(json);
2968        },
2969        complete: function (json) {
2970        },
2971      });
2972    });
2973  }
2974
2975  // enable SET button after selecting collection method
2976  $(document).on("change", "#select_collection_type_sticky_wizard", function () {
2977    var selected_retailer_id = $("#select_store_sticky_wizard").val();
2978    var selected_menu_type = $("#select_menu_type_sticky_wizard_" + selected_retailer_id).val();
2979    $("#menu_types_selector_wrapper").attr("selected_menu_type", selected_menu_type);
2980
2981    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
2982
2983    if (leafbridge_wizard_data != null) {
2984      leafbridge_wizard_data.menu_type = selected_menu_type;
2985      leafbridge_wizard_data.event = "on change select_collection_type_sticky_wizard";
2986    }
2987
2988    localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
2989
2990    $("#set_floating_wizard_data").prop("disabled", false);
2991
2992    setTimeout(function () {
2993      $("#set_floating_wizard_data").trigger("click");
2994    }, 100);
2995  });
2996
2997  // set button
2998  $(document).on("click", "#set_floating_wizard_data", function () {
2999    var leafbridge_wizard_data = {
3000      age_confirm: true,
3001      created_time: new Date(),
3002      collection_method: $("#select_collection_type_sticky_wizard").val(),
3003      retailer_id: $("#select_store_sticky_wizard").val(),
3004      menu_type: $("#menu_types_selector_wrapper").attr("selected_menu_type"),
3005      event: "on change set_floating_wizard_data",
3006    };
3007
3008    localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
3009
3010    // reset filter url paremeters
3011    reset_url_params();
3012
3013    setTimeout(function () {
3014      location.reload();
3015      // show_products_from_filter();
3016    }, 100);
3017  });
3018
3019  function load_default_retailer_settings() {
3020    return new Promise(function (resolve, reject) {
3021      var data = {
3022        action: "get_default_retailer",
3023        nonce_ajax: leafbridge_public_ajax_obj.nonce,
3024      };
3025      $.ajax({
3026        url: leafbridge_public_ajax_obj.ajaxurl,
3027        dataType: "json",
3028        cache: false,
3029        data: data,
3030        type: "POST",
3031        proccessData: false,
3032        success: function (json) {
3033          resolve(json);
3034        },
3035        error: function (json) {
3036          reject(json);
3037        },
3038        complete: function (json) { },
3039      });
3040    });
3041  }
3042  // sticky wizard reset button
3043  $(document).on("click", "#reset_retailer_selection , #reset_retailer_selection_v2", function () {
3044    $("#reset_notice_header").fadeIn();
3045    $("#floating_cart").removeClass("open_the_cart");
3046  });
3047
3048  // on confirm box button click
3049  $(document).on("click", ".new_reset_buttons_wrapper button", function (e) {
3050    var reset_button_val = $(this).val();
3051    if (reset_button_val == "no") {
3052      $("#reset_notice_header").hide();
3053    } else {
3054      e.preventDefault();
3055      localStorage.removeItem("leafbridge_wizard_data");
3056      reset_cart();
3057      location.reload();
3058    }
3059  });
3060
3061  // Force retailer change popup
3062  $(document).on("click", ".retailer-link", function (e) {
3063    e.preventDefault();
3064    var retailerId = $(this).closest(".available-retailer-name").data("retailer-id");
3065    var $menuTypeSelect = $(this).closest(".available-retailer-name").find("#menu-type-select");
3066    // var $menuTypeSelect = $(this).closest(".available-retailer-name").find(".OR_toggle").attr('data_menu_type');
3067    var menuType = $(this).closest(".available-retailer-name").find(".OR_toggle").attr('data_menu_type');
3068    var productLink = $(this).closest(".available-retailer-name").find(".OR_toggle").attr('data-product-link');
3069
3070    if (menuType) {
3071      productLink += "&menu_type=" + menuType;
3072    }
3073
3074    //var productLink = $(this).attr("href");
3075
3076    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data")) || {};
3077    var collection_type = leafbridge_wizard_data.collection_method || "PICKUP";
3078    leafbridge_wizard_data.retailer_id = retailerId;
3079    leafbridge_wizard_data.menu_type = menuType;
3080    leafbridge_wizard_data.collection_method = collection_type;
3081    reset_cart();
3082    localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
3083    window.location.href = productLink;
3084
3085    // $("#reset_notice_header").fadeIn();
3086    // $(document).on("click", ".new_reset_buttons_wrapper button", function(e) {
3087    //     var reset_button_val = $(this).val();
3088    //     if (reset_button_val === "no") {
3089    //         $("#reset_notice_header").hide();
3090    //     } else {
3091    //         var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data")) || {};
3092    //         var collection_type = leafbridge_wizard_data.collection_method || "PICKUP";
3093    //         leafbridge_wizard_data.retailer_id = retailerId;
3094    //         leafbridge_wizard_data.menu_type = menuType;
3095    //         leafbridge_wizard_data.collection_method = collection_type;
3096    //         reset_cart();
3097    //         localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
3098    //         window.location.href = productLink;
3099    //     }
3100    // });
3101  });
3102
3103  $(document).on('click', '.OR_toggle', function (e) {
3104    var selected_value = $(this).attr('data_menu_type');
3105    var new_value = "";
3106    new_value = (selected_value == "RECREATIONAL") ? "MEDICAL" : "RECREATIONAL";
3107    $(this).attr('data_menu_type', new_value);
3108    var old_url = $(this).closest('.available-retailer-name').find('.retailer-link').attr('href');
3109    var old_url_obj = new URL(old_url);
3110    var old_url_params = new URLSearchParams(old_url_obj.search);
3111    old_url_params.set('menu_type', new_value);
3112    old_url_obj.search = old_url_params.toString();
3113    var update_url = old_url_obj.toString();
3114    $(this).closest('.available-retailer-name').find('.retailer-link').attr('href', update_url);
3115  });
3116
3117  $(document).on('click', '.available_locations_seemore', function (e) {
3118    $('.lb_other-available_locations.lb_prod_single_section').toggleClass('showmore');
3119    $(this).remove();
3120  });
3121
3122  function prod_page_show_relevant_retailer() {
3123    /* * Show relevant available locations in single product page */
3124    const leafbridgeWizardData = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
3125    const currentRetailerId = leafbridgeWizardData.retailer_id;
3126    const retailerLinks = document.querySelectorAll('.available-retailer-name');
3127    let allHidden = true;
3128    retailerLinks.forEach(link => {
3129      const linkRetailerId = link.getAttribute('data-retailer-id');
3130      if (currentRetailerId === linkRetailerId) {
3131        link.style.display = 'none';
3132      } else {
3133        if (link.style.display !== 'none') {
3134          allHidden = false;
3135        }
3136      }
3137    });
3138
3139    const titleElement = document.querySelector('.available_location_title');
3140    const seeMoreElement = document.querySelector('.available_locations_seemore');
3141
3142    if (allHidden && titleElement) {
3143      titleElement.style.display = 'none';
3144      seeMoreElement.style.display = 'none';
3145    }
3146  }
3147
3148  // function to reset cart data
3149  function reset_cart() {
3150    var get_local_cart = localStorage.getItem("leafbridge_cart_data");
3151    if (get_local_cart) {
3152      let text = "You have added products to the cart. Changing retailer or menu type will remove items from your cart.";
3153      if (confirm(text) == true) {
3154        localStorage.removeItem("leafbridge_cart_data");
3155        render_empty_cart();
3156      } else {
3157        var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3158
3159        var selected_retailer = leafbridge_wizard_data.retailer_id;
3160        var menu_type = leafbridge_wizard_data.menu_type;
3161        var collection_type = leafbridge_wizard_data.collection_method;
3162
3163        $("#select_store_sticky_wizard").val(selected_retailer);
3164        $('.menu_type_selector[retailer_id="' + selected_retailer + '"]').show();
3165        $('.menu_type_selector[retailer_id="' + selected_retailer + '"]')
3166          .siblings("div")
3167          .hide();
3168        $('.menu_type_selector[retailer_id="' + selected_retailer + '"] select').val(menu_type);
3169        $('#select_collection_type_sticky_wizard option[value="' + collection_type + '"]').attr("selected", "selected");
3170      }
3171    } else {
3172      localStorage.removeItem("leafbridge_cart_data");
3173      render_empty_cart();
3174    }
3175  }
3176
3177  // reset url params
3178  function reset_url_params() {
3179    var page_url = window.location.href;
3180    var url = new URL(page_url);
3181
3182    var updated_url = "";
3183    updated_url = url.origin + url.pathname + "?pagination=1";
3184    window.history.pushState({}, "", updated_url);
3185  }
3186
3187  //main function to show specials page content
3188  function specials_page_get_specials_data() {
3189    // if ($('div').hasClass('leafbridge_special_products_wrapper')) {
3190    if ($("div").hasClass("leafbridge_special_products_wrapper specials_page_wrapper")) {
3191      // remove pagination url param from url
3192      var page_url = window.location.href;
3193      var url = new URL(page_url);
3194      var params = new URLSearchParams(url.search);
3195      var updated_url = "";
3196      var sort_order = $("#leafbridge_special_products_wrapper").attr("data_sort_order");
3197
3198      params.delete("pagination");
3199      var special_id_to_click = params.get("specials_id");
3200
3201      updated_url = url.origin + url.pathname + "?" + params.toString();
3202      window.history.pushState({}, "", updated_url);
3203
3204      // check selected retailer , menutype and collection if same on url and localstorage. if different, show a message to select them manually
3205      var leafbridge_wizard_data = {};
3206      if ($("div").hasClass("retailer_based_store")) {
3207        var force_leafbridge_wizard_data = {
3208          retailer_id: $(".retailer_based_store").attr("retailer_id"),
3209          menu_type: $(".retailer_based_store").attr("menu_type"),
3210          collection_method: $(".retailer_based_store").attr("order_type"),
3211        };
3212
3213        leafbridge_wizard_data = {
3214          age_confirm: true,
3215          collection_method: force_leafbridge_wizard_data.collection_method,
3216          created_time: new Date(),
3217          default_set: true,
3218          event: "FORCE WIZARD",
3219          menu_type: force_leafbridge_wizard_data.menu_type,
3220          retailer_id: force_leafbridge_wizard_data.retailer_id,
3221        };
3222      } else {
3223        leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3224      }
3225
3226      var selected_retailer = leafbridge_wizard_data.retailer_id;
3227      var menu_type = leafbridge_wizard_data.menu_type;
3228      var collection_type = leafbridge_wizard_data.collection_method;
3229
3230      var url_retailer = params.get("retailer_id") ? params.get("retailer_id") : selected_retailer;
3231      var url_menutype = params.get("menu_type");
3232      var url_collection_type = params.get("collection_type");
3233      var url_viewmore = params.get("viewmore") == "true" ? true : false;
3234
3235      if (url_retailer !== selected_retailer || url_menutype !== menu_type) {
3236        // var retailer_name = $('#select_store_sticky_wizard').find('option[value='+url_retailer+']').text();
3237        // var show_menu_type = url_menutype;
3238        // var collection_type = url_collection_type;
3239        // var show_combination = '<b>Retailer : '+retailer_name+', Menu Type : '+show_menu_type+', Collection type: '+collection_type+'</b>';
3240        // $('.specials_tab_notice').html("<b>You have selected a different retailer.</b><p>In order to view the specials mentioned in the url, please change the retailer, menutype and collection type combination to, <br/>"+show_combination+". <br/> or you can select a special menu given by the retailer you have already selected.</p>");
3241        // $('#select_store_sticky_wizard').val(url_retailer);
3242        // $('#select_menu_type_sticky_wizard_'+url_retailer).val(url_menutype);
3243        // $('#select_collection_type_sticky_wizard').val(url_collection_type);
3244      } else {
3245      }
3246
3247      ajax_get_retailer_specials(sort_order)
3248        .then(function (json) {
3249          if (json.data.getSpecials_html == "") {
3250            $("#leafbridge_special_products_wrapper .specials_tabs").html('<p style="text-align:center;">No Specials found with the selected retailer. Please select another retailer.</p>');
3251            $("#leafbridge_special_products_wrapper .specials_tabs").css("display", "block");
3252          } else {
3253            $("#leafbridge_special_products_wrapper .specials_tabs").css("display", "inline-grid");
3254            $("#leafbridge_special_products_wrapper .specials_tabs").html(json.data.getSpecials_html);
3255
3256            //check if url has viewmore attribute
3257            if (url_viewmore) {
3258              $(".leafbridge_special_products_wrapper .specials_tabs .specials_tab").fadeIn();
3259              $("#specials_view_more_wrapper").hide();
3260            } else {
3261              if (json.data.getSpecials.length > 4) {
3262                $("#specials_view_more_wrapper").fadeIn();
3263              } else {
3264                $("#specials_view_more_wrapper").hide();
3265              }
3266            }
3267
3268            // check if specials id is selected or not
3269            if (special_id_to_click != null) {
3270              $("#leafbridge_special_products_wrapper .specials_tabs .specials_tab[specials_id=" + special_id_to_click + "]").trigger("click");
3271            } else {
3272              // if specials_id is not assigned, click the 1st specials box
3273              $("#leafbridge_special_products_wrapper .specials_tabs .specials_tab").first().trigger("click");
3274            }
3275          }
3276        })
3277        .catch(function (json) {
3278          console.error(json);
3279        });
3280    }
3281  }
3282
3283  // ajax function to get retailer's specials data
3284  function ajax_get_retailer_specials(sort_order) {
3285    return new Promise(function (resolve, reject) {
3286      var data = {
3287        action: "get_retailer_specials",
3288        wizard_data: JSON.parse(localStorage.getItem("leafbridge_wizard_data")),
3289        user_timestamp: new Date(),
3290        sort_order: sort_order,
3291        // user_timestamp: new Date('2024-09-12 04:57:02'),
3292        nonce_ajax: leafbridge_public_ajax_obj.nonce,
3293      };
3294      $.ajax({
3295        url: leafbridge_public_ajax_obj.ajaxurl,
3296        dataType: "json",
3297        cache: false,
3298        data: data,
3299        type: "POST",
3300        proccessData: false,
3301        success: function (json) {
3302          resolve(json);
3303        },
3304        error: function (json) {
3305          show_system_error(json.data);
3306          reject(json);
3307        },
3308        complete: function (json) { },
3309      });
3310    });
3311  }
3312
3313  // on click specials page view more button
3314  $(document).on("click", ".special_cards_view_more_btn", function (e) {
3315    e.preventDefault();
3316    $(this).closest(".special_cards_view_more_btn").hide();
3317    $(".leafbridge_special_products_wrapper .specials_tabs .specials_tab").fadeIn();
3318  });
3319
3320  // on click of special id button
3321  $(document).on("click", ".specials_tab", function () {
3322    
3323    $(".wizard_specials_products_pagination").removeClass("visible_specials_pagination");
3324    var specials_id = $(this).attr("specials_id");
3325    var specials_override_count = $('#leafbridge_special_products_wrapper').attr('data_product_count');
3326    var filter_attributes = {};
3327
3328    filter_attributes.MenuSectionFilter = "SPECIALS";
3329    filter_attributes.special_id = specials_id;
3330    filter_attributes.sort_order = "PRICE_ASC";
3331    filter_attributes.search_key_word = "";
3332    filter_attributes.specials_override_count = specials_override_count;
3333    
3334
3335    var this_special_card = $(this);
3336
3337    $(this).siblings(".specials_tab").removeClass("active_tab");
3338    $(".specials_tab_content").addClass("loading_animation");
3339    $(this).addClass("active_tab");
3340    $(".specials_tab_content_inner").hide();
3341    $(".specials_tab_content_inner").html("");
3342
3343    $(".specials_tab_notice").html("");
3344    // set url params
3345    var page_url = window.location.href;
3346    var url = new URL(page_url);
3347    var params = new URLSearchParams(url.search);
3348    var updated_url = "";
3349
3350    params.delete("pagination");
3351
3352    // var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3353    var leafbridge_wizard_data = {};
3354    if ($("div").hasClass("retailer_based_store")) {
3355      var force_leafbridge_wizard_data = {
3356        retailer_id: $(".retailer_based_store").attr("retailer_id"),
3357        menu_type: $(".retailer_based_store").attr("menu_type"),
3358        collection_method: $(".retailer_based_store").attr("order_type"),
3359      };
3360
3361      leafbridge_wizard_data = {
3362        age_confirm: true,
3363        collection_method: force_leafbridge_wizard_data.collection_method,
3364        created_time: new Date(),
3365        default_set: true,
3366        event: "FORCE WIZARD",
3367        menu_type: force_leafbridge_wizard_data.menu_type,
3368        retailer_id: force_leafbridge_wizard_data.retailer_id,
3369      };
3370    } else {
3371
3372      leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3373    }
3374
3375    if (leafbridge_wizard_data != null) {
3376      var selected_retailer = leafbridge_wizard_data.retailer_id;
3377      var menu_type = leafbridge_wizard_data.menu_type;
3378      var collection_type = leafbridge_wizard_data.collection_method;
3379
3380      !params.get("retailer_id") ? params.append("retailer_id", selected_retailer) : params.set("retailer_id", selected_retailer);
3381      !params.get("menu_type") ? params.append("menu_type", menu_type) : params.set("menu_type", menu_type);
3382      !params.get("collection_type") ? params.append("collection_type", collection_type) : params.set("collection_type", collection_type);
3383      !params.get("specials_id") ? params.append("specials_id", specials_id) : params.set("specials_id", specials_id);
3384    }
3385
3386    updated_url = url.origin + url.pathname + "?" + params.toString();
3387    window.history.pushState({}, "", updated_url);
3388
3389    var specials_title_display = $(".specials_tab.active_tab .special_title").text();
3390    var specials_para_display = $(".specials_tab.active_tab .special_description").text();
3391    $(".specials_tabs_top .specials_title .specials_title_h2").text(specials_title_display);
3392    $(".specials_tabs_top .specials_title .specials_title_p").text(specials_para_display);
3393
3394    ajax_get_filtered_products(filter_attributes)
3395      .then(function (json) {
3396        dl_view_item_list(this_special_card,json);
3397        $(".specials_tab_content").removeClass("loading_animation");
3398        $(".specials_tab_content_inner").html(json.data.products_html);
3399        $(".specials_tab_content_inner").fadeIn();
3400
3401        prepare_specials_filter(json.data.specials_filter_html);
3402        var scroll_offset = window.screen.width > 768 ? parseInt(parseInt(window.screen.height)) / 2 : parseInt(parseInt(window.screen.height) / 3.3);
3403        var max_page_count = Math.ceil(json.data.products_count / json.data.prods_per_page + 1);
3404        var total_prod_count = json.data.products_count;
3405        $("html, body").animate({ scrollTop: $("#specials_tab_content").offset().top - scroll_offset }, 350);
3406        $("#sp_pagination_text").text(json.data.pagination_show_current_page_text);
3407        // Update pagination_text_with_no
3408        var paginationText = '';
3409        var pageNumbers = json.data.pagination_show_current_page_with_no.split(' ');
3410        var currentPageNumber = filter_attributes.prods_pageNumber;
3411
3412        for (var i = 0; i < pageNumbers.length; i++) {
3413          if (pageNumbers[i] === '...') {
3414            paginationText += '<span>' + pageNumbers[i] + '</span>';
3415          } else {
3416            // Check if the current page number matches the current page being iterated
3417            if (parseInt(pageNumbers[i]) === currentPageNumber) {
3418              paginationText += '<a href="#" class="leaf_bridge_btn sp_pagination_number current-page" data_page="' + pageNumbers[i] + '">' + pageNumbers[i] + '</a>';
3419            } else {
3420              paginationText += '<a href="#" class="leaf_bridge_btn sp_pagination_number" data_page="' + pageNumbers[i] + '">' + pageNumbers[i] + '</a>';
3421            }
3422          }
3423        }
3424
3425        $('#sp_pagination_text_with_no').html(paginationText);
3426
3427        var paginationStyle = json.data.pagination_style;
3428
3429        $(".wizard_specials_products_pagination.allow_pages").hide();
3430
3431        // Show the appropriate pagination container based on pagination_style
3432        if (paginationStyle === 'next_prev') {
3433          $(".wizard_specials_products_pagination.allow_pages:first").show();
3434        }
3435        else if (paginationStyle === 'next_prev_with_page_buttons') {
3436          $(".wizard_specials_products_pagination.allow_pages:last").show();
3437        }
3438
3439        // if (total_prod_count < 20) {
3440        if (total_prod_count < json.data.prods_per_page) {
3441          $(".wizard_specials_products_pagination button.sp_prev").hide();
3442          $(".wizard_specials_products_pagination button.sp_next").hide();
3443          $("#sp_pagination_text").hide();
3444        }
3445        else {
3446          $("#sp_pagination_text").show();
3447          // hide prev btn on first page
3448          if ($(".wizard_specials_products_pagination button.sp_prev").attr("data_page") == 0) {
3449            $(".wizard_specials_products_pagination button.sp_prev").hide();
3450            $(".wizard_specials_products_pagination button.sp_next").show();
3451          } else if ($(".wizard_specials_products_pagination button.sp_next").attr("data_page") == max_page_count) {
3452            $(".wizard_specials_products_pagination button.sp_next").hide();
3453            $(".wizard_specials_products_pagination button.sp_prev").show();
3454          } else {
3455            $(".wizard_specials_products_pagination button.sp_prev").show();
3456            $(".wizard_specials_products_pagination button.sp_next").show();
3457          }
3458          $(".wizard_specials_products_pagination").addClass("visible_specials_pagination");
3459          var display_page_number = parseInt(json.data.prods_pageNumber) + 1;
3460          $('.leaf_bridge_btn[data_page="' + display_page_number + '"]').addClass('current-page');
3461        }
3462
3463
3464        // dl_view_promotion
3465        dl_view_promotion(this_special_card,true);
3466      })
3467      .catch(function (json) {
3468        console.error("get filtered prods ", json);
3469      });
3470  });
3471
3472
3473  $(document).on("click", ".wizard_specials_products_pagination .leaf_bridge_btn", function () {
3474
3475    var item_list_element = $(this);
3476    var specials_id = $(".specials_tab.active_tab").attr("specials_id");
3477    var get_page_number = parseInt($(this).attr("data_page"));
3478    $(".wizard_specials_products_pagination").removeClass("visible_specials_pagination");
3479
3480    if ($(this).hasClass("sp_prev")) {
3481      $(".wizard_specials_products_pagination button.sp_prev").attr("data_page", get_page_number - 1);
3482      $(".wizard_specials_products_pagination button.sp_next").attr("data_page", get_page_number + 1);
3483      // hide prev btn on first page
3484      if ($(".wizard_specials_products_pagination button.sp_prev").attr("data_page") == 0) {
3485        $(".wizard_specials_products_pagination button.sp_prev").hide();
3486        $(".wizard_specials_products_pagination button.sp_next").show();
3487      } else {
3488        $(".wizard_specials_products_pagination button.sp_prev").show();
3489        $(".wizard_specials_products_pagination button.sp_next").show();
3490      }
3491    }
3492    else {
3493      $(".wizard_specials_products_pagination button.sp_prev").attr("data_page", get_page_number - 1);
3494      $(".wizard_specials_products_pagination button.sp_next").attr("data_page", get_page_number + 1);
3495      if ($(".wizard_specials_products_pagination button.sp_prev").attr("data_page") == 0) {
3496        $(".wizard_specials_products_pagination button.sp_prev").hide();
3497        $(".wizard_specials_products_pagination button.sp_next").show();
3498      }
3499      // else if ($(".wizard_specials_products_pagination button.sp_next").attr("data_page") == max_page_count) {
3500      //   $(".wizard_specials_products_pagination button.sp_next").hide();
3501      //   $(".wizard_specials_products_pagination button.sp_prev").show();
3502      // }
3503      else {
3504        $(".wizard_specials_products_pagination button.sp_prev").show();
3505        $(".wizard_specials_products_pagination button.sp_next").show();
3506      }
3507    }
3508    
3509    var filter_attributes = {};
3510    var specials_override_count = $('#leafbridge_special_products_wrapper').attr('data_product_count');
3511    filter_attributes.specials_override_count = specials_override_count;
3512    filter_attributes.MenuSectionFilter = "SPECIALS";
3513    filter_attributes.special_id = specials_id;
3514    filter_attributes.sort_order = "NAME_ASC";
3515    filter_attributes.search_key_word = "";
3516    filter_attributes.prods_pageNumber = get_page_number;
3517    filter_attributes.fetch_prod_count = 100;
3518
3519    //$(this).siblings(".specials_tab").removeClass("active_tab");
3520    $(".specials_tab_content").addClass("loading_animation");
3521    //$(this).addClass("active_tab");
3522
3523    $(".specials_tab_content_inner").hide();
3524    $(".specials_tab_content_inner").html("");
3525
3526    $(".specials_tab_notice").html("");
3527    // set url params
3528    var page_url = window.location.href;
3529    var url = new URL(page_url);
3530    var params = new URLSearchParams(url.search);
3531    var updated_url = "";
3532
3533    // params.delete("pagination");
3534
3535    // var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3536    var leafbridge_wizard_data = {};
3537    if ($("div").hasClass("retailer_based_store")) {
3538      var force_leafbridge_wizard_data = {
3539        retailer_id: $(".retailer_based_store").attr("retailer_id"),
3540        menu_type: $(".retailer_based_store").attr("menu_type"),
3541        collection_method: $(".retailer_based_store").attr("order_type"),
3542      };
3543
3544      leafbridge_wizard_data = {
3545        age_confirm: true,
3546        collection_method: force_leafbridge_wizard_data.collection_method,
3547        created_time: new Date(),
3548        default_set: true,
3549        event: "FORCE WIZARD",
3550        menu_type: force_leafbridge_wizard_data.menu_type,
3551        retailer_id: force_leafbridge_wizard_data.retailer_id,
3552      };
3553    } else {
3554      leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3555    }
3556
3557    if (leafbridge_wizard_data != null) {
3558      var selected_retailer = leafbridge_wizard_data.retailer_id;
3559      var menu_type = leafbridge_wizard_data.menu_type;
3560      var collection_type = leafbridge_wizard_data.collection_method;
3561      !params.get("retailer_id") ? params.append("retailer_id", selected_retailer) : params.set("retailer_id", selected_retailer);
3562      !params.get("menu_type") ? params.append("menu_type", menu_type) : params.set("menu_type", menu_type);
3563      !params.get("collection_type") ? params.append("collection_type", collection_type) : params.set("collection_type", collection_type);
3564      !params.get("specials_id") ? params.append("specials_id", specials_id) : params.set("specials_id", specials_id);
3565    }
3566
3567    updated_url = url.origin + url.pathname + "?" + params.toString();
3568    window.history.pushState({}, "", updated_url);
3569
3570    var specials_title_display = $(".specials_tab.active_tab .special_title").text();
3571    var specials_para_display = $(".specials_tab.active_tab .special_description").text();
3572    $(".specials_tabs_top .specials_title .specials_title_h2").text(specials_title_display);
3573    $(".specials_tabs_top .specials_title .specials_title_p").text(specials_para_display);
3574
3575    ajax_get_filtered_products(filter_attributes)
3576      .then(function (json) {
3577        $(".specials_tab_content").removeClass("loading_animation");
3578        $(".specials_tab_content_inner").html(json.data.products_html);
3579        $(".specials_tab_content_inner").fadeIn();
3580
3581        prepare_specials_filter(json.data.specials_filter_html);
3582        var scroll_offset = window.screen.width > 768 ? parseInt(parseInt(window.screen.height)) / 2 : parseInt(parseInt(window.screen.height) / 3.3);
3583        $("html, body").animate({ scrollTop: $("#specials_tab_content").offset().top - scroll_offset }, 350);
3584        $("#sp_pagination_text").text(json.data.pagination_show_current_page_text);
3585
3586        // Update pagination_text_with_no
3587        var paginationText = '';
3588        var pageNumbers = json.data.pagination_show_current_page_with_no.split(' ');
3589        var currentPageNumber = filter_attributes.prods_pageNumber;
3590
3591        for (var i = 0; i < pageNumbers.length; i++) {
3592          if (pageNumbers[i] === '...') {
3593            paginationText += '<span>' + pageNumbers[i] + '</span>';
3594          } else {
3595            // Check if the current page number matches the current page being iterated
3596            if (parseInt(pageNumbers[i]) === currentPageNumber) {
3597              paginationText += '<a href="#" class="leaf_bridge_btn sp_pagination_number  current-page" data_page="' + pageNumbers[i] + '">' + pageNumbers[i] + '</a>';
3598            } else {
3599              paginationText += '<a href="#" class="leaf_bridge_btn sp_pagination_number " data_page="' + pageNumbers[i] + '">' + pageNumbers[i] + '</a>';
3600            }
3601          }
3602        }
3603
3604        $('#sp_pagination_text_with_no').html(paginationText);
3605
3606        var paginationStyle = json.data.pagination_style;
3607
3608        $(".wizard_specials_products_pagination.allow_pages").hide();
3609
3610        // Show the appropriate pagination container based on pagination_style
3611        if (paginationStyle === 'next_prev') {
3612          $(".wizard_specials_products_pagination.allow_pages:first").show();
3613        } else if (paginationStyle === 'next_prev_with_page_buttons') {
3614          $(".wizard_specials_products_pagination.allow_pages:last").show();
3615        }
3616
3617        var max_page_count = Math.ceil(json.data.products_count / json.data.prods_per_page + 1);
3618        if ($(".wizard_specials_products_pagination button.sp_next").attr("data_page") == max_page_count) {
3619          $(".wizard_specials_products_pagination button.sp_next").hide();
3620          $(".wizard_specials_products_pagination button.sp_prev").show();
3621        }
3622
3623        $(".wizard_specials_products_pagination").addClass("visible_specials_pagination");
3624
3625
3626        dl_view_item_list(item_list_element,json);
3627      })
3628      .catch(function (json) {
3629        console.error("get filtered prods ", json);
3630      });
3631  });
3632
3633  function prepare_specials_filter(products_filter_attrs) {
3634    $(".specials_tab_filter .specials_tab_filter_inner").html("");
3635    products_filter_attrs.category.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.category) : "";
3636    products_filter_attrs.subcategory.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.subcategory) : "";
3637    products_filter_attrs.brand.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.brand) : "";
3638    products_filter_attrs.effects.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.effects) : "";
3639    products_filter_attrs.strainType.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.strainType) : "";
3640    products_filter_attrs.potencyCbd.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.potencyCbd) : "";
3641    products_filter_attrs.potencyThc.includes("li") ? $(".specials_tab_filter .specials_tab_filter_inner").append(products_filter_attrs.potencyThc) : "";
3642  }
3643
3644  $(document).on('click', '.lb_toast_close', function (e) {
3645    e.preventDefault();
3646    $(this).closest('.lb_toast_msg_box').remove();
3647  });
3648
3649  //main function to show specials cards when it's shortcode is called
3650  function get_specials_menus_cards() {
3651    if ($("div").hasClass("leafbridge_special_cards_wrapper")) {
3652      var sort_order = $("#leafbridge_special_products_wrapper").attr("data_sort_order");
3653      ajax_get_special_menu_cards(sort_order)
3654        .then(function (json) {
3655          if (json.data.getSpecials_html == "") {
3656            $("#leafbridge_special_products_wrapper .specials_tabs_new").html('<p style="text-align:center;">No Specials found with the selected retailer. Please select another retailer.</p>');
3657            $("#leafbridge_special_products_wrapper .specials_tabs_new").css("display", "block");
3658          } else {
3659            $("#leafbridge_special_products_wrapper .specials_tabs_new").css("display", "inline-grid");
3660            $("#leafbridge_special_products_wrapper .specials_tabs_new").html(json.data.getSpecials_html);
3661            json.data.getSpecials.length > 4 ? $(".specials_view_more_wrapper").fadeIn() : $(".specials_view_more_wrapper").hide();
3662            add_parameter_to_specials_cards_url();
3663          }
3664        })
3665        .catch(function (err) {
3666          console.error('special cards error',err);
3667        });
3668    }
3669
3670    if($('div').hasClass('specials_cards_slider')){
3671      var sort_order = $("#leafbridge_special_products_wrapper").attr("data_sort_order");
3672      ajax_get_special_menu_cards(sort_order)
3673      .then(function(json){
3674          var specials_data = json.data;
3675        
3676          var slider_autoplay = $('.specials_cards_slider').attr('slider_autoplay');
3677          var slide_spacing = $('.specials_cards_slider').attr('slide_spacing');
3678          var pause_on_hover = $('.specials_cards_slider').attr('pause_on_hover');
3679
3680          slide_spacing = !isNaN(slide_spacing) ? parseInt(slide_spacing) : 0;
3681          slider_autoplay = !isNaN(slider_autoplay) ? parseInt(slider_autoplay) : false;
3682          var slide_pause_on_hover = (pause_on_hover == 'false' || pause_on_hover == false ) ? false : true;      
3683          var slider_autoplay = (slider_autoplay == false ) ? false : {delay:slider_autoplay,disableOnInteraction:false,pauseOnMouseEnter:slide_pause_on_hover};
3684          var display_rule = $('.specials_cards_slider').attr('display_rule');
3685
3686          promise_prepare_specials_cards_slider(specials_data,display_rule)
3687          .then(function(slider_build_msg){
3688
3689            var swiper = new Swiper(".specials_cards_slider.swiper", {
3690              spaceBetween: slide_spacing,
3691              loop: false,
3692              autoplay: slider_autoplay,
3693              pagination: {
3694                el: ".specials_cards_slider .swiper-pagination",
3695                clickable: true,
3696              },
3697              navigation: {
3698                nextEl: ".specials_cards_slider .swiper-button-next",
3699                prevEl: ".specials_cards_slider .swiper-button-prev",
3700              },
3701              centeredSlides: false,
3702              slidesPerView: "auto",
3703            });
3704          })
3705          .catch(function(err){
3706            console.error('specials_cards_slider error ',err);
3707          })
3708        
3709      })
3710      .catch(function(err){
3711        console.error('special cards slider error',err)
3712      })
3713    }
3714  }
3715
3716  function promise_prepare_specials_cards_slider(specials_data,display_rule){
3717    return new Promise(function(resolve,reject){
3718      try{
3719        // generate specials slides html
3720        var leafbridgeData = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3721        var spRetId = leafbridgeData.retailer_id;
3722        var spCollectionType = leafbridgeData.collection_method;
3723        var spMenuType = leafbridgeData.menu_type;
3724        var special_cards_json = specials_data.getSpecials;
3725
3726        var cards_sort = $('.specials_cards_slider').attr('data_sort_order');
3727        
3728        if(cards_sort == 'name_asc'){
3729          special_cards_json = sortSpecialCardsByName(special_cards_json, 'asc');
3730        }
3731        else if(cards_sort == 'name_desc'){
3732          special_cards_json = sortSpecialCardsByName(special_cards_json, 'desc');
3733        }
3734
3735        Object.keys(special_cards_json).forEach(key => {
3736          var slide_data = special_cards_json[key];
3737          const today = new Date();
3738          var current_date_number = today.getDay();
3739          var special_config_days = (slide_data.scheduleConfiguration.days != null) ? slide_data.scheduleConfiguration.days : [];
3740
3741          var show_special_card = ((display_rule != 'today')) ? true : ((display_rule == 'today') && (special_config_days.includes(current_date_number)) ) ? true : false ; 
3742          show_special_card = (special_config_days.length == 0) ? true : show_special_card;
3743          
3744          if(show_special_card){            
3745            var special_name = slide_data.menuDisplayConfiguration.name;
3746            var special_description = slide_data.menuDisplayConfiguration.description;
3747            special_description = special_description == null ? '' : special_description; 
3748            var special_id = slide_data.id;
3749            var special_image = slide_data.menuDisplayConfiguration.image;
3750            var special_url =  window.location.origin+'/specials/?specials_id='+special_id+'&retailer_id='+spRetId+'&menu_type='+spMenuType+'&collection_type='+spCollectionType;
3751            var slide_html = '<div class="swiper-slide">';
3752            slide_html += '<div class="special_slide_container" style="background-image:url('+special_image+');">';
3753            slide_html += '<div class="special_slide_inner">';
3754            slide_html += '<div class="special_slide_name">'+special_name+'</div>';
3755            slide_html += '<div class="special_slide_description">'+special_description+'</div>';
3756            slide_html += '<div class="special_slide_link"><a href="'+special_url+'">Shop Now</a></div>';
3757            slide_html += '</div>'; //special_slide_inner
3758            slide_html += '</div>'; //special_slide_container
3759            slide_html += '</div>'; //swiper-slide
3760            $('.specials_cards_slider .swiper-wrapper').append(slide_html);
3761          }
3762        });
3763        resolve('slider sorted');
3764      }
3765      catch(error){
3766        reject(error);
3767      }
3768    });
3769  }
3770
3771  function sortSpecialCardsByName(cards, order = 'asc') {
3772    // Create a copy of the array to avoid mutating the original
3773    const cardsCopy = [...cards];
3774    
3775    // Sort the copy based on the menuDisplayConfiguration.name attribute
3776    cardsCopy.sort((a, b) => {
3777        const nameA = (a.menuDisplayConfiguration?.name || '').toLowerCase();
3778        const nameB = (b.menuDisplayConfiguration?.name || '').toLowerCase();
3779        
3780        if (order === 'asc') {
3781            return nameA.localeCompare(nameB);
3782        } else if (order === 'desc') {
3783            return nameB.localeCompare(nameA);
3784        }
3785        return 0;
3786    });
3787    
3788    // Convert sorted array to object with numeric keys
3789    const sortedObject = {};
3790    cardsCopy.forEach((card, index) => {
3791        sortedObject[index] = card;
3792    });
3793    
3794    return sortedObject;
3795  }
3796
3797  // adding additional url parameter to specials card url to fix caching issue on rocket.net/cloudflare
3798  function add_parameter_to_specials_cards_url() {
3799    const anchors = document.querySelectorAll('.specials_tabs_new a');
3800
3801    anchors.forEach(anchor => {
3802      const href = anchor.getAttribute('href');
3803
3804      const url = new URL(href, window.location.origin);
3805
3806      const params = new URLSearchParams(url.search);
3807
3808      const now = new Date();
3809      const hours = String(now.getHours()).padStart(2, '0');
3810      const minutes = String(now.getMinutes()).padStart(2, '0');
3811      const seconds = String(now.getSeconds()).padStart(2, '0');
3812      const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
3813      const random = Math.floor(Math.random() * 90) + 10;
3814      const timestamp = `${hours}${minutes}${seconds}${milliseconds}${random}`;
3815
3816      params.append('checksum', timestamp);
3817
3818      url.search = params.toString();
3819
3820      anchor.setAttribute('href', url.toString());
3821    });
3822  }
3823
3824  // show selected retailer name and link to locations page
3825  function show_retailer_name_bar() {
3826    var leafbridgeData = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3827    if (leafbridgeData) {
3828      var menu_type = leafbridgeData.menu_type.toLowerCase();
3829      var name_bar_collection = leafbridgeData.collection_method.toLowerCase();
3830    }
3831
3832    var data = {
3833      action: "load_retailer_name",
3834      retailer_id: leafbridgeData.retailer_id,
3835      nonce_ajax: leafbridge_public_ajax_obj.nonce,
3836    };
3837
3838    $.ajax({
3839      type: "POST",
3840      dataType: "json",
3841      cache: false,
3842      proccessData: false,
3843      url: leafbridge_public_ajax_obj.ajaxurl,
3844      data: data,
3845      success: function (response) {
3846        $(".retailer_name").html(response.data.lb_retailer_custom_name);
3847        $(".name_bar_menutype").html(menu_type);
3848        $(".name_bar_collection").html(name_bar_collection);
3849        $(".name_bar_address").html(response.data.lb_retailer_address);
3850        $(".name_bar_phone").html(response.data.lb_retailer_phone);
3851
3852        $(".name_bar_day_monday").html(response.data.lb_retailer_day_monday);
3853        if (response.data.lb_retailer_day_monday_active == true) {
3854          $(".name_bar_day_monday_start").html(response.data.lb_retailer_day_monday_start);
3855          $(".name_bar_day_monday_end").html(response.data.lb_retailer_day_monday_end);
3856        } else {
3857          $(".monday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3858        }
3859
3860        $(".name_bar_day_tuesday").html(response.data.lb_retailer_day_tuesday);
3861        if (response.data.lb_retailer_day_tuesday_active == true) {
3862          $(".name_bar_day_tuesday_start").html(response.data.lb_retailer_day_tuesday_start);
3863          $(".name_bar_day_tuesday_end").html(response.data.lb_retailer_day_tuesday_end);
3864        } else {
3865          $(".tuesday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3866        }
3867
3868        $(".name_bar_day_wednesday").html(response.data.lb_retailer_day_wednesday);
3869        if (response.data.lb_retailer_day_mwednesday_active == true) {
3870          $(".name_bar_day_wednesday_start").html(response.data.lb_retailer_day_wednesday_start);
3871          $(".name_bar_day_wednesday_end").html(response.data.lb_retailer_day_wednesday_end);
3872        } else {
3873          $(".wednesday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3874        }
3875
3876        $(".name_bar_day_thursday").html(response.data.lb_retailer_day_thursday);
3877        if (response.data.lb_retailer_day_thursday_active == true) {
3878          $(".name_bar_day_thursday_start").html(response.data.lb_retailer_day_thursday_start);
3879          $(".name_bar_day_thursday_end").html(response.data.lb_retailer_day_thursday_end);
3880        } else {
3881          $(".thursday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3882        }
3883
3884        $(".name_bar_day_friday").html(response.data.lb_retailer_day_friday);
3885        if (response.data.lb_retailer_day_friday_active == true) {
3886          $(".name_bar_day_friday_start").html(response.data.lb_retailer_day_friday_start);
3887          $(".name_bar_day_friday_end").html(response.data.lb_retailer_day_friday_end);
3888        } else {
3889          $(".friday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3890        }
3891
3892        $(".name_bar_day_saturday").html(response.data.lb_retailer_day_saturday);
3893        if (response.data.lb_retailer_day_saturday_active == true) {
3894          $(".name_bar_day_saturday_start").html(response.data.lb_retailer_day_saturday_start);
3895          $(".name_bar_day_saturday_end").html(response.data.lb_retailer_day_saturday_end);
3896        } else {
3897          $(".saturday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3898        }
3899
3900        $(".name_bar_day_sunday").html(response.data.lb_retailer_day_sunday);
3901        if (response.data.lb_retailer_day_sunday_active == true) {
3902          $(".name_bar_day_sunday_start").html(response.data.lb_retailer_day_sunday_start);
3903          $(".name_bar_day_sunday_end").html(response.data.lb_retailer_day_sunday_end);
3904        } else {
3905          $(".sunday_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3906        }
3907
3908        $(".name_bar_today_closing_time").html(response.data.lb_retailer_today_closing_time);
3909        if (response.data.lb_retailer_day_today_active == true) {
3910          $(".seperate_today_opening_time").html(response.data.lb_retailer_today_open_time);
3911          $(".seperate_today_closing_time").html(response.data.lb_retailer_today_closing_time);
3912        } else {
3913          $(".today_bar_day .time_start_end_wrapper").html('<span class="closed_day">Closed</span>');
3914        }
3915      },
3916    });
3917  }
3918
3919  function ajax_get_special_menu_cards(sort_order) {
3920    return new Promise(function (resolve, reject) {
3921      var leafbridge_wizard_data = {};
3922      if ($("div").hasClass("retailer_based_store")) {
3923        var force_leafbridge_wizard_data = {
3924          retailer_id: $(".retailer_based_store").attr("retailer_id"),
3925          menu_type: $(".retailer_based_store").attr("menu_type"),
3926          collection_method: $(".retailer_based_store").attr("order_type"),
3927        };
3928
3929        leafbridge_wizard_data = {
3930          age_confirm: true,
3931          collection_method: force_leafbridge_wizard_data.collection_method,
3932          created_time: new Date(),
3933          default_set: true,
3934          event: "FORCE WIZARD",
3935          menu_type: force_leafbridge_wizard_data.menu_type,
3936          retailer_id: force_leafbridge_wizard_data.retailer_id,
3937        };
3938      } else {
3939        leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3940      }
3941
3942      var data = {
3943        action: "get_retailer_special_menus",
3944        wizard_data: leafbridge_wizard_data,
3945        nonce_ajax: leafbridge_public_ajax_obj.nonce,
3946        sort_order: sort_order,
3947      };
3948      $.ajax({
3949        url: leafbridge_public_ajax_obj.ajaxurl,
3950        dataType: "json",
3951        cache: false,
3952        data: data,
3953        type: "POST",
3954        proccessData: false,
3955        success: function (json) {
3956          resolve(json);
3957        },
3958        error: function (json) {
3959          show_system_error(json.data);
3960          reject(json);
3961        },
3962        complete: function (json) { },
3963      });
3964    });
3965  }
3966
3967  // ajax function to get selected specials products
3968  function ajax_get_filtered_products(filter_attributes) {
3969    return new Promise(function (resolve, reject) {
3970
3971      var wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
3972
3973      try {
3974        var lb_prod_prefixes = ($('meta[name="lb_prod_prefixes"]').length > 0) ? JSON.parse($('meta[name="lb_prod_prefixes"]').attr('content')) : '';
3975      }
3976      catch (err) {
3977        var lb_prod_prefixes = '';
3978      }
3979      wizard_data.prod_prefix = lb_prod_prefixes[wizard_data.retailer_id];
3980
3981      if ($("div").hasClass("retailer_based_store")) {
3982        wizard_data = {
3983          retailer_id: $(".retailer_based_store").attr("retailer_id"),
3984          menu_type: $(".retailer_based_store").attr("menu_type"),
3985          collection_method: $(".retailer_based_store").attr("order_type"),
3986        };
3987      }
3988
3989      var data = {
3990        action: "wizard_show_products",
3991        wizard_data: wizard_data,
3992        nonce_ajax: leafbridge_public_ajax_obj.nonce,
3993        prods_pageNumber: filter_attributes.prods_pageNumber,
3994        prod_categories: filter_attributes,
3995        search_key_word: filter_attributes.search_key_word,
3996        filter_attributes: filter_attributes,
3997      };
3998
3999      $.ajax({
4000        url: leafbridge_public_ajax_obj.ajaxurl,
4001        dataType: "json",
4002        cache: false,
4003        data: data,
4004        type: "POST",
4005        proccessData: false,
4006        success: function (json) {
4007          resolve(json);
4008        },
4009        error: function (json) {
4010          reject(json);
4011        },
4012        complete: function (json) { },
4013      });
4014    });
4015  }
4016
4017  function specific_product_filter_slider() {
4018    if ($("div").hasClass("leafbridge_specific_product_filter_wrapper")) {
4019      $(".leafbridge_specific_product_filter_wrapper").each(function (index, el) {
4020
4021        var this_slider_wrapper = $(this);
4022        var this_slider_wrapper_animation = $(this).find("#loading_animation");
4023        var lb_specific_prods_slider_inner = $(this).find(".lb_specific_prods_slider_inner");
4024
4025        var inside_prod_popup = $(this).attr('inside_prod_popup');
4026        var bypass_search_string = '';
4027       
4028
4029        // if (isElementInViewport(this_slider_wrapper[0]) && !this_slider_wrapper.data('loaded')) {
4030        // this_slider_wrapper.data('loaded', true);
4031
4032        var filter_attributes_html = JSON.parse($(this).find(".lb_specific_prods_slider_wrapper").attr("filter_attributes"));
4033        var filter_attributes = {};
4034        // filter_attributes.search_key_word = "";
4035        if(inside_prod_popup == 'true'){
4036          bypass_search_string = $('#popup_container').find('h1').find('a').text();
4037          filter_attributes_html.search_product = bypass_search_string;
4038        }
4039        
4040        // filter_attributes.fetch_prod_count = 1000;
4041        filter_attributes.fetch_prod_count = filter_attributes_html.count ? filter_attributes_html.count : 100;
4042        filter_attributes_html.special == "true" ? (filter_attributes.MenuSectionFilter = "SPECIALS") : "";
4043        filter_attributes_html.staff_picks == "yes" ? (filter_attributes.MenuSectionFilter = "STAFF_PICKS") : "";
4044        filter_attributes_html.show_unrelated == "true" ? (filter_attributes.staff_picks_show_unrelated = true ) : "";
4045
4046        filter_attributes_html.custom_selection == "true" ? (filter_attributes.MenuSectionFilter = "CUSTOM_SECTION") : ""; // set if custom selection menu
4047        filter_attributes_html.special_id ? (filter_attributes.special_id = filter_attributes_html.special_id) : "";
4048        filter_attributes_html.custom_selection == "true" ? (filter_attributes.special_id = filter_attributes_html.custom_menu_name) : ""; //set custom selection menu name
4049        filter_attributes_html.category ? (filter_attributes.categories = filter_attributes_html.category.toUpperCase()) : "";
4050        filter_attributes_html.sub_category ? (filter_attributes.subcategory = filter_attributes_html.sub_category.toUpperCase()) : "";
4051        filter_attributes_html.effect ? (filter_attributes.effects = filter_attributes_html.effect.toUpperCase()) : "";
4052        filter_attributes_html.strain_type ? (filter_attributes.strainType = filter_attributes_html.strain_type.toUpperCase()) : "";
4053        //filter_attributes_html.brand ? (filter_attributes.brands = '"' + filter_attributes_html.brand + '"') : "";
4054        if (filter_attributes_html.brand) {
4055          const brands = filter_attributes_html.brand.split(',')
4056              .map(brand => `"${brand.trim()}"`)
4057              .join(',');
4058          filter_attributes.brands = brands;
4059        }
4060
4061        filter_attributes_html.pos_tag ? (filter_attributes.POS_Tags = filter_attributes_html.pos_tag) : "";
4062        filter_attributes_html.pos_category ? (filter_attributes.POS_Categories = filter_attributes_html.pos_category) : "";
4063
4064        filter_attributes_html.search_product ? (filter_attributes.search_key_word = filter_attributes_html.search_product) : "";
4065
4066        filter_attributes.sort_order = filter_attributes_html.sort ? filter_attributes_html.sort.toUpperCase() : "PRICE_DESC";
4067        // filter_attributes.sort_order = filter_attributes_html.sort ? String(filter_attributes_html.sort).toUpperCase() : "PRICE_DESC";
4068        // filter_attributes.sort_order = filter_attributes_html.sort ? filter_attributes_html.sort.toUpperCase() : "";
4069        filter_attributes.prod_slider = true;
4070
4071        filter_attributes.today_specials_only = (filter_attributes_html.today_specials_only) ? (filter_attributes_html.today_specials_only == 'yes' ? true : false) : false;
4072
4073        
4074        
4075        ajax_get_filtered_products(filter_attributes)
4076          .then(function (json) {
4077            if (json.data.products_count > 0) {
4078              this_slider_wrapper_animation.hide();
4079              lb_specific_prods_slider_inner.show();
4080              this_slider_wrapper.find(".lb_specific_prods_slider_inner").find(".swiper-wrapper").html(json.data.products_html);
4081              // this_slider_wrapper.find('.leafbridge_product_modal_outer').remove();
4082              prepare_owl_carousel_filter(this_slider_wrapper);
4083              dl_view_item_list(this_slider_wrapper,json);
4084            } else {
4085              this_slider_wrapper.find(".lb_specific_prods_slider_wrapper").html("We can't find what you're looking for. Please browse our other products using the filters on this page.");
4086            }
4087          })
4088          .catch(function (json) {
4089            this_slider_wrapper.find(".lb_specific_prods_slider_wrapper").append('<div class="slider_server_con_issue">Cannot get products from the Dutchie server.</div>');
4090            console.error("filtered prods error ", json);
4091            show_system_error(json.data);
4092          });
4093        // }
4094      });
4095    }
4096  }
4097
4098  // recently viewed products
4099  function display_recently_viewed_products() {
4100    if ($("div").hasClass("leafbridge_recently_viewed_products_wrapper")) {
4101      $(".leafbridge_recently_viewed_products_wrapper").each(function (index, el) {
4102
4103        // if slider runs inside popup . grab product id
4104        var popup_product_id = $(this).closest('.popup_no_pdp_wrapper').find('.lb_single_prod_page_wrapper').attr('data_product_id');
4105
4106        var this_slider_wrapper = $(this);
4107        var this_slider_wrapper_animation = $(this).find("#loading_animation");
4108        var lb_recently_viewed_slider_inner = $(this).find(".lb_recently_viewed_slider_inner");
4109
4110        const leafbridgeWizardData = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
4111        const currentRetailerId = leafbridgeWizardData.retailer_id;
4112        const currentMenuType = leafbridgeWizardData.menu_type;
4113
4114        let recently_viewed_products = localStorage.getItem("recently_viewed_products");
4115
4116        if (recently_viewed_products && currentRetailerId) {
4117          recently_viewed_products = JSON.parse(recently_viewed_products);
4118
4119          var products_html = '';
4120          let hasProducts = false;
4121
4122          let products = recently_viewed_products[currentRetailerId];
4123
4124          if (products && products.length > 0) {
4125            products.reverse().forEach(function (product) {
4126              let variants = product.variants;
4127              let priceNormal = '';
4128              let priceSpecial = '';
4129
4130              if (currentMenuType === 'MEDICAL') {
4131                priceNormal = variants[0].priceMed;
4132                priceSpecial = variants[0].specialPriceMed;
4133              } else if (currentMenuType === 'RECREATIONAL') {
4134                priceNormal = variants[0].priceRec;
4135                priceSpecial = variants[0].specialPriceRec;
4136              }
4137
4138              if(popup_product_id != product.productId){
4139                  products_html += `
4140                              <div class="swiper-slide" data-product-id="${product.productId}">
4141                                  <div class="leafbridge_product_card">
4142                                  <div class="leafbridge_product_a">
4143                                      <a href="${product.productLink}">
4144                                          <img src="${product.image}" alt="${product.name}" class="lb_prod_card_thumb" />
4145                                          </a>
4146                                          <div class="leafbridge_product_price" data_menu_type ="${currentMenuType}">
4147                                          ${priceSpecial ? `
4148                                            <div class="discount-price">
4149                                                <span><del>$${priceNormal}</del> <span class="special_price">$${priceSpecial}</span></span>
4150                                            </div>` : `
4151                                            <div class="normal-price">
4152                                                <span>$${priceNormal}</span>
4153                                            </div>`
4154                  }
4155                                          </div>
4156                                          <div class="leafbridge_brand_name">${product.brand}</div>
4157                                          <h5 class="leafbridge_product_name">
4158                                          <a href="${product.productLink}">
4159                                          ${product.name}
4160                                          </a>
4161                                          </h5>
4162                                      
4163                                  </div>  
4164                                  </div>
4165                              </div>
4166                          `;
4167                hasProducts = true;
4168              }
4169            });
4170
4171            if (hasProducts) {
4172              this_slider_wrapper_animation.hide();
4173              lb_recently_viewed_slider_inner.show();
4174              lb_recently_viewed_slider_inner.find(".swiper-wrapper").html(products_html);
4175              setTimeout(function () {
4176                prepare_swiper_carousel_filter(this_slider_wrapper);
4177              }, 0);
4178            } else {
4179              lb_recently_viewed_slider_inner.html("<p>No recently viewed products available for this retailer.</p>");
4180            }
4181          } else {
4182            lb_recently_viewed_slider_inner.html("<p>No recently viewed products available for this retailer.</p>");
4183          }
4184        } else {
4185          lb_recently_viewed_slider_inner.html("<p>No recently viewed products available.</p>");
4186        }
4187      });
4188    }
4189  }
4190
4191  // Function to check if an element is in the viewport
4192  function isElementInViewport(el) {
4193    var rect = el.getBoundingClientRect();
4194    return rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth);
4195  }
4196
4197  // Add an event listener to trigger lazy loading when the page is scrolled
4198  // $(window).on("scroll", function () {
4199  //     specific_product_filter_slider();
4200  // });
4201
4202  // prepare owl carousel after loading products for filtered slider content
4203  function prepare_owl_carousel_filter(this_slider_wrapper) {
4204    this_slider_wrapper.find(".swiper-wrapper").removeClass("preload-card");
4205    var swiper_autoplay = this_slider_wrapper.attr("data_autoplay") == "true" ? true : false;
4206
4207    var this_slider_wrapper_id = $("#" + this_slider_wrapper.attr("id"));
4208    var this_slider_wrapper_idstr = "#" + this_slider_wrapper.attr("id");
4209
4210    this_slider_wrapper_id.find(".swipernav_wrapper").show(); // show slider nav after initializing the slider
4211
4212    var swiper = new Swiper(this_slider_wrapper_idstr + " .lb_specific_prods_slider_inner.swiper", {
4213      spaceBetween: 20,
4214      loop: false,
4215      pagination: {
4216        el: ".swiper-pagination",
4217        clickable: true,
4218      },
4219      navigation: {
4220        nextEl: this_slider_wrapper_idstr + " .swiper-button-next",
4221        prevEl: this_slider_wrapper_idstr + " .swiper-button-prev",
4222      },
4223      centeredSlides: false,
4224      breakpoints: {
4225        0: {
4226          slidesPerView: "auto",
4227          spaceBetween: 8,
4228        },
4229        481: {
4230          slidesPerView: "auto",
4231        },
4232      },
4233    });
4234  }
4235
4236  function prepare_swiper_carousel_filter(this_slider_wrapper) {
4237    this_slider_wrapper.find(".swiper-wrapper").removeClass("preload-card");
4238    var swiper_autoplay = this_slider_wrapper.attr("data_autoplay") == "true" ? true : false;
4239
4240    var this_slider_wrapper_id = this_slider_wrapper.attr("id");
4241    var this_slider_wrapper_idstr = "#" + this_slider_wrapper_id;
4242
4243    this_slider_wrapper.find(".swipernav_wrapper").show();
4244
4245    var swiper = new Swiper(this_slider_wrapper.find(".swiper")[0], {
4246      spaceBetween: 20,
4247      loop: false,
4248      pagination: {
4249        el: this_slider_wrapper.find(".swiper-pagination")[0],
4250        clickable: true,
4251      },
4252      navigation: {
4253        nextEl: this_slider_wrapper.find(".swiper-button-next")[0],
4254        prevEl: this_slider_wrapper.find(".swiper-button-prev")[0],
4255      },
4256      centeredSlides: false,
4257      breakpoints: {
4258        0: {
4259          slidesPerView: "auto",
4260          spaceBetween: 8,
4261        },
4262        481: {
4263          slidesPerView: "auto",
4264        },
4265      },
4266    });
4267  }
4268
4269  // promise to check
4270  function check_wizard_attributes() {
4271    return new Promise(function (resolve, reject) {
4272      var leafbridge_wizard_data = localStorage.getItem("leafbridge_wizard_data") ? JSON.parse(localStorage.getItem("leafbridge_wizard_data")) : {};
4273      var leafbridge_cart_data = localStorage.getItem("leafbridge_cart_data") ? JSON.parse(localStorage.getItem("leafbridge_cart_data")) : {};
4274
4275      var force_leafbridge_wizard_data = {};
4276      var retailer_based_store = false;
4277
4278      if ($("div").hasClass("retailer_based_store")) {
4279        retailer_based_store = true;
4280
4281        force_leafbridge_wizard_data.retailer_id = $(".retailer_based_store").attr("retailer_id");
4282        force_leafbridge_wizard_data.menu_type = $(".retailer_based_store").attr("menu_type");
4283        force_leafbridge_wizard_data.collection_method = $(".retailer_based_store").attr("order_type");
4284
4285        if (Object.keys(leafbridge_cart_data).length != 0 && Object.keys(leafbridge_wizard_data).length != 0) {
4286          if (leafbridge_wizard_data.retailer_id != force_leafbridge_wizard_data.retailer_id || leafbridge_wizard_data.menu_type != force_leafbridge_wizard_data.menu_type || leafbridge_cart_data.retailer_id != force_leafbridge_wizard_data.retailer_id || leafbridge_cart_data.menutype != force_leafbridge_wizard_data.menu_type) {
4287            var confirm_change_cart = confirm("There are products from another retailer / menutype so adding this product will reset your current cart. Proceed?");
4288            if (confirm_change_cart) {
4289              leafbridge_cart_data = {};
4290              localStorage.removeItem("leafbridge_cart_data");        
4291              leafbridge_wizard_data.retailer_id = force_leafbridge_wizard_data.retailer_id;
4292              leafbridge_wizard_data.menu_type = force_leafbridge_wizard_data.menu_type;
4293              leafbridge_wizard_data.collection_method = force_leafbridge_wizard_data.collection_method;
4294            } else {
4295            }
4296          }
4297        } else {
4298          leafbridge_wizard_data.retailer_id = force_leafbridge_wizard_data.retailer_id;
4299          leafbridge_wizard_data.menu_type = force_leafbridge_wizard_data.menu_type;
4300          leafbridge_wizard_data.collection_method = force_leafbridge_wizard_data.collection_method;
4301        }
4302      }
4303
4304      var urlParams = new URLSearchParams(window.location.search);
4305
4306      var page_url = window.location.href;
4307      var url = new URL(page_url);
4308
4309      var url_par_retailer = urlParams.get("retailer_id");
4310      var url_par_menu_type = urlParams.get("menu_type");
4311      var url_par_collection_type = urlParams.get("collection_type");
4312      var url_par_sort = urlParams.get("sort");
4313
4314      // filter params
4315      var leafbridge_filter_params = {};
4316
4317      urlParams.get("products_search") ? (leafbridge_filter_params.products_search = urlParams.get("products_search")) : "";
4318      // urlParams.get("products_search") ? (leafbridge_filter_params.products_search = urlParams.get("products_search").replace(/['\s]/g, "")) : "";
4319      urlParams.get("MenuSectionFilter") ? (leafbridge_filter_params.MenuSectionFilter = urlParams.get("MenuSectionFilter")) : "";
4320      urlParams.get("potency_cbd") ? (leafbridge_filter_params.potency_cbd = urlParams.get("potency_cbd")) : "";
4321      urlParams.get("potency_thc") ? (leafbridge_filter_params.potency_thc = urlParams.get("potency_thc")) : "";
4322      urlParams.get("effects") ? (leafbridge_filter_params.effects = urlParams.get("effects")) : "";
4323      urlParams.get("weight") ? (leafbridge_filter_params.weight = urlParams.get("weight")) : "";
4324      urlParams.get("categories") ? (leafbridge_filter_params.categories = urlParams.get("categories")) : "";
4325      urlParams.get("subcategory") ? (leafbridge_filter_params.subcategory = urlParams.get("subcategory")) : "";
4326      urlParams.get("brands") ? (leafbridge_filter_params.brands = urlParams.get("brands")) : "";
4327      urlParams.get("strainType") ? (leafbridge_filter_params.strainType = urlParams.get("strainType")) : "";
4328
4329      localStorage.setItem("leafbridge_filter_params", JSON.stringify(leafbridge_filter_params));
4330
4331      if (localStorage.getItem("leafbridge_wizard_data") != null) {
4332
4333        // var collection_method = leafbridge_wizard_data.collection_method.toUpperCase();
4334        var collection_method = leafbridge_wizard_data.collection_method;
4335        var created_time = leafbridge_wizard_data.created_time;
4336        var menu_type = leafbridge_wizard_data.menu_type;
4337        var retailer_id = leafbridge_wizard_data.retailer_id;
4338
4339        var cart_data_size = Object.keys(leafbridge_cart_data).length;
4340        if (url_par_retailer && url_par_menu_type && url_par_collection_type) {
4341          if (cart_data_size>0) {
4342            if (url_par_retailer != retailer_id || url_par_menu_type != menu_type || url_par_collection_type != collection_method) {
4343              var text = "You have added products to the cart. Changing retailer or menu type will remove items from your cart.";
4344
4345              if (confirm(text) == true) {
4346                leafbridge_wizard_data.created_time = new Date();
4347                leafbridge_wizard_data.collection_method = url_par_collection_type;
4348                leafbridge_wizard_data.menu_type = url_par_menu_type;
4349                leafbridge_wizard_data.retailer_id = url_par_retailer;
4350                leafbridge_wizard_data.sort = url_par_sort;
4351                leafbridge_wizard_data.event = "reset cart";
4352
4353                link_wizard_set_values(url_par_collection_type, url_par_retailer, url_par_menu_type, url_par_sort);
4354                localStorage.removeItem("leafbridge_cart_data");
4355                render_empty_cart();
4356              } else {
4357                leafbridge_wizard_data.created_time = new Date();
4358                leafbridge_wizard_data.collection_method = collection_method;
4359                leafbridge_wizard_data.menu_type = menu_type;
4360                leafbridge_wizard_data.retailer_id = retailer_id;
4361                leafbridge_wizard_data.sort = url_par_sort;
4362                leafbridge_wizard_data.event = "DONT reset cart";
4363
4364                link_wizard_set_values(collection_method, retailer_id, menu_type, url_par_sort);
4365                urlParams.set("collection_type", collection_method);
4366                urlParams.set("menu_type", menu_type);
4367                urlParams.set("retailer_id", retailer_id);
4368                var updated_url = url.origin + url.pathname + "?" + urlParams.toString();
4369                window.history.pushState({}, "", updated_url);
4370              }
4371            } else {
4372              leafbridge_wizard_data.created_time = new Date();
4373              leafbridge_wizard_data.collection_method = collection_method;
4374              leafbridge_wizard_data.menu_type = menu_type;
4375              leafbridge_wizard_data.retailer_id = retailer_id;
4376              leafbridge_wizard_data.sort = url_par_sort;
4377              leafbridge_wizard_data.event = "CART DATA - url and localStorage data MATCH";
4378
4379              link_wizard_set_values(collection_method, retailer_id, menu_type, url_par_sort);
4380            }
4381          } else {
4382            leafbridge_wizard_data.created_time = new Date();
4383            leafbridge_wizard_data.collection_method = url_par_collection_type;
4384            leafbridge_wizard_data.menu_type = url_par_menu_type;
4385            leafbridge_wizard_data.retailer_id = url_par_retailer;
4386            leafbridge_wizard_data.sort = url_par_sort;
4387            leafbridge_wizard_data.event = "EMPTY CART";
4388
4389            link_wizard_set_values(url_par_collection_type, url_par_retailer, url_par_menu_type, url_par_sort);
4390          }
4391        }
4392        else {
4393          leafbridge_wizard_data.created_time = new Date();
4394          leafbridge_wizard_data.collection_method = collection_method;
4395          leafbridge_wizard_data.menu_type = menu_type;
4396          leafbridge_wizard_data.retailer_id = retailer_id;
4397          leafbridge_wizard_data.sort = url_par_sort;
4398          leafbridge_wizard_data.event = "NO URL DATA";
4399          link_wizard_set_values(collection_method, retailer_id, menu_type, url_par_sort);
4400        }
4401
4402        localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
4403
4404        // add default location as recent location
4405        var check_leafbridge_recent_location = localStorage.getItem("leafbridge_recent_location");
4406        if (!check_leafbridge_recent_location) {
4407          set_default_retailer_as_recent_retailer(retailer_id);
4408        }
4409        resolve();
4410      }
4411      else {
4412        load_default_retailer_settings()
4413          .then(function (json) {
4414            var leafbridge_wizard_data = {};
4415
4416            const urlParams = new URLSearchParams(window.location.search);
4417            const url_par_retailer = urlParams.get("retailer_id");
4418            const url_par_menu_type = urlParams.get("menu_type");
4419            const url_par_collection_type = urlParams.get("collection_type");
4420
4421            if (url_par_retailer && url_par_menu_type && url_par_collection_type) {
4422              var collection_method = url_par_collection_type;
4423              var created_time = new Date();
4424              var menu_type = url_par_menu_type;
4425              var retailer_id = url_par_retailer;
4426
4427              leafbridge_wizard_data.age_confirm = json.data.leafbridge_default_settings.age_confirmation == "1" ? false : true; // if age_confirmation 1 means age modal is enabled. so age_confirmation should be kept false otherwise it won't show the age confirmation modal
4428              leafbridge_wizard_data.created_time = new Date();
4429              leafbridge_wizard_data.default_set = true;
4430              leafbridge_wizard_data.collection_method = retailer_based_store ? force_leafbridge_wizard_data.collection_method : url_par_collection_type;
4431              leafbridge_wizard_data.menu_type = retailer_based_store ? force_leafbridge_wizard_data.menu_type : url_par_menu_type;
4432              leafbridge_wizard_data.retailer_id = retailer_based_store ? force_leafbridge_wizard_data.retailer_id : url_par_retailer;
4433              leafbridge_wizard_data.sort = url_par_sort;
4434              leafbridge_wizard_data.event = "LOCAL STORAGE NULL - have URL DATA";
4435
4436              localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
4437              link_wizard_set_values(collection_method, retailer_id, menu_type, url_par_sort);
4438
4439              // add default location as recent location
4440              var check_leafbridge_recent_location = localStorage.getItem("leafbridge_recent_location");
4441              if (!check_leafbridge_recent_location) {
4442                set_default_retailer_as_recent_retailer(retailer_id);
4443              }
4444
4445              resolve();
4446            } else {
4447              leafbridge_wizard_data.age_confirm = json.data.leafbridge_default_settings.age_confirmation == "1" ? false : true; // if age_confirmation 1 means age modal is enabled. so age_confirmation should be kept false otherwise it won't show the age confirmation modal
4448              leafbridge_wizard_data.created_time = new Date();
4449              leafbridge_wizard_data.default_set = true;
4450
4451              leafbridge_wizard_data.collection_method = retailer_based_store ? force_leafbridge_wizard_data.collection_method : json.data.leafbridge_default_settings.default_order_type.toUpperCase();
4452              leafbridge_wizard_data.menu_type = retailer_based_store ? force_leafbridge_wizard_data.menu_type : json.data.leafbridge_default_settings.default_menu_type;
4453              leafbridge_wizard_data.retailer_id = retailer_based_store ? force_leafbridge_wizard_data.retailer_id : json.data.leafbridge_default_settings.default_store;
4454
4455              leafbridge_wizard_data.sort = url_par_sort;
4456              leafbridge_wizard_data.event = "LOCAL STORAGE NULL - CALL AJAX DEFAULTS";
4457
4458              var collection_method = leafbridge_wizard_data.collection_method;
4459              var created_time = leafbridge_wizard_data.created_time;
4460              var menu_type = leafbridge_wizard_data.menu_type;
4461              var retailer_id = leafbridge_wizard_data.retailer_id;
4462
4463              localStorage.setItem("leafbridge_wizard_data", JSON.stringify(leafbridge_wizard_data));
4464              link_wizard_set_values(collection_method, retailer_id, menu_type, url_par_sort);
4465
4466              // add default location as recent location
4467              var check_leafbridge_recent_location = localStorage.getItem("leafbridge_recent_location");
4468              if (!check_leafbridge_recent_location) {
4469                set_default_retailer_as_recent_retailer(retailer_id);
4470              }
4471
4472              resolve();
4473            }
4474
4475            // popup wizard only
4476            if (!leafbridge_wizard_data.age_confirm) {
4477              $("#leafbridge_shop_wizard_popup").show();
4478              $(".leafbridge_popup_box").show();
4479            }
4480          })
4481          .catch(function (json) {
4482            console.error("load_default_retailer_settings", json);
4483            reject(json);
4484          });
4485      }
4486
4487      // get saved filter attrs and append to url again.
4488      var localstorage_leafbridge_filter_params = JSON.parse(localStorage.getItem("leafbridge_filter_params"));
4489      
4490      for (const filter_attr in localstorage_leafbridge_filter_params) {
4491        var filter_val = localstorage_leafbridge_filter_params[filter_attr];
4492        urlParams.set(filter_attr, filter_val);
4493      }
4494
4495      var urlparamsstring = urlParams.toString();
4496      var url_origin_pathname = url.origin + url.pathname;
4497      var updated_url = urlparamsstring == "" ? url_origin_pathname : url_origin_pathname + "?" + urlParams.toString();
4498
4499      // var updated_url = url.origin + url.pathname + "?" + urlParams.toString();
4500      window.history.pushState({}, "", updated_url);
4501
4502      // if cart is expired remove it
4503      var newCart = localStorage.getItem("leafbridge_cart_data") ? JSON.parse(localStorage.getItem("leafbridge_cart_data")) : null;
4504      if (newCart != null) {
4505        if (newCart.cart_creation_utc) {
4506          var current_utc = new Date();
4507          var cart_creation_utc = new Date(newCart.cart_creation_utc);
4508
4509          // To calculate the time difference of two dates
4510          var Difference_In_Time = current_utc.getTime() - cart_creation_utc.getTime();
4511
4512          // To calculate the no. of days between two dates
4513          var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
4514
4515          if (Difference_In_Days > 21) {
4516            localStorage.removeItem("leafbridge_cart_data");
4517          }
4518        }
4519      } else {
4520        localStorage.removeItem("leafbridge_cart_data");
4521      }
4522    });
4523  }
4524
4525  function set_default_retailer_as_recent_retailer(retailer_id) {
4526    ajax_get_retailer_details(retailer_id)
4527      .then(function (json) {
4528        var recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
4529        var lbwd = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
4530
4531        var ret_pages = json.data.ret_pages;
4532
4533        if (!recent_location && ret_pages) {
4534          var retailer_page = '';
4535
4536          if(lbwd.menu_type == "RECREATIONAL" && lbwd.collection_method == "DELIVERY"){
4537            retailer_page = json.data.ret_pages[lbwd.retailer_id].recDelivery;
4538          }
4539          else if(lbwd.menu_type == "RECREATIONAL" && lbwd.collection_method == "PICKUP"){
4540            retailer_page = json.data.ret_pages[lbwd.retailer_id].recPickup;
4541          }
4542          else if(lbwd.menu_type == "MEDICAL" && lbwd.collection_method == "DELIVERY"){
4543            retailer_page = json.data.ret_pages[lbwd.retailer_id].medDelivery;
4544          }
4545          else if(lbwd.menu_type == "MEDICAL" && lbwd.collection_method == "PICKUP"){
4546            retailer_page = json.data.ret_pages[lbwd.retailer_id].medPickup;
4547          }
4548          
4549          var set_recent_location = {
4550            retailer_id: retailer_id,
4551            retailer_name: json.data.lb_retailer_custom_name,
4552            retailer_page: retailer_page,
4553          };
4554          localStorage.setItem("leafbridge_recent_location", JSON.stringify(set_recent_location));
4555        }
4556      })
4557      .catch(function (err) {
4558        console.error("get default retailer failed : ", err);
4559      });
4560  }
4561
4562  function link_wizard_set_values(collection_method, retailer_id, menu_type, set_sort) {
4563    // prepare dropdown
4564    populate_delivery_pickup_dropdown(retailer_id, collection_method);
4565
4566    // set retailer
4567    $("#select_store_sticky_wizard").val(retailer_id);
4568    $("#select_store_sticky_wizard").prop("disabled", false);
4569
4570    // set menu type
4571    $(".header_stiky_wizard_select_wrapper[retailer_id=" + retailer_id + "]")
4572      .siblings(".header_stiky_wizard_select_wrapper")
4573      .hide();
4574    $(".header_stiky_wizard_select_wrapper[retailer_id=" + retailer_id + "]").show();
4575    $("#select_menu_type_sticky_wizard_" + retailer_id).val(menu_type);
4576    $("#select_menu_type_sticky_wizard_" + retailer_id).prop("disabled", false);
4577
4578    // set sort
4579    set_sort ? $("#leafbridge_products_sort_by").val(set_sort) : "";
4580  }
4581
4582  // breadcrumbs_modifications
4583  function breadcrumbs_modifications() {
4584    if ($(".pagination_button").hasClass("lb_recent_location")) {
4585      var lb_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
4586      if (lb_recent_location) {
4587        $(".pagination_button.lb_recent_location").find("a").attr("href", lb_recent_location.retailer_page);
4588        $(".pagination_button.lb_recent_location").find("a").text(lb_recent_location.retailer_name);
4589      } else {
4590        $(".pagination_button.lb_recent_location").remove();
4591      }
4592    } else {
4593    }
4594  }
4595
4596    // Retailer banners
4597    function retailer_banners() {
4598      const bannerContainers = document.querySelectorAll('.retailer-banner-container');
4599      
4600      bannerContainers.forEach(container => {
4601          const retailerId = container.dataset.retailerId;
4602          if (retailerId) {
4603            load_retailer_banner(container, retailerId);
4604          }
4605      });
4606  }
4607  
4608  function load_retailer_banner(container, retailerId) {
4609      const data = {
4610          action: 'get_retailer_banner',
4611          retailer_id: retailerId
4612      };
4613  
4614      jQuery.ajax({
4615          url: leafbridge_public_ajax_obj.ajaxurl,
4616          type: 'POST',
4617          data: data,
4618          cache: false,
4619          success: function(response) {
4620              if (response.success && response.banner) {
4621                  const banner = response.banner;
4622                  const bannerHtml = `
4623                      <div class="retailer_banner" style="
4624                          color: ${banner.colors.color};
4625                          border: 1px solid ${banner.colors.border};
4626                          background-color: ${banner.colors.background};
4627                          padding: 30px;">
4628                          ${banner.html}
4629                      </div>
4630                  `;
4631                  container.innerHTML = bannerHtml;
4632              } else {
4633                  console.error('Failed to load banner:', response.message);
4634              }
4635          },
4636          error: function (json) {
4637            reject(json);
4638          },
4639      });
4640  }
4641
4642  function retailer_ads() {
4643    if ($("div").hasClass("retailer_ad_wrapper")) {
4644      retailer_ads_promise()
4645        .then(function (json) {
4646          $("#retailer_ad_wrapper").html(json.data._lb_retailer_ad);
4647        })
4648        .catch(function (err) {
4649          console.error("retailer ads error", err);
4650        });
4651    }
4652  }
4653
4654  function retailer_ads_promise() {
4655    return new Promise(function (resolve, reject) {
4656      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
4657
4658      var data = {
4659        action: "get_retailer_ads",
4660        retailer_id: leafbridge_wizard_data.retailer_id,
4661      };
4662
4663      $.ajax({
4664        url: leafbridge_public_ajax_obj.ajaxurl,
4665        dataType: "json",
4666        cache: false,
4667        data: data,
4668        type: "POST",
4669        proccessData: false,
4670        success: function (json) {
4671          resolve(json);
4672        },
4673        error: function (json) {
4674          reject(json);
4675        },
4676        complete: function (json) { },
4677      });
4678    });
4679  }
4680
4681  function retailer_dynamic_content() {
4682    $(".retailer_dynamic_content").each(function () {
4683      const thiselement = $(this);
4684
4685      // Hide all child divs initially
4686      thiselement.children("div").hide();
4687
4688      retailer_dynamic_content_promise()
4689        .then(function (json) {
4690          const retailerID = json.data.retailer_id;
4691          // Show the div with class equal to retailer_id
4692          thiselement.children("." + retailerID).show();
4693        })
4694        .catch(function (err) {
4695          console.error("retailer dynamic content error", err);
4696        });
4697    });
4698  }
4699
4700  function retailer_dynamic_content_promise() {
4701    return new Promise(function (resolve, reject) {
4702      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
4703
4704      var data = {
4705        action: "get_retailer_dynamic_content",
4706        retailer_id: leafbridge_wizard_data.retailer_id,
4707      };
4708
4709      $.ajax({
4710        url: leafbridge_public_ajax_obj.ajaxurl,
4711        dataType: "json",
4712        cache: false,
4713        data: data,
4714        type: "POST",
4715        proccessData: false,
4716        success: function (json) {
4717          resolve(json);
4718        },
4719        error: function (json) {
4720          reject(json);
4721        },
4722        complete: function (json) { },
4723      });
4724    });
4725  }
4726
4727  function show_current_retailer_name() {
4728
4729    var leafbridge_wizard_data = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
4730    var current_ret_ID = leafbridge_wizard_data.retailer_id;
4731    var retailers_data = JSON.parse($('#lb_retailers_details').attr('data-retailer-details'));
4732    var current_ret_data = retailers_data[current_ret_ID];
4733
4734    const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
4735    const currentDayName = days[new Date().getDay()];
4736
4737    var currentDelivery = current_ret_data.hours.delivery[currentDayName];
4738    var currentPickup = current_ret_data.hours.pickup[currentDayName];
4739
4740    $('.put_lb_retailer_name').each(function () {
4741      $(this).html(current_ret_data.name);
4742    });
4743
4744    $('.put_lb_retailer_phone').each(function () {
4745      $(this).html(current_ret_data.phone);
4746    })
4747
4748
4749    if (currentDelivery.active) {
4750      if (currentDelivery.start == "open") {
4751        $('.lb_ret_delivery_today_open_h_start').each(function () {
4752          $(this).html('24 hours');
4753        })
4754        $('.lb_ret_delivery_today_open_h_end').each(function () {
4755          $(this).html('');
4756        })
4757      }
4758      else {
4759        $('.lb_ret_delivery_today_open_h_start').each(function () {
4760          $(this).html(currentDelivery.start);
4761        })
4762        $('.lb_ret_delivery_today_open_h_end').each(function () {
4763          $(this).html(currentDelivery.end);
4764        })
4765      }
4766    }
4767    else {
4768      $('.lb_ret_delivery_today_open_h_start').each(function () {
4769        $(this).html('closed');
4770      })
4771      $('.lb_ret_delivery_today_open_h_end').each(function () {
4772        $(this).html('');
4773      })
4774    }
4775
4776
4777    if (currentPickup.active) {
4778      if (currentPickup.start == "open") {
4779        $('.lb_ret_pickup_today_open_h_start').each(function () {
4780          $(this).html('24 hours');
4781        })
4782        $('.lb_ret_pickup_today_open_h_end').each(function () {
4783          $(this).html('');
4784        })
4785      }
4786      else {
4787        $('.lb_ret_pickup_today_open_h_start').each(function () {
4788          $(this).html(currentPickup.start);
4789        })
4790        $('.lb_ret_pickup_today_open_h_end').each(function () {
4791          $(this).html(currentPickup.end);
4792        })
4793      }
4794    }
4795    else {
4796      $('.lb_ret_pickup_today_open_h_start').each(function () {
4797        $(this).html('closed');
4798      })
4799      $('.lb_ret_pickup_today_open_h_end').each(function () {
4800        $(this).html('');
4801      })
4802    }
4803
4804  }
4805
4806  function retailer_dynamic_content_promise() {
4807    return new Promise(function (resolve, reject) {
4808      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
4809
4810      var data = {
4811        action: "get_retailer_dynamic_content",
4812        retailer_id: leafbridge_wizard_data.retailer_id,
4813      };
4814
4815      $.ajax({
4816        url: leafbridge_public_ajax_obj.ajaxurl,
4817        dataType: "json",
4818        cache: false,
4819        data: data,
4820        type: "POST",
4821        proccessData: false,
4822        success: function (json) {
4823          resolve(json);
4824        },
4825        error: function (json) {
4826          reject(json);
4827        },
4828        complete: function (json) { },
4829      });
4830    });
4831  }
4832
4833  // CSS by Location
4834  function css_by_location() {
4835    var retailerData = localStorage.getItem('leafbridge_wizard_data');
4836    if (retailerData) {
4837      var retailerDataObj = JSON.parse(retailerData);
4838      var currentRetailerId = retailerDataObj.retailer_id;
4839
4840      promise_css_by_location(currentRetailerId)
4841        .then(function (json) {
4842          if (json.data.css_by_location) {
4843            var location_css = json.data.css_by_location;
4844            $('#leafbridge_css_by_location').html(location_css);
4845          }
4846        })
4847        .catch(function (err) {
4848          console.error('css_by_location', json);
4849        });
4850    }
4851  };
4852
4853  function promise_css_by_location(retailer_id) {
4854    return new Promise(function (resolve, reject) {
4855      var data = {
4856        action: 'get_css_by_location',
4857        retailer_id: retailer_id,
4858      };
4859
4860      $.ajax({
4861        url: leafbridge_public_ajax_obj.ajaxurl,
4862        dataType: 'json',
4863        cache: false,
4864        data: data,
4865        type: "POST",
4866        proccessData: false,
4867        success: function (json) {
4868          resolve(json);
4869        },
4870        error: function (json) {
4871          reject(json);
4872        },
4873        complete: function (json) {
4874
4875        },
4876      })
4877    });
4878  }
4879
4880  // display system errors
4881  function show_system_error(error_msg) {
4882    console.error("System Error : ", error_msg);
4883    error_msg = error_msg == "" || typeof error_msg == "undefined" ? "Service is unavailable." : error_msg;
4884    var error_html = '<div class="lb_error_server"><div class="lb-error-box"><div class="lb-error-text"><p class="lb-error-heading">' + error_msg + '</p><a href="#" id="clear_all_wizard_data">Click here to reset selection</a> or <a href="#" class="lb-error-link">Please contact the site administrator if the same issue persists.</a></div></div></div>';
4885    if (!$("body div").hasClass("lb_error_server")) {
4886      $("body").prepend(error_html);
4887    }
4888  }
4889
4890  function hide_null_filter_attrs_shop(available_filters) {
4891    var available_filter_attrs = {
4892      brands: Array.isArray(available_filters.brands) ? available_filters.brands.map(brand => brand.id) : [],
4893      tags: Array.isArray(available_filters.tags) ? available_filters.tags : [],
4894      weights: Array.isArray(available_filters.weights) ? available_filters.weights : []
4895    };
4896
4897    var leafbridge_wizard_data = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
4898    var selected_retailer = leafbridge_wizard_data.retailer_id;
4899
4900    // Find if there's any pre-selected filter attrs
4901    var selected_array = [];
4902    $('.lb_prod_filter_attr_box').each(function () {
4903      var get_fsv = $(this).attr('filter_selected_val');
4904      var get_filtattr = $(this).attr('filter_attr');
4905      if (get_fsv.length > 0) {
4906        selected_array.push(get_filtattr);
4907      }
4908    });
4909
4910    if (selected_array.length > 0) {
4911      var brands_selected = selected_array.includes('brands') || selected_array.includes('brand');
4912
4913      // Loop through available_filter_attrs and hide/show filter attributes accordingly
4914      for (const [attr, values_set] of Object.entries(available_filter_attrs)) {
4915        var attr_name = (attr === "brands") ? 'brands' : (attr === 'category') ? 'categories' : (attr === 'tags') ? 'POS_Tags' : (attr === "weights") ? 'weight' : attr;
4916        var selected_filter_attr_box = $('.lb_prod_filter_attr_box[filter_attr="' + attr_name + '"]');
4917
4918        if (values_set.length === 0) {
4919          selected_filter_attr_box.hide();
4920        } else {
4921          selected_filter_attr_box.show();
4922
4923          // If 'brands' is selected, show all items in the 'brands' filter attribute box
4924          if (brands_selected && attr === 'brands') {
4925            selected_filter_attr_box.find('li').removeClass('null_filter_hide');
4926          } else {
4927            // Hide all items initially
4928            selected_filter_attr_box.find('li').addClass('null_filter_hide');
4929            // Show items that match available values
4930            for (const value of values_set) {
4931              if (attr === 'brands') {
4932                selected_filter_attr_box.find('li[attr_value="' + value + '"][brand_retailer="' + selected_retailer + '"]').removeClass('null_filter_hide');
4933              } else {
4934                selected_filter_attr_box.find('li[attr_value="' + value + '"]').removeClass('null_filter_hide');
4935              }
4936            }
4937          }
4938        }
4939      }
4940    } else {
4941      // No filters selected, show all items
4942      $('.lb_prod_filter_attr_box ul li.null_filter_hide').removeClass('null_filter_hide');
4943      $('.lb_prod_filter_attr_box').show();
4944    }
4945
4946    // Check if all available_filter_attrs values are empty and hide the box if so
4947    var allEmpty = Object.values(available_filter_attrs).every(arr => arr.length === 0);
4948    if (allEmpty) {
4949      $('.lb_prod_filter_attr_box').show();
4950    }
4951  }
4952
4953  // GTM dataLayer push functions
4954  function gtm_push_single_item_data(pushData, eventName) {
4955    var prepped_pushData = {};
4956
4957    var item_price = 0;
4958    var item_value = 0;
4959    var item_discounted_price = 0; // discounted price of item ( original price - discount )
4960    var item_discount = 0;
4961    var item_discounted_value = 0;
4962
4963    var get_special_price = 0;
4964    var get_discounted_price = 0;
4965
4966    var item_variants = pushData.moreDataLayerPush.item_data.variants;
4967    var selected_menu_type = pushData.moreDataLayerPush.menu_type;
4968    var item_qty = parseFloat(pushData.moreDataLayerPush.cart_prod.prod_count);
4969
4970    for (var i = 0; i < item_variants.length; i++) {
4971      var this_item_variant = item_variants[i];
4972      if (this_item_variant.option == pushData.moreDataLayerPush.cart_prod.variation) {
4973        item_price = (selected_menu_type == "MEDICAL") ? parseFloat(this_item_variant.priceMed) : parseFloat(this_item_variant.priceRec);
4974        item_discounted_price = (selected_menu_type == "MEDICAL") ? ((this_item_variant.specialPriceMed != null) ? parseFloat(this_item_variant.specialPriceMed) : item_price) : ((this_item_variant.specialPriceRec != null) ? parseFloat(this_item_variant.specialPriceRec) : item_price);
4975        item_value = item_discounted_price * item_qty;
4976        item_discount = item_price - item_discounted_price;
4977        item_discounted_value = item_discount * item_qty;
4978      }
4979    }
4980
4981    prepped_pushData.event = eventName;
4982    prepped_pushData.item_id = pushData.moreDataLayerPush.item_data.item_id ? pushData.moreDataLayerPush.item_data.item_id : "N/A";
4983    prepped_pushData.item_name = pushData.moreDataLayerPush.item_data.item_name ? pushData.moreDataLayerPush.item_data.item_name : "N/A";
4984    prepped_pushData.currency = "USD";
4985    prepped_pushData.quantity = pushData.moreDataLayerPush.cart_prod.prod_count ? pushData.moreDataLayerPush.cart_prod.prod_count : "N/A";
4986    prepped_pushData.item_value = parseFloat(item_value.toFixed(2)); // discounted price * qty | ( discounted price  = original price - discount ) 
4987    prepped_pushData.item_price = parseFloat(item_price.toFixed(2)); // orginal price of one item ( without discounts )
4988    prepped_pushData.item_discount = parseFloat(item_discount.toFixed(2));
4989    prepped_pushData.item_discounted_value = parseFloat(item_discounted_value.toFixed(2));
4990    prepped_pushData.item_brand = pushData.moreDataLayerPush.item_data.brand_name ? pushData.moreDataLayerPush.item_data.brand_name : "N/A";
4991    prepped_pushData.item_category = pushData.moreDataLayerPush.item_data.category ? pushData.moreDataLayerPush.item_data.category : "N/A";
4992    prepped_pushData.item_subcategory = pushData.moreDataLayerPush.item_data.subcategory ? pushData.moreDataLayerPush.item_data.subcategory : "N/A";
4993    prepped_pushData.item_variant = pushData.moreDataLayerPush.cart_prod.variation ? pushData.moreDataLayerPush.cart_prod.variation : "N/A";
4994    prepped_pushData.location_id = pushData.moreDataLayerPush.location_id ? pushData.moreDataLayerPush.location_id : "N/A";
4995    prepped_pushData.location_name = pushData.moreDataLayerPush.location_name ? pushData.moreDataLayerPush.location_name : "N/A";
4996    prepped_pushData.menu_type = pushData.moreDataLayerPush.menu_type ? pushData.moreDataLayerPush.menu_type : "N/A";
4997    prepped_pushData.item_strain_type = pushData.moreDataLayerPush.item_data.strainType ? pushData.moreDataLayerPush.item_data.strainType : "N/A";
4998    prepped_pushData.item_potency_thc = pushData.moreDataLayerPush.item_data.potencyThc ? pushData.moreDataLayerPush.item_data.potencyThc : "N/A";
4999    prepped_pushData.item_potency_cbd = pushData.moreDataLayerPush.item_data.potencyCbd ? pushData.moreDataLayerPush.item_data.potencyCbd : "N/A";
5000
5001    if (eventName == "LB_ViewItem") {
5002      prepped_pushData.quantity = "1";
5003    }
5004
5005    window.dataLayer = window.dataLayer || [];
5006    window.dataLayer.push(prepped_pushData);
5007    
5008    // dl_add_to_cart
5009    var dl_data_layer_location = return_dl_data_layer_location();
5010    if(eventName == "LB_AddToCart"){
5011      
5012      var dl_add_to_cart_method = 'PLP_SHOP_ALL';
5013      
5014      var check_shop_page = ($('.leafbridge_shop_wizard_wrapper').length > 0) ? true : false;
5015      var check_category_page = ($('.leafbridge_category_page').length > 0) ? true : false;
5016      var check_pdp_page = ($('.lb_single_prod_page_wrapper').length > 0) ? true : false;
5017
5018      dl_add_to_cart_method = ( check_category_page ? 'PLP_CATEGORY' : ( check_shop_page ? 'PLP_SHOP_ALL' : ( check_pdp_page ? 'PDP' : 'UNKNOWN' ) ) );
5019      
5020      var dl_push_data_addToCart = Object.assign({}, prepped_pushData);
5021      var dl_push_data_all = {
5022        event: "dl_add_to_cart",
5023        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
5024        ecommerce: {
5025          method : dl_add_to_cart_method,
5026          items : prepare_items_list(dl_push_data_addToCart,'dl_add_to_cart')  
5027        }
5028      }
5029      if(dl_push_data_addToCart.event) delete dl_push_data_addToCart.event;
5030      if(dl_push_data_addToCart.location_name) delete dl_push_data_addToCart.location_name;
5031      if(dl_push_data_addToCart.location_id) delete dl_push_data_addToCart.location_id;
5032
5033      window.dataLayer = window.dataLayer || [];
5034      window.dataLayer.push(dl_push_data_all);
5035    }
5036
5037    // dl_select_item
5038    if(eventName == "LB_ViewItem"){
5039      var dl_push_data_addToCart = Object.assign({}, prepped_pushData);
5040      var dl_push_data_all = {
5041        event: "dl_view_item",
5042        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
5043        ecommerce: {
5044          method : dl_add_to_cart_method,
5045          items : prepare_items_list(dl_push_data_addToCart,'dl_view_item')  
5046        }
5047      }
5048
5049      var dl_push_data_addToCart = Object.assign({}, prepped_pushData);
5050      var dl_push_data_all = {
5051        event: "dl_view_item",
5052        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
5053        ecommerce: {
5054          method : dl_add_to_cart_method,
5055          items : prepare_items_list(dl_push_data_addToCart,'dl_select_item')  
5056        }
5057      }
5058      if(dl_push_data_addToCart.event) delete dl_push_data_addToCart.event;
5059      if(dl_push_data_addToCart.location_name) delete dl_push_data_addToCart.location_name;
5060      if(dl_push_data_addToCart.location_id) delete dl_push_data_addToCart.location_id;
5061
5062      window.dataLayer = window.dataLayer || [];
5063      window.dataLayer.push(dl_push_data_all);
5064    }
5065
5066    // surfside action start
5067    if ($("body").hasClass("lbsrf_enabled")) {
5068      var currency = "USD";
5069      var lbSurf_impressionFieldObject = {};
5070      lbSurf_impressionFieldObject;
5071      lbSurf_impressionFieldObject.id = prepped_pushData.item_id; // The ID
5072      lbSurf_impressionFieldObject.name = prepped_pushData.item_name; // The name (string)
5073      lbSurf_impressionFieldObject.list = "N/A"; //The list (string)
5074      lbSurf_impressionFieldObject.brand = prepped_pushData.item_brand; // The brand (string)
5075      lbSurf_impressionFieldObject.category = prepped_pushData.item_category; // The category (string)
5076      lbSurf_impressionFieldObject.variant = prepped_pushData.item_variant; // The variant (string)
5077      lbSurf_impressionFieldObject.price = prepped_pushData.item_price; // The price (number)
5078      lbSurf_impressionFieldObject.quantity = prepped_pushData.quantity; //  The quantity (number)
5079      lbSurf_impressionFieldObject.coupon = "N/A"; // The coupon (number)
5080      lbSurf_impressionFieldObject.position = "N/A"; // The position (number)
5081      lbSurf_impressionFieldObject.currency = currency; // The currency (string)
5082
5083      surf("addProduct:digital", lbSurf_impressionFieldObject);
5084      if (eventName == "LB_ViewItem") {
5085        surf("setCommerceAction:digital", "detail");
5086      }
5087      else if (eventName == "LB_AddToCart" || eventName == "LB_RemoveCartItem") {
5088        var lbSurf_transactionFieldObject = {
5089          id: pushData.data.update_cart.id, // Transaction ID
5090          affiliation: pushData.moreDataLayerPush.location_id, // Transaction Affiliation
5091          revenue: pushData.data.update_cart.priceSummary?.total, // Transaction Revenue
5092          tax: pushData.data.update_cart.priceSummary?.taxes, // Transaction Tax
5093          shipping: pushData.data.update_cart.orderType, // Transaction Shipping
5094          coupon: "N/A", // Transaction Coupon
5095          list: "N/A", // Transaction List
5096          step: eventName, // Transaction Step
5097          option: pushData.data.update_cart.pricingType, // Transaction Option
5098          currency: currency, // Transaction Currency
5099        };
5100
5101        var commerceAction = eventName == "LB_AddToCart" ? "add" : eventName == "LB_RemoveCartItem" ? "remove" : "detail";
5102        surf("setCommerceAction:digital", commerceAction);
5103        // surf("addTransaction:digital", lbSurf_transactionFieldObject);
5104      }
5105    }
5106    // surfside action end
5107  }
5108
5109  function gtm_push_items_data(pushData, eventName) {
5110    var prepped_pushData = {};
5111
5112    // prep items related data
5113    var prep_items = {};
5114    var pushDataItems = pushData.moreDataLayerPush.order_details.items;
5115
5116    // prep items data
5117    var prep_items = [];
5118
5119    if (Array.isArray(pushDataItems)) {
5120      for (var i = 0; i < pushDataItems.length; i++) {
5121        var temp_pushDataItem = {};
5122        var selected_menu_type = pushData.moreDataLayerPush.menu_type;
5123        var pushDataItem = pushDataItems[i];
5124        var item_qty = parseInt(pushDataItem.quantity);
5125        var item_price_single = 0;
5126
5127        var item_varient = pushDataItem.option;
5128        var iteration_count = i + 1;
5129
5130        var item_price = 0;
5131        var item_value = 0;
5132        var item_discounted_price = 0; // discounted price of item ( original price - discount )
5133        var item_discount = 0;
5134        var item_discounted_value = 0;
5135
5136        var item_variants = pushDataItem.product.variants;
5137        for (var vrnts = 0;
5137 vrnts < item_variants.length; vrnts++) {
5138          var current_variant = item_variants[vrnts];
5139          if (current_variant.option == item_varient) {
5140            item_price = selected_menu_type == "RECREATIONAL" ? current_variant.priceRec : current_variant.priceMed;
5141            item_discounted_price = (selected_menu_type == "MEDICAL") ? ((current_variant.specialPriceMed != null) ? parseFloat(current_variant.specialPriceMed) : item_price) : ((current_variant.specialPriceRec != null) ? parseFloat(current_variant.specialPriceRec) : item_price);
5142            item_value = item_discounted_price * item_qty;
5143            item_discount = item_price - item_discounted_price;
5144            item_discounted_value = item_discount * item_qty;
5145          }
5146        }
5147
5148        // set prices values
5149        if (eventName == "LB_Purchase") {
5150          for (var vrnts = 0; vrnts < item_variants.length; vrnts++) {
5151            var current_variant = item_variants[vrnts];
5152            if (current_variant.option == item_varient) {
5153              item_price = selected_menu_type == "RECREATIONAL" ? current_variant.priceRec : current_variant.priceMed;
5154              item_discounted_price = (selected_menu_type == "MEDICAL") ? ((current_variant.specialPriceMed != null) ? parseFloat(current_variant.specialPriceMed) : item_price) : ((current_variant.specialPriceRec != null) ? parseFloat(current_variant.specialPriceRec) : item_price);
5155              item_value = item_discounted_price * item_qty;
5156              item_discount = item_price - item_discounted_price;
5157              item_discounted_value = item_discount * item_qty;
5158            }
5159          }
5160        }
5161        else if (eventName == "LB_UpdateCart" || eventName == "LB_BeginCheckout") {
5162          item_varient = pushDataItem.option;
5163          for (var vrnts = 0; vrnts < item_variants.length; vrnts++) {
5164            var current_variant = item_variants[vrnts];
5165            if (current_variant.option == item_varient) {
5166              item_price = selected_menu_type == "RECREATIONAL" ? current_variant.priceRec : current_variant.priceMed;
5167              item_discounted_price = (selected_menu_type == "MEDICAL") ? ((current_variant.specialPriceMed != null) ? parseFloat(current_variant.specialPriceMed) : item_price) : ((current_variant.specialPriceRec != null) ? parseFloat(current_variant.specialPriceRec) : item_price);
5168              item_value = item_discounted_price * item_qty;
5169              item_discount = item_price - item_discounted_price;
5170              item_discounted_value = item_discount * item_qty;
5171            }
5172          }
5173        }
5174
5175        temp_pushDataItem.index = iteration_count;
5176        temp_pushDataItem.item_id = pushDataItem.productId;
5177        temp_pushDataItem.item_name = pushDataItem.product.name;
5178        temp_pushDataItem.quantity = pushDataItem.quantity;
5179
5180        temp_pushDataItem.item_price = parseFloat(item_price.toFixed(2)); // orginal price of one item ( without discounts )
5181        temp_pushDataItem.item_value = parseFloat(item_value.toFixed(2)); // discounted price * qty ( original price - discount )
5182        temp_pushDataItem.item_discount = parseFloat(item_discount.toFixed(2)); // discount for 1 product 
5183        temp_pushDataItem.item_discounted_value = parseFloat(item_discounted_value.toFixed(2)); // discount * qty
5184
5185        temp_pushDataItem.item_brand_id = pushDataItem.product.brand != null ? pushDataItem.product.brand.id : "N/A";
5186        temp_pushDataItem.item_brand_name = pushDataItem.product.brand != null ? pushDataItem.product.brand.name : "N/A";
5187        temp_pushDataItem.item_category = pushDataItem.product.category;
5188        temp_pushDataItem.item_subcategory = pushDataItem.product.subcategory;
5189        temp_pushDataItem.item_variant = item_varient;
5190        temp_pushDataItem.item_strain_type = pushDataItem.product.strainType;
5191        temp_pushDataItem.item_potency_thc = pushDataItem.product.potencyThc.formatted != null ? pushDataItem.product.potencyThc.formatted : "N/A";
5192        temp_pushDataItem.item_potency_cbd = pushDataItem.product.potencyCbd.formatted != null ? pushDataItem.product.potencyCbd.formatted : "N/A";
5193
5194        prep_items.push(temp_pushDataItem);
5195        
5196      } //end of pushDataItems looping
5197    } // end check if pushDataItems is array
5198
5199    // localStorage.setItem('purchase_checkout_id', '12312312');
5200
5201    // prepped_pushData.allData = pushData.moreDataLayerPush.order_details ? pushData.moreDataLayerPush.order_details : {};
5202
5203    // set cart totals
5204    var all_items_cart_total = 0;
5205    var all_items_cart_subtotal = 0;
5206    var all_items_cart_tax = 0;
5207    var all_items_cart_discount = 0;
5208
5209    if (eventName == "LB_Purchase") {
5210      all_items_cart_total = pushData.moreDataLayerPush.order_details.total ? pushData.moreDataLayerPush.order_details.total : "N/A";
5211      all_items_cart_subtotal = pushData.moreDataLayerPush.order_details.subtotal ? pushData.moreDataLayerPush.order_details.subtotal : "N/A";
5212      all_items_cart_tax = pushData.moreDataLayerPush.order_details.tax ? pushData.moreDataLayerPush.order_details.tax : "N/A";
5213      all_items_cart_discount = pushData.moreDataLayerPush.order_details.discounts.total ? pushData.moreDataLayerPush.order_details.discounts.total : 0;
5214
5215    } 
5216    else if (eventName == "LB_UpdateCart" || eventName == "LB_BeginCheckout") {
5217      all_items_cart_total = pushData.moreDataLayerPush.order_details.priceSummary.total / 100;
5218      all_items_cart_subtotal = pushData.moreDataLayerPush.order_details.priceSummary.subtotal / 100;
5219      all_items_cart_tax = pushData.moreDataLayerPush.order_details.priceSummary.taxes / 100;
5220      all_items_cart_discount = pushData.moreDataLayerPush.order_details.priceSummary.discounts / 100;
5221    }
5222
5223    prepped_pushData.event = eventName;
5224    prepped_pushData.currency = "USD";
5225    prepped_pushData.items = prep_items;
5226    prepped_pushData.location_id = pushData.moreDataLayerPush.location_id ? pushData.moreDataLayerPush.location_id : "N/A";
5227    prepped_pushData.location_name = pushData.moreDataLayerPush.location_name ? pushData.moreDataLayerPush.location_name : "N/A";
5228    prepped_pushData.menu_type = pushData.moreDataLayerPush.menu_type ? pushData.moreDataLayerPush.menu_type : "N/A";
5229    prepped_pushData.transaction_id = pushData.moreDataLayerPush.order_details.orderNumber ? pushData.moreDataLayerPush.order_details.orderNumber : "N/A";
5230    prepped_pushData.transaction_total = all_items_cart_total;
5231    prepped_pushData.transaction_subtotal = all_items_cart_subtotal;
5232    prepped_pushData.transaction_tax = all_items_cart_tax;
5233    prepped_pushData.transaction_discount = all_items_cart_discount;
5234    // prepped_pushData.transaction_discount = (pushData.moreDataLayerPush.order_details) ? pushData.moreDataLayerPush.order_details.orderNumber : "N/A";
5235    // prepped_pushData.transaction_fee = (pushData.moreDataLayerPush.order_details) ? pushData.moreDataLayerPush.order_details.orderNumber : "N/A";
5236    // prepped_pushData.transaction_mixmatch = (pushData.moreDataLayerPush.order_details) ? pushData.moreDataLayerPush.order_details.orderNumber : "N/A";
5237    // prepped_pushData.transaction_rewards = (pushData.moreDataLayerPush.order_details) ? pushData.moreDataLayerPush.order_details.orderNumber : "N/A";
5238    prepped_pushData.transaction_type = pushData.moreDataLayerPush.order_details.pickup ? (pushData.moreDataLayerPush.order_details.pickup ? "PICKUP" : "DELIVER") : "N/A";
5239    prepped_pushData.transaction_user = pushData.moreDataLayerPush.order_details.customer ? pushData.moreDataLayerPush.order_details.customer : "N/A";
5240    prepped_pushData.transaction_date = pushData.moreDataLayerPush.order_details.createdAt ? pushData.moreDataLayerPush.order_details.createdAt : "N/A";
5241    // prepped_pushData.pushData = pushData; // REMOVE IT LATER _ ONLY FOR TEST
5242    window.dataLayer = window.dataLayer || [];
5243    // dataLayer.push(prepped_pushData);
5244
5245    if (window.dataLayer && Array.isArray(window.dataLayer)) {
5246      window.dataLayer.push(prepped_pushData);
5247    } else {
5248      console.error("GTM dataLayer has been tampered by another plugin/script");
5249    }
5250
5251    // surfside action start
5252    if ($("body").hasClass("lbsrf_enabled")) {
5253      var currency = "USD";
5254
5255      // loop through all items
5256      var items_list = prepped_pushData.items;
5257
5258      for (const [key, value] of Object.entries(items_list)) {
5259        var prods_list_item = value;
5260
5261        var lbSurf_impressionFieldObject = {};
5262        lbSurf_impressionFieldObject;
5263        // lbSurf_impressionFieldObject.id = prods_list_item.item_id; // The ID
5264        // lbSurf_impressionFieldObject.id = prepped_pushData.transaction_id; // The ID
5265        lbSurf_impressionFieldObject.id = prods_list_item.item_id; // The Product ID
5266        lbSurf_impressionFieldObject.name = prods_list_item.item_name; // The name (string)
5267        lbSurf_impressionFieldObject.list = "N/A"; //The list (string)
5268        lbSurf_impressionFieldObject.brand = prods_list_item.item_brand_name; // The brand (string)
5269        lbSurf_impressionFieldObject.category = prods_list_item.item_category; // The category (string)
5270        lbSurf_impressionFieldObject.variant = prods_list_item.item_variant; // The variant (string)
5271        lbSurf_impressionFieldObject.price = prods_list_item.item_price; // The price (number)
5272        lbSurf_impressionFieldObject.quantity = prods_list_item.quantity; //  The quantity (number)
5273        lbSurf_impressionFieldObject.coupon = "N/A"; // The coupon (number)
5274        lbSurf_impressionFieldObject.position = "N/A"; // The position (number)
5275        lbSurf_impressionFieldObject.currency = currency; // The currency (string)
5276
5277        surf("addProduct:digital", lbSurf_impressionFieldObject);
5278
5279      }
5280
5281      if (eventName == "LB_Purchase" || eventName == "LB_BeginCheckout") {
5282        var check_delivery_pickeup = pushData.moreDataLayerPush.order_details.pickup;
5283        var lbSurf_transactionFieldObject = {
5284          id: (eventName == "LB_BeginCheckout") ? pushData.moreDataLayerPush.order_details.id : prepped_pushData.transaction_id, // pass checkout ID if begin checkout . send order ID if purchased as Transaction ID
5285          affiliation: pushData.moreDataLayerPush.location_id, // Transaction Affiliation
5286          revenue: all_items_cart_total, // Transaction Revenue
5287          tax: all_items_cart_tax, // Transaction Tax
5288          shipping: check_delivery_pickeup ? "pickup" : "delivery", // Transaction Shipping
5289          coupon: "N/A", // Transaction Coupon
5290          list: "N/A", // Transaction List
5291          step: eventName, // Transaction Step
5292          option: (eventName == "LB_BeginCheckout") ? "N/A" : pushData.moreDataLayerPush.order_details.id, // Transaction Option
5293          currency: currency, // Transaction Currency
5294        };
5295
5296        surf("addTransaction:digital", lbSurf_transactionFieldObject);
5297
5298        if (eventName == "LB_Purchase") {
5299          var customer_email = pushData.moreDataLayerPush.order_details.customer ? pushData.moreDataLayerPush.order_details.customer.email : null;
5300          // lbSurf_transactionFieldObject.option = customer_email;
5301          if (customer_email !== null) {
5302            surf("setUserId", customer_email);
5303          }
5304        }
5305
5306        var commerceAction = eventName == "LB_BeginCheckout" ? "checkout" : eventName == "LB_Purchase" ? "purchase" : "checkout_option";
5307        surf("setCommerceAction:digital", commerceAction);
5308      }
5309    }
5310    // surfside action end
5311
5312    var dl_data_layer_location = return_dl_data_layer_location();
5313    // dl_begin_checkout
5314    if(eventName == "LB_BeginCheckout"){
5315      // dl_add_to_cart
5316      // var dl_push_data_ = Object.assign({}, prepped_pushData);
5317      var dl_push_data_all = {
5318        event: "dl_begin_checkout",
5319        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
5320        ecommerce: {
5321          value : prepped_pushData.transaction_subtotal,
5322          currency : 'USD',
5323          items : prepare_items_list(prepped_pushData.items,'dl_begin_checkout')  
5324        }
5325      }
5326      if (window.dataLayer && Array.isArray(window.dataLayer)) {
5327        // window.dataLayer.push(prepped_pushData);
5328        window.dataLayer.push(dl_push_data_all);
5329      } else {
5330        console.error("GTM dataLayer has been tampered by another plugin/script");
5331      }
5332      
5333    }
5334
5335    // dl_purchase
5336    if(eventName == "LB_Purchase"){
5337      var payment_type = pushData.data.order_details[0].paymentMethod;
5338      prepped_pushData.fees = pushData.moreDataLayerPush.order_details.fees.total ? pushData.moreDataLayerPush.order_details.fees.total : 0;
5339
5340      var customer_type = "new";
5341      var lb_new_user = localStorage.getItem('lb_new_user');
5342      if(lb_new_user !== null && lb_new_user == 'false'){
5343        customer_type = "returning";
5344      }     
5345
5346      prepped_pushData.transaction_total = (!isNaN(prepped_pushData.transaction_total)) ? prepped_pushData.transaction_total : 0;
5347      prepped_pushData.transaction_tax = (!isNaN(prepped_pushData.transaction_tax)) ? prepped_pushData.transaction_tax : 0;
5348      prepped_pushData.fees = (!isNaN(prepped_pushData.fees)) ? prepped_pushData.fees : 0;
5349        
5350      var calc_value = prepped_pushData.transaction_total - prepped_pushData.transaction_tax - prepped_pushData.fees
5351
5352      var dl_push_data_all = {
5353        event: "dl_purchase",
5354        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
5355        customer: {customer_type : customer_type},
5356        ecommerce: {
5357          value : calc_value,
5358          sub_total : prepped_pushData.transaction_subtotal ,
5359          currency : 'USD',
5360          items : prepare_items_list(prepped_pushData.items,'dl_purchase'),  
5361
5362          transaction_id : prepped_pushData.transaction_id,
5363          // coupon : '',
5364          discount : all_items_cart_discount,
5365          tax : prepped_pushData.transaction_tax,
5366          payment_type: payment_type,
5367          fees : prepped_pushData.fees,
5368        }
5369      }
5370      if (window.dataLayer && Array.isArray(window.dataLayer)) {
5371        // window.dataLayer.push(prepped_pushData);
5372        window.dataLayer.push(dl_push_data_all);
5373      } else {
5374        console.error("GTM dataLayer has been tampered by another plugin/script");
5375      }
5376    }
5377  }
5378
5379  function trigger_surfside_cart_ad(){
5380    var this_ad_wrapper = $('.lb_surfside_ads_wrapper[data_section="_cart"]');
5381    var ad_section = this_ad_wrapper.attr("data_section");
5382
5383    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5384
5385    get_ad_html(ad_section)
5386      .then(function (json) {
5387        var ad_html = json.data.ad_html;
5388        var ad_html_obj = $.parseHTML(ad_html, document, false);
5389
5390        $(ad_html_obj).each(function () {
5391          $(this).attr("storeId", leafbridge_wizard_data.retailer_id);
5392
5393          if ($("div").hasClass("leafbridge_category_page")) {
5394            var category_name = $("#leafbridge_category_page").attr("data_lb_category");
5395            category_name = category_name[0].toUpperCase() + category_name.substring(1).toLowerCase();
5396            $(this).attr("zone", category_name);
5397            $(this).attr("keywords", category_name);
5398          }
5399        });
5400
5401        // ad_html_obj.attr('storeId', 'f0ff5c46-2f0c-4137-941b-b79b71e1d85c');
5402        this_ad_wrapper.html(ad_html_obj);
5403
5404        if (ad_section == "_cart") {
5405          $(".floating_cart_inner").addClass("ad_injected");
5406        }
5407      })
5408      .catch(function (json) {
5409        console.error(json);
5410      });
5411  }
5412
5413  function call_surfside_ads() {
5414    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5415    
5416    $(".lb_surfside_ads_wrapper").each(function (i, el) {
5417
5418      // check if cart and only continue if it's not cart.
5419      var this_ad_wrapper = $(this);
5420      var ad_section = this_ad_wrapper.attr("data_section");
5421      if(ad_section == "_cart"){
5422        return 0;
5423      }
5424
5425      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5426
5427      get_ad_html(ad_section)
5428        .then(function (json) {
5429          var ad_html = json.data.ad_html;
5430          var ad_html_obj = $.parseHTML(ad_html, document, false);
5431
5432          $(ad_html_obj).each(function () {
5433            $(this).attr("storeId", leafbridge_wizard_data.retailer_id);
5434
5435            if ($("div").hasClass("leafbridge_category_page")) {
5436              var category_name = $("#leafbridge_category_page").attr("data_lb_category");
5437              category_name = category_name[0].toUpperCase() + category_name.substring(1).toLowerCase();
5438              $(this).attr("zone", category_name);
5439              $(this).attr("keywords", category_name);
5440            }
5441          });
5442
5443          // ad_html_obj.attr('storeId', 'f0ff5c46-2f0c-4137-941b-b79b71e1d85c');
5444          this_ad_wrapper.html(ad_html_obj);
5445
5446          if (ad_section == "_cart") {
5447            $(".floating_cart_inner").addClass("ad_injected");
5448          }
5449        })
5450        .catch(function (json) {
5451          console.error(json);
5452        });
5453    });
5454  }
5455
5456  function get_ad_html(ad_section) {
5457    return new Promise(function (resolve, reject) {
5458      var data = {
5459        action: "get_surfside_ad_html",
5460        ad_section: ad_section,
5461      };
5462
5463      $.ajax({
5464        url: leafbridge_public_ajax_obj.ajaxurl,
5465        dataType: "json",
5466        cache: false,
5467        data: data,
5468        type: "POST",
5469        proccessData: false,
5470        success: function (json) {
5471          resolve(json);
5472        },
5473        error: function (json) {
5474          reject(json);
5475        },
5476        complete: function (json) { },
5477      });
5478    });
5479  }
5480
5481
5482  function leafbridge_toast(toast_toppings) {
5483    var lb_toast_messages_deck = $('#lb_toast_messages_deck');
5484    var now_time = new Date();
5485    var toast_id = now_time.getHours() + now_time.getMinutes() + now_time.getSeconds() + now_time.getMilliseconds();
5486    var toast_heading = toast_toppings.heading;
5487    var tost_descr = toast_toppings.text;
5488    var toast_icon = toast_toppings.icon;
5489    var timeout_milis = toast_toppings.hideAfter ? toast_toppings.hideAfter : 3000;
5490
5491    // alert(JSON.stringify(toast_toppings));
5492
5493    lb_toast_messages_deck.show();
5494    lb_toast_messages_deck.append(generate_lb_toast(toast_heading, tost_descr, toast_icon, timeout_milis, toast_id)).fadeIn();
5495
5496    setTimeout(function () {
5497      $('#lb_toast_messages_deck[data_toast_id="' + toast_id + '"]').remove();
5498    }, timeout_milis);
5499  }
5500
5501  function generate_lb_toast(toast_heading, tost_descr, toast_icon, timeout_milis, toast_id) {
5502
5503    var lb_toast_logo = (toast_icon == "success") ? '<i class="fa-solid fa-check"></i>' : ((toast_icon == "error") ? '<i class="fa-solid fa-triangle-exclamation"></i>' : '<i class="fa-solid fa-circle-exclamation"></i>');
5504    var lb_toast_bg_color = (toast_icon == "success") ? '#3c763d' : ((toast_icon == "error") ? '#a94442' : '#426ca9');
5505    var timeout_seconds = parseFloat(timeout_milis) / 1000;
5506    var lb_toast_html = '<span style="background-color:' + lb_toast_bg_color + ' !important; animation-duration:' + timeout_seconds + 's;" class="lb_toast_msg_box" data_timeout_milis="' + timeout_milis + '" data_toast_id="' + toast_id + '">';
5507    lb_toast_html += '<span class="lb_toast_col"><span class="lb_toast_logo">' + lb_toast_logo + '</span></span>';
5508    lb_toast_html += '<span class="lb_toast_col">'
5509    lb_toast_html += '<span class="lb_toast_heading">' + toast_heading + '</span>';
5510    lb_toast_html += '<span class="lb_tost_descr">' + tost_descr + '</span>';
5511    lb_toast_html += '</span>';
5512    lb_toast_html += '<span class="lb_toast_col"><span class="lb_toast_close"><i class="fa-solid fa-xmark"></i></span></span>';
5513    lb_toast_html += '</span>';
5514    return lb_toast_html;
5515  }
5516
5517  function get_brand_data() {
5518    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5519    var retailer_id = leafbridge_wizard_data.retailer_id;
5520    var brand_page_id = $('#lb_brand_image').attr('brand_page_id');
5521
5522    var passing_data = {
5523      'action': 'get_brand_data',
5524      'brand_page_id': brand_page_id,
5525      'retailer_id': retailer_id,
5526    };
5527    promise_load_brand_details(passing_data)
5528      .then(function (json) {
5529        $('#lb_brand_image').find('img').attr('src', json.data.retailer_brand_node['_leafbridge_brands_imagee_url']);
5530      })
5531      .catch(function (err) {
5532        console.error('get_brand_data err', err);
5533      });
5534  }
5535
5536  function get_brand_products_slider() {
5537    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5538    var retailer_id = leafbridge_wizard_data.retailer_id;
5539    var brand_page_id = $('.brands_page_brands_prod_slider_wrappr').attr('brand_page_id');
5540
5541    var passing_data = {
5542      'action': 'get_brand_products_slider',
5543      'brand_page_id': brand_page_id,
5544      'retailer_id': retailer_id,
5545    };
5546
5547    promise_load_brand_details(passing_data)
5548      .then(function (json) {
5549        $('.brands_page_brands_prod_slider_wrappr').each(function () {
5550          if ($(this).attr('data_brand_id') == json.data.related_brand_id) {
5551            $(this).show();
5552          }
5553          else {
5554            $(this).remove();
5555          }
5556        });
5557      })
5558      .catch(function (err) {
5559        console.error('get_brand_products_slider err', err);
5560      });
5561  }
5562
5563  function promise_load_brand_details(passing_data) {
5564    return new Promise(function (resolve, reject) {
5565      var data = {
5566        action: passing_data.action,
5567        brand_page_id: passing_data.brand_page_id,
5568        retailer_id: passing_data.retailer_id,
5569        _ajax_nonce: leafbridge_public_ajax_obj.nonce,
5570      };
5571
5572      $.ajax({
5573        url: leafbridge_public_ajax_obj.ajaxurl,
5574        dataType: "json",
5575        cache: false,
5576        data: data,
5577        type: "POST",
5578        proccessData: false,
5579        success: function (json) {
5580          resolve(json);
5581        },
5582        error: function (json) {
5583          reject(json);
5584        },
5585        complete: function (json) { },
5586      });
5587
5588    });
5589  }
5590
5591  function update_featured_brand_carousel(category) {
5592    const leafbridgeWizardData = JSON.parse(localStorage.getItem('leafbridge_wizard_data'));
5593    const retailer_id = leafbridgeWizardData.retailer_id;
5594    if (retailer_id) {
5595        $(".featured-brand-carousel").each(function () {
5596            var container = $(this);
5597            var autoCategory = container.attr("data-auto-category");
5598            var count = container.attr("data-count") || 20;
5599            
5600            var categoryToUse;
5601            if (autoCategory === "true" && category) {
5602                categoryToUse = category;
5603            } else {
5604                categoryToUse = container.data("category");
5605            }
5606            
5607            $.ajax({
5608                url: leafbridge_public_ajax_obj.ajaxurl,
5609                type: "POST",
5610                data: {
5611                    action: "fetch_featured_brand_carousel",
5612                    retailer_id: retailer_id,
5613                    category: categoryToUse,
5614                    brand: container.data("brand"),
5615                    count: count,
5616                },
5617                success: function (response) {
5618                    if (response.success) {
5619                        container.html(response.data.html);
5620                        specific_product_filter_slider();
5621                        
5622                        setTimeout(function() {
5623                            if (container.text().includes("We can't find what you're looking for")) {
5624                                $.ajax({
5625                                    url: leafbridge_public_ajax_obj.ajaxurl,
5626                                    type: "POST",
5627                                    data: {
5628                                        action: "fetch_featured_brand_carousel",
5629                                        retailer_id: retailer_id,
5630                                        category: categoryToUse,
5631                                        brand: "",
5632                                        count: count,
5633                                    },
5634                                    success: function (secondResponse) {
5635                                        if (secondResponse.success) {
5636                                            container.html(secondResponse.data.html);
5637                                            specific_product_filter_slider();
5638                                        }
5639                                    }
5640                                });
5641                            }
5642                        }, 1000);
5643                    } else {
5644                        container.html('<p>No featured products for this retailer</p>');
5645                    }
5646                },
5647                error: function (xhr, status, error) {
5648                    console.error("AJAX Error:", status, error);
5649                }
5650            });
5651        });
5652    }
5653  }
5654
5655  // Run all the functions that is necessary to run after page load
5656  function page_load_functions() {
5657    // use a promise to check the attributes then call the related functions
5658    check_wizard_attributes()
5659      .then(function () {
5660        //show products based on retailer selection - ajax
5661        if ($("div").hasClass("show_products_based_on_retailer")) {
5662          show_products_from_filter();
5663          show_prefiltered_products();
5664          $('.wizard_prods_categories').attr('data_event', 'justlanded');
5665        }
5666
5667        if ($("div").hasClass("leafbridge_featured_products_wrapper")) {
5668          var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5669          if (leafbridge_wizard_data) {
5670            get_featured_products_ajax();
5671            $("#leafbridge_shop_wizard_view_products").fadeIn("250");
5672          }
5673        }
5674
5675        //load order details
5676        if ($("div").hasClass("leafbridge_order_details_wrapper")) {
5677          ajax_get_order_details()
5678            .then(function (json) {
5679              $("#leafbridge_order_details_wrapper").html(json.data.order_html);
5680              $("#loading_animation").hide();
5681              localStorage.removeItem("leafbridge_cart_data");
5682
5683              //GTM view_item push to data layer - START
5684              var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5685              var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
5686
5687              var order_details = json.data.order_details[0];
5688
5689              if (order_details != null) {
5690                json.moreDataLayerPush = {
5691                  order_details: order_details,
5692                  location_id: leafbridge_wizard_data.retailer_id,
5693                  // location_name: leafbridge_recent_location.lb_retailer_custom_name,
5694                  location_name: leafbridge_recent_location.retailer_name,
5695                  menu_type: leafbridge_wizard_data.menu_type,
5696                };
5697                gtm_push_items_data(json, "LB_Purchase");
5698              }
5699              //GTM view_item push to data layer - END
5700            })
5701            .catch(function (err) {
5702              console.error("ajax get order details err", err);
5703              $("#leafbridge_order_details_wrapper").html(err);
5704              $("#loading_animation").hide();
5705            });
5706        } else {
5707          // check and prepare cart items on page load
5708          check_and_prepare_cart_items();
5709        }
5710
5711        // css by location
5712        css_by_location();
5713
5714        //nearby retailer locations
5715        gmaps_store_locator_func();
5716
5717        //product single page load prodct data
5718        single_prod_page_fetch();
5719
5720        //categories page show products
5721        show_category_products();
5722
5723        // specials shortcode get specials data
5724        specials_page_get_specials_data();
5725
5726        // specific product filter slider
5727        specific_product_filter_slider();
5728
5729        // featured brand carousel
5730        update_featured_brand_carousel();
5731
5732        // recently viewed produtcs
5733        display_recently_viewed_products();
5734
5735        // show special cards
5736        get_specials_menus_cards();
5737
5738        // show selected retailer name and link to locations page
5739        show_retailer_name_bar();
5740
5741        // show retailer banners
5742        retailer_banners();
5743
5744        // force showing custom name instead of actual name of retailer
5745        if ($("div").hasClass("retailer_based_store")) {
5746          ajax_get_retailer_details($(".retailer_based_store").attr("retailer_id"))
5747            .then(function (json) {
5748              $(".retailer_based_store").attr("retailer_name", json.data.lb_retailer_custom_name);
5749
5750              // var recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
5751              // if (recent_location) {
5752              //   recent_location.retailer_page = window.location.href;
5753              // } else {
5754                var lbwd = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5755                var rbsdpg_menu = $(".retailer_based_store").attr("menu_type");
5756                var rbsdpg_collection = $(".retailer_based_store").attr("order_type");
5757                var rbsdpg_retailer_id = $(".retailer_based_store").attr("retailer_id");
5758
5759                var retailer_page = '';
5760                if(rbsdpg_menu == "RECREATIONAL" && rbsdpg_collection == "DELIVERY"){
5761                  retailer_page = json.data.ret_pages[rbsdpg_retailer_id].recDelivery;
5762                }
5763                else if(rbsdpg_menu == "RECREATIONAL" && rbsdpg_collection == "PICKUP"){
5764                  retailer_page = json.data.ret_pages[rbsdpg_retailer_id].recPickup;
5765                }
5766                else if(rbsdpg_menu == "MEDICAL" && rbsdpg_collection == "DELIVERY"){
5767                  retailer_page = json.data.ret_pages[rbsdpg_retailer_id].medDelivery;
5768                }
5769                else if(rbsdpg_menu == "MEDICAL" && rbsdpg_collection == "PICKUP"){
5770                  retailer_page = json.data.ret_pages[rbsdpg_retailer_id].medPickup;
5771                }
5772
5773                recent_location = {
5774                  retailer_id: leafbridge_wizard_data.retailer_id,
5775                  retailer_name: json.data.lb_retailer_custom_name,
5776                  retailer_page: retailer_page,
5777                };
5778              // }
5779              localStorage.setItem("leafbridge_recent_location", JSON.stringify(recent_location));
5780            })
5781            .catch(function (json) {
5782              console.error("ajax_get_retailer_details", json);
5783            });
5784        } 
5785        else {
5786          var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5787          ajax_get_retailer_details(leafbridge_wizard_data.retailer_id)
5788            .then(function (json) {
5789              var lbwd = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5790
5791              var retailer_page = '';
5792              var ret_pages = json.data.ret_pages;
5793
5794              if(lbwd.menu_type == "RECREATIONAL" && lbwd.collection_method == "DELIVERY" && ret_pages){
5795                retailer_page = json.data.ret_pages[lbwd.retailer_id].recDelivery;
5796              }
5797              else if(lbwd.menu_type == "RECREATIONAL" && lbwd.collection_method == "PICKUP" && ret_pages){
5798                retailer_page = json.data.ret_pages[lbwd.retailer_id].recPickup;
5799              }
5800              else if(lbwd.menu_type == "MEDICAL" && lbwd.collection_method == "DELIVERY" && ret_pages){
5801                retailer_page = json.data.ret_pages[lbwd.retailer_id].medDelivery;
5802              }
5803              else if(lbwd.menu_type == "MEDICAL" && lbwd.collection_method == "PICKUP" && ret_pages){
5804                retailer_page = json.data.ret_pages[lbwd.retailer_id].medPickup;
5805              }
5806
5807              var recent_location = {
5808                retailer_id: leafbridge_wizard_data.retailer_id,
5809                retailer_name: json.data.lb_retailer_custom_name,
5810                retailer_page: retailer_page,
5811              };
5812
5813            
5814              localStorage.setItem('leafbridge_recent_location', JSON.stringify(recent_location));
5815            })
5816            .catch(function (json) {
5817              console.error("get retailer data  err", json);
5818            });
5819        }
5820
5821        // breadcrumbs modifications
5822        breadcrumbs_modifications();
5823        retailer_ads();
5824        retailer_dynamic_content();
5825        show_current_retailer_name();
5826        call_surfside_ads();
5827
5828        // fetch brand image and brand product slider on brand pages
5829        if ($('div').hasClass('lb_brand_image')) {
5830          get_brand_data();
5831        }
5832
5833        if ($('div').hasClass('brands_page_brands_prod_slider_wrappr')) {
5834          get_brand_products_slider();
5835        }
5836
5837        lb_product_page_image_sliders();
5838
5839        dl_data_layer_ready();
5840
5841      }) // enc check wizard attrs
5842      .catch(function (json) {
5843        console.error("check wizard attrs error", json);
5844      });
5845  }
5846
5847  function no_pdp_popup_load_functions(){
5848    setTimeout(function(){
5849      specific_product_filter_slider();
5850      lb_product_page_image_sliders();
5851      update_featured_brand_carousel();
5852      get_featured_products_ajax();
5853      display_recently_viewed_products();
5854
5855    },1000);
5856  }
5857  
5858  function lb_product_page_image_sliders(){
5859    $(document).ready(function () {
5860      var pswiper = new Swiper(".lb_prod_thumb_slider", {
5861        loop: true,
5862        spaceBetween: 10,
5863        slidesPerView: 4,
5864        freeMode: true,
5865        watchSlidesProgress: true,
5866        navigation: {
5867          nextEl: ".swiper-button-next",
5868          prevEl: ".swiper-button-prev",
5869        },
5870      });
5871      var pswiper2 = new Swiper(".lb_product_main_image_swiper", {
5872        loop: true,
5873        spaceBetween: 10,
5874        navigation: {
5875          nextEl: ".swiper-button-next",
5876          prevEl: ".swiper-button-prev",
5877        },
5878        thumbs: {
5879          swiper: pswiper,
5880        },
5881      });
5882    });
5883  }
5884
5885  // run all required functions at page load
5886  $(window).on("load", function () {
5887    page_load_functions();
5888  });
5889
5890  $(document).on('mousedown', 'body', function () {
5891    ($('.wizard_prods_categories').attr('data_event') == 'justlanded') ? $('.wizard_prods_categories').attr('data_event', 'first_interation') : '';
5892  });
5893
5894  $(document).on('click', '#clear_all_wizard_data', function () {
5895    localStorage.clear();
5896    location.reload();
5897  });
5898
5899  $(document).on("click","#open_the_cart , #nav_open_the_cart , .open_the_cart_button , .open_the_cart_button_icon",function (e) {
5900    e.preventDefault();
5901    $("#floating_cart").addClass("open_the_cart");
5902    trigger_surfside_cart_ad();
5903  });
5904
5905  // PDP disabled product popup version 
5906  $(document).on('click','.leafbridge_product_card.product_popup_enabled',function(e){
5907    const this_prod_box = $(this);
5908    var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5909    
5910    var product_id = $(this).attr('data_product_id');
5911    var retailer_id = $(this).attr('data_retailer_id');
5912    var menu_type = leafbridge_wizard_data.menu_type;
5913
5914    $('#popup_container').show();
5915    $('#popup_container').addClass('no_pdp_popup');
5916
5917    // grab image url , name , description , brand, thc
5918    var prod_card_filter_data = JSON.parse(this_prod_box.attr('filter_data'));
5919    var prod_card_image_url = this_prod_box.find('.lb_prod_card_thumb').attr('src');
5920    var prod_card_name = prod_card_filter_data.item_name;  //leafbridge_product_name
5921    var prod_card_descr = prod_card_filter_data.description;
5922    var prod_card_brand = prod_card_filter_data.brand_name; //leafbridge_brand_name
5923    var prod_card_thc = prod_card_filter_data.potencyThc;
5924
5925    var temp_html_for_popup = '<div class="lb_single_prod_page_wrapper"><div class="lb_single_prod_page_container"><div class="lb_prod_single_grid lb_prod_popup_row"><div class="lb_prod_single_img"><img src="'+prod_card_image_url+'" alt=""></div><div class="lb_prod_single_details"><div id="tags_locator"></div><span class="lb_prod_single_brand">Brand: <a href="">'+prod_card_brand+'</a></span><h1>
5925'+prod_card_name+'</h1><div class="lb_prod_single_add_to_cart gg lb_prod_single_section" filter_data=""><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="margin: auto; background: none; display: block; shape-rendering: auto;" width="200px" height="200px" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid"><circle cx="50" cy="50" fill="none" stroke="#c8c8c8" stroke-width="10" r="35" stroke-dasharray="164.93361431346415 56.97787143782138"><animateTransform attributeName="transform" type="rotate" repeatCount="indefinite" dur="1s" values="0 50 50;360 50 50" keyTimes="0;1"></animateTransform></circle></svg></div><div class="lb_prod_single_thc_cbd lb_prod_single_section"><span><strong>THC:</strong> '+prod_card_thc+' </span></div><div class="lb_prod_single_descr lb_prod_single_section"><p>'+prod_card_descr+'</p></div></div></div></div></div>';
5926    $('#popup_container .popup_no_pdp_wrapper .popup_no_pdp_inner').html(temp_html_for_popup);
5927    // $('#popup_container .popup_no_pdp_wrapper .popup_no_pdp_inner').html('');
5928
5929    // scroll popup pdp to top
5930    $('.popup_no_pdp_inner').scrollTop(0);
5931
5932    promise_render_product_detailed_popup(product_id,retailer_id,menu_type)
5933    .then(function (json) {
5934
5935      $('#popup_container .popup_no_pdp_wrapper .popup_no_pdp_inner').html(json.data.popup_html);
5936
5937      no_pdp_popup_load_functions();
5938      //GTM view_item push to data layer - START
5939      var prod_card = this_prod_box;
5940      var leafbridge_wizard_data = JSON.parse(localStorage.getItem("leafbridge_wizard_data"));
5941      var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
5942
5943      var json = {};
5944      var item_data = null;
5945      item_data = JSON.parse(prod_card.attr("filter_data"));
5946
5947      var cart_prod = {
5948        product_id: item_data.product_id,
5949        variation: item_data.variants[0].option,
5950        prod_count: 1,
5951        prod_name: item_data.item_name,
5952      };
5953
5954      if (item_data != null) {
5955        json.moreDataLayerPush = {
5956          item_data: item_data,
5957          cart_prod: cart_prod,
5958          location_id: leafbridge_wizard_data.retailer_id,
5959          location_name: leafbridge_recent_location.retailer_name,
5960          menu_type: leafbridge_wizard_data.menu_type,
5961        };
5962        gtm_push_single_item_data(json, "LB_ViewItem");
5963      }
5964      //GTM view_item push to data layer - END
5965
5966    })
5967    .catch(function (err) {
5968      console.error('render_product_popup err', err);
5969    });
5970  });
5971
5972
5973  $(document).on('click','.no_pdp_popup_close',function(){
5974    $('#popup_container').hide();
5975    $('#popup_container .popup_no_pdp_wrapper .popup_no_pdp_inner').html('');
5976  });
5977
5978  function promise_render_product_detailed_popup(product_id,retailer_id,menu_type){
5979    return new Promise(function (resolve, reject) {
5980      var data = {
5981        action: 'render_product_detailed_popup',
5982        product_id : product_id, 
5983        retailer_id : retailer_id,
5984        menu_type : menu_type,
5985        _ajax_nonce: leafbridge_public_ajax_obj.nonce,
5986      };
5987
5988      $.ajax({
5989        url: leafbridge_public_ajax_obj.ajaxurl,
5990        dataType: "json",
5991        cache: false,
5992        data: data,
5993        type: "POST",
5994        proccessData: false,
5995        success: function (json) {
5996          resolve(json);
5997        },
5998        error: function (json) {
5999          reject(json);
6000        },
6001        complete: function (json) { },
6002      });
6003    });
6004  }
6005  
6006  jQuery(document).on('elementor/popup/show', function (popup) {
6007    gmaps_store_locator_func();
6008    retailer_banners();
6009    no_pdp_popup_load_functions();
6010  });
6011
6012  // dl_nav_click - new datalayer event for navigation menu clicks
6013  $(document).on('click', 'nav a', function (e) {
6014    e.preventDefault();
6015
6016    var nav_text = $(this).text().trim();
6017    var nav_url = $(this).attr('href');
6018    var get_target = $(this).attr('target');
6019    var nav_target = (typeof get_target !== 'undefined' && get_target === '_blank') ? '_blank' : '_self';
6020
6021    var nav_push_data = {
6022      event: 'dl_nav_click',
6023      navigation : {
6024        navigation_selection: nav_text,
6025        navigation_url: nav_url,
6026      },
6027    };
6028
6029    promise_push_dataLayerEvent_forURL(nav_push_data)
6030    .then(function(result){
6031      if(nav_target == '_blank'){
6032        setTimeout(() => {
6033          window.open(nav_url, '_blank');
6034        }, 750);
6035      }
6036      else{
6037        setTimeout(() => {
6038          window.location.href = nav_url;
6039        }, 750);
6040      }
6041    })
6042    .catch(function(err){
6043      console.error('nav push data err', err);
6044      if(nav_target == '_blank'){
6045        setTimeout(() => {
6046          window.open(nav_url, '_blank');
6047        }, 750);
6048      }
6049      else{
6050        setTimeout(() => {
6051          window.location.href = nav_url;
6052        }, 750);
6053      }
6054    });
6055
6056    
6057  });
6058  
6059  function promise_push_dataLayerEvent_forURL(push_data) {
6060    return new Promise(function (resolve, reject) {
6061      if (push_data) {
6062        window.dataLayer = window.dataLayer || [];
6063        if (window.dataLayer && Array.isArray(window.dataLayer)) {
6064          window.dataLayer.push(push_data);
6065        } 
6066        else {
6067          console.error("GTM dataLayer has been tampered by another plugin/script");
6068        } 
6069        resolve(true);
6070      } else {
6071        reject("No data to push");
6072      }
6073    });
6074  }
6075
6076  function dl_data_layer_ready(){
6077
6078    setTimeout(() => {
6079      var get_lb_new_user = localStorage.getItem("lb_new_user");
6080      var lb_new_user = (get_lb_new_user) ? get_lb_new_user : false;
6081      var login_status = (lb_new_user == 'true') ? 'logged out' : 'logged in';
6082      
6083      var dl_data_layer_location = return_dl_data_layer_location();
6084
6085      var dl_data_layer_ready_push = {
6086        event: 'dl_data_layer_ready',
6087        page: {
6088          customer_email : (lb_new_user == true) ? 'new' : 'returning',
6089          login_status: login_status,
6090          page_type: 'product', //product, category, blog, homepage   
6091        },
6092        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
6093      };
6094
6095      window.dataLayer = window.dataLayer || [];
6096            
6097      // var temp_data_layer = window.dataLayer;
6098      // var manipulated_data_layer = [];
6099      // manipulated_data_layer[0] = dl_data_layer_ready_push;
6100      // manipulated_data_layer.push(...temp_data_layer);
6101
6102      // window.dataLayer = manipulated_data_layer;
6103
6104      if (window.dataLayer && Array.isArray(window.dataLayer)) {
6105        window.dataLayer.push(dl_data_layer_ready_push);
6106      } 
6107      else {
6108        console.error("GTM dataLayer has been tampered by another plugin/script");
6109      }
6110  
6111    }, 1000);
6112
6113  }
6114
6115  function return_dl_data_layer_location(){
6116    var leafbridge_recent_location = JSON.parse(localStorage.getItem("leafbridge_recent_location"));
6117    var dl_lb_lcnm = (leafbridge_recent_location) ? leafbridge_recent_location.retailer_name : 'None';
6118    var dl_lb_lc_details = (localStorage.getItem("dl_lb_lc_details")) ? JSON.parse(localStorage.getItem("dl_lb_lc_details")) : null;
6119
6120    var dl_lb_locationState = (dl_lb_lc_details != null ) ? dl_lb_lc_details.addressObject.state : 'None';
6121
6122    var dl_location_data = {
6123      location_name: dl_lb_lcnm,
6124      location_state : dl_lb_locationState,
6125    };
6126
6127    return dl_location_data;
6128  }
6129
6130
6131  // dl_view_promotion at page scroll
6132  var scrollTimer = null;
6133  $(window).on('resize scroll', function() {
6134    clearTimeout(scrollTimer);
6135    scrollTimer = setTimeout(function() {
6136      promotionGrabAfterScrollStop();}, 
6137    250);
6138  });
6139
6140  function promotionGrabAfterScrollStop(){
6141    $('.specials_tab').each(function() {
6142      var currentSpTab = $(this);
6143      var specialCardgetBoundingClientRect = this.getBoundingClientRect();
6144      var isVisible = specialCardgetBoundingClientRect.top < window.innerHeight && specialCardgetBoundingClientRect.top > 0 && specialCardgetBoundingClientRect.bottom > 0;
6145
6146      if(isVisible){
6147        var spName = $(this).find('.special_title').text().trim();
6148        dl_view_promotion(currentSpTab);
6149      }
6150    }); 
6151    
6152    $('.specials_tab_new').each(function() {
6153      var currentSpTab = $(this);
6154      var specialCardgetBoundingClientRect = this.getBoundingClientRect();
6155      var isVisible = specialCardgetBoundingClientRect.top < window.innerHeight && specialCardgetBoundingClientRect.top > 0 && specialCardgetBoundingClientRect.bottom > 0;
6156      
6157      if(isVisible){
6158        var spName = $(this).find('.special_title').text().trim();
6159
6160        dl_view_promotion(currentSpTab);
6161      }
6162    });
6163  }
6164  
6165  function dl_view_promotion(promotional_element,click_promotional=false){
6166    
6167    var promotion_name = promotional_element.find('.special_title').text().trim();
6168    var promotion_description = promotional_element.find('.special_description').text().trim();
6169    
6170    var dl_data_layer_location = return_dl_data_layer_location();
6171    var dl_event = click_promotional ? 'dl_select_promotion' : 'dl_view_promotion';
6172
6173    var dl_view_promotion_push = {
6174      event: dl_event,
6175      location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
6176      ecommerce: {
6177        promotion_name: promotion_name,  
6178        promotion_description: promotion_description,  
6179      },
6180    };
6181
6182    window.dataLayer = window.dataLayer || [];
6183    if (window.dataLayer && Array.isArray(window.dataLayer)) {
6184      window.dataLayer.push(dl_view_promotion_push);
6185    } 
6186    else {
6187      console.error("GTM dataLayer has been tampered by another plugin/script");
6188    }
6189
6190  }
6191
6192  // dl_view_item_list at product list load
6193  function dl_view_item_list(item_list_element,json){
6194    
6195    var main_wrapper_item = 'none';
6196    var main_wrapper_item_values= {};
6197    var elemShopWizardWrapper = item_list_element.closest('.leafbridge_shop_wizard_wrapper');
6198
6199    if(elemShopWizardWrapper.length >= 1){
6200      if(elemShopWizardWrapper.hasClass('leafbridge_category_page')){ 
6201        main_wrapper_item = 'PLP_'+elemShopWizardWrapper.attr('data_lb_category'); 
6202      }
6203      else{
6204        main_wrapper_item = 'PLP_shop_all';
6205      }
6206    }
6207    else{
6208      // try for product sliders
6209      var elemFeaturedCarousel = item_list_element.find('.lb_specific_prods_slider_wrapper');
6210      var elemFeaturedCrslAttrs = elemFeaturedCarousel.attr('filter_attributes');
6211
6212      main_wrapper_item = 'CAROUSEL_';
6213      try{
6214        var fca = JSON.parse(elemFeaturedCrslAttrs);
6215        delete fca['count'];
6216        delete fca['sort'];
6217        delete fca['custom_selection'];
6218        
6219        main_wrapper_item_values= fca;
6220
6221        var gcfsd = Object.keys(main_wrapper_item_values)[0];
6222        main_wrapper_item = main_wrapper_item_values[gcfsd] ? main_wrapper_item_values[gcfsd] : 'error fetching name';
6223        if(gcfsd == 'special'){
6224          main_wrapper_item = 'special';
6225        }
6226      }
6227      catch(err){
6228        var fca = {};
6229      }
6230      
6231   }
6232    var dl_data_layer_location = return_dl_data_layer_location();
6233    // var dl_event = 'dl_view_item_list';
6234    var dl_view_item_list_push = {
6235      event: 'dl_view_item_list',
6236      location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
6237      ecommerce: {
6238        item_list_name: main_wrapper_item,
6239        items : prepare_items_list(json.data.products_list,'dl_view_item_list'),  
6240      },
6241    };
6242
6243    if(main_wrapper_item_values.length != 0){
6244      dl_view_item_list_push.ecommerce.item_list_other_attributes = main_wrapper_item_values;
6245    }
6246
6247    window.dataLayer = window.dataLayer || [];
6248    if (window.dataLayer && Array.isArray(window.dataLayer)) {
6249      window.dataLayer.push(dl_view_item_list_push);
6250    } 
6251    else {
6252      console.error("GTM dataLayer has been tampered by another plugin/script");
6253    }
6254
6255  }
6256
6257  // function prepare_items_list(items_list,event_name){
6258  //   var returning_items_obj = {};
6259  //   return returning_items_obj; 
6260  // }
6261
6262
6263  function prepare_items_list(items_list, event_name){
6264
6265    if(event_name=='dl_select_item' || event_name=='dl_add_to_cart' || event_name == 'dl_view_item'){
6266      var prepared = [];
6267      var calc_paying_price = parseFloat(items_list.item_price) - parseFloat(items_list.item_discount);
6268      prepared.item_name =  items_list.item_name;
6269      prepared.item_id =  items_list.item_id;
6270      prepared.item_brand =  items_list.item_brand;
6271      prepared.item_category =  items_list.item_category;
6272      prepared.currency =  'USD';
6273      prepared.price = calc_paying_price,
6274      prepared.item_original_price = items_list.item_price,
6275      prepared.index =  0;
6276      
6277      return [prepared];
6278    }
6279    
6280    if(event_name == 'dl_view_item_list'){
6281      // event_name is here in case you want to branch later (e.g., impressions vs. clicks)
6282      var prepared = [];
6283      try{
6284        var wiz = JSON.parse(localStorage.getItem("leafbridge_wizard_data")) || {};
6285        var menuType = (wiz && wiz.menu_type) ? wiz.menu_type : 'RECREATIONAL';
6286        var currency = 'USD';
6287  
6288        if(Array.isArray(items_list)){
6289          for (var i = 0; i < items_list.length; i++){
6290            var raw = items_list[i] || {};
6291            // Support both our simplified objects and Dutchie raw objects
6292            var name = raw.item_name || raw.name || '';
6293            var id   = raw.item_id || raw.product_id || raw.id || raw.posId || '';
6294            var brand = raw.brand_name || (raw.brand && (raw.brand.name || raw.brand)) || '';
6295            var category = (raw.item_category || raw.category || '').toString();
6296  
6297            // Price resolution (prefer special -> regular; use MED/REC based on wizard)
6298            var price = null;
6299            var payingPrice = null;
6300            var variants = raw.variants || [];
6301            if (variants && variants.length){
6302              var v0 = variants[0];
6303              if (menuType === 'MEDICAL'){
6304                price = v0.priceMed;
6305                payingPrice = (v0.specialPriceMed != null && v0.specialPriceMed !== '') ? v0.specialPriceMed : v0.priceMed;
6306              } 
6307              else {
6308                price = v0.priceRec;
6309                payingPrice = (v0.specialPriceRec != null && v0.specialPriceRec !== '') ? v0.specialPriceRec : v0.priceRec;
6310              }
6311            }
6312            if (price == null && raw.price != null){ price = raw.price; } // absolute fallback
6313  
6314            // Cast to strings to match your requested format
6315            var get_price = parseFloat(price) - parseFloat();
6316            var original_price = (price != null) ? parseFloat(price) : '0';
6317  
6318            prepared.push({
6319              item_name: String(name || 'N/A'),
6320              item_id:   String(id || 'N/A'),
6321              item_brand: String(brand || 'N/A'),
6322              item_category: String(category || 'N/A').toLowerCase(),
6323              currency: currency,
6324              price: payingPrice,
6325              item_original_price: original_price,
6326              index: String(i)
6327            });
6328          }
6329        }
6330      }catch(err){
6331        console.error('prepare_items_list error:', err);
6332      }
6333      return prepared;
6334    }
6335
6336    if(event_name == 'dl_begin_checkout' || event_name == 'dl_purchase'){
6337      var prepared = [];
6338      if(Array.isArray(items_list)){
6339        for (var i = 0; i < items_list.length; i++){
6340
6341          var raw = items_list[i] || {};
6342          
6343          var push_name = raw.item_name;
6344          var push_id = raw.item_id;
6345          var push_brand = raw.item_brand_name;
6346          var push_category = raw.item_category;
6347          var push_currency = 'USD';
6348          var push_original_price = raw.item_price;
6349          var get_discount = raw.item_discount
6350          var push_price = parseFloat(raw.item_price) - parseFloat(get_discount);
6351
6352          prepared.push({
6353            item_name: String(push_name || 'N/A'),
6354            item_id:   String(push_id || 'N/A'),
6355            item_brand: String(push_brand || 'N/A'),
6356            item_category: String(push_category || 'N/A').toLowerCase(),
6357            currency: push_currency,
6358            price: push_price,
6359            item_original_price: push_original_price,
6360            index: String(i)
6361          });
6362        }
6363      }
6364
6365      return prepared;
6366    }
6367
6368    
6369
6370
6371  }
6372
6373
6374  $(document).on('click', '.leafbridge_product_card', function(e){
6375    if(!$(this).hasClass('product_popup_enabled')){
6376      e.preventDefault();
6377      
6378      var this_prod_card = $(this);
6379
6380      var this_child_a = $(this).find('a');
6381      var prod_url = this_child_a.attr('href');
6382
6383      dl_select_item(this_prod_card).then(function(result){
6384        window.location.href = prod_url;
6385      }).catch(function(err){
6386        console.error('dl_select_item err', err);
6387        window.location.href = prod_url;
6388      });
6389    }
6390  });
6391
6392  function dl_select_item(this_prod_card){
6393    return new Promise(function (resolve, reject) {
6394      var item_data = null;
6395      item_data = JSON.parse(this_prod_card.attr("filter_data"));
6396
6397      var dl_data_layer_location = return_dl_data_layer_location();
6398      
6399      var dl_select_item_list_push = {
6400        event: 'dl_select_item',
6401        location: {location_name : dl_data_layer_location.location_name , location_state : dl_data_layer_location.location_state},
6402        ecommerce: {
6403          item_list_name: 'main_wrapper_item',
6404          items : prepare_items_list(item_data,'dl_select_item')  
6405        },
6406      };
6407  
6408  
6409      window.dataLayer = window.dataLayer || [];
6410      if (window.dataLayer && Array.isArray(window.dataLayer)) {
6411        window.dataLayer.push(dl_select_item_list_push);
6412      } 
6413      else {
6414        console.error("GTM dataLayer has been tampered by another plugin/script");
6415      }
6416
6417      resolve(true);
6418    });
6419  }
6420
6421})(jQuery);

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.