Untitled

 avatar
unknown
plain_text
2 years ago
12 kB
6
Indexable
(function () {
  try {
    var debug = 1;
    var variation_name = "";
    var testData = {
      cards: [
        {
          "img": "https://expogrowth.in/wp-content/uploads/2023/08/Thumbnail.svg",
          "title": "Mix & Match to Save 25%",
          "titleLink": "https://www.gracobaby.com/bundles/",
          "para": "25% Off 3 Items",
          "promoCode": "BUNDLE3",
          "ctaLink": ""
        },
        {
          "img": "https://expogrowth.in/wp-content/uploads/2023/08/Thumbnail.svg",
          "title": "Bundle & Save",
          "titleLink": "https://www.gracobaby.com/graco-premier/graco-premier-midtown-collection/",
          "para": "25% Off 2 Graco Premier Items",
          "promoCode": "PREMIERBUNDLE",
          "ctaLink": ""
        },
        {
          "img": "https://expogrowth.in/wp-content/uploads/2023/08/Thumbnail.svg",
          "title": "Up to 30% Off",
          "titleLink": "https://www.gracobaby.com/featured-promotions",
          "para": "30% Off Car Seats, Strollers, Travel Systems & Home",
          "promoCode": "",
          "ctaLink": "https://www.gracobaby.com/featured-promotions"
        }
      ],
      "icons": {
        applied: "https://expogrowth.in/wp-content/uploads/2023/08/success-hover.svg",
        success: "https://expogrowth.in/wp-content/uploads/2023/08/success-hover.svg",
        arrow: "https://svgshare.com/i/wH6.svg",
        moneyIcon: "https://svgshare.com/i/wGt.svg"
      }
    }
    var genCards = function () {
      const cards = testData.cards;
      console.log("hello")
      const cardsHTML = cards.reduce((t, crd) => {
        let buttons = "";
        if (crd.promoCode !== "") {
          buttons = ` <button class="eg-cta" data-cpn="${crd.promoCode}">Apply Offer</button>
                      <button class="eg-cta eg-remove-cta eg-hidden-default">
                        <img src="${testData.icons.applied}">&nbsp;&nbsp;Applied&nbsp;&nbsp;<span class="remove-text">Remove</span>
                      </button>`
        } else {
          buttons = `<button class="eg-cta" data-rd-url="${crd.ctaLink}">Visit Now</button>`;
        }
        return t += `
        <div class="eg-slide">
          <div class="eg-uppr-part">
            <div class="eg-img"><img src="${crd.img}"></div>
            <div class="eg-content">
              <a class="eg-title" href="${crd.titleLink}">${crd.title}</a>
              <span class="eg-time-left-msg eg-sub-title">${crd.para}</span>
            </div>
          </div>
          <div class="eg-btm-part">${buttons}</div>
        </div>
        `;
      }, "");
      return cardsHTML;
    }
    var cardsHTML = genCards();
    var egpopup1 = `<div class="eg-main-cta-wrapper container"> <button class="eg-main-cta eg-open-popup"> <div class="eg-img-grp"> <span class="eg-img"><img src="${testData.icons.moneyIcon}"></span> </div><span class="eg-text">Available Offers</span> <span class="eg-arrow"><img src="${testData.icons.arrow}"></span> </button> <div class="eg-wallet-popup eg-hide" aria-hidden="false"> <div class="eg-popup-container"> <div class="eg-content-box"> <div class="eg-success-msg"> <img src="${testData.icons.success}">Congratulations, you've added a coupon! </div><div class="eg-slider">${cardsHTML}</div></div></div></div></div>`;
    function waitForElement(selector, trigger, delayInterval, delayTimeout) {
      var interval = setInterval(function () {
        if (
          document &&
          document.querySelector(selector) &&
          document.querySelectorAll(selector).length > 0
        ) {
          clearInterval(interval);
          trigger();
        }
      }, delayInterval);
      setTimeout(function () {
        clearInterval(interval);
      }, delayTimeout);
    }

    function live(selector, event, callback, context) {
      function addEvent(el, type, handler) {
        if (el.attachEvent) el.attachEvent("on" + type, handler);
        else el.addEventListener(type, handler);
      }
      this.Element &&
        (function (ElementPrototype) {
          ElementPrototype.matches =
            ElementPrototype.matches ||
            ElementPrototype.matchesSelector ||
            ElementPrototype.webkitMatchesSelector ||
            ElementPrototype.msMatchesSelector ||
            function (selector) {
              var node = this,
                nodes = (node.parentNode || node.document).querySelectorAll(selector),
                i = -1;
              while (nodes[++i] && nodes[i] != node);
              return !!nodes[i];
            };
        })(Element.prototype);
      function live(selector, event, callback, context) {
        addEvent(context || document, event, function (e) {
          var found,
            el = e.target || e.srcElement;
          while (el && el.matches && el !== context && !(found = el.matches(selector))) el = el.parentElement;
          if (el && found) callback.call(el, e);
        });
      }
      live(selector, event, callback, context);
    }

    const applyCoupon = (cpn) => {
      const couponBox = document.querySelector("html body .cart-page .promo-code #couponCode");
      if (couponBox) {
        couponBox.value = cpn;
        couponBox.parentElement.querySelector('button[type="submit"]').click();
      }
    }

    const removeCoupon = () => {
      const removeCta = document.querySelector("html body .coupons-and-promos .remove-coupon");
      removeCta && removeCta.click();
    }
    const send = XMLHttpRequest.prototype.send
    XMLHttpRequest.prototype.send = function () {
      this.addEventListener('load', function () {
        if (this.responseURL.indexOf("/Cart-RemoveCouponLineItem") != -1) {
          const els = document.querySelectorAll(".eg-cpn-applied");
          els.forEach(el => {
            if (el) {
              el.classList.remove("eg-cpn-applied");
              document.querySelector(".eg-wallet-popup").classList.remove("eg-happen");
              console.log("coupon removed");
            }
          });
        } else if (this.responseURL.indexOf("/Cart-AddCoupon") != -1) {
          const searchQuery = new URL(this.responseURL).search;
          const code = searchToObject(searchQuery).couponCode;
          const els = document.querySelectorAll(`[data-cpn*="${code}"]`);
          els.forEach(el => {
            if (el) {
              const parentBox = el.closest(".eg-slide");
              parentBox.classList.add("eg-cpn-applied");
              changeMessageText("eg-wallet-popup", "Congratulations, you've added a coupon!");
              console.log("coupon applied");
            }
          });
        }
      })
      return send.apply(this, arguments)
    }
    function init() {
      if (!document.querySelector(".eg-main-cta-wrapper")) {
        document.querySelector('html body .loaded-cart').insertAdjacentHTML("beforebegin", egpopup1);
        walletEvents();
        // if any coupon applied
        ifAnyPreappliedCoupon();
        checkIfChooseItemInBag();
      }
    }
    const walletEvents = () => {
      // visit site btns click
      live('.eg-wallet-popup button[data-rd-url]', "click", function () {
        window.location.href = this.getAttribute("data-rd-url");
      });

      // open popup
      live(".eg-open-popup", "click", function () {
        document.querySelector(".eg-wallet-popup:not(.eg-sample-popup)").classList.toggle("eg-hide");
        this.classList.toggle("eg-wallet-in");
      });
      // apply cpn on click
      live(".eg-wallet-popup button[data-cpn]", "click", function () {
        const cpn = this.getAttribute("data-cpn");
        applyCoupon(cpn);
      });
      // remove cpn on click
      live(".eg-wallet-popup button[data-cpn] + .eg-remove-cta", "click", function () {
        const parentEl = this.closest(".eg-slide");
        if (parentEl) {
          removeCoupon();
        }
      });
      // add to bag 
      live('.eg-wallet-popup button[data-add-to-cart]', "click", function () {
        const pid = this.getAttribute("data-add-to-cart");
        addToCart(pid);
      });
      //remove from bag
      live('html body .eg-item-added-to-bag-choose .eg-cta.eg-remove-cta', "click", function () {
        const uuid = this.getAttribute("data-uuid");
        const removeCta = document.querySelector(`.remove-line-item button[data-uuid="${uuid}"]`);
        removeCta && removeCta.click();
        this.closest(".eg-item-added-to-bag-choose") && this.closest(".eg-item-added-to-bag-choose").classList.remove("eg-item-added-to-bag-choose");
        this.closest(".eg-happen") && this.closest(".eg-happen").classList.remove("eg-happen");
      });

    }
    const ifAnyPreappliedCoupon = () => {
      waitForElement("html body .coupons-and-promos .coupon-text", function () {
        const cCode = document.querySelector("html body .coupons-and-promos .coupon-text").getAttribute("aria-label").replace("Promo Applied", "").trim();
        const els = document.querySelectorAll(`[data-cpn*="${cCode}"]`);
        els.forEach(el => {
          if (el) {
            const parentBox = el.closest(".eg-slide");
            parentBox.classList.add("eg-cpn-applied");
            changeMessageText("eg-wallet-popup", "Congratulations, you've added a coupon!");
          }
        });
      }, 50, 15000);
    }
    function searchToObject(searchQuery) {
      var pairs = searchQuery.substring(1).split("&"),
        obj = {},
        pair,
        i;

      for (i in pairs) {
        if (pairs[i] === "") continue;

        pair = pairs[i].split("=");
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      }

      return obj;
    }
    const changeMessageText = (walletSelector, msg) => {
      [...document.querySelector(`html body .${walletSelector} .eg-success-msg`).childNodes].slice(-1)[0].textContent = msg;
      document.querySelector(`html body .${walletSelector}`).classList.add("eg-happen");
    }
    function addToCart(pid) {
      var form = new FormData();
      form.append('pid', pid);
      form.append('quantity', '1');
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          data = JSON.parse(this.responseText);
          console.log(data.pliUUID);
          console.log("added to cart");
          window.location.reload();
        }
      };
      xhttp.open("POST", "https://www.yankeecandle.com/on/demandware.store/Sites-homefragranceus-Site/en_US/Cart-AddProduct", true);
      xhttp.send(form);
    }
    const checkIfChooseItemInBag = () => {
      waitForElement(".product-grouping .line-item-name", function () {
        document.querySelectorAll(".product-grouping .line-item-name").forEach(itm => {
          if (itm) {
            const txt = itm.innerText.trim().toUpperCase();
            const removeEl = itm.closest(".card").querySelector(".remove-line-item");
            if (document.querySelector(`[data-choose-title="${txt}"]`)) {
              document.querySelector(`[data-choose-title="${txt}"]`).classList.add("eg-item-added-to-bag-choose");
              document.querySelector(`[data-choose-title="${txt}"] .eg-remove-cta`).setAttribute("data-uuid", `${removeEl.querySelector("button[data-uuid]").getAttribute("data-uuid")}`);
              changeMessageText("eg-wallet-popup.eg-sample-popup", "Congratulations, you've added a sample!");
            }
          }
        })
      }, 1000, 15000);
    }

    waitForElement('html body .loaded-cart', init, 50, 15000);
  } catch (e) {
    if (debug) console.log(e, "error in Test" + variation_name);
  }
})();

Editor is loading...