"use strict"; // TODO: Minimise this so that it's injected as a minimised script. import("https://code.jquery.com/jquery-3.4.1.min.js") .then(() => { var treeQuantity = 0; // Html selector to insert frame depending on theme const AFTER_IDENTIFIERS = [ ".cart-items", // Default ".cart-table", // Venture theme ]; const BEFORE_IDENTIFIERS = [ ".cart__footer", // Bath Fairy ]; // Debugging set-up const logging = true; const enable_debugging = true; function logError(msg) { log(msg, "error"); } function debug(msg) { if (enable_debugging) { log(msg, "debug"); } } function log(msg, type = "info") { if (logging) { if (type == "error") { console.error(new Date().toString(), type.toUpperCase() + ": " + msg); } else { console.log(new Date().toString(), type.toUpperCase() + ": " + msg); } } } log(jQuery); jQuery(document).ready(function () { // Only insert block once if ($(".skoot-planting-frame").length) return; $("head").append(``); // Create app block log("attempting to append block"); const planting_block = `
Small planted tree

We plant 1 tree every order to help offset emissions

We’ll use your email address to create your own Impact Profile page where you can view of all of the trees you have planted. See an example here.
Offset by planting a tree for 68p.
Planted with SKOOT
Make your order more sustainable We’ll match every extra tree you plant Planted with SKOOT We’ve helped plant - trees
`; function identifier_exists(identifiers) { // Iterate identifiers and return identifier if exists for (let i = 0; i < identifiers.length; i++) { if ($(identifiers[i]).length) return identifiers[i]; } } // Insert block let identifier; if ((identifier = identifier_exists(AFTER_IDENTIFIERS)) !== undefined) { $(identifier).after(planting_block); // Default } else if ( (identifier = identifier_exists(BEFORE_IDENTIFIERS)) !== undefined ) { $(identifier).before(planting_block); // Bath Fairy } else { log("No block identifiers found"); return; } // Handle tree planting button const addToCartButton = $("#skoot-plant"); addToCartButton.off(); addToCartButton.bind("click", handlePlanting); fetch("/cart.js", { method: "GET", }) .then((response) => response.json()) .then((data) => { // Check if tree was added to cart let treePlantedAlready = false; data.items.forEach((element) => { // variant_id is a number, the handlebars is a number wrapped as a string if (element.variant_id == "39691071062102") { treePlantedAlready = true; // Return quantity treeQuantity = element.quantity; // call the quantity update function now... not before updatetotalQuantity(); } }); // Disable button once first tree is added to the cart if (treePlantedAlready) { addToCartButton.addClass("disabled"); addToCartButton.html("Extra trees added"); } else { addToCartButton.removeClass("disabled"); addToCartButton.html("Plant an extra tree for £0.99"); } }) .catch((error) => { logError(error); }); totalCount(); // Forest checkbox const forestCheckbox = document.querySelector("#skoot-checkbox"); const inMyForest = sessionStorage.getItem("InMyForest"); if (inMyForest) { forestCheckbox.checked = true; } forestCheckbox.addEventListener("change", function () { if (this.checked) { setInMyForest(); } else { unsetInMyForest(); } }); function setInMyForest() { sessionStorage.setItem("InMyForest", true); //jQuery.post("/cart/update.js", { attributes: { InMyForest: 1 } }, null, 'json'); fetch("/cart/update.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ attributes: { InMyForest: 1 } }), }) .catch((error) => { logError(error); }); } function unsetInMyForest() { sessionStorage.removeItem("InMyForest"); //jQuery.post("/cart/update.js", { attributes: { InMyForest: 0 } }, null, 'json'); fetch("/cart/update.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ attributes: { InMyForest: 0 } }), }) .catch((error) => { logError(error); }); } function totalCount() { // Fetch total trees planted by shop fetch("/apps/forest/61e04362caaefb398e26b8f9/count", { method: "GET", }) .then((response) => { if (response.ok) return response.json(); }) .then((data) => { var treeCount = 0; if (data) { treeCount = data.tree_count.toLocaleString("en"); } else { treeCount = "-"; } document .querySelectorAll(".skoot-shop-tree-count") .forEach((element) => (element.innerHTML = treeCount)); }) .catch((error) => { logError(error); }); } function updatetotalQuantity() { // TODO: Update to use the configuration set: // const DEFAULT_TREE_COUNT = 1; // const DEFAULT_MATCHED_TREES = 5; var quantity = 0; const treeMatching = true; // Store defaults (TODO: from config) const treesPerOrder = 1; // TODO: setup logic for trees per product const treesPerProduct = 0; if (treeQuantity) { if (treeMatching) { quantity = +2 * treeQuantity; } else { quantity = treeQuantity; } } quantity += treesPerOrder; document.getElementById( "skoot-planting-order-total" ).innerHTML = quantity; } // low jack the fetch so we can listen to the cart const original_fetch = fetch; fetch = function (url, options) { /* logic that notifies your plugin goes here */ if (url.includes("/cart/change")) { handleCartChange(options); } return original_fetch(url, options).then((response) => { return response; }); }; // low jack xhr requests (function (send) { XMLHttpRequest.prototype.send = function (body) { var callback = this.onreadystatechange; this.onreadystatechange = function () { if (this.readyState == 4) { var responseURL = this.responseURL; // If tree variant in cart, update quantity if (responseURL.match(/.*\/cart\/change.*/g)) { //TODO: fix & test for ajax themes } } if (callback) { callback.apply(this, arguments); } }; send.apply(this, arguments); }; })(XMLHttpRequest.prototype.send); function handlePlanting(event) { event.preventDefault(); let formData = { items: [ { id: "39691071062102", quantity: 1, }, ], }; setInMyForest(); fetch("/cart/add.js", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }) .then((response) => location.reload()) .catch((error) => { logError(error); }); } }); }) .catch((error) => logError(error));