class CauUtils {
    static getShopifyRootRoute() {
        try {
            if (window.hasOwnProperty('Shopify') && window.Shopify.hasOwnProperty('routes') && window.Shopify.routes.hasOwnProperty('root') && window.Shopify.routes.root !== undefined && window.Shopify.routes.root.startsWith('/') && window.Shopify.routes.root.endsWith('/') && (window.Shopify.routes.root.length === 1 || window.Shopify.routes.root.length === 4)) {
                return window.Shopify.routes.root;
            }
            else {
                return "/";
            }
        }
        catch(err) {
            return "/";
        }
    }

    static detectAddToCartButton() {
        let atcButtonSelectors = [
            '*[cau-atc-override="true"]',
            '*[name="qbk-add-to-cart"]:not([disabled])',
            'button[class*="so-btn-add-to-cart"]:not([disabled])',
            '*[name="buttonBuy"]:not([disabled])',
            '[upsell-hooked-add-to-cart-btn="true"]:not([disabled])',
            '[id="new-form-atc"]:not([disabled])',
            '*[class*="engoj-btn-addtocart"]:not([disabled])',
            'input[name="add"]:not([disabled])',
            'button[name="add"]:not([disabled])',
            'button[id="add"]:not([disabled])',
            'input[id="add"]:not([disabled])',
            'button[id="addToCart"]:not([disabled])',
            'input[id="addToCart"]:not([disabled])',
            'input[name="AddToCart"]:not([disabled])',
            'button[name="AddToCart"]:not([disabled])',
            'input[id="AddToCart"]:not([disabled])',
            'button[id="AddToCart"]:not([disabled])',
            '*[id*="AddToCart"]:not([id*="modalAddToCartButton"]):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([class*="form-add-to-cart"]):not([disabled])',
            '*[class*="add_to_cart"]:not([disabled])',
            '*[class*="addtocart"]:not([disabled])',
            '*[class*="AddToCart"]:not([disabled])',
            '*[data-action="add-to-cart"]:not([disabled])',
            '*[data-add-to-cart]:not([disabled])',
            '*[name="add"]:not([disabled])',
            '*[id="add-to-cart"]:not([disabled])',
            '*[data-lhi="trans_buynow"]:not([disabled])',
            '*[class*="add_to_cart_button"]:not([disabled])',
            '*[data-add-to-cart-text]:not([disabled])',
            '*[class*="btn-cart"]: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])',
            '*[data-pf-type="ProductATC"]:not([disabled])',
            '*[class*="single_add_to_cart_button"]:not([disabled])',
            '*[data-text*="Add To Cart"]:not([disabled])',
            '*[id="adbtn"]:not([disabled])',
            '*[class*="addToCart"]:not([disabled])',
            '*[data-add-button]:not([disabled])',
            '*[data-buy-button]:not([disabled])',
            'buy-buttons [is="custom-button"]:not([disabled])',
            'buy-buttons:not([disabled])',
            'product-to-cart button[data-to-cart]:not([disabled])',
            'button[id="AddToCart"]:not([disabled])',
            '*[data-product-add-to-cart-button]:not([disabled])',
            '*[class*="product-form__add-button"]:not([disabled])'
        ];
    
        for (let selector of atcButtonSelectors) {
            let elementSearchResult = document.querySelector(selector);
            if (elementSearchResult !== null && elementSearchResult.getAttribute('cau-ignore') === "true") {
                continue;
            }
    
            if (elementSearchResult !== null) {
                return elementSearchResult;
            }
        }
    
        return null;
    }

    static detectQuantityElement() {
        let quantityElementSelectors = [
            '*[cau-qty-override="true"]',
            '[class*="VolumeDiscountRadio"] [name*="variant-selector"]:checked',
            '.product__quantity--radios [name="quantity"]:checked',
            '[name="quantity"]',
        ];

        for (let selector of quantityElementSelectors) {
            let elementSearchResult = document.querySelector(selector);
            if (elementSearchResult !== null && elementSearchResult.getAttribute('cau-ignore') === "true") {
                continue;
            }

            if (elementSearchResult !== null) {
                return elementSearchResult;
            }
        }

        return null;
    }
    
    static cloneElement(elementToClone, onclickFunctionToApply, originalElementAttribute, clonedElementAttribute) {
        let clonedButton = elementToClone.cloneNode(true);
        elementToClone.setAttribute('style', 'width: 0 !important; height: 0 !important; display: none !important;');
        elementToClone.setAttribute(originalElementAttribute, "true");
        clonedButton.setAttribute("type", "button");
        clonedButton.style.cursor = "pointer";
        clonedButton.removeAttribute("name");
        clonedButton.removeAttribute("data-action");
        clonedButton.removeAttribute("data-product-atc");
        if (window.CAU_THEME_NAME.indexOf('fastlane') === -1) {
            clonedButton.removeAttribute("id");
        }

        clonedButton.removeAttribute("href");
        clonedButton.setAttribute(clonedElementAttribute, "true");
        clonedButton.setAttribute("onclick", onclickFunctionToApply);
        elementToClone.insertAdjacentElement('beforebegin', clonedButton);
    }

    static getCurrentShopifyPageType() {
        try {
            return ShopifyAnalytics.meta.page.pageType;
        }
        catch(err) {
            return "";
        }
    }

    static 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 && ShopifyAnalytics.meta.selectedVariantId.length > 0) {
                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 > 0) {
                return ShopifyAnalytics.meta.product.variants[0].id;
            }

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

    static getCurrentShopifyProductId() {
        try {
            return ShopifyAnalytics.meta.product.id.toString();
        }
        catch(err) {
            return "";
        }
    }
}

class SkipToCheckout {
    constructor(stcType, stcSpecificProducts) {
        this._stcType = stcType;
        this._stcSpecificProducts = stcSpecificProducts.length === 0 ? [] : stcSpecificProducts.split(',');
    }

    sceSkipToCheckout(event) {
        const rootRoute = CauUtils.getShopifyRootRoute();
        if (this._stcSpecificProducts.length > 0) {
            if (event['detail'] !== undefined && event['detail']['product_id'] !== undefined && this._stcSpecificProducts.indexOf(event['detail']['product_id'].toString()) > -1) {
                location.href = rootRoute + 'checkout';
            }
        }
        else {
            location.href = rootRoute + 'checkout';
        }
    }

    externalSkipToCheckout() {
        if ('' != '') {
            appendCssToHead('');
        }
        let quantityElement = CauUtils.detectQuantityElement();
        let quantity = 1;
        let selectedProductVariantId = CauUtils.getCurrentShopifySelectedProductVariantId();
        if (quantityElement !== null) {
            quantity = quantityElement.value;
        }

        const rootRoute = CauUtils.getShopifyRootRoute();
        location.href = rootRoute + 'cart/' + selectedProductVariantId + ":" + quantity;
    }
    
    runLogic() {
        if (this._stcType === 3 || this._stcType === 4) {
            try {
                const pageType = CauUtils.getCurrentShopifyPageType();
                const productId = CauUtils.getCurrentShopifyProductId();
                const rootRoute = CauUtils.getShopifyRootRoute();
                if (this._stcType === 4 && (pageType === "product" || pageType === "collection" || pageType === "home") && (this._stcSpecificProducts.length === 0 || this._stcSpecificProducts.indexOf(productId) > -1)) {
                    navigation.addEventListener("navigate", (e) => {
                        if (e.destination.url.indexOf('/cart') > -1) {
                            e.preventDefault();
                            if (1 === 1) {
                                location.href = rootRoute + 'checkout';
                            }
                        }
                    });
                }
            }
            catch(err) {

            }

            window.EFFECTIVE_APPS_CAU_STC_INTERVAL = setInterval(() => {
                const stcLs = CAU_getLsWithExpiry('cau_stc');
                if (stcLs !== null) {
                    const event = JSON.parse(stcLs);
                    const productVariantId = event.data.cartLine.merchandise.id;
                    const productId = event.data.cartLine.merchandise.product.id;
                    if (this._stcSpecificProducts.length === 0 || this._stcSpecificProducts.indexOf(productId) > -1) {
                        const rootRoute = CauUtils.getShopifyRootRoute();
                        if ('' != '') {
                            appendCssToHead('');
                        }

                        if (document.getElementById('_rsi-cod-form-modal') !== null && document.getElementById('_rsi-cod-form-modal').getAttribute('class') !== null && document.getElementById('_rsi-cod-form-modal').getAttribute('class').indexOf('_rsi-cod-form-modal-open') > -1) {
                            return;
                        }

                        if (1 === 1) {
                            const quantity = event.data.cartLine.quantity;
                            localStorage.removeItem('cau_stc');
                            location.href = rootRoute + 'cart/' + productVariantId + ":" + quantity;
                        }
                        else {
                            location.href = rootRoute + 'checkout';
                        }
                    }
                }
            }, 500);
        }
        else {
            let atcButton = CauUtils.detectAddToCartButton();
            let currentSelectedProductVariantId = CauUtils.getCurrentShopifySelectedProductVariantId();
            if (this._stcType === 1 || CauUtils.getCurrentShopifyPageType() === "collection" || atcButton === null || currentSelectedProductVariantId === null) {
                !function(){if(window&&window.Shopify){const a={add:"SCE:add",update:"SCE:update",change:"SCE:change",clear:"SCE:clear",mutate:"SCE:mutate"},c=["/cart/add","/cart/update","/cart/change","/cart/clear","/cart/add.js","/cart/update.js","/cart/change.js","/cart/clear.js"];if(window.fetch&&"function"==typeof window.fetch){const d=window.fetch;window.fetch=function(){const t=d.apply(this,arguments);return e(arguments[0])&&t.then(e=>{e.clone().json().then(t=>n(e.url,t))}),t}}if(window.XMLHttpRequest){const i=window.XMLHttpRequest.prototype.open;window.XMLHttpRequest.prototype.open=function(){const t=arguments[1];return this.addEventListener("load",function(){e(t)&&n(t,this.response)}),i.apply(this,arguments)}}function e(t){if(t)return t=t.split("/").pop(),c.includes("/cart/"+t)}function n(t,e){if("string"==typeof e)try{e=JSON.parse(e)}catch{}window.dispatchEvent(new CustomEvent(a.mutate,{detail:e}));t=!!(t=t)&&(t.includes("cart/add")?"add":t.includes("cart/update")?"update":t.includes("cart/change")?"change":!!t.includes("cart/clear")&&"clear");switch(t){case"add":window.dispatchEvent(new CustomEvent(a.add,{detail:e}));break;case"update":window.dispatchEvent(new CustomEvent(a.update,{detail:e}));break;case"change":window.dispatchEvent(new CustomEvent(a.change,{detail:e}));break;case"clear":window.dispatchEvent(new CustomEvent(a.clear,{detail:e}))}}}}();
                window.addEventListener('SCE:add', (event) => { this.sceSkipToCheckout(event) });
            }
            else if ((this._stcSpecificProducts.length === 0 || this._stcSpecificProducts.indexOf(CauUtils.getCurrentShopifyProductId()) > -1) && atcButton !== null) {
                CauUtils.cloneElement(atcButton, "window.skipToCheckout.externalSkipToCheckout();", "cau-original-atc", "cau-cloned-atc");
            }
        }
    }
}

window.quantityUpdateChange = function(event) {
    if (window.CAU_THEME_NAME.indexOf('venture') > -1) {
        setTimeout(triggerCartUpdate, 1250);
    }
    else {
        triggerCartUpdate();
    }
}

function CAU_isLocalStorageAvailable() {
    try {
        const testKey = '__storage_test__';
        localStorage.setItem(testKey, 'test');
        localStorage.removeItem(testKey);
        return true;
    }
    catch (e) {
        return false;
    }
}

function CAU_getLsWithExpiry(key) {
    try {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) {
            return null
        }

        const item = JSON.parse(itemStr)
        const now = new Date()
        if (now.getTime() > item.expiry) {
            localStorage.removeItem(key)
            return null
        }

        return item.value.toString();
	}
	catch(err) {
	    return null;
	}
}

function CAU_setLsWithExpiry(key, value, ttl) {
    try {
        value = value.toString();
        const now = new Date()
        const item = {
            value: value,
            expiry: now.getTime() + ttl,
        }
        localStorage.setItem(key, JSON.stringify(item));
	}
	catch(err) {
	    return null;
	}
}

function triggerCartUpdate() {
    if (jQuery("*[name='update']")[0] === undefined && jQuery("*[class*='update btn item']")[0] === undefined && jQuery("*[class*='btn-update']")[0] === undefined && jQuery("*[class*='update-cart']")[0] === undefined) {
        jQuery('form[action*="/cart"]')[0].submit();
    }
    else {
        jQuery("*[name='update']").trigger("click");
        jQuery("*[class*='update btn item']").trigger("click");
        jQuery("*[class*='btn-update']").trigger("click");
        jQuery("*[class*='update-cart']").trigger("click");
    }
}

window.inputFieldQuantityUpdateChange = function(e) {
    if ([48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105].indexOf(e.keyCode) === -1) {
        return;
    }

    setTimeout(function() {
        if (jQuery("*[name='update']")[0] === undefined && jQuery("*[class*='update btn item']")[0] === undefined && jQuery("*[class*='btn-update']")[0] === undefined && jQuery("*[class*='update-cart']")[0] === undefined) {
            jQuery('form[action*="/cart"]')[0].submit();
        }
        else {
            jQuery("*[name='update']").trigger("click");
            jQuery("*[class*='update btn item']").trigger("click");
            jQuery("*[class*='btn-update']").trigger("click");
            jQuery("*[class*='update-cart']").trigger("click");
        }
    }, 1250);
}

window.CartAutoUpdate = function() {
    if ('false' === 'true') {
        jQuery("*[name='update']").css("display", "none");
        jQuery("*[class*='update btn item']").css("display", "none");
        jQuery("*[class*='btn-update']").css("display", "none");
        jQuery("*[class*='update-cart']").css("display", "none");
    }
    
    jQuery("input[name='updates[]'], input[name*='updates'], input[class='cart-qty'], input[id*='updates']").on('keydown', function(event) {
        window.inputFieldQuantityUpdateChange(event);
    });

    jQuery("input[name='updates[]'], input[name*='updates'], input[class='cart-qty'], input[id*='updates']").on('change', function(event) {
        setTimeout(function() {
            window.quantityUpdateChange(event);
        }, 750);
    });


    jQuery('*[class*="-plus"]:not([class*="site-header"]), *[class*="-add"]:not(".cart__note-add"), *[class="increase"], *[class*=" plus"]').bind('click', function(event) {
        event.preventDefault();
        window.quantityUpdateChange(event);
    });

    jQuery('*[class*="-minus"], *[class="decrease"], *[class*=" minus"]').bind('click', function(event) {
        event.preventDefault();
        window.quantityUpdateChange(event);
    });

    jQuery('*[class*="qtyplus"], *[class="plus button"]').bind('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[class*="qtyminus"],  *[class="minus button"]').bind('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[id*="quantity"]').on('change paste input', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[class*="qty-btn"]').on('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[class*="inc button"], *[class*="dec button"]').on('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[data-minus=""], *[data-plus=""]').on('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[class*="reduced items"], *[class*="increase items"]').on('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });

    jQuery('*[class*="cart-item-increase"], *[class*="cart-item-decrease"]').on('click', function(event) {
        setTimeout(function() { window.quantityUpdateChange(event);}, 300);
    });
}

function CAU_loadjQuery(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 CAU_getShopifyThemeName() {
    try {
        if (window.CAU_THEME_NAME_OVERRIDE !== undefined) {
            return window.TAC_THEME_NAME_OVERRIDE;
        }
        else if (window.BOOMR !== undefined && window.BOOMR.themeName !== undefined && window.BOOMR.themeName.length > 0) {
            return window.BOOMR.themeName.toLowerCase();
        }
        else if (window.Shopify !== undefined && window.Shopify.theme !== undefined && window.Shopify.theme.schema_name !== undefined && window.Shopify.theme.schema_name.length > 0) {
            return window.Shopify.theme.schema_name.toLowerCase();
        }
        else {
            return Shopify.theme.name.toLowerCase();
        }
    }
    catch (err) {
        return "";
    }
}

function hideATCButton() {
    appendCssToHead('[class="cart-bar__form"] { display: none !important; } input[name="add"]{display: none !important;} button[name="add"]{display: none !important;} button[id="add"]{display: none !important;} input[id="add"]{display: none !important;} button[id="addToCart"]{display: none !important;} input[id="addToCart"]{display: none !important;} input[name="AddToCart"]{display: none !important;} button[name="AddToCart"]{display: none !important;} input[id="AddToCart"]{display: none !important;} button[id="AddToCart"]{display: none !important;} [class*="product-form--atc-button"]{display: none !important;} [class*="product__add-to-cart"]{display: none !important;} [id="shopify_add_to_cart"]{display: none !important;} [class*="product-form--add-to-cart"]{display: none !important;} [class*="ProductForm__AddToCart"]{display: none !important;} [class*="add-to-cart"]:not([class*="form-add-to-cart"]){display: none !important;} [class*="addtocart"]:not(body){display: none !important;} [class*="AddToCart"]{display: none !important;} [data-action="add-to-cart"]{display: none !important;} [data-add-to-cart]{display: none !important;} [name="add"]{display: none !important;} [id="add-to-cart"]{display: none !important;} [data-lhi="trans_buynow"]{display: none !important;} [data-add-to-cart-text]{display: none !important;} [id="multivariants_add_to_cart_button"]{visibility: hidden !important;} buy-buttons [is="custom-button"]:first-of-type { display: none; }');
}

function hideBINButton() {
    appendCssToHead('[class*="shopify-payment-button"]{display: none !important;} [class="td-submit"]{display: none !important;}');
}

function hideACB() {
    appendCssToHead('[class*="additional-checkout-buttons"]{display: none !important;}[class*="additional_checkout_buttons"]{display: none !important;}');
}

function appendCssToHead(css) {
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    if (s.styleSheet) {
        s.styleSheet.cssText = css;
    } else {
        s.appendChild(document.createTextNode(css));
    }

    head.appendChild(s);
}

function hideCartButton() {
    if (window.CAU_THEME_NAME.indexOf('express') > -1) {
        appendCssToHead('[href="/cart"]{visibility: hidden !important;} [class*="header__icon--cart"]{visibility: hidden !important;}[class*="cart-icon"]{visibility: hidden !important;}');
    }
    else {
        appendCssToHead('[href="/cart"]{display: none !important;} [href$="/cart"]{display: none !important;} [class*="header__icon--cart"]{display: none !important;}[class*="cart-icon"]{visibility: hidden !important;}');
    }
}

function CAU_main() {
    console.log('%c------ Poof: Store Elements Remover 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.CAU_THEME_NAME = CAU_getShopifyThemeName();
    window.effectiveAppsCauAtcSp = '6647148937286,6646321840198,6646322102342,6646321872966,6646322135110,6646321905734,6646322167878,6646321938502,6646321971270,6646322004038,6646322036806,6646322069574';
    window.effectiveAppsCauAtcAllowedProducts = window.effectiveAppsCauAtcSp.split(',');
    if (window.CAU_SCRIPT_INJECTED === undefined) {
        window.CAU_SCRIPT_INJECTED = true;
        if ('3' === '7' && null === CAU_getLsWithExpiry('cau_payg_i')) {
            jQuery.get('https://app.skiptocheckout.com/ri/486396fe865b11ef9a5b3ed829201946.js');
            CAU_setLsWithExpiry('cau_payg_i', 'true', 604800000);
        }

        if ('False' === 'True') {
            let stcType = 2;
            if (!CAU_isLocalStorageAvailable()) {
                stcType = 2;
            }

            if (window.CAU_THEME_NAME.indexOf('showtime') > -1) {
                stcType = 1;
            }

            window.EFFECTIVE_APPS_CAU_STC_SP = '';
            window.skipToCheckout = new SkipToCheckout(stcType, window.EFFECTIVE_APPS_CAU_STC_SP);
            window.skipToCheckout.runLogic();
        }

        if ('True' === 'True') {
            if (window.effectiveAppsCauAtcSp.length > 0) {
                if (window.effectiveAppsCauAtcAllowedProducts.indexOf(CauUtils.getCurrentShopifyProductId()) > -1) {
                    hideATCButton();
                }
            }
            else {
                hideATCButton();
            }
        }

        if ('False' === 'True') {
            if (window.effectiveAppsCauAtcSp.length > 0 && ShopifyAnalytics.meta.page.pageType === "product") {
                if (window.effectiveAppsCauAtcAllowedProducts.indexOf(CauUtils.getCurrentShopifyProductId()) > -1) {
                    hideBINButton();
                }
            }
            else {
                hideBINButton();
            }
        }

        if ('False' === 'True') {
            hideACB();
        }

        if ('False' === 'True') {
            hideCartButton();
            if (window.location.pathname.indexOf("/cart") > -1) {
                window.location.href = "/checkout";
            }
        }

        if (0 === 1 && window.location.pathname.indexOf("/cart") > -1) {
            window.CartAutoUpdate();
        }
    }
}

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