function giftOptionsChanged(e) {
    var giftOptionsStatus = e.target.checked;
    var giftOptionsToApply = null;
    if ('True' === 'True') {
        if (giftOptionsStatus === true) {
            if (document.getElementById('egw_options') !== null) {
                jQuery("#egw_options").fadeIn();
            }
            if (document.getElementById('egw_options_atc') !== null) {
                jQuery("#egw_options_atc").fadeIn();
            }
        }
        else {
            submitCartUpdates({"effectiveAppsEgwGiftMessage": false});
            if (document.getElementById('egw_options') !== null) {
                jQuery("#egw_options").fadeOut();
            }
            if (document.getElementById('egw_options_atc') !== null) {
                jQuery("#egw_options_atc").fadeOut();
            }
        }
        return;
    }

    else if ('False' === 'True') {
        giftOptionsToApply = updateGiftReceiptStatus();
    }

    else if ('False' === 'True') {
        if (document.getElementById('egw_options') !== null || document.getElementById('egw_options_atc') !== null) {
            if (giftOptionsStatus === true) {
                if (document.getElementById('egw_options') !== null) {
                    jQuery("#egw_options").fadeIn();
                }
                if (document.getElementById('egw_options_atc') !== null) {
                    jQuery("#egw_options_atc").fadeIn();
                }
            }
            else {
                if (document.querySelector('input[name="effective_apps_gw_option"]:checked') !== null) {
                    submitCartUpdates({"effectiveAppsEgwGiftWrap": false});
                }

                if (document.getElementById('egw_options') !== null) {
                    jQuery("#egw_options").fadeOut();
                }
                if (document.getElementById('egw_options_atc') !== null) {
                    jQuery("#egw_options_atc").fadeOut();
                }
            }
            return;
        }
        else {
            giftOptionsToApply = {"effectiveAppsEgwGiftWrap": giftOptionsStatus}
        }
    }

    submitCartUpdates(giftOptionsToApply);
}

function updateGiftReceiptStatus() {
	var giftReceiptStatus = false;
	if (document.getElementById('effectiveAppsEGW') !== null) {
	    giftReceiptStatus = document.getElementById('effectiveAppsEGW').checked;
	}
	else if (document.getElementById('effectiveAppsEGWATC') !== null) {
	    giftReceiptStatus = document.getElementById('effectiveAppsEGWATC').checked;
	}
	return {
		"effectiveAppsEgwGiftReceipt": giftReceiptStatus
	};
}

function generateCartGiftOptionsNote(currentGiftOptions) {
    let result = "";
    if (currentGiftOptions === undefined) {
        currentGiftOptions = JSON.parse(EGW_getLsWithExpiry("effective_apps_egw_rc_options_LS"));
        if (currentGiftOptions === null) {
            return "";
        }
    }

    if (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftMessage") && currentGiftOptions["effectiveAppsEgwGiftMessage"] === true) {
        result += "Gift Message: " + currentGiftOptions["effectiveAppsEgwGiftMessageText"];
    }
    else if (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftWrap") && currentGiftOptions["effectiveAppsEgwGiftWrap"] === true) {
        if (window.effectiveAppsGwOptions["gift_wrap_options"].length > 1) {
            for (var giftOption of window.effectiveAppsGwOptions["gift_wrap_options"]) {
                if (currentGiftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"] === giftOption["gw_variant_id"]) {
                    result += giftOption["gw_title"] + ": ✓";
                }
            }
        }
        else {
            result += window.effectiveAppsGwLabelText + ": ✓";
        }
    }
    else if (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftReceipt") && currentGiftOptions["effectiveAppsEgwGiftReceipt"] === true) {
        result += "Gift Receipt: ✓";
    }

    return result;
}

function updateGiftMessageStatus() {
    var giftMessageText = document.getElementById('effectiveAppsEgwGiftMessageText').value;
	var giftMessageOptions = {
        "effectiveAppsEgwGiftMessage": true,
        "effectiveAppsEgwGiftMessageText": giftMessageText
    };
	if (giftMessageText.length > 0) {
        submitCartUpdates(giftMessageOptions, false, true);
    }
}

function updateGiftMessageStatusATC() {
    var giftMessageText = document.getElementById('effectiveAppsEgwGiftMessageTextATC').value;
	var giftMessageOptions = {
        "effectiveAppsEgwGiftMessage": true,
        "effectiveAppsEgwGiftMessageText": giftMessageText
    };
	if (giftMessageText.length > 0) {
        submitCartUpdates(giftMessageOptions, false, true);
    }
}

function updateRemainingCharacters() {
	var remainingCharactersElement = document.getElementById('effectiveAppsEgwGiftMessageRC');
	var remainingCharacters = parseInt(document.getElementById('effectiveAppsEgwGiftMessageText').maxLength) - parseInt(document.getElementById('effectiveAppsEgwGiftMessageText').textLength);
	remainingCharactersElement.innerText = `Remaining characters: ` + remainingCharacters.toString();
}

function updateRemainingCharactersATC() {
	var remainingCharactersElement = document.getElementById('effectiveAppsEgwGiftMessageRCATC');
	var remainingCharacters = parseInt(document.getElementById('effectiveAppsEgwGiftMessageTextATC').maxLength) - parseInt(document.getElementById('effectiveAppsEgwGiftMessageTextATC').textLength);
	remainingCharactersElement.innerText = `Remaining characters: ` + remainingCharacters.toString();
}

function EGW_setLsWithExpiry(key, value, ttl) {
    value = value.toString();
	const now = new Date()
	const item = {
		value: value,
		expiry: now.getTime() + ttl,
	}
	localStorage.setItem(key, JSON.stringify(item))
}

function EGW_getLsWithExpiry(key) {
	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();
}

function selectGwOption(gwVariantId) {
    var giftOptionsToApply = {"effectiveAppsEgwGiftWrap": true, "effectiveAppsEgwGiftWrapSelectedVariantId": gwVariantId};
    submitCartUpdates(giftOptionsToApply);
}

function EGW_runLogic() {
    if (location.pathname.indexOf('thank_you') > -1) {
        localStorage.removeItem('effective_apps_egw_rc_options_LS');
        return;
    }

    window.effectiveAppsEgwSp = '';
    window.effectiveAppsAllowedProducts = window.effectiveAppsEgwSp.split(',');
    window.effectiveAppsEgwText = `<label style="display:inline; float:none" for="effectiveAppsEGW"><input style="padding: 0 0 0 0 !important; -webkit-appearance: checkbox; float:none; vertical-align: middle; width: 15px !important;" type="checkbox" id="effectiveAppsEGW" name="effectiveAppsEGW" onchange="giftOptionsChanged(event);" /> <span><img class="effectiveAppsEGWImage" alt="Gift options checkbox image" src="https://cdn.shopify.com/s/files/1/0395/1797/8787/t/6/assets/gift_image_9.png" /> <strong style="color: black; font-size: 14px;">Is this a gift?&nbsp; Add a gift message</strong></span></label>`;
    window.effectiveAppsGwOptions = JSON.parse(`{"gift_wrap_options": []}`);
    window.effectiveAppsGwLabelText = `Gift Wrap`;
    var giftOptionHtml = "";

    if ('False' === 'True') {
        if (window.effectiveAppsGwOptions["gift_wrap_options"].length > 1) {
            var giftWrapOptionsHtml = "";
            for (var giftOption of window.effectiveAppsGwOptions["gift_wrap_options"]) {
                var gw_title = giftOption["gw_title"];
                var gw_price = giftOption["gw_price"];
                var gw_explanation = giftOption["gw_explanation"];
                var gw_variant_id = giftOption["gw_variant_id"];
                var gw_img = giftOption["gw_img"];
                if (parseFloat(gw_price) > 0) {
                    gw_title = gw_title + ' ($' + gw_price + ')';
                }
                giftWrapOptionsHtml += '<label gw-variant-id='+ gw_variant_id +' style="display: inline-block !important;" class="radio-img egw-tooltip"><span class="egw-tooltiptext"><u>' + gw_title + '</u><br /> ' + gw_explanation + '</span><input type="radio" onclick="selectGwOption(`' + gw_variant_id + '`)" name="effective_apps_gw_option" value="' + gw_variant_id + '"><div class="effective-apps-egw-gw-swatch" style="background-image: url(' + gw_img + ')"></div></label>';
            }

            giftOptionHtml += '<div id="egw_options_text"></div><div id="egw_options" style="display: none;">' + giftWrapOptionsHtml + '</div>';
        }
    }
    else if ('True' === 'True') {
        giftOptionHtml += `<div id="egw_options" style="display: none;"><textarea aria-label="Gift Message" tabindex="-1" onkeyup="updateRemainingCharacters(); updateGiftMessageStatus();" maxlength="250" name="effectiveAppsEgwGiftMessageText" id="effectiveAppsEgwGiftMessageText" placeholder="Add a personal gift message" rows="4"></textarea><div id="effectiveAppsEgwGiftMessageRC" name="effectiveAppsEgwGiftMessageRC">Remaining characters: 250 </div></div>`;
    }

    window.effectiveAppsEgwText += giftOptionHtml;
    window.EFFECTIVE_APPS_EGW_CUSTOM_CSS = ``;
    if (window.EGW_THEME_NAME.indexOf('xtra') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGWATC"] * {display:inline !important;} [for="effectiveAppsEGW"] * {display:inline !important;} .effective-apps-egw-modal span {display: inline !important;}';
    }

    if (window.EGW_THEME_NAME.indexOf('ecommax') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '#effectiveAppsEGWATC {display:inline !important;width: 20px;} #effectiveAppsEGW {display:inline !important;width: 20px;}';
    }

    if (window.EGW_THEME_NAME.indexOf('modular') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGW"] p { display: inline!important; }[for="effectiveAppsEGWATC"] p { display: inline!important; } #effectiveAppsEGW { display: inline!important; margin-top: -3px; } #effectiveAppsEGWATC { display: inline!important; margin-top: -3px; }';
    }

    if (window.EGW_THEME_NAME.indexOf('icon') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '.effectiveAppsEGWATCImage { width: unset!important; } .effectiveAppsEGWImage { width: unset!important; }';
    }

    if (window.EGW_THEME_NAME.indexOf('testament') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '.effectiveAppsEGWImage { width: unset !important; height: unset !important; } .effectiveAppsEGWATCImage { width: unset !important; height: unset !important; } [for="effectiveAppsEGWATC"] { display: block!important; margin-bottom: -10px; padding-top: 25px; }';
    }

    if (window.EGW_THEME_NAME.indexOf('emerge') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '.effectiveAppsEGWImage { width: unset !important; height: unset !important; } .effectiveAppsEGWATCImage { width: unset !important; height: unset !important; }';
    }

    if (window.EGW_THEME_NAME.indexOf('impulse') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '#effectiveAppsEGWATC{margin-top: -4px !important; margin: 5px;}#effectiveAppsEGW{margin-top: -4px !important; margin: 5px;} [for="effectiveAppsEGW"] p {display: inline !important;} [for="effectiveAppsEGW"] img {display: inline !important;} [for="effectiveAppsEGWATC"] p {display: inline !important;} [for="effectiveAppsEGWATC"] img {display: inline !important;}';
    }

    if (window.EGW_THEME_NAME.indexOf('kalles') > -1 && location.pathname.indexOf('/cart') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGW"] { text-align: right !important;}';
    }

    if (document.querySelector('[class*="icart"]') !== null) {
        if (location.pathname.indexOf('/cart') > -1) {
            window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '#effectiveAppsEGW { max-width: 13px; } div.icart-pg-checkout > div:nth-child(2) { width: 100%; }'
        }
        else {
            window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '.icart .icart-main { z-index: 111111111110!important; } [class*="icart-slider-drawer"] [for="effectiveAppsEGW"] { margin-left: -4px!important; } .icart .icart-main .icart-slider-drawer.icart-inner { z-index: 111111111 !important; }';
        }
    }

    if (window.EGW_THEME_NAME.indexOf("vision") > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGW"] {display:block !important;}';
    }

    if (window.EGW_THEME_NAME.indexOf("ella") > -1 && window.EGW_THEME_NAME.indexOf('shella') === -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += 'input[id*="effective"] { display: unset !important; border: unset !important; clip: unset !important; height: unset !important; overflow: unset !important; padding: unset !important; position: unset !important; width: unset !important; box-sizing: unset !important; } .tingle-modal-box__footer { backface-visibility: unset!important; } [for="effectiveAppsEGW"] img { display: inline !important;} [for="effectiveAppsEGWATC"] img { display: inline !important;}';
    }

    if (window.EGW_THEME_NAME.indexOf('local') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGWATC"] * {display:inline !important;} [for="effectiveAppsEGW"] * {display:inline !important;}';
    }

    jQuery('head').append('<style>' + window.EFFECTIVE_APPS_EGW_CUSTOM_CSS + ' .egw-tooltip{position:relative;display:inline-block}.egw-tooltip .egw-tooltiptext{visibility:hidden;width:150px;background-color:#555;color:#fff;text-align:center;border-radius:6px;padding:10px 10px 10px 10px;position:absolute;z-index:1;bottom:100%;left:25%;margin-left:-60px;opacity:0;transition:opacity .3s}.egw-tooltip .egw-tooltiptext::after{content:"";position:absolute;top:100%;left:50%;margin-left:-5px;border-width:5px;border-style:solid;border-color:#555 transparent transparent transparent}.egw-tooltip:hover .egw-tooltiptext{visibility:visible;opacity:1} #effectiveAppsEgwGiftMessageRC { font-size:11px; position: relative; bottom: 5px !important; padding: 0 0 0 0; } .effective-apps-egw-gw-swatch{opacity:.8;width:40px;height:40px;background-position:center center;background-size: cover;background-color:gray;display:inline-block !important;margin:10px}.effective-apps-egw-gw-swatch:hover{opacity:1}.radio-img>input{display:none}.radio-img>.effective-apps-egw-gw-swatch{cursor:pointer;border:2px solid #000}.radio-img>input:checked+.effective-apps-egw-gw-swatch{border:2px solid green} @keyframes effectiveAppsWiggle{0%{transform:rotate(0)}80%{transform:rotate(0)}85%{transform:rotate(5deg)}95%{transform:rotate(-5deg)}100%{transform:rotate(0)}}div.effectiveAppsWiggle{display:inline-block;animation:effectiveAppsWiggle 1.5s infinite}div.effectiveAppsWiggle:hover{animation:none} div.effectiveAppsBlink{animation:egwBlinker 1.5s step-start infinite}@keyframes egwBlinker{50%{opacity:0}} div.effectiveAppsBlink:hover{animation:none} .effectiveAppsEGWImage { display: inline; } .effectiveAppsEGWATCImage { display: inline; } #effectiveAppsEgwGiftMessageText { width: 100% } #effectiveAppsEgwGiftMessageTextATC { width: 100% }</style>');
    EGW_attachToCart();
}

function EGW_isElementVisible(element) {
    if (element.getAttribute('egw-override') === 'true' || element.getAttribute('id') === 'cart-form-minicart' || element.getAttribute('id') === 'corner-cowi-cart-summary-card-cta-button' || window.EGW_THEME_NAME.indexOf('palo alto') > -1 || window.EGW_THEME_NAME.indexOf('ecommax') > -1 || window.EGW_THEME_NAME.indexOf('turbo') > -1 || window.EGW_THEME_NAME.indexOf('aurora') > -1 || element.classList.contains('qsc2-checkout-button') || element.classList.contains('picky-bundle-add-to-cart-button') || (element.tagName !== undefined && element.tagName === 'CW-WISE-CART')) {
        return true;
    }

    if (element.getAttribute('class') !== null && element.getAttribute('class').indexOf('upcart-checkout-button') > -1) {
        return true;
    }

    if (element.getAttribute('class') !== null && element.getAttribute('class').indexOf('picky') > -1) {
        return true;
    }

    if (element.getAttribute('class') !== null && element.getAttribute('class').indexOf('shiprocket-headless') > -1) {
        return true;
    }

	if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;
	var height = document.documentElement.clientHeight,
		rects = element.getClientRects(),
		on_top = function (r) {
			var x = (r.left + r.right) / 2,
				y = (r.top + r.bottom) / 2;
			var pointElement = document.elementFromPoint(x, y);
			var isParentVisible = (pointElement !== null && (pointElement.parentElement === element))
			return ((pointElement === element) || (isParentVisible));
		};
	for (var i = 0, l = rects.length; i < l; i++) {
		var r = rects[i],
			in_viewport = r.top > 0 ? r.top <= height : (r.bottom > 0 && r.bottom <= height);
		if (in_viewport && on_top(r)) return true;
	}
	return false;
}

function EGW_detectATCButton() {
    var atcButtonSelectors = [
        '*[egw-atc-override="true"]',
        '*[data-pf-type="ProductATC"]:not([disabled])',
        '*[data-instant-action-type="add-to-cart"]:not([disabled])',
        'button[class="pmpr_bundle__add_to_cart"]:not([disabled])',
        'product-payment-container:not([class*="sticky"]):not([disabled])',
        'button[class*="ProductForm__submit"]:not([disabled])',
        'product-buy-buttons-element:not([disabled])',
        '*[class*="cowlendar-btn"]:not([disabled])',
        '*[class*="add AddtoCart"]:not([disabled])',
        '*[class*="barracuda-cart-addToCartButton"]:not([disabled])',
        '[upsell-hooked-add-to-cart-btn="true"]:not([disabled])',
        '[id="new-form-atc"]:not([disabled])',
        '[id*="ProductSubmitButton-"]:not([disabled])',
        '*[class*="engoj-btn-addtocart"]:not([disabled])',
	    'input[name="add"]:not([disabled])',
        'button[name="add"]:not([class*="product-bar__submit"]):not([class*="btn--small"]):not([class*="focus-inset"]):not([data-quick-add-btn]):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])',
        'button[class*="button--addToCart"]:not([disabled])',
        '*[class*="product-form--atc-button"]:not([disabled])',
        '*[class*="product__add-to-cart"]:not([disabled])',
        '*[class*="product__form-buttons"] [class*="add"]: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(img):not([aria-label*="wishlist"]):not([class*="focus-inset"]):not([data-quick-add-btn]):not([disabled])',
        '*[class*="add_to_cart"]:not([class*="complementary-atc"]):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([class*="product-bar__submit"]):not([class*="btn--small"]):not([class*="focus-inset"]):not([data-quick-add-btn]):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([class*="product-buy-buttons--cta-text"]):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])',
        '*[id="adbtn"]:not([disabled])',
        '*[class*="addToCart"]:not([disabled])',
        '*[data-add-button]:not([disabled])',
        '*[data-buy-button]:not([disabled])',
        'buy-buttons:not([disabled])',
        '*[data-product-add]:not([disabled])',
        '.quantity-submit-row__submit [class*="button"]:not([disabled])',
        '*[class*="f8pr-buy-button"]:not([disabled])'
    ];

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

        if (elementSearchResult !== null && elementSearchResult.innerText.toLowerCase().indexOf('sold out') === -1) {
            return elementSearchResult;
        }
    }

    return null;
}

function EGW_listenForCartChanges() {
    var giftMessageProductFound = false;
    if ('' === '') {
        giftMessageProductFound = true;
    }

    var giftWrapProductFound = false;
    var currentGiftOptions = JSON.parse(EGW_getLsWithExpiry("effective_apps_egw_rc_options_LS"));

    jQuery.getJSON('/cart.js').done(function(data) {
        for (var item of data['items']) {
            if (item["product_id"].toString() === 'None') {
                giftWrapProductFound = true;
            }

            if (item["product_id"].toString() === 'None') {
                giftMessageProductFound = true;
            }
        }

        if (giftMessageProductFound === false && currentGiftOptions["effectiveAppsEgwGiftMessage"] === true) {
        	currentGiftOptions["effectiveAppsEgwGiftMessage"] = false;
        	if ("1" === "1") {
        	    jQuery.post('/cart/update.js',{attributes: {'Gift Message': null} }, null, "json");
        	}
        	else {
        	    jQuery.post('/cart/update.js',{note: "" }, null, "json");
        	}

        	EGW_setLsWithExpiry("effective_apps_egw_rc_options_LS", JSON.stringify(currentGiftOptions), 600000);
        }

        if (giftWrapProductFound === false && currentGiftOptions["effectiveAppsEgwGiftWrap"] === true) {
        	var attributesDict = {};
        	if (window.effectiveAppsGwOptions["gift_wrap_options"].length > 1) {
                for (var giftOption of window.effectiveAppsGwOptions["gift_wrap_options"]) {
                    attributesDict[giftOption["gw_title"]] = null;
                }
            }
            else {
                attributesDict[window.effectiveAppsGwLabelText] = null;
            }

        	currentGiftOptions["effectiveAppsEgwGiftWrap"] = false;
        	if (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftWrapSelectedVariantId")) {
                delete currentGiftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]
        	}

            if ("1" === "1") {
                jQuery.post('/cart/update.js', {attributes: attributesDict }, null, "json");
            }
        	else {
                let giftOptionsNote = generateCartGiftOptionsNote(currentGiftOptions);
                jQuery.post('/cart/update.js',{note: giftOptionsNote }, null, "json");
            }

        	EGW_setLsWithExpiry("effective_apps_egw_rc_options_LS", JSON.stringify(currentGiftOptions), 600000);
        }

        if (false === shouldGiftOptionsCBBeTicked(currentGiftOptions)) {
            if (document.getElementById('effectiveAppsEGWATC') !== null) {
                document.getElementById('effectiveAppsEGWATC').checked = false;
                if (document.getElementById('egw_options_atc') !== null) {
                    jQuery("#egw_options_atc").fadeOut();
                    if (document.querySelector('input[name="effective_apps_gw_option"]:checked') !== null) {
                        document.querySelector('input[name="effective_apps_gw_option"]:checked').checked = false;
                    }
                }
            }

            if (document.getElementById('effectiveAppsEGW') !== null) {
                document.getElementById('effectiveAppsEGW').checked = false;
                if (document.getElementById('egw_options') !== null) {
                    jQuery("#egw_options").fadeOut();
                    if (document.querySelector('input[name="effective_apps_gw_option"]:checked') !== null) {
                        document.querySelector('input[name="effective_apps_gw_option"]:checked').checked = false;
                    }
                }
            }

            clearInterval(window.EFFECTIVE_APPS_EGW_CART_CHANGE_LISTENER);
        }

	});
}

function shouldGiftOptionsCBBeTicked(currentGiftOptions=null) {
    if (currentGiftOptions === null) {
        currentGiftOptions = JSON.parse(EGW_getLsWithExpiry("effective_apps_egw_rc_options_LS"));
        if (currentGiftOptions === null) {
            return false;
        }
    }

    return (
        (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftMessage") && currentGiftOptions["effectiveAppsEgwGiftMessage"] === true) ||
        (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftWrap") && currentGiftOptions["effectiveAppsEgwGiftWrap"] === true) ||
        (currentGiftOptions.hasOwnProperty("effectiveAppsEgwGiftReceipt") && currentGiftOptions["effectiveAppsEgwGiftReceipt"] === true)
    );
}

function EGW_detectCheckoutButton(isCartPage=false) {
	var resultElement = null;
	var checkoutButtonSelectors = [
	    '*[egw-co-override="true"]',
	    'button[class*="icart-pg-checkout-btn"]:not([disabled])',
	    '*[name="icartCheckout"]:not([disabled])',
	    '*[id="mu-checkout-button"]:not([disabled])',
	    '*[data-type="mini-cart"][id="headless-button"]',
	    'cw-wise-cart',
	    'a[class*="upcart-checkout-button"]:not([disabled])',
	    '*[class*="_buttonsWrapper"] *[class*="picky-bundle-add-to-cart-button"]:not([disabled])',
	    '*[class*="picky-widget"] *[class*="footer"] *[class*="_buttonsWrapper_"] *[class*="picky-cart__button"]:not([disabled])',
	    '*[id="cart-form-minicart"]:not([disabled])',
	    '*[class*="qsc2-checkout-button"]:not([disabled])',
	    'button[form="cart-form"][name="checkout"]:not([disabled])',
	    'button[form="cartForm"][name="checkout"]:not([disabled])',
	    'button[form="cart-drawer-form"][name="checkout"][class*="js-cart-drawer-submit-btn"]:not([disabled])',
	    'aside .link-btn:not([class*="mobile-only"]) button:not([disabled])',
	    '*[class="gokwik-checkout"]:not([disabled])',
	    '*[id="corner-cowi-cart-summary-card-cta-button"]:not([disabled])',
	    '*[name*="checkout-route-"]:not([disabled])',
	    '*[data-ocu-checkout="true"]:not([disabled])',
	    '*[class*="rebuy-cart__checkout-button"]',
        '*[id="cart_checkout"]:not([disabled])',
		'*[name="checkout"]:not([disabled]):not([class*="product-cart-message__checkout-button"]):not([class*="product-message__btn"])',
		'*[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([href*="asset"]):not(link)',
        '*[href*="/checkout"]:not([href*="asset"]):not(link)',
		'*[onclick*="/checkout"]',
		'*[class*=satcb-cs-checkout-btn]',
        '*[class*="evm_upsell_checkout"]',
        '*[name="qbk-checkout"]',
	    '*[class="shiprocket-headless"]:not([disabled])',
        '*[class*="ymq-fake-checkout-btn"]:not([disabled])',
        '*[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="cart-checkout"]:not([disabled])',
        '*[data-href="/checkout"]:not([disabled])',
        '*[aria-label="Checkout"]:not([disabled])',
        '*[aria-label="checkout"]:not([disabled])',
	];
	var cartFormSelectors = [
		'input[type="submit"]:not([disabled])',
		'input[type="button"]:not([disabled])'
	];

	for (var selector of checkoutButtonSelectors) {
		var elementSearchResult = document.querySelectorAll(selector);
		if (elementSearchResult.length > 1 && window.EGW_THEME_NAME.indexOf('dawn') === -1) {
		    if (selector === '*[id="cart-form-minicart"]:not([disabled])') {
		        return elementSearchResult[0];
		    }

		    if (elementSearchResult[1].getAttribute('egw-ignore') === "true") {
		        continue;
		    }

		    if (window.EGW_THEME_NAME.indexOf('shapes') > -1 && isCartPage === true) {
		        return elementSearchResult[0];
		    }

		    if (elementSearchResult[1].hasOwnProperty('href')) {
		        if (elementSearchResult[1].getAttribute('href').indexOf("/front_end/login") > -1) {
		            continue;
		        }
		    }

			return elementSearchResult[1];
		} else if (elementSearchResult.length > 0) {
		    if (elementSearchResult[0].getAttribute('egw-ignore') === "true") {
		        continue;
		    }
		    if (elementSearchResult[0].hasOwnProperty('href')) {
		        if (elementSearchResult[0].getAttribute('href').indexOf("/front_end/login") > -1) {
		            continue;
		        }
		    }

            if (window.EGW_THEME_NAME.indexOf('dawn') > -1 && isCartPage === true && elementSearchResult.length > 1) {
                return elementSearchResult[1];
            }

			return elementSearchResult[0];
		}
	}

	var cartFormElement = document.querySelector('form[action="/cart"]');
	if (cartFormElement !== null) {
		for (var selector of cartFormSelectors) {
			var element = cartFormElement.querySelector(selector);
			if (element !== null) {
                if (element.getAttribute('egw-ignore') === "true") {
                    continue;
                }

				return element;
			}
		}
	}

	return null;
}

function EGW_waitForCartDrawer() {
	if (document.getElementById('effectiveAppsEGW') !== null) {
		return;
	}

    var atcButtonElement = null;
    if ('True' === 'True' && location.pathname.indexOf('/products') > -1) {
        atcButtonElement = EGW_detectATCButton();
    }

    if (atcButtonElement !== null) {
        if (window.effectiveAppsEgwSp.length > 0) {
            const productId = (typeof ShopifyAnalytics !== "undefined" && ShopifyAnalytics.meta && ShopifyAnalytics.meta.product && ShopifyAnalytics.meta.product.id ? ShopifyAnalytics.meta.product.id.toString() : null);
            if (productId !== null && window.effectiveAppsAllowedProducts.indexOf(productId) > -1) {
                EGW_attachToATC(atcButtonElement);
            }
        }
        else {
            EGW_attachToATC(atcButtonElement);
        }
    }

	var checkoutButtonElement = EGW_detectCheckoutButton();
	if ('True' === 'False' || checkoutButtonElement === null) {
		return;
	}

	if (EGW_isElementVisible(checkoutButtonElement) === true) {
		if (window.effectiveAppsEgwSp.length > 0) {
            jQuery.getJSON('/cart.js').done(function(data) {
                for (var item of data['items']) {
                    if (window.effectiveAppsAllowedProducts.indexOf(item["product_id"].toString()) > -1) {
                        EGW_attachToCart(true);
                        break;
                    }
                }
            });
        }
        else {
            EGW_attachToCart(true);
        }
	}
}

function EGW_attachToATC(atcElementToAttachTo) {
    if (document.getElementById('effectiveAppsEGWATC') !== null) {
        return;
    }
	if (null === atcElementToAttachTo) {
		return;
	}

    var insertionType = 'afterbegin';
	var elementContainer = atcElementToAttachTo.parentElement;
	var checkboxElement = document.createElement('p');
	checkboxElement.innerHTML = window.effectiveAppsEgwText.replaceAll('effectiveAppsEGW', 'effectiveAppsEGWATC').replaceAll('egw_options', 'egw_options_atc').replaceAll('updateRemainingCharacters', 'updateRemainingCharactersATC').replaceAll('effectiveAppsEgwGiftMessageText', 'effectiveAppsEgwGiftMessageTextATC').replaceAll('effectiveAppsEgwGiftMessageRC', 'effectiveAppsEgwGiftMessageRCATC').replaceAll('updateGiftMessageStatus', 'updateGiftMessageStatusATC');
    if ('' !== '' && '' !== 'openModal') {
        checkboxElement.innerHTML = '<div class="">' + checkboxElement.innerHTML + '</div>';
    }
	if (window.EGW_THEME_NAME.indexOf("brooklyn") > -1 || window.EGW_THEME_NAME.indexOf("minimal") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("blockshop") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("corano") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("sitar") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("sahara") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("pipeline") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("kingdom") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("ecommax") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf('maker') > -1) {
        window.EFFECTIVE_APPS_EGW_CUSTOM_CSS += '[for="effectiveAppsEGWATC"] img { all: unset !important; } [for="effectiveAppsEGW"] img { all: unset !important; } #effectiveAppsEgwModalImage img { all: unset !important; }';
    }

    if (window.EGW_THEME_NAME.indexOf("m&j website") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("sleek") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME === "kp") {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("cornerstone") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("motion") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("enterprise") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("wokiee") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("fastor") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("broadcast") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("blum") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("north") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("plantza") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("xtra") > -1) {
        elementContainer = atcElementToAttachTo
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("split") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("be yours") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("eva") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("local") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("yuva") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("meroxio") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("reformation") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("andaman") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("vegist") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("beyond") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("trademark") > -1 || window.EGW_THEME_NAME.indexOf("avone") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("minimog") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("woodstock") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("decorks") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("flex") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("simple") > -1) {
        elementContainer = atcElementToAttachTo.parentElement;
        if ("" === "openModal" || "" === "") {
            checkboxElement.innerHTML = checkboxElement.innerHTML.replace('display:inline', 'display:block');
        }
        else {
            checkboxElement.innerHTML = checkboxElement.innerHTML.replace('class=""', 'class="" style="display: block;"');
        }
    }

    if (window.EGW_THEME_NAME.indexOf("booster-6.0.5") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("boost") > -1 && window.EGW_THEME_NAME.indexOf("booster-6.0.5") === -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("turbo") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("icon") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("empire") > -1) {
        insertionType = 'beforebegin';
    }

    if (atcElementToAttachTo.getAttribute('data-pf-type') === 'ProductATC') {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo;
    }

    if (atcElementToAttachTo.getAttribute('class') === 'pmpr_bundle__add_to_cart') {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo;
    }

    if (atcElementToAttachTo.getAttribute('data-instant-action-type') === 'add-to-cart') {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo;
    }

    if (window.EGW_THEME_NAME.indexOf("flex") > -1) {
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("august") > -1) {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("emerge") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("parallax") > -1) {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo.parentElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("kalles") > -1) {
        insertionType = 'beforebegin';
        elementContainer = atcElementToAttachTo.parentElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("warehouse") > -1) {
        insertionType = 'beforebegin';
    }

    if (window.EGW_THEME_NAME.indexOf("drop") > -1) {
        insertionType = "beforebegin";
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("themekit template") > -1) {
        insertionType = "beforebegin";
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("atlantic") > -1) {
        insertionType = "beforebegin";
        elementContainer = atcElementToAttachTo;
    }

    if (window.EGW_THEME_NAME.indexOf("canopy") > -1) {
        insertionType = "beforebegin";
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("habitat") > -1) {
        insertionType = "beforebegin";
        elementContainer = atcElementToAttachTo.parentElement.parentElement;
    }

	elementContainer.insertAdjacentHTML(insertionType, checkboxElement.innerHTML);
	if (shouldGiftOptionsCBBeTicked() === true) {
        document.getElementById('effectiveAppsEGWATC').checked = true;
        if (document.getElementById('egw_options_atc') !== null) {
            jQuery("#egw_options_atc").fadeIn();
            var savedOptions = EGW_getLsWithExpiry("effective_apps_egw_rc_options_LS");
            if (savedOptions !== null) {
                var giftOptions = JSON.parse(savedOptions);
                if (giftOptions.hasOwnProperty('effectiveAppsEgwGiftWrapSelectedVariantId') && document.querySelector('[value="'+giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]+'"]') !== null) {
                    document.querySelector('[value="'+giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]+'"]').checked = true;
                }
                if (document.getElementById('effectiveAppsEgwGiftMessageTextATC') !== null) {
                    document.getElementById('effectiveAppsEgwGiftMessageTextATC').value = giftOptions["effectiveAppsEgwGiftMessageText"];
                    updateRemainingCharactersATC();
                }
            }
        }
        if (window.EFFECTIVE_APPS_EGW_CART_CHANGE_LISTENER === undefined) {
            window.EFFECTIVE_APPS_EGW_CART_CHANGE_LISTENER = setInterval(EGW_listenForCartChanges, 1000);
        }
    }
    else {
        document.getElementById('effectiveAppsEGWATC').checked = false;
    }

	window.effectiveAppsEGWSuccessfullyAttachedToATC = true;
}

function EGW_attachToCart(isCartDrawer = false) {
    if (document.getElementById('effectiveAppsEGW') !== null) {
        return;
    }

	var isCartPage = (typeof ShopifyAnalytics !== "undefined" && ShopifyAnalytics.meta && ShopifyAnalytics.meta.page && ShopifyAnalytics.meta.page.pageType === "cart") || (typeof location !== "undefined" && location.pathname && location.pathname.indexOf('/cart') === 0);
	if (isCartDrawer === false && isCartPage === false) {
		window.EFFECTIVE_APPS_EGW_CART_LISTENER = setInterval(EGW_waitForCartDrawer, 500);
		return;
	}

	if (window.effectiveAppsEgwSp.length > 0) {
        jQuery.getJSON('/cart.js').done(function(data) {
            for (var item of data['items']) {
                if (window.effectiveAppsAllowedProducts.indexOf(item["product_id"].toString()) > -1) {
                    EGW_attachToCartPage(isCartPage);
                    break;
                }
            }
        });
    }
    else {
        EGW_attachToCartPage(isCartPage);
    }
}

function EGW_attachToCartPage(isCartPage) {
    if ('True' === 'False') {
        return;
    }

    var checkboxElement = document.createElement('p');
    var insertionType = "beforeelement";
	checkboxElement.innerHTML = window.effectiveAppsEgwText;
    if ('' !== '' && '' !== 'openModal') {
        checkboxElement.innerHTML = '<div class="">' + checkboxElement.innerHTML + '</div>';
    }
	var checkoutButtonElement = EGW_detectCheckoutButton(isCartPage);
	if (null === checkoutButtonElement) {
		return;
	}

	let elementContainer = checkoutButtonElement.parentElement;
	if (window.EGW_THEME_NAME.indexOf('debut') > -1 || window.EGW_THEME_NAME.indexOf('express') > -1) {
		elementContainer = checkoutButtonElement.parentElement.parentElement;
	}

	if (window.EGW_THEME_NAME.indexOf('dawn') > -1 || window.EGW_THEME_NAME.indexOf('taste') > -1 || window.EGW_THEME_NAME.indexOf('studio') > -1 || window.EGW_THEME_NAME.indexOf('craft') > -1 || window.EGW_THEME_NAME.indexOf('crave') > -1 || window.EGW_THEME_NAME.indexOf('sense') > -1) {
	    if (isCartPage !== true) {
	        elementContainer = checkoutButtonElement.parentElement.parentElement;
	    }
        else {
            insertionType = "beforebegin";
        }
    }

    if (window.EGW_THEME_NAME.indexOf('maker') > -1) {
        elementContainer = checkoutButtonElement.parentElement.parentElement;
        checkboxElement.innerHTML = '<div style="width: 100%;">' + checkboxElement.innerHTML + '</div>';
    }

    if (window.EGW_THEME_NAME.indexOf("simple") > -1) {
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("drop") > -1 || window.EGW_THEME_NAME.indexOf('shrine') > -1 || window.EGW_THEME_NAME.indexOf("district") > -1 || window.EGW_THEME_NAME.indexOf("aurora") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("ecommax") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("modular") > -1) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement;
    }

    if (window.EGW_THEME_NAME.indexOf("impact") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("combine") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("sleek") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("blum") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("vision") > -1 && isCartPage !== true) {
        elementContainer = checkoutButtonElement.parentElement.parentElement;
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("local") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("atlantic") > -1) {
        insertionType = "beforebegin";
        if (isCartPage === false) {
            elementContainer = checkoutButtonElement.parentElement.parentElement;
        }
    }

    if (window.EGW_THEME_NAME.indexOf("capital") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
        checkboxElement.innerHTML = checkboxElement.innerHTML.replace('display:inline', 'display:block');
    }

    if (window.EGW_THEME_NAME.indexOf("kalles") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
    }

    if (location.pathname.indexOf('apps/giftregistry') > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("xtra") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("envy") > -1) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('satcb-cs-checkout-btn')) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('picky-bundle-add-to-cart-button')) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('icart-pg-checkout-btn')) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.getAttribute('id') === 'corner-cowi-cart-summary-card-cta-button') {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('cd-cart-checkout-button')) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('rebuy-cart__checkout-button')) {
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.classList.contains('upcart-checkout-button')) {
        elementContainer = checkoutButtonElement.parentElement.parentElement;
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.getAttribute('data-ocu-checkout') !== null) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("label") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("editions") > -1 && isCartPage === true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("themekit template") > -1) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement;
    }

    if (window.EGW_THEME_NAME.indexOf("shapes") > -1) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("blockshop") > -1) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("be yours") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("motion") > -1 && isCartPage === false) {
        elementContainer = checkoutButtonElement;
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("fastlane") > -1) {
        elementContainer = checkoutButtonElement;
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("ella") > -1 && window.EGW_THEME_NAME.indexOf('shella') === -1) {
        insertionType = "beforebegin";
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("plantza") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("emerge") > -1) {
        elementContainer = checkoutButtonElement.parentElement.parentElement;
    }

    if (window.EGW_THEME_NAME.indexOf("showcase") > -1 && isCartPage !== true) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("symmetry") > -1) {
        insertionType = "beforebegin";
    }

    if (window.EGW_THEME_NAME.indexOf("warehouse") > -1) {
        insertionType = 'beforebegin';
        if (isCartPage === true) {
            elementContainer = checkoutButtonElement;
        }
    }

    if (checkoutButtonElement.getAttribute('id') !== null && checkoutButtonElement.getAttribute('id').indexOf("mu-checkout-button") > -1) {
        elementContainer = checkoutButtonElement;
        insertionType = "beforebegin";
    }

    if (checkoutButtonElement.tagName !== undefined && checkoutButtonElement.tagName === 'CW-WISE-CART' && checkoutButtonElement.shadowRoot) {
        if (checkoutButtonElement.shadowRoot.getElementById('effectiveAppsEGW') !== null && checkoutButtonElement.shadowRoot.getElementById('effectiveAppsEGW') !== undefined) {
            return;
        }

        let shadowRootStyle = document.createElement('style');
        shadowRootStyle.type = 'text/css';
        shadowRootStyle.appendChild(document.createTextNode('.effectiveAppsEGWImage {display: inline !important;}[for="effectiveAppsEGW"]{padding-bottom: 20px; display: block!important; }'));
        document.querySelector('cw-wise-cart').shadowRoot.appendChild(shadowRootStyle);
        checkoutButtonElement.shadowRoot.querySelector('[style*="z-index"]').style.zIndex -= 1;
        checkoutButtonElement = checkoutButtonElement.shadowRoot.querySelector('[class*="cart--checkout-button"]')
        elementContainer = checkoutButtonElement.parentElement;
        insertionType = "beforebegin";
    }

    if (document.getElementById('effectiveAppsEGW') !== null && document.getElementById('effectiveAppsEGW') !== undefined) {
        return;
    }

    if (insertionType === "beforebegin") {
        elementContainer.insertAdjacentHTML('beforebegin', checkboxElement.innerHTML);
    }
    else {
	    elementContainer.innerHTML = checkboxElement.innerHTML + elementContainer.innerHTML;
    }

	if (shouldGiftOptionsCBBeTicked() === true) {
        document.getElementById('effectiveAppsEGW').checked = true;
        if (document.getElementById('egw_options') !== null) {
            jQuery("#egw_options").fadeIn();
            var savedOptions = EGW_getLsWithExpiry("effective_apps_egw_rc_options_LS");
            if (savedOptions !== null) {
                var giftOptions = JSON.parse(savedOptions);
                if (giftOptions.hasOwnProperty('effectiveAppsEgwGiftWrapSelectedVariantId') && document.querySelector('[value="'+giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]+'"]') !== null) {
                    document.querySelector('[value="'+giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]+'"]').checked = true;
                }
                if (document.getElementById('effectiveAppsEgwGiftMessageText') !== null) {
                    document.getElementById('effectiveAppsEgwGiftMessageText').value = giftOptions["effectiveAppsEgwGiftMessageText"];
                    updateRemainingCharacters();
                }
            }
        }
        if (window.EFFECTIVE_APPS_EGW_CART_CHANGE_LISTENER === undefined) {
            window.EFFECTIVE_APPS_EGW_CART_CHANGE_LISTENER = setInterval(EGW_listenForCartChanges, 1000);
        }
    }
    else {
        document.getElementById('effectiveAppsEGW').checked = false;
    }

	if ('' === 'openModal' && location.pathname.indexOf('/cart') === 0 && shouldGiftOptionsCBBeTicked() === false) {
	    document.getElementById('effectiveAppsEGW').click();
    }

	window.effectiveAppsEGWSuccessfullyAttachedToCart = true;
}

// ---- cart options ----

function submitCartUpdates(giftOptions, validateAddition=true, isFromUpdateGiftMessage=false) {
    effectiveAppsSelectedGwVariantId = '0';
    effectiveAppsSelectedGmVariantId = '0';
    var attributesUpdates = {};
    var quantityUpdates = {};
    var quantityUpdatesItems = [];
    var shouldReload = false;
    if ('True' === 'True') {
        if (giftOptions.hasOwnProperty('effectiveAppsEgwGiftMessage') && giftOptions['effectiveAppsEgwGiftMessage'] === true) {
            attributesUpdates['Gift Message'] = giftOptions['effectiveAppsEgwGiftMessageText'];
            if (parseFloat('0.0') > 0 && effectiveAppsSelectedGmVariantId.length > 1) {
                shouldReload = true;
                quantityUpdates[parseInt(effectiveAppsSelectedGmVariantId)] = 1;
                quantityUpdatesItems.push(parseInt(effectiveAppsSelectedGmVariantId));
            }
        }
        else {
            attributesUpdates['Gift Message'] = null;
            if (effectiveAppsSelectedGmVariantId.length > 1) {
                shouldReload = true;
                quantityUpdates[parseInt(effectiveAppsSelectedGmVariantId)] = 0;
            }
        }
    }

    else if ('False' === 'True') {
        if (giftOptions.hasOwnProperty('effectiveAppsEgwGiftReceipt') && giftOptions['effectiveAppsEgwGiftReceipt'] === true) {
            attributesUpdates['Gift Receipt'] = "✓";
        }
        else {
            attributesUpdates['Gift Receipt'] = null;
        }
    }

    else if ('False' === 'True') {
        shouldReload = true;
        if (giftOptions.hasOwnProperty('effectiveAppsEgwGiftWrap') && giftOptions['effectiveAppsEgwGiftWrap'] === true) {
            if (window.effectiveAppsGwOptions["gift_wrap_options"].length > 1) {
                for (var giftOption of window.effectiveAppsGwOptions["gift_wrap_options"]) {
                    if (giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"] === giftOption["gw_variant_id"]) {
                        attributesUpdates[giftOption["gw_title"]] = "✓";
                        quantityUpdates[parseInt(giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"])] = 1;
                        quantityUpdatesItems.push(parseInt(giftOptions["effectiveAppsEgwGiftWrapSelectedVariantId"]));
                    }
                    else {
                        quantityUpdates[parseInt(giftOption["gw_variant_id"])] = 0;
                        attributesUpdates[giftOption["gw_title"]] = null;
                    }
                }
            }
            else {
                attributesUpdates[window.effectiveAppsGwLabelText] = "✓";
                quantityUpdates[parseInt(effectiveAppsSelectedGwVariantId)] = 1;
                quantityUpdatesItems.push(parseInt(effectiveAppsSelectedGwVariantId));
            }
        }
        else {
            attributesUpdates[window.effectiveAppsGwLabelText] = null;
            if (window.effectiveAppsGwOptions["gift_wrap_options"].length > 1) {
                for (var giftOption of window.effectiveAppsGwOptions["gift_wrap_options"]) {
                    attributesUpdates[giftOption["gw_title"]] = null;
                    quantityUpdates[parseInt(giftOption["gw_variant_id"])] = 0;
                }
            }
            else {
                attributesUpdates[window.effectiveAppsGwLabelText] = null;
                if ('0'.length > 1) {
                    quantityUpdates[parseInt(effectiveAppsSelectedGwVariantId)] = 0;
                }
            }
        }
    }
    if ("1" === "1") {
        jQuery.post('/cart/update.js',
                    {
                        attributes: attributesUpdates,
                        updates: quantityUpdates
                    }, null, "json"
        ).always(function() {
            var didAttributesApplied = true;
            var itemsList = [];
            jQuery.getJSON('/cart.js').done(function(data) {
                for (var attribute in attributesUpdates) {
                    if (attributesUpdates[attribute] !== null && data['attributes'][attribute] !== attributesUpdates[attribute]) {
                        didAttributesApplied = false;
                        break;
                    }
                }
                for (var item in data['items']) {
                    itemsList.push(data['items'][item]['id']);
                }

                if (validateAddition === true && (didAttributesApplied === false || arraysComparison(quantityUpdatesItems, itemsList) === false)) {
                    submitCartUpdates(giftOptions)
                }
                else {
                    EGW_setLsWithExpiry("effective_apps_egw_rc_options_LS", JSON.stringify(giftOptions), 600000);
                    if (isFromUpdateGiftMessage === false && shouldReload === true && 1 === 1) {
                        location.reload();
                    }
                }
            });
        });
    }
    else {
        let giftOptionsNote = generateCartGiftOptionsNote(giftOptions);
        jQuery.post('/cart/update.js',
                    {
                        note: giftOptionsNote,
                        updates: quantityUpdates
                    }, null, "json"
        ).always(function() {
            var didNoteApplied = true;
            var itemsList = [];
            jQuery.getJSON('/cart.js').done(function(data) {
                if (data['note'].indexOf(giftOptionsNote) === -1) {
                    didNoteApplied = false;
                }

                for (var item in data['items']) {
                    itemsList.push(data['items'][item]['id']);
                }

                if (validateAddition === true && (didNoteApplied === false || arraysComparison(quantityUpdatesItems, itemsList) === false)) {
                    submitCartUpdates(giftOptions)
                }
                else {
                    EGW_setLsWithExpiry("effective_apps_egw_rc_options_LS", JSON.stringify(giftOptions), 600000);
                    if (isFromUpdateGiftMessage === false && shouldReload === true && 1 === 1) {
                        location.reload();
                    }
                }
            });
        });
    }
}

function arraysComparison(arr, arr2) {
  return arr.every(i => arr2.includes(i));
}

function encode(r) {
  return r.replace(/[\x26\x0A\x3c\x3e\x22\x27]/g, function(r) {
    return "&#" + r.charCodeAt(0) + ";";
  });
}

/// ------
function EGW_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 EGW_getShopifyThemeName() {
    try {
        if (window.EGW_THEME_NAME_OVERRIDE !== undefined) {
            return window.EGW_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 EGW_mainLoader() {
    window.EGW_THEME_NAME = EGW_getShopifyThemeName();
    if (window.EGW_THEME_NAME.indexOf('prestige') > -1 || window.EGW_THEME_NAME.indexOf('fashionopolism') > -1 || window.EGW_THEME_NAME.indexOf('mr parker') > -1) {
        setTimeout(EGW_main, 1200);
    }
    else {
        EGW_main();
    }
}

function EGW_main() {
    console.log('%c------ Super Gift Options by Effective Apps is Initializing (Regular) ------', 'color: cyan');
    console.log('%c------ Contact us at support@effectify.co for help and questions about the app ------', 'color: cyan');
	if (window.EGW_SCRIPT_INJECTED === undefined) {
	    window.EGW_SCRIPT_INJECTED = true;
		if (typeof jQuery === 'undefined') {
            EGW_loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js', EGW_runLogic);
        }
        else {
            EGW_runLogic();
        }
	}
}

EGW_mainLoader();