function TPI_main() {
    console.log('%c------ TiXel: Install Multiple Pixels by Effective Apps is Initializing ------', 'color: cyan');
    console.log('%c------ Contact us at support@effectify.co for help and questions about the app ------', 'color: cyan');
    window.EFFECTIVE_APPS_TPI_PIXEL_CODE = ``;
    window.EFFECTIVE_APPS_TPI_PIXELS = {"tiktok_pixels": [{"id": "777b68c6c6ff11ed8fe1964ae8df3c71", "pixel_status": true, "pixel_id": "CGBV3A3C77UBA109AVB0", "pixel_type": 1, "pixel_code": "<script> !function (w, d, t) { w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=[\"page\",\"track\",\"identify\",\"instances\",\"debug\",\"on\",\"off\",\"once\",\"ready\",\"alias\",\"group\",\"enableCookie\",\"disableCookie\"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i=\"https://analytics.tiktok.com/i18n/pixel/events.js\";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement(\"script\");o.type=\"text/javascript\",o.async=!0,o.src=i+\"?sdkid=\"+e+\"&lib=\"+t;var a=document.getElementsByTagName(\"script\")[0];a.parentNode.insertBefore(o,a)}; ttq.load(\"CGBV3A3C77UBA109AVB0\"); ttq.page(); }(window, document, \"ttq\"); </script>", "pixel_name": "gigalumi", "pixel_pv_event": true, "pixel_pv_event_details": false, "pixel_pv_event_homepage": false, "pixel_atc_event": true, "pixel_atc_event_details": false, "pixel_pao_event": true, "pixel_pao_event_details": false, "pixel_cp_event": true, "pixel_access_token": "", "pixel_cp_event_details": true, "pixel_cp_event_identification": false, "pixel_total_pv_events": 0, "pixel_total_cp_events": 0, "pixel_total_atc_events": 0, "pixel_total_pao_events": 0, "pixel_access_token_health": false, "pixel_sp": ""}]};
    window.TPI_THEME_NAME = TPI_getShopifyThemeName();
    window.isLS = TPI_isLSAvailable();
    if (window.TPI_SCRIPT_INJECTED === undefined) {
        window.TPI_SCRIPT_INJECTED = true;
        if (window.hasOwnProperty('Shopify') && window.Shopify.hasOwnProperty('designMode') && Shopify.designMode === true) {
            return;
        }

        if (document.getElementById('eaManualTPI') === null) {
            let shouldCheckForTpiSp = false;
            jQuery('head').prepend(window.EFFECTIVE_APPS_TPI_PIXEL_CODE);
            for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
                if (pixel.pixel_sp.length > 0 && location.href.indexOf('tpiOnboarding=true') === -1) {
                    shouldCheckForTpiSp = true;
                    if (location.pathname.indexOf('/products/') > -1 && pixel.pixel_sp.indexOf(ShopifyAnalytics.meta.product.id) > -1) {
                        jQuery('head').prepend(pixel.pixel_code);
                        pixel.sp_loaded_in_page = true;
                    }

                    if ((location.pathname.indexOf('/thank_you') > -1 || location.pathname.indexOf('/post_purchase') > -1) && (typeof Shopify !== 'undefined' && Shopify.hasOwnProperty('checkout') && Shopify.checkout.hasOwnProperty('line_items'))) {
                        for (let lineItem of Shopify.checkout.line_items) {
                            if (pixel.pixel_sp.indexOf(lineItem.product_id.toString()) > -1) {
                                jQuery('head').prepend(pixel.pixel_code);
                                pixel.sp_loaded_in_page = true;
                            }
                        }
                    }
                }
                else {
                    jQuery('head').prepend(pixel.pixel_code);
                }
            }

            if (shouldCheckForTpiSp) {
                checkForTpiSp();
            }
        }

        if ('True' === 'True' || 'True' === 'True') {
            if (location.pathname.indexOf('/products/') > -1 || ('True' === 'False' && ShopifyAnalytics.meta.page.pageType === "home") || ('True' === 'False' && ShopifyAnalytics.meta.page.pageType === "home")) {
                triggerProductDetailsPageViewReport();
            }
        }

        if ('True' === 'True' || 'True' === 'True') {
            if (location.pathname.indexOf('/thank_you') > -1 || location.pathname.indexOf('/post_purchase') > -1) {
                triggerCompletePaymentReport();
            }
        }

        if ('True' === 'True' || 'True' === 'True') {
            if (location.pathname.indexOf('/cart') > -1) {
                let checkoutButtonElements = TPI_detectCheckoutButtons();
                for (let checkoutButtonElement of checkoutButtonElements) {
                    if (checkoutButtonElement.getAttribute('tpi-pao-registered') === null) {
                        checkoutButtonElement.addEventListener('click', triggerCheckoutInitiationReport);
                        checkoutButtonElement.setAttribute('tpi-pao-registered', 'true');
                    }
                }
            }
            else {
                window.EFFECTIVE_APPS_TPI_CART_LISTENER = setInterval(TPI_waitForCartDrawer, 500);
            }
        }

        if ('True' === 'True' || 'True' === 'True') {
            const atcButtons = TPI_detectAddToCartButtons();
            for (let atcButton of atcButtons) {
                if (atcButton.getAttribute('tpi-atc-registered') === null) {
                    atcButton.addEventListener('click', triggerAddToCartReport);
                    atcButton.setAttribute('tpi-atc-registered', 'true');
                }
            }
        }
    }

    if (location.href.indexOf('tpiOnboarding=true') > -1) {
        jQuery("head").prepend('<style>.swal-confirm-btn {font-size:22px !important; }.sweet_loader { width: 140px; height: 140px; margin: 0 auto; animation-duration: 0.5s; animation-timing-function: linear; animation-iteration-count: infinite; animation-name: ro; transform-origin: 50% 50%; transform: rotate(0) translate(0,0); } @keyframes ro { 100% { transform: rotate(-360deg) translate(0,0); } }</style>');
        let urlParams = new URLSearchParams(location.search);
        const currenciesList = ['AED','ARS','AUD','BDT','BHD','BIF','BOB','BRL','CAD','CHF','CLP','CNY','COP','CRC','CZK','DKK','DZD','EGP','EUR','GBP','GTQ','HKD','HNL','HUF','IDR','ILS','INR','ISK','JPY','KES','KHR','KRW','KWD','KZT','MAD','MOP','MXN','MYR','NGN','NIO','NOK','NZD','OMR','PEN','PHP','PHP','PKR','PLN','PYG','QAR','RON','RUB','SAR','SEK','SGD','THB','TRY','TWD','UAH','USD','VES','VND','ZAR'];
        let pixelId = urlParams.get("pixelId");
        let eventsToTrigger = urlParams.get("eventsToTrigger");
        window.ttq.identify({email: "user" + Math.floor(Math.random() * 9999).toString() + "@gmail.com", phone_number: '+1554' + Math.floor(Math.random() * 9999).toString() + '527'});
        if (eventsToTrigger.indexOf("CP") > -1) {
            setInterval(function() {
                let randomContentId = Math.floor(Math.random() * 10000000000).toString();
                let randomQuantity = Math.floor(Math.random() * 10) + 1;
                let randomValue = (Math.random() * 100).toFixed(2);
                window.ttq.instance(pixelId).track('CompletePayment', {
                    content_id: randomContentId,
                    content_type: "product",
                    quantity: randomQuantity,
                    currency: currenciesList[Math.floor(Math.random() * currenciesList.length)],
                    value: randomValue
                });
            }, 1000);
        }

        if (eventsToTrigger.indexOf("ATC") > -1) {
            setInterval(function() {
                let randomContentId = Math.floor(Math.random() * 10000000000).toString();
                let randomQuantity = Math.floor(Math.random() * 10) + 1;
                let randomValue = (Math.random() * 100).toFixed(2);
                window.ttq.instance(pixelId).track('AddToCart', {
                    content_id: randomContentId,
                    content_type: "product",
                    quantity: randomQuantity,
                    currency: currenciesList[Math.floor(Math.random() * currenciesList.length)],
                    value: randomValue
                });
            }, 1750);
        }

        if (eventsToTrigger.indexOf("IC") > -1) {
            setInterval(function() {
                let randomContentId = Math.floor(Math.random() * 10000000000).toString();
                let randomQuantity = Math.floor(Math.random() * 10) + 1;
                let randomValue = (Math.random() * 100).toFixed(2);
                window.ttq.instance(pixelId).track('InitiateCheckout', {
                    content_id: randomContentId,
                    content_type: "product",
                    quantity: randomQuantity,
                    currency: currenciesList[Math.floor(Math.random() * currenciesList.length)],
                    value: randomValue
                });
            }, 2500);
        }

        if (eventsToTrigger.indexOf("PV") > -1) {
            setInterval(function() {
                let randomContentId = Math.floor(Math.random() * 10000000000).toString();
                let randomQuantity = Math.floor(Math.random() * 10) + 1;
                let randomValue = (Math.random() * 100).toFixed(2);
                window.ttq.instance(pixelId).track('ViewContent', {
                    content_id: randomContentId,
                    content_type: "product",
                    quantity: randomQuantity,
                    currency: currenciesList[Math.floor(Math.random() * currenciesList.length)],
                    value: randomValue
                });
            }, 3250);
        }

        TPI_loadScript('https://cdn.jsdelivr.net/npm/sweetalert2@9', function() {
            if (pixelId.length > 10) {
                Swal.fire({
                  title: 'Triggering events for the ' + pixelId + ' pixel...',
                  type: "none",
                  html: '<div class="sweet_loader"><svg viewBox="0 0 140 140" width="140" height="140"><g class="outline"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="rgba(0,0,0,0.1)" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round"></path></g><g class="circle"><path d="m 70 28 a 1 1 0 0 0 0 84 a 1 1 0 0 0 0 -84" stroke="#71BBFF" stroke-width="4" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dashoffset="200" stroke-dasharray="300"></path></g></svg></div>',
                  showCloseButton: false,
                  showCancelButton: false,
                  showConfirmButton: false,
                  allowOutsideClick: false
                });
                setTimeout(function() {
                    Swal.close();
                    Swal.fire({
                        title: '<strong style="font-family: \'Arial\'; font-size: 26px;">Success</strong>',
                        icon: 'success',
                        customClass: {
                            confirmButton: 'swal-confirm-btn',
                        },
                        html: '<p style="font-size: 22px">A Pixel with ID <b><font style="color:green;">' + pixelId + '</font></b> is up and running!<br /> You may close this window now.</p>',
                        showCloseButton: false,
                        showCancelButton: false,
                        showConfirmButton: true,
                        confirmButtonText: 'Close',
                        width: 600,
                        focusConfirm: true,
                        allowOutsideClick: false
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.close();
                        }
                    });
                }, 15000);
            }
            else {
                Swal.fire({
                    title: '<strong style="font-family: \'Arial\'; font-size: 26px;">Pixel Not Detected</strong>',
                    icon: 'error',
                    customClass: {
                        confirmButton: 'swal-confirm-btn',
                    },
                    html: '<p style="font-size: 22px">A Pixel was not detect. Please copy and paste the exact Pixel code and try again or contact our support team.</p>',
                    showCloseButton: false,
                    showCancelButton: false,
                    showConfirmButton: true,
                    confirmButtonText: 'Close',
                    width: 600,
                    focusConfirm: true,
                    allowOutsideClick: false
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.close();
                    }
                });
            }
        });
    }
}

function TPI_getShopifyThemeName() {
    try {
        if (window.BOOMR !== undefined && window.BOOMR.themeName !== undefined && window.BOOMR.themeName.length > 0) {
            return window.BOOMR.themeName.toLowerCase();
        }
        else {
            return Shopify.theme.name.toLowerCase();
        }
    }
    catch (err) {
        return "";
    }
}

function TPI_isLSAvailable() {
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

function TPI_loadScript(url, success){
    var script = document.createElement('script');
    script.src = url;
    var head = document.getElementsByTagName('head')[0],
    done = false;
    head.appendChild(script);
    script.onload = script.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
            done = true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
    };
}

function checkForTpiSp() {
    jQuery.getJSON('/cart.js').done(function(data) {
        for (let item of data['items']) {
            for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
                if (pixel.pixel_sp.length > 0 && pixel.pixel_sp.indexOf(item["product_id"].toString()) > -1 && pixel.sp_loaded_in_page === undefined) {
                    jQuery('head').prepend(pixel.pixel_code);
                    pixel.sp_loaded_in_page = true;
                }
            }
        }
    });
}

function triggerCheckoutInitiationReport() {
    if ('True' === 'True' && window.EFFECTIVE_APPS_TPI_PIXEL_CODE.length !== 0) {
        window.ttq.track('InitiateCheckout');
    }

    for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
        if (pixel.pixel_pao_event === true) {
            if (pixel.pixel_sp.length > 0) {
                if (pixel.sp_loaded_in_page === true) {
                    window.ttq.instance(pixel.pixel_id).track('InitiateCheckout');
                }
            }
            else {
                window.ttq.instance(pixel.pixel_id).track('InitiateCheckout');
            }
        }
    }
}

function triggerAddToCartReport() {
    if ('True' === 'True' && window.EFFECTIVE_APPS_TPI_PIXEL_CODE.length !== 0) {
        const productId = TPI_getCurrentShopifyProductId();
        if ('False' === 'True' && productId !== null) {
            window.ttq.track('AddToCart', {
                content_id: productId,
                content_type: "product",
                quantity: TPI_getCurrentSelectedProductQuantity(),
                currency: TPI_getCurrentShopifyShopCurrency(),
                value: TPI_getCurrentShopifySelectedProductVariantPrice()
            });
        }
        else {
            window.ttq.track('AddToCart');
        }
    }

    for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
        if (pixel.pixel_atc_event === true) {
            const productId = TPI_getCurrentShopifyProductId();
            if (pixel.pixel_sp.length > 0) {
                if (location.pathname.indexOf('/products/') > -1 && pixel.pixel_sp.indexOf(ShopifyAnalytics.meta.product.id) > -1) {
                    if (pixel.pixel_atc_event_details === true && productId !== null) {
                        window.ttq.instance(pixel.pixel_id).track('AddToCart', {
                            content_id: productId,
                            content_type: "product",
                            quantity: TPI_getCurrentSelectedProductQuantity(),
                            currency: TPI_getCurrentShopifyShopCurrency(),
                            value: TPI_getCurrentShopifySelectedProductVariantPrice()
                        });
                    }
                    else {
                        window.ttq.instance(pixel.pixel_id).track('AddToCart');
                    }
                }
            }
            else {
                if (pixel.pixel_atc_event_details === true && productId !== null) {
                    window.ttq.instance(pixel.pixel_id).track('AddToCart', {
                        content_id: productId,
                        content_type: "product",
                        quantity: TPI_getCurrentSelectedProductQuantity(),
                        currency: TPI_getCurrentShopifyShopCurrency(),
                        value: TPI_getCurrentShopifySelectedProductVariantPrice()
                    });
                }
                else {
                    window.ttq.instance(pixel.pixel_id).track('AddToCart');
                }
            }
        }
    }
}

function triggerProductDetailsPageViewReport() {
    if ('True' === 'True' && window.EFFECTIVE_APPS_TPI_PIXEL_CODE.length !== 0 && (location.pathname.indexOf('/products/') > -1 || ('True' === 'False' && ShopifyAnalytics.meta.page.pageType === "home"))) {
        const productId = TPI_getCurrentShopifyProductId();
        if ('False' === 'True' && productId !== null) {
            window.ttq.track('ViewContent', {
                content_id: productId,
                content_type: "product",
                quantity: 1,
                currency: TPI_getCurrentShopifyShopCurrency(),
                value: TPI_getCurrentShopifySelectedProductVariantPrice()
            });
        }
        else {
            window.ttq.track('ViewContent');
        }
    }

    for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
        if (pixel.pixel_pv_event === true && location.pathname.indexOf('/products/') > -1) {
            const productId = TPI_getCurrentShopifyProductId();
            if (pixel.pixel_sp.length > 0) {
                if (pixel.sp_loaded_in_page === true) {
                    if (pixel.pixel_atc_event_details === true && productId !== null) {
                        window.ttq.instance(pixel.pixel_id).track('ViewContent', {
                            content_id: productId,
                            content_type: "product",
                            quantity: 1,
                            currency: TPI_getCurrentShopifyShopCurrency(),
                            value: TPI_getCurrentShopifySelectedProductVariantPrice()
                        });
                    }
                    else {
                        window.ttq.instance(pixel.pixel_id).track('ViewContent');
                    }
                }
            }
            else {
                if (pixel.pixel_atc_event_details === true && productId !== null) {
                    window.ttq.instance(pixel.pixel_id).track('ViewContent', {
                        content_id: productId,
                        content_type: "product",
                        quantity: 1,
                        currency: TPI_getCurrentShopifyShopCurrency(),
                        value: TPI_getCurrentShopifySelectedProductVariantPrice()
                    });
                }
                else {
                    window.ttq.instance(pixel.pixel_id).track('ViewContent');
                }
            }
        }

        if (pixel.pixel_pv_event_homepage === true && ShopifyAnalytics.meta.page.pageType === "home") {
            window.ttq.instance(pixel.pixel_id).track('ViewContent');
        }
    }
}

function triggerCompletePaymentReport() {
    let registerLsOrder = false;
    if ('True' === 'True' && window.EFFECTIVE_APPS_TPI_PIXEL_CODE.length !== 0) {
        if (window.isLS && localStorage.getItem('already_reported_' + Shopify.checkout.order_id) !== null) {
            return;
        }

        if ('False' === 'True') {
            if (typeof Shopify !== 'undefined' && typeof Shopify.checkout !== 'undefined') {
                const identifyObject = {};
                const checkout = Shopify.checkout;

                if (checkout.email) {
                    identifyObject.email = checkout.email;
                }

                if (Shopify.checkout.phone === null || Shopify.checkout.phone === undefined) {
                    if (checkout.billing_address && checkout.billing_address.phone) {
                        identifyObject.phone_number = checkout.billing_address.phone;
                    }
                }
                else {
                    identifyObject.phone_number = Shopify.checkout.phone;
                }

                if (Object.keys(identifyObject).length > 0) {
                    window.ttq.identify(identifyObject);
                }
            }
        }

        if ('True' === 'True') {
            let lineItems = [];
            for (let lineItem of Shopify.checkout.line_items) {
               lineItems.push({
                   content_id: lineItem.product_id.toString(),
                   content_type: "product",
                   quantity: parseInt(lineItem.quantity),
                   price: parseFloat(lineItem.price)
               });
            }

            if (lineItems.length === 1) {
                window.ttq.track('CompletePayment', {
                    content_id: lineItems[0]['content_id'].toString(),
                    content_type: "product",
                    quantity: parseInt(lineItems[0]['quantity']),
                    currency: Shopify.checkout.currency,
                    value: parseFloat(Shopify.checkout.total_price)
                });
            }
            else {
                window.ttq.track('CompletePayment', {
                    content_type: "product_group",
                    currency: Shopify.checkout.currency,
                    value: parseFloat(Shopify.checkout.total_price),
                    contents: lineItems
                });
            }
        }
        else {
            window.ttq.track('CompletePayment');
        }

        registerLsOrder = true;
    }

    for (let pixel of window.EFFECTIVE_APPS_TPI_PIXELS['tiktok_pixels']) {
        if (pixel.pixel_cp_event === true) {
            if (window.isLS && localStorage.getItem('already_reported_' + Shopify.checkout.order_id) !== null) {
                return;
            }

            if (pixel.pixel_cp_event_identification === true) {
                if (typeof Shopify !== 'undefined' && typeof Shopify.checkout !== 'undefined') {
                    const identifyObject = {};
                    const checkout = Shopify.checkout;

                    if (checkout.email) {
                        identifyObject.email = checkout.email;
                    }

                    if (Shopify.checkout.phone === null || Shopify.checkout.phone === undefined) {
                        if (checkout.billing_address && checkout.billing_address.phone) {
                            identifyObject.phone_number = checkout.billing_address.phone;
                        }
                    }
                    else {
                        identifyObject.phone_number = Shopify.checkout.phone;
                    }

                    if (Object.keys(identifyObject).length > 0) {
                        window.ttq.identify(identifyObject);
                    }
                }
            }

            if (pixel.pixel_cp_event_details === true) {
                let lineItems = [];
                for (let lineItem of Shopify.checkout.line_items) {
                    if (pixel.pixel_sp.length > 0) {
                        if (pixel.pixel_sp.indexOf(lineItem.product_id.toString()) === -1) {
                            continue;
                        }
                        else {
                            pixel.sp_loaded_in_page = true;
                            jQuery('head').prepend(pixel.pixel_code);
                        }
                    }

                    lineItems.push({
                        content_id: lineItem.product_id.toString(),
                        content_type: "product",
                        quantity: parseInt(lineItem.quantity),
                        price: parseFloat(lineItem.price)
                    });
                }

                if (pixel.pixel_sp.length > 0 && lineItems.length === 0) {
                    continue;
                }

                if (lineItems.length === 1) {
                    window.ttq.instance(pixel.pixel_id).track('CompletePayment', {
                        content_id: lineItems[0]['content_id'].toString(),
                        content_type: "product",
                        quantity: parseInt(lineItems[0]['quantity']),
                        currency: Shopify.checkout.currency,
                        value: parseFloat(Shopify.checkout.total_price)
                    });
                }
                else {
                    window.ttq.instance(pixel.pixel_id).track('CompletePayment', {
                        content_type: "product_group",
                        currency: Shopify.checkout.currency,
                        value: parseFloat(Shopify.checkout.total_price),
                        contents: lineItems
                    });
                }
            }
            else {
                if (pixel.pixel_sp.length > 0) {
                    for (let lineItem of Shopify.checkout.line_items) {
                        if (pixel.pixel_sp.indexOf(lineItem.product_id.toString()) > -1) {
                            jQuery('head').prepend(pixel.pixel_code);
                            setTimeout(function() {
                                window.ttq.instance(pixel.pixel_id).track('CompletePayment');
                            }, 500);
                        }
                    }
                }
                else {
                    window.ttq.instance(pixel.pixel_id).track('CompletePayment');
                }
            }

            registerLsOrder = true;
        }
    }

    if (window.isLS && registerLsOrder) {
        localStorage.setItem('already_reported_' + Shopify.checkout.order_id, 'true');
    }
}

function TPI_waitForCartDrawer() {
	const checkoutButtonElements = TPI_detectCheckoutButtons();
    for (let checkoutButtonElement of checkoutButtonElements) {
        if (checkoutButtonElement.getAttribute('tpi-pao-registered') === null) {
            checkoutButtonElement.addEventListener('click', triggerCheckoutInitiationReport);
            checkoutButtonElement.setAttribute('tpi-pao-registered', 'true');
        }
    }
}

function TPI_detectAddToCartButtons() {
    let resultElements = [];
    const atcButtonSelectors = [
        '*[tpi-override="true"]:not([disabled])',
        '*[class="add_to_cart cxBundleBtn"]:not([disabled])',
        '*[aria-label="Add to cart"]:not([disabled])',
        '*[id="teeAtcButton"]:not([disabled])',
        'button[name="ajax_add"]:not([disabled])',
        'input[name="add"]:not([disabled])',
        'button[name="add"]:not([disabled])',
        'button[id="add"]:not([disabled])',
        'input[id="add"]:not([disabled])',
        ".shopify-app-block .ButtonBlockButton",
        'button[id="addToCart"]:not([disabled])',
        'input[id="addToCart"]:not([disabled])',
        'input[name="AddToCart"]:not([disabled])',
        'button[name="AddToCart"]:not([disabled])',
        '*[data-add-to-cart]:not([disabled])',
        'input[id="AddToCart"]:not([disabled])',
        'button[id="AddToCart"]:not([disabled])',
        '*[id="add-to-cart"]:not([disabled])',
        '*[id="adbtn"]:not([disabled])',
        '*[class*="product-form--atc-button"]:not([disabled])',
        '*[class*="product__add-to-cart"]:not([disabled])',
        '*[id="shopify_add_to_cart"]:not([disabled])',
        '*[class*="product-form--add-to-cart"]:not([disabled])',
        '*[class*="ProductForm__AddToCart"]:not([disabled])',
        '*[class*="add-to-cart"]:not(div):not([disabled])',
        '*[class*="addtocart"]:not([disabled])',
        '*[class*="AddToCart"]:not([disabled])',
        '*[class*="addToCart"]:not([disabled])',
        '*[data-action="add-to-cart"]:not([disabled])',
        '*[data-add-to-cart-text]:not([disabled])',
        '*[name="add"]:not([disabled])',
        '*[data-add-button]:not([disabled])',
        '*[data-buy-button]:not([disabled])',
        '*[data-lhi="trans_buynow"]:not([disabled])',
        '*[class*="add_to_cart_button"]:not([disabled])',
        '*[data-pf-type="ProductATC"]:not([disabled])',
        '*[data-add-cart]:not([disabled])',
        '*[class*="product-buy-buttons--cta"]:not([disabled])',
        '*[data-aid="product-form-submit-button"]:not([disabled])',
        '*[class*="lh-add_to_cart"]:not([disabled])',
        '*[data-text-add-to-cart]:not([disabled])',
        '*[class*="single_add_to_cart_button"]:not([disabled])',
        '*[data-text*="Add To Cart"]:not([disabled])',
        '*[data-add-to-cart-text]',
        '*[class*="btn-cart"]:not([disabled])',
        '*[class*="ButtonBlock__Container"]:not([disabled])',
        'buy-buttons>[is="custom-button"]:not([disabled])',
        '*[data-pf-type="ProductATC2"]:not([disabled])',
    ];
    const addToCartFormSelectors = [
        'button[type="submit"]:not([disabled])',
        'input[type="submit"]:not([disabled])',
    ];

    for (let selector of atcButtonSelectors) {
		for (let elementSearchResult of document.querySelectorAll(selector)) {
            if (elementSearchResult.getAttribute('tpi-ignore') === "true") {
                continue;
            }

            resultElements.push(elementSearchResult);
        }
	}

    if (resultElements.length === 0) {
        for (const addToCartFormElement of document.querySelectorAll('form[action="/cart/add"]')) {
            for (let selector of addToCartFormSelectors) {
                let element = addToCartFormElement.querySelector(selector);
                if (element !== null && element.getAttribute('tpi-ignore') !== "true") {
                    resultElements.push(element);
                }
            }
        }
    }

    return resultElements;
}

function TPI_getCurrentSelectedProductQuantity() {
	let resultElement = null;
	const quantityElementSelectors = [
	    '[tpi-quantity-override="true"]',
        '*[name="quantity"]:not([disabled])'
	];
	for (let selector of quantityElementSelectors) {
		let elementSearchResult = document.querySelector(selector);
		if (elementSearchResult === null) {
		    continue;
		}

        if (elementSearchResult.getAttribute('tpi-ignore') === "true") {
            continue;
        }
        else {
            return parseInt(elementSearchResult.value);
        }
	}

	return 1;
}

function TPI_getCurrentShopifyShopCurrency() {
    try {
        if (window.hasOwnProperty('Shopify') && window.Shopify.hasOwnProperty('currency') && window.Shopify.currency.hasOwnProperty('active') && window.Shopify.currency.active !== undefined) {
            return window.Shopify.currency.active;
        }

        return 'USD';
    }
    catch(err) {
        return 'USD';
    }
}

function TPI_getCurrentShopifySelectedProductVariantId() {
    try {
        const queryParams = new URLSearchParams(window.location.search);
        if (window.hasOwnProperty('ShopifyAnalytics') && window.ShopifyAnalytics.hasOwnProperty('meta') && window.ShopifyAnalytics.meta.hasOwnProperty('selectedVariantId') && ShopifyAnalytics.meta.selectedVariantId !== undefined) {
            return ShopifyAnalytics.meta.selectedVariantId;
        }

        if (queryParams.get('variant') !== null) {
            return queryParams.get('variant').toString();
        }

        let selectedProductVariantIdSelectors = ['[class="product-variant-id"]'];
        for (let selector of selectedProductVariantIdSelectors) {
            if (document.querySelector(selector) !== null) {
                return document.querySelector(selector).value.toString();
            }
        }

        if (window.hasOwnProperty('ShopifyAnalytics') && window.ShopifyAnalytics.hasOwnProperty('meta') && window.ShopifyAnalytics.meta.hasOwnProperty('product') && window.ShopifyAnalytics.meta.product.hasOwnProperty('variants') && window.ShopifyAnalytics.meta.product.variants.length === 1) {
            return ShopifyAnalytics.meta.product.variants[0].id;
        }

        return null;
    }
    catch(err) {
        return null;
    }
}

function TPI_getCurrentShopifySelectedProductVariantPrice() {
    try {
        if (ShopifyAnalytics?.meta?.product?.variants?.length === 1) {
            return (ShopifyAnalytics?.meta?.product?.variants[0]?.price/100).toFixed(2);
        }

        const selectedVariantId = TPI_getCurrentShopifySelectedProductVariantId().toString();
        for (let variant of ShopifyAnalytics.meta.product.variants) {
            if (selectedVariantId === variant.id.toString()) {
                return (variant.price/100).toFixed(2);
            }
        }

        return 1;
    }
    catch(err) {
        return 1;
    }
}

function TPI_getCurrentShopifyProductId() {
    try {
        if (window.hasOwnProperty('ShopifyAnalytics') && window.ShopifyAnalytics.hasOwnProperty('meta') && window.ShopifyAnalytics.meta.hasOwnProperty('product') && ShopifyAnalytics.meta.product.id !== undefined) {
            return ShopifyAnalytics.meta.product.id;
        }

        return null;
    }
    catch(err) {
        return null;
    }
}

function TPI_detectCheckoutButtons() {
	let resultElements = [];
	const checkoutButtonSelectors = [
	    '[tpi-co-override="true"]',
        '*[name="tpi-checkout"]:not([disabled])',
        '*[class*="checkout_btn"]:not([disabled])',
        '*[id="corner-cowi-cart-summary-card-cta-button"]:not([disabled])',
        '*[aria-label="checkout-call-to-action-button"]:not([disabled])',
        '*[class*="rebuy-cart__checkout-button"]:not([disabled])',
        '*[class*="upcart-checkout-button"]:not([disabled])',
	    '*[class*="ymq-fake-checkout-btn"]:not([disabled])',
		'*[name="checkout"]:not([disabled])',
		'*[name="goto_pp"]:not([disabled])',
		'*[name="goto_gc"]:not([disabled])',
		'*[value*="Checkout"]',
		'*[value*="Check out"]',
        '*[href*="/checkout"]:not([href*="front_end/login"]):not([href*="/manage/subscription/"]):not([href*="/admin/settings/checkout"]):not([href*="checkout-sandbox"]):not(link):not([disabled])',
		'*[onclick*="/checkout"]',
		'*[name="checkout-exemptify"]:not([disabled])',
        '*[id="checkout"]:not([disabled])',
        '*[data-cart-checkout-button]',
        '*[class*="cart-button-checkout"]',
        '*[class*="Cart__Checkout"]',
        '*[class*="checkout__fbtn"]',
        '*[name="ddcheckout"]:not([disabled])',
        '*[class*="btnCheckout"]:not([disabled])',
        '*[id="mu-checkout-button"]:not([disabled])',
        '*[class*=satcb-cs-checkout-btn]',
        '*[name="qbk-checkout"]',
        '*[class*="evm_upsell_checkout"]',
	];
	const cartFormSelectors = [
		'input[type="submit"]:not([disabled])',
		'button[type="submit"]:not([disabled])'
	];

	for (let selector of checkoutButtonSelectors) {
		for (let elementSearchResult of document.querySelectorAll(selector)) {
            if (elementSearchResult.getAttribute('tpi-ignore') === "true") {
                continue;
            }

            resultElements.push(elementSearchResult);
        }
	}

    if (resultElements.length === 0) {
        for (const cartFormElement of document.querySelectorAll('form[action="/cart"]')) {
            for (let selector of cartFormSelectors) {
                let element = cartFormElement.querySelector(selector);
                if (element !== null && element.getAttribute('tpi-ignore') !== "true") {
                    resultElements.push(element);
                }
            }
        }
    }

	return resultElements;
}

if (typeof jQuery === 'undefined'){
    TPI_loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js', TPI_main);
} else {
    TPI_main();
}