var scriptSrc = "https://www.googletagmanager.com/gtag/js?id=G-BPE90SHXSE";
  const scriptElem = document.createElement('script');
  scriptElem.setAttribute('src', scriptSrc);
  scriptElem.setAttribute('async', '');
  document.head.appendChild(scriptElem);

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', "G-BPE90SHXSE", { send_page_view: false });

  gtag('consent', 'default', {
    'ad_storage': 'denied',
    'analytics_storage': 'denied',
    'ad_user_data': 'denied',
    'ad_personalization': 'denied',
  });

  gtag('consent', 'update', {
    'ad_storage': 'granted',
    'analytics_storage': 'granted',
    'ad_user_data': 'granted',
    'ad_personalization': 'granted',
  });

  // Get COOKIE
  function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
      let c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }

  function getFacebookCookies() {
    var allCookies = document.cookie.split(";");
    var fbCookieObject = {};
    var i, len;
    for(i = 0, len = allCookies.length; i < len; i += 1){
      var cookieItem = allCookies[i].split("=");
      if(cookieItem[0] === " _fbp"){
        fbCookieObject["fbp"] = cookieItem[1];
      } else if(cookieItem[0] === " _fbc"){
        fbCookieObject["fbc"] = cookieItem[1];
      }
    }

    return fbCookieObject;
  }

  // Set COOKIE
  function setCookie(cvalue, cname) {
    const d = new Date();
    d.setTime(d.getTime() + (365*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

  // This function generates a random string
  const rand = () => {
    // Math.random() returns a random floating point number between 0 and 1
    // toString(36) base-36 is a notation for representing numbers using the 26 letters of the alphabet along with ten digits
    // substring(2) returns a new string containing all characters starting at index 2 to the end of the original string
    return Math.random().toString(36).substring(2);
  };

  // Defining a function that generates a random token by concatenating two random strings.
  const generateRandomToken = () => {
    // Invoking the rand() function twice and concatenating the output strings
    // thus producing a longer and more complex random token
    return rand() + rand();
  };

  function sendCustomEvent(data, event, shopId) {
    fetch('https://connect.leafsignal.com/shopify/webhook/custom', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-topic': event,
        'X-Shopify-shop-id': shopId
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      return response.json();
    })
    .catch((error) => {
      console.error('Error sending custom event to app: ', JSON.stringify(error));
    });
  }

  function getCustomerData(eventName){
    var connectCustomer = {};
    var customerData = window.dataLayer.find(element => element.event === 'logState');
    if (customerData) {
      var addressInfo = customerData.customerInfo;
      if (eventName === 'purchase') {
        addressInfo = customerData.billingInfo;
        connectCustomer = { email: customerData.checkoutEmail, first_name: customerData.billingInfo.firstName, last_name: customerData.billingInfo.lastName, default_address: addressInfo };
      } else if (customerData.customerInfo) {
        connectCustomer = { email: customerData.customerEmail, first_name: customerData.customerInfo.firstName, last_name: customerData.customerInfo.lastName, default_address: addressInfo };
      }
    }
    return connectCustomer;
  }

  function getCurrentTime() {
    return Math.floor(Date.now() / 1000);
  }

  function getLatestETMSec() {
    var latestETMSecCookie = getCookie('latestETMSec');
    var currentTime = getCurrentTime();
    if (!latestETMSecCookie || latestETMSecCookie === '') {
      setCookie(currentTime, 'latestETMSec');
      return 1;
    }
    var etmSec = currentTime - latestETMSecCookie;
    if (etmSec === 0) return 1;
    return etmSec;
  }

  function extractSessionId(cookieValue) {
    if (!cookieValue) return '';

    if (cookieValue.startsWith('GS1')) {
      // GS1 format: GS1.1.<session_id>...
      var parts = cookieValue.split('.');
      return parts.length > 2 ? parts[2] : '';
    } else if (cookieValue.startsWith('GS2')) {
      // GS2 format: GS2.1.<random>$o1$s<session_id>$...
      const marker = '.s';
      const start = cookieValue.indexOf(marker);
      if (start === -1) return '';
      const sessionStart = start + marker.length;
      const sessionEnd = cookieValue.indexOf('$', sessionStart);
      return cookieValue.substring(
        sessionStart,
        sessionEnd > -1 ? sessionEnd : cookieValue.length
      );
    }

    return '';
  }

  function getConnectData(customer, ga4Id){
    var gaCookie = getCookie('_ga');
    var gaCookieFormatted = gaCookie.split('.').splice(2,3).join('.');

    var gaSessionId = '';

    if (ga4Id) {
      var formattedGA4Id = ga4Id.split('-')[1];
      var sessionCookieName = '_ga_' + formattedGA4Id;
      var gaSessionCookie = getCookie(sessionCookieName);
      gaSessionId = extractSessionId(gaSessionCookie);
    }

    var externalId = getCookie('connect_cid');
    var eventId = generateRandomToken();
    var pageReferrer = document.referrer;
    var engagementTimeMsec = getLatestETMSec();

    var fbCookies = getFacebookCookies();
    var fbp = '';
    var fbc = '';
    if (fbCookies.fbp) {
      fbp = fbCookies.fbp
    } else {
      fbp = null;
    }
    if (fbCookies.fbc) {
      fbc = fbCookies.fbc
    } else {
      fbc = null;
    }

    var pageLocation = window.location.href;
    var pageTitle = document.title;

    var data = {
      id: eventId,
      platform_source: 'cms',
      user_data: {
        cid: gaCookieFormatted,
        ga_session_id: gaSessionId,
        external_id: externalId,
        fbp,
        fbc,
        page_referrer: pageReferrer,
        engagement_time_msec: engagementTimeMsec,
        page_location: pageLocation,
        page_title: pageTitle
      },
      event_source_url: window.location.href,
    }
    if (Object.keys(customer).length > 0) { data['customer'] = customer; }
    return data;
  }

  function sendFbBrowserEvent(eventName, eventData, eventID, pixelId) {
    if (pixelId) {
      fbq('trackSingle', pixelId, eventName, eventData, {eventID: eventID});
    }
  }

  function sendGA4BrowserEvent(eventName, eventData) {
    gtag("event", eventName, eventData);
  }

  function parseEventsValueToFloat(value) {
    if (typeof value === 'string') {
      value = value.trim();
      var result = value.replace(/[^0-9]/g, '');
      if (/[,.]d{2}$/.test(value)) {
          result = result.replace(/(d{2})$/, '.$1');
      }
      return parseFloat(result);
    }
    return value;
  }

  function getFBViewItemData(viewItemData) {
    var item = viewItemData.items[0];
    var itemData = {
      'contents' : [{'id': item.item_id, 'quantity': 1}],
      'content_type' : 'product',
      'value': parseEventsValueToFloat(item.price),
      'currency': item.currency
    };
    return itemData;
  }

  function getProductData(eventData) {
    var contents = [];
    eventData.items.forEach(function(item){
      contents.push({ 'id': item.item_id, 'quantity': item.quantity, 'item_price': item.price });
    });
    var data = {
      'content_type' : 'product',
      'value': eventData.value,
      'currency': eventData.currency,
      'contents': contents
    };
    return data;
  }

  function getFBPurchaseData(data) {
    var purchaseData = {
      'content_name': 'Thank You',
      'content_type': 'product',
      'currency': data.currency,
    }
    var contentIds = [];
    var contents = [];

    purchaseData['value'] = parseEventsValueToFloat(data.value);

    data.items.forEach(function(item) {
        contentIds.push(item.item_id);
        contents.push({ id: item.item_id, quantity: item.quantity });
    });
    purchaseData['content_ids'] = contentIds;
    purchaseData['contents'] = contents;

    return purchaseData;
  }

  function getFBInitCheckoutData(data) {
    var initCheckoutData = {
      currency: data.currency,
      content_type: 'product',
      value: parseFloat(data.value),
    }
    var contents = [];
    data.items.forEach(function(item) {
      contents.push({ 'id': item.item_id, 'quantity': item.quantity });
    });

    initCheckoutData['contents'] = contents;
    return initCheckoutData;
  }

  function formatPurchaseItems(purchaseItems) {
    var items = [];
    purchaseItems.forEach(function(item) {
      var itemObj = {};
      itemObj['sku'] = item['item_id'];
      itemObj['title'] = item['item_name'];
      itemObj['vendor'] = item['item_brand'];
      itemObj['variant_title'] = item['item_variant'] || 'default_title';
      itemObj['price'] = parseEventsValueToFloat(item['price']);
      itemObj['quantity'] = item['quantity'];
      itemObj['product_id'] = item['item_id'];
      if (item['item_variant_id']) {
        itemObj['variant_id'] = item['item_variant_id'];
      } else {
        itemObj['variant_id'] = item['item_id'];
      }
      items.push(itemObj);
    });
    return items;
  }

  function formatServerPurchaseData(data, dataLayer) {
    data['id'] = dataLayer['transaction_id'];
    if (data['product_data'] && data['product_data']['content_name']) {
      delete data['product_data']['content_name'];
    }

    data['line_items'] = formatPurchaseItems(dataLayer['items']);
    data['source_name'] = 'web';
    data['total_price'] = parseEventsValueToFloat(dataLayer['value']);
    data['total_tax'] = parseEventsValueToFloat(dataLayer['tax']);
    data['subtotal_price'] = parseEventsValueToFloat(dataLayer['transaction_subtotal']);
    data['shipping_price'] = parseEventsValueToFloat(dataLayer['shipping']);
    data['currency'] = dataLayer['currency'];
    data['name'] = String(dataLayer['transaction_id']);
    data['gateway'] = dataLayer['gateway'];
    if (dataLayer['coupon']) {
      data['discount_code'] = dataLayer['coupon'];
      data['discount_amount'] = parseEventsValueToFloat(dataLayer['discount']) || 0;
    }

    return data;
  }

  function formatGA4Data(ga4Data) {
    var items = [];
    var dataClone = JSON.parse(JSON.stringify(ga4Data));
    if (dataClone.shop_id) {
      delete dataClone.shop_id;
    }
    if (dataClone.token) {
      delete dataClone.token;
    }
    dataClone.value = parseEventsValueToFloat(ga4Data.value);
    ga4Data.items.forEach(function(item) {
      var itemPrice = parseEventsValueToFloat(item.price);
      item.price = itemPrice;
      items.push(item);
    });
    dataClone.items = items;
    return dataClone;
  }

  function formatCheckoutStepItemsData(eventData) {
    var items = [];
    var dataClone = JSON.parse(JSON.stringify(eventData));
    if (dataClone.shop_id) {
      delete dataClone.shop_id;
    }
    if (dataClone.items) {
      delete dataClone.items;
    }
    if (eventData.discount) {
      dataClone.discount = parseEventsValueToFloat(eventData.discount);
    }
    dataClone.total_price = parseEventsValueToFloat(eventData.value);
    dataClone.tax = parseEventsValueToFloat(eventData.tax);
    dataClone.shipping = parseEventsValueToFloat(eventData.shipping);
    dataClone.subtotal = parseEventsValueToFloat(eventData.subtotal);
    eventData.items.forEach(function(item) {
      var itemData = {
        'sku': item['item_id'],
        'product_id': item['item_id'],
        'title': item['item_name'],
        'variant_title': item['item_variant'] || 'default_title',
        'vendor': item['item_brand'],
        ...item,
      };
      if (item['item_variant_id']) {
        itemData['variant_id'] = item['item_variant_id'];
      }
      itemData['price'] = parseEventsValueToFloat(item['price']);
      items.push(itemData);
    });
    dataClone['line_items'] = items;
    return dataClone;
  }

  function formatGA4BrowserEventData(data) {
    var ga4Data = {};
    if (data.currency) {
      ga4Data.currency = data.currency;
    }
    if (data.value) {
      ga4Data.value = data.value;
    }
    if (data.items) {
      ga4Data.items = data.items;
    }
    if (data.transaction_id) {
      ga4Data.transaction_id = String(data['transaction_id']);
    }
    return ga4Data;
  }

  function eventHandler(eventObj, pixelId, ga4Id) {
    var customerData = getCustomerData(eventObj.event);
    var connectData = getConnectData(customerData, ga4Id);
    var currentTime = getCurrentTime();

    switch(eventObj.event){
      case 'view_item':
        var viewItemData = getFBViewItemData(eventObj.ecommerce);
        connectData['product_data'] = viewItemData;
        connectData['ga4_data'] = formatGA4Data(eventObj.ecommerce);
        if (eventObj.ecommerce.shop_id) {
          sendFbBrowserEvent('ViewContent', viewItemData, connectData.id, pixelId);

          var ga4BrowserEventData = formatGA4BrowserEventData(eventObj.ecommerce);
          sendGA4BrowserEvent('view_item', ga4BrowserEventData);

          sendCustomEvent(connectData, 'custom/content_view', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;

      case 'page_view':
        if (eventObj.shop_id && !eventObj.hasFired) {
          sendCustomEvent(connectData, 'custom/page_view', eventObj.shop_id);
          var pageViewData = {};
          sendFbBrowserEvent('PageView', pageViewData, connectData.id, pixelId);

          var ga4BrowserEventData = {
            page_location: document.location.href,
            page_title: document.title,
          }
          sendGA4BrowserEvent('page_view', ga4BrowserEventData);

          setCookie(currentTime, 'latestETMSec');

          if (window.location.href === 'https://brookandwildesleep.com/checkout') {
            eventObj.hasFired = 1;
          }
        }
        break;

      case 'add_to_cart':
        var cartData = getProductData(eventObj.ecommerce);
        connectData['product_data'] = cartData;
        connectData['items'] = eventObj.ecommerce.items;
        if (eventObj.ecommerce.shop_id) {
          sendFbBrowserEvent('AddToCart', cartData, connectData.id, pixelId);

          var ga4BrowserEventData = formatGA4BrowserEventData(eventObj.ecommerce);
          sendGA4BrowserEvent('add_to_cart', ga4BrowserEventData);

          sendCustomEvent(connectData, 'custom/add_to_cart', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;

      case 'purchase':
        if (eventObj.ecommerce.shop_id) {
          var purchaseData = getFBPurchaseData(eventObj.ecommerce);
          sendFbBrowserEvent('Purchase', purchaseData, eventObj.ecommerce.transaction_number, pixelId);

          var ga4BrowserEventData = formatGA4BrowserEventData(eventObj.ecommerce);
          sendGA4BrowserEvent('purchase', ga4BrowserEventData);

          connectData['product_data'] = JSON.parse(JSON.stringify(purchaseData));
          var severPurchaseData = formatServerPurchaseData(connectData, eventObj.ecommerce);
          sendCustomEvent(severPurchaseData, 'custom/purchase', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;

      case 'initiate_checkout':
        if (eventObj.ecommerce.shop_id && !eventObj.hasFired) {
          var initCheckoutData = getFBInitCheckoutData(eventObj.ecommerce);
          sendFbBrowserEvent('InitiateCheckout', initCheckoutData, connectData.id, pixelId);

          var ga4BrowserEventData = formatGA4BrowserEventData(eventObj.ecommerce);
          sendGA4BrowserEvent('begin_checkout', ga4BrowserEventData);

          connectData['ga4_data'] = formatGA4Data(eventObj.ecommerce);
          connectData['product_data'] = getProductData(eventObj.ecommerce);
          sendCustomEvent(connectData, 'custom/begin_checkout', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');

          if (window.location.href === 'https://brookandwildesleep.com/checkout') {
            eventObj.hasFired = 1;
          }
        }
        break;

      case 'add_contact_info':
        if (eventObj.ecommerce.shop_id) {
          connectData['event_data'] = formatCheckoutStepItemsData(eventObj.ecommerce);
          connectData['step'] = eventObj.event;
          sendCustomEvent(connectData, 'custom/update_checkout', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;

      case 'add_shipping_info':
        if (eventObj.ecommerce.shop_id) {
          connectData['event_data'] = formatCheckoutStepItemsData(eventObj.ecommerce);
          connectData['step'] = eventObj.event;
          sendCustomEvent(connectData, 'custom/update_checkout', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;

      case 'add_payment_info':
        if (eventObj.ecommerce.shop_id) {
          connectData['event_data'] = formatCheckoutStepItemsData(eventObj.ecommerce);
          connectData['step'] = eventObj.event;
          sendCustomEvent(connectData, 'custom/update_checkout', eventObj.ecommerce.shop_id);

          setCookie(currentTime, 'latestETMSec');
        }
        break;
    }
  }

  function getMarketFBID() {
    var domainName = window.location.hostname;
    var connectElements = document.getElementsByTagName('connect-fb');
    var fbPixelId = '';

    for (var i = 0; i < connectElements.length; i++) {
      var elementDomainName = connectElements[i].getAttribute('domain');
      if (elementDomainName === null) {
        fbPixelId = connectElements[i].getAttribute('fbid');
        i = connectElements.length;
      } else if (elementDomainName === domainName) {
        fbPixelId = connectElements[i].getAttribute('fbid');
        i = connectElements.length;
      }
    }
    return fbPixelId;
  }

  function getGA4ID() {
    var domainName = window.location.hostname;
    var connectElements = document.getElementsByTagName('connect-ga');
    var ga4Id = '';

    for (var i = 0; i < connectElements.length; i++) {
      var elementDomainName = connectElements[i].getAttribute('domain');
      if (elementDomainName === null) {
        ga4Id = connectElements[i].getAttribute('ga');
        i = connectElements.length;
      } else if (elementDomainName === domainName) {
        ga4Id = connectElements[i].getAttribute('ga');
        i = connectElements.length;
      }
    }
    return ga4Id;
  }

  function initFB(pixelId, customerData) {
    if (pixelId) {
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script',
      'https://connect.facebook.net/en_US/fbevents.js');

      fbq('init', pixelId , customerData);
    }
  }

  function getCountriesCodes() {
    return [
      {
        "country": "Afghanistan",
        "code": "93",
        "iso": "AF"
      },
      {
        "country": "Albania",
        "code": "355",
        "iso": "AL"
      },
      {
        "country": "Algeria",
        "code": "213",
        "iso": "DZ"
      },
      {
        "country": "American Samoa",
        "code": "1-684",
        "iso": "AS"
      },
      {
        "country": "Andorra",
        "code": "376",
        "iso": "AD"
      },
      {
        "country": "Angola",
        "code": "244",
        "iso": "AO"
      },
      {
        "country": "Anguilla",
        "code": "1-264",
        "iso": "AI"
      },
      {
        "country": "Antarctica",
        "code": "672",
        "iso": "AQ"
      },
      {
        "country": "Antigua and Barbuda",
        "code": "1-268",
        "iso": "AG"
      },
      {
        "country": "Argentina",
        "code": "54",
        "iso": "AR"
      },
      {
        "country": "Armenia",
        "code": "374",
        "iso": "AM"
      },
      {
        "country": "Aruba",
        "code": "297",
        "iso": "AW"
      },
      {
        "country": "Australia",
        "code": "61",
        "iso": "AU"
      },
      {
        "country": "Austria",
        "code": "43",
        "iso": "AT"
      },
      {
        "country": "Azerbaijan",
        "code": "994",
        "iso": "AZ"
      },
      {
        "country": "Bahamas",
        "code": "1-242",
        "iso": "BS"
      },
      {
        "country": "Bahrain",
        "code": "973",
        "iso": "BH"
      },
      {
        "country": "Bangladesh",
        "code": "880",
        "iso": "BD"
      },
      {
        "country": "Barbados",
        "code": "1-246",
        "iso": "BB"
      },
      {
        "country": "Belarus",
        "code": "375",
        "iso": "BY"
      },
      {
        "country": "Belgium",
        "code": "32",
        "iso": "BE"
      },
      {
        "country": "Belize",
        "code": "501",
        "iso": "BZ"
      },
      {
        "country": "Benin",
        "code": "229",
        "iso": "BJ"
      },
      {
        "country": "Bermuda",
        "code": "1-441",
        "iso": "BM"
      },
      {
        "country": "Bhutan",
        "code": "975",
        "iso": "BT"
      },
      {
        "country": "Bolivia",
        "code": "591",
        "iso": "BO"
      },
      {
        "country": "Bosnia and Herzegovina",
        "code": "387",
        "iso": "BA"
      },
      {
        "country": "Botswana",
        "code": "267",
        "iso": "BW"
      },
      {
        "country": "Brazil",
        "code": "55",
        "iso": "BR"
      },
      {
        "country": "British Indian Ocean Territory",
        "code": "246",
        "iso": "IO"
      },
      {
        "country": "British Virgin Islands",
        "code": "1-284",
        "iso": "VG"
      },
      {
        "country": "Brunei",
        "code": "673",
        "iso": "BN"
      },
      {
        "country": "Bulgaria",
        "code": "359",
        "iso": "BG"
      },
      {
        "country": "Burkina Faso",
        "code": "226",
        "iso": "BF"
      },
      {
        "country": "Burundi",
        "code": "257",
        "iso": "BI"
      },
      {
        "country": "Cambodia",
        "code": "855",
        "iso": "KH"
      },
      {
        "country": "Cameroon",
        "code": "237",
        "iso": "CM"
      },
      {
        "country": "Canada",
        "code": "1",
        "iso": "CA"
      },
      {
        "country": "Cape Verde",
        "code": "238",
        "iso": "CV"
      },
      {
        "country": "Cayman Islands",
        "code": "1-345",
        "iso": "KY"
      },
      {
        "country": "Central African Republic",
        "code": "236",
        "iso": "CF"
      },
      {
        "country": "Chad",
        "code": "235",
        "iso": "TD"
      },
      {
        "country": "Chile",
        "code": "56",
        "iso": "CL"
      },
      {
        "country": "China",
        "code": "86",
        "iso": "CN"
      },
      {
        "country": "Christmas Island",
        "code": "61",
        "iso": "CX"
      },
      {
        "country": "Cocos Islands",
        "code": "61",
        "iso": "CC"
      },
      {
        "country": "Colombia",
        "code": "57",
        "iso": "CO"
      },
      {
        "country": "Comoros",
        "code": "269",
        "iso": "KM"
      },
      {
        "country": "Cook Islands",
        "code": "682",
        "iso": "CK"
      },
      {
        "country": "Costa Rica",
        "code": "506",
        "iso": "CR"
      },
      {
        "country": "Croatia",
        "code": "385",
        "iso": "HR"
      },
      {
        "country": "Cuba",
        "code": "53",
        "iso": "CU"
      },
      {
        "country": "Curacao",
        "code": "599",
        "iso": "CW"
      },
      {
        "country": "Cyprus",
        "code": "357",
        "iso": "CY"
      },
      {
        "country": "Czech Republic",
        "code": "420",
        "iso": "CZ"
      },
      {
        "country": "Democratic Republic of the Congo",
        "code": "243",
        "iso": "CD"
      },
      {
        "country": "Denmark",
        "code": "45",
        "iso": "DK"
      },
      {
        "country": "Djibouti",
        "code": "253",
        "iso": "DJ"
      },
      {
        "country": "Dominica",
        "code": "1-767",
        "iso": "DM"
      },
      {
        "country": "Dominican Republic",
        "code": "1-809, 1-829, 1-849",
        "iso": "DO"
      },
      {
        "country": "East Timor",
        "code": "670",
        "iso": "TL"
      },
      {
        "country": "Ecuador",
        "code": "593",
        "iso": "EC"
      },
      {
        "country": "Egypt",
        "code": "20",
        "iso": "EG"
      },
      {
        "country": "El Salvador",
        "code": "503",
        "iso": "SV"
      },
      {
        "country": "Equatorial Guinea",
        "code": "240",
        "iso": "GQ"
      },
      {
        "country": "Eritrea",
        "code": "291",
        "iso": "ER"
      },
      {
        "country": "Estonia",
        "code": "372",
        "iso": "EE"
      },
      {
        "country": "Ethiopia",
        "code": "251",
        "iso": "ET"
      },
      {
        "country": "Falkland Islands",
        "code": "500",
        "iso": "FK"
      },
      {
        "country": "Faroe Islands",
        "code": "298",
        "iso": "FO"
      },
      {
        "country": "Fiji",
        "code": "679",
        "iso": "FJ"
      },
      {
        "country": "Finland",
        "code": "358",
        "iso": "FI"
      },
      {
        "country": "France",
        "code": "33",
        "iso": "FR"
      },
      {
        "country": "French Polynesia",
        "code": "689",
        "iso": "PF"
      },
      {
        "country": "Gabon",
        "code": "241",
        "iso": "GA"
      },
      {
        "country": "Gambia",
        "code": "220",
        "iso": "GM"
      },
      {
        "country": "Georgia",
        "code": "995",
        "iso": "GE"
      },
      {
        "country": "Germany",
        "code": "49",
        "iso": "DE"
      },
      {
        "country": "Ghana",
        "code": "233",
        "iso": "GH"
      },
      {
        "country": "Gibraltar",
        "code": "350",
        "iso": "GI"
      },
      {
        "country": "Greece",
        "code": "30",
        "iso": "GR"
      },
      {
        "country": "Greenland",
        "code": "299",
        "iso": "GL"
      },
      {
        "country": "Grenada",
        "code": "1-473",
        "iso": "GD"
      },
      {
        "country": "Guam",
        "code": "1-671",
        "iso": "GU"
      },
      {
        "country": "Guatemala",
        "code": "502",
        "iso": "GT"
      },
      {
        "country": "Guernsey",
        "code": "44-1481",
        "iso": "GG"
      },
      {
        "country": "Guinea",
        "code": "224",
        "iso": "GN"
      },
      {
        "country": "Guinea-Bissau",
        "code": "245",
        "iso": "GW"
      },
      {
        "country": "Guyana",
        "code": "592",
        "iso": "GY"
      },
      {
        "country": "Haiti",
        "code": "509",
        "iso": "HT"
      },
      {
        "country": "Honduras",
        "code": "504",
        "iso": "HN"
      },
      {
        "country": "Hong Kong",
        "code": "852",
        "iso": "HK"
      },
      {
        "country": "Hungary",
        "code": "36",
        "iso": "HU"
      },
      {
        "country": "Iceland",
        "code": "354",
        "iso": "IS"
      },
      {
        "country": "India",
        "code": "91",
        "iso": "IN"
      },
      {
        "country": "Indonesia",
        "code": "62",
        "iso": "ID"
      },
      {
        "country": "Iran",
        "code": "98",
        "iso": "IR"
      },
      {
        "country": "Iraq",
        "code": "964",
        "iso": "IQ"
      },
      {
        "country": "Ireland",
        "code": "353",
        "iso": "IE"
      },
      {
        "country": "Isle of Man",
        "code": "44-1624",
        "iso": "IM"
      },
      {
        "country": "Israel",
        "code": "972",
        "iso": "IL"
      },
      {
        "country": "Italy",
        "code": "39",
        "iso": "IT"
      },
      {
        "country": "Ivory Coast",
        "code": "225",
        "iso": "CI"
      },
      {
        "country": "Jamaica",
        "code": "1-876",
        "iso": "JM"
      },
      {
        "country": "Japan",
        "code": "81",
        "iso": "JP"
      },
      {
        "country": "Jersey",
        "code": "44-1534",
        "iso": "JE"
      },
      {
        "country": "Jordan",
        "code": "962",
        "iso": "JO"
      },
      {
        "country": "Kazakhstan",
        "code": "7",
        "iso": "KZ"
      },
      {
        "country": "Kenya",
        "code": "254",
        "iso": "KE"
      },
      {
        "country": "Kiribati",
        "code": "686",
        "iso": "KI"
      },
      {
        "country": "Kosovo",
        "code": "383",
        "iso": "XK"
      },
      {
        "country": "Kuwait",
        "code": "965",
        "iso": "KW"
      },
      {
        "country": "Kyrgyzstan",
        "code": "996",
        "iso": "KG"
      },
      {
        "country": "Laos",
        "code": "856",
        "iso": "LA"
      },
      {
        "country": "Latvia",
        "code": "371",
        "iso": "LV"
      },
      {
        "country": "Lebanon",
        "code": "961",
        "iso": "LB"
      },
      {
        "country": "Lesotho",
        "code": "266",
        "iso": "LS"
      },
      {
        "country": "Liberia",
        "code": "231",
        "iso": "LR"
      },
      {
        "country": "Libya",
        "code": "218",
        "iso": "LY"
      },
      {
        "country": "Liechtenstein",
        "code": "423",
        "iso": "LI"
      },
      {
        "country": "Lithuania",
        "code": "370",
        "iso": "LT"
      },
      {
        "country": "Luxembourg",
        "code": "352",
        "iso": "LU"
      },
      {
        "country": "Macao",
        "code": "853",
        "iso": "MO"
      },
      {
        "country": "Macedonia",
        "code": "389",
        "iso": "MK"
      },
      {
        "country": "Madagascar",
        "code": "261",
        "iso": "MG"
      },
      {
        "country": "Malawi",
        "code": "265",
        "iso": "MW"
      },
      {
        "country": "Malaysia",
        "code": "60",
        "iso": "MY"
      },
      {
        "country": "Maldives",
        "code": "960",
        "iso": "MV"
      },
      {
        "country": "Mali",
        "code": "223",
        "iso": "ML"
      },
      {
        "country": "Malta",
        "code": "356",
        "iso": "MT"
      },
      {
        "country": "Marshall Islands",
        "code": "692",
        "iso": "MH"
      },
      {
        "country": "Mauritania",
        "code": "222",
        "iso": "MR"
      },
      {
        "country": "Mauritius",
        "code": "230",
        "iso": "MU"
      },
      {
        "country": "Mayotte",
        "code": "262",
        "iso": "YT"
      },
      {
        "country": "Mexico",
        "code": "52",
        "iso": "MX"
      },
      {
        "country": "Micronesia",
        "code": "691",
        "iso": "FM"
      },
      {
        "country": "Moldova",
        "code": "373",
        "iso": "MD"
      },
      {
        "country": "Monaco",
        "code": "377",
        "iso": "MC"
      },
      {
        "country": "Mongolia",
        "code": "976",
        "iso": "MN"
      },
      {
        "country": "Montenegro",
        "code": "382",
        "iso": "ME"
      },
      {
        "country": "Montserrat",
        "code": "1-664",
        "iso": "MS"
      },
      {
        "country": "Morocco",
        "code": "212",
        "iso": "MA"
      },
      {
        "country": "Mozambique",
        "code": "258",
        "iso": "MZ"
      },
      {
        "country": "Myanmar",
        "code": "95",
        "iso": "MM"
      },
      {
        "country": "Namibia",
        "code": "264",
        "iso": "NA"
      },
      {
        "country": "Nauru",
        "code": "674",
        "iso": "NR"
      },
      {
        "country": "Nepal",
        "code": "977",
        "iso": "NP"
      },
      {
        "country": "Netherlands",
        "code": "31",
        "iso": "NL"
      },
      {
        "country": "Netherlands Antilles",
        "code": "599",
        "iso": "AN"
      },
      {
        "country": "New Caledonia",
        "code": "687",
        "iso": "NC"
      },
      {
        "country": "New Zealand",
        "code": "64",
        "iso": "NZ"
      },
      {
        "country": "Nicaragua",
        "code": "505",
        "iso": "NI"
      },
      {
        "country": "Niger",
        "code": "227",
        "iso": "NE"
      },
      {
        "country": "Nigeria",
        "code": "234",
        "iso": "NG"
      },
      {
        "country": "Niue",
        "code": "683",
        "iso": "NU"
      },
      {
        "country": "North Korea",
        "code": "850",
        "iso": "KP"
      },
      {
        "country": "Northern Mariana Islands",
        "code": "1-670",
        "iso": "MP"
      },
      {
        "country": "Norway",
        "code": "47",
        "iso": "NO"
      },
      {
        "country": "Oman",
        "code": "968",
        "iso": "OM"
      },
      {
        "country": "Pakistan",
        "code": "92",
        "iso": "PK"
      },
      {
        "country": "Palau",
        "code": "680",
        "iso": "PW"
      },
      {
        "country": "Palestine",
        "code": "970",
        "iso": "PS"
      },
      {
        "country": "Panama",
        "code": "507",
        "iso": "PA"
      },
      {
        "country": "Papua New Guinea",
        "code": "675",
        "iso": "PG"
      },
      {
        "country": "Paraguay",
        "code": "595",
        "iso": "PY"
      },
      {
        "country": "Peru",
        "code": "51",
        "iso": "PE"
      },
      {
        "country": "Philippines",
        "code": "63",
        "iso": "PH"
      },
      {
        "country": "Pitcairn",
        "code": "64",
        "iso": "PN"
      },
      {
        "country": "Poland",
        "code": "48",
        "iso": "PL"
      },
      {
        "country": "Portugal",
        "code": "351",
        "iso": "PT"
      },
      {
        "country": "Puerto Rico",
        "code": "1-787, 1-939",
        "iso": "PR"
      },
      {
        "country": "Qatar",
        "code": "974",
        "iso": "QA"
      },
      {
        "country": "Republic of the Congo",
        "code": "242",
        "iso": "CG"
      },
      {
        "country": "Reunion",
        "code": "262",
        "iso": "RE"
      },
      {
        "country": "Romania",
        "code": "40",
        "iso": "RO"
      },
      {
        "country": "Russia",
        "code": "7",
        "iso": "RU"
      },
      {
        "country": "Rwanda",
        "code": "250",
        "iso": "RW"
      },
      {
        "country": "Saint Barthelemy",
        "code": "590",
        "iso": "BL"
      },
      {
        "country": "Saint Helena",
        "code": "290",
        "iso": "SH"
      },
      {
        "country": "Saint Kitts and Nevis",
        "code": "1-869",
        "iso": "KN"
      },
      {
        "country": "Saint Lucia",
        "code": "1-758",
        "iso": "LC"
      },
      {
        "country": "Saint Martin",
        "code": "590",
        "iso": "MF"
      },
      {
        "country": "Saint Pierre and Miquelon",
        "code": "508",
        "iso": "PM"
      },
      {
        "country": "Saint Vincent and the Grenadines",
        "code": "1-784",
        "iso": "VC"
      },
      {
        "country": "Samoa",
        "code": "685",
        "iso": "WS"
      },
      {
        "country": "San Marino",
        "code": "378",
        "iso": "SM"
      },
      {
        "country": "Sao Tome and Principe",
        "code": "239",
        "iso": "ST"
      },
      {
        "country": "Saudi Arabia",
        "code": "966",
        "iso": "SA"
      },
      {
        "country": "Senegal",
        "code": "221",
        "iso": "SN"
      },
      {
        "country": "Serbia",
        "code": "381",
        "iso": "RS"
      },
      {
        "country": "Seychelles",
        "code": "248",
        "iso": "SC"
      },
      {
        "country": "Sierra Leone",
        "code": "232",
        "iso": "SL"
      },
      {
        "country": "Singapore",
        "code": "65",
        "iso": "SG"
      },
      {
        "country": "Sint Maarten",
        "code": "1-721",
        "iso": "SX"
      },
      {
        "country": "Slovakia",
        "code": "421",
        "iso": "SK"
      },
      {
        "country": "Slovenia",
        "code": "386",
        "iso": "SI"
      },
      {
        "country": "Solomon Islands",
        "code": "677",
        "iso": "SB"
      },
      {
        "country": "Somalia",
        "code": "252",
        "iso": "SO"
      },
      {
        "country": "South Africa",
        "code": "27",
        "iso": "ZA"
      },
      {
        "country": "South Korea",
        "code": "82",
        "iso": "KR"
      },
      {
        "country": "South Sudan",
        "code": "211",
        "iso": "SS"
      },
      {
        "country": "Spain",
        "code": "34",
        "iso": "ES"
      },
      {
        "country": "Sri Lanka",
        "code": "94",
        "iso": "LK"
      },
      {
        "country": "Sudan",
        "code": "249",
        "iso": "SD"
      },
      {
        "country": "Suriname",
        "code": "597",
        "iso": "SR"
      },
      {
        "country": "Svalbard and Jan Mayen",
        "code": "47",
        "iso": "SJ"
      },
      {
        "country": "Swaziland",
        "code": "268",
        "iso": "SZ"
      },
      {
        "country": "Sweden",
        "code": "46",
        "iso": "SE"
      },
      {
        "country": "Switzerland",
        "code": "41",
        "iso": "CH"
      },
      {
        "country": "Syria",
        "code": "963",
        "iso": "SY"
      },
      {
        "country": "Taiwan",
        "code": "886",
        "iso": "TW"
      },
      {
        "country": "Tajikistan",
        "code": "992",
        "iso": "TJ"
      },
      {
        "country": "Tanzania",
        "code": "255",
        "iso": "TZ"
      },
      {
        "country": "Thailand",
        "code": "66",
        "iso": "TH"
      },
      {
        "country": "Togo",
        "code": "228",
        "iso": "TG"
      },
      {
        "country": "Tokelau",
        "code": "690",
        "iso": "TK"
      },
      {
        "country": "Tonga",
        "code": "676",
        "iso": "TO"
      },
      {
        "country": "Trinidad and Tobago",
        "code": "1-868",
        "iso": "TT"
      },
      {
        "country": "Tunisia",
        "code": "216",
        "iso": "TN"
      },
      {
        "country": "Turkey",
        "code": "90",
        "iso": "TR"
      },
      {
        "country": "Turkmenistan",
        "code": "993",
        "iso": "TM"
      },
      {
        "country": "Turks and Caicos Islands",
        "code": "1-649",
        "iso": "TC"
      },
      {
        "country": "Tuvalu",
        "code": "688",
        "iso": "TV"
      },
      {
        "country": "U.S. Virgin Islands",
        "code": "1-340",
        "iso": "VI"
      },
      {
        "country": "Uganda",
        "code": "256",
        "iso": "UG"
      },
      {
        "country": "Ukraine",
        "code": "380",
        "iso": "UA"
      },
      {
        "country": "United Arab Emirates",
        "code": "971",
        "iso": "AE"
      },
      {
        "country": "United Kingdom",
        "code": "44",
        "iso": "GB"
      },
      {
        "country": "United States",
        "code": "1",
        "iso": "US"
      },
      {
        "country": "Uruguay",
        "code": "598",
        "iso": "UY"
      },
      {
        "country": "Uzbekistan",
        "code": "998",
        "iso": "UZ"
      },
      {
        "country": "Vanuatu",
        "code": "678",
        "iso": "VU"
      },
      {
        "country": "Vatican",
        "code": "379",
        "iso": "VA"
      },
      {
        "country": "Venezuela",
        "code": "58",
        "iso": "VE"
      },
      {
        "country": "Vietnam",
        "code": "84",
        "iso": "VN"
      },
      {
        "country": "Wallis and Futuna",
        "code": "681",
        "iso": "WF"
      },
      {
        "country": "Western Sahara",
        "code": "212",
        "iso": "EH"
      },
      {
        "country": "Yemen",
        "code": "967",
        "iso": "YE"
      },
      {
        "country": "Zambia",
        "code": "260",
        "iso": "ZM"
      },
      {
        "country": "Zimbabwe",
        "code": "263",
        "iso": "ZW"
      }
    ];
  }

  function handleConnectCid() {
    var connectCidCookie = getCookie('connect_cid');
    if (!connectCidCookie || connectCidCookie === '') {
      var connectCid = generateRandomToken();
      setCookie(connectCid, 'connect_cid');
    }
  }

  var load = 0;
  function listenDLEvents(dlPushedObject) {
    handleConnectCid();
    var pixelId = getMarketFBID();
    var ga4Id = getGA4ID();
    var externalId = getCookie('connect_cid');
    var customerData = {
      'external_id': externalId
    };
    var customerDataDL = window.dataLayer.find(element => element.event === 'logState');
    if (customerDataDL && customerDataDL.customerInfo) {
      var email = customerDataDL.customerEmail ? customerDataDL.customerEmail.toLowerCase() : null;
      customerData['em'] = email;
      var name = customerDataDL.customerInfo.firstName ? customerDataDL.customerInfo.firstName.toLowerCase() : null;
      customerData['fn'] = name;
      var lastName = customerDataDL.customerInfo.lastName ? customerDataDL.customerInfo.lastName.toLowerCase() : null;
      customerData['ln'] = lastName;
      var city = customerDataDL.customerInfo.city ? customerDataDL.customerInfo.city : null;
      customerData['ct'] = city ? city.replace(/ /g, "").toLowerCase() : null;
      if (customerDataDL.customerInfo.state !== null) {
        var state = customerDataDL.customerInfo.state;
        customerData['st'] = state ? state.replace(/ /g, "").toLowerCase() : null;
      }
      var zip = customerDataDL.customerInfo.zip;
      customerData['zp'] = zip ? zip.replace(/ /g, "").replace("-","").toLowerCase() : null;

      var countryCodes = {};
      if (customerDataDL.customerInfo.country) {
        var countriesCodes = getCountriesCodes();
        var countryCode = customerDataDL.customerInfo.country ? customerDataDL.customerInfo.country : '';
        countryCodes = countriesCodes.find(element => element.country === countryCode);
        customerData['country'] = countryCodes.iso;
      }

      var defaultPhone = customerDataDL.customerInfo.phone;
      if (defaultPhone) {
        var phoneWithoutExtraCharacters = defaultPhone.replace(/D/g, '');
        var phoneWithoutLeadingZero = parseInt(phoneWithoutExtraCharacters, 10);
        var phoneWithCountryDialCode = "" + countryCodes.code + phoneWithoutLeadingZero;
        customerData['ph'] = phoneWithCountryDialCode;
      }
    }

    if (load === 0) {
      load = 1;
      initFB(pixelId, customerData);
    //   initGA4(ga4Id);
    }
    eventHandler(dlPushedObject, pixelId, ga4Id);
  };

  // This code sets up a listener on the window dataLayer object that waits for events to be pushed to it.
  var listenerDL = setInterval(function() {

    // Initializes the dataLayer array if it doesn't exist yet.
    window.dataLayer = window.dataLayer || [];

    // Only proceeds if there is a dataLayer object.
    if (window.dataLayer) {

      // Clears the listener interval once the dataLayer is present.
      clearInterval(listenerDL);

      // Overrides the push method in the dataLayer so that it can listen for events being pushed.
      (function() {
        var oldPush = window?.dataLayer?.push;
        window.dataLayer.push = function() {
          var states = [].slice.call(arguments, 0);

          // Sends the event object to a separate function for processing.
          listenDLEvents(states[0]);

          return oldPush.apply(window.dataLayer, states);
        }
      })()

      // If there are existing events in the dataLayer, sends them to the processing function.
      if (window.dataLayer.length > 0) {
        window.dataLayer.forEach(function(eventObj) {
          listenDLEvents(eventObj);
        });
      }
    }
  }, 200);