Untitled

 avatar
unknown
plain_text
2 years ago
10 kB
2
Indexable
(function () {
  if(!document.querySelector('.eg-pagination'))
  try {
    /* main variables */
    var debug = 0;
    var variation_name = "";
    var $;
    /* all Pure helper functions */

    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) {
      /****Helper Functions****/
      // helper for enabling IE 8 event bindings
      function addEvent(el, type, handler) {
        if (el.attachEvent) el.attachEvent("on" + type, handler);
        else el.addEventListener(type, handler);
      }
      // matches polyfill
      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);
      // live binding helper using matchesSelector
      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);
    }

    let paginationHTML = `
    <div class="eg-pagination">
      <button class="eg-prev">Prev</button>
      <div class="eg-pages"></div>
      <button class="eg-next">Next</button>
    </div>
`;
    let egLoader = '<div class="veil eg-loader"><div class="underlay"></div><div class="spinner" style="position: fixed;"><div class="dot1"></div><div class="dot2"></div></div></div>';
    let totalPages;
    let totalProducts = 0;
    let currentPage = 1; // Current page number
    const init = () => {
      addCss();
      updateCurrentPage();
      let totalResEl = document.querySelector("#search-result-count-label");
      if (totalResEl) {
        let crr = +totalResEl.getAttribute("data-page-num-results");
        let rst = +totalResEl.getAttribute("data-total-results");
        totalPages = Math.ceil(rst / crr);
      }
      waitForElement(".show-more", function () {
        if (!document.querySelector(".eg-pagination")) {
          document.querySelector(".show-more").insertAdjacentHTML("afterend", paginationHTML);
        }
        updatePages();
      }, 500, 15000);
    }

    const updateCurrentPage = () => {
      if (window.location.href.indexOf("start") !== -1) {
        if (sessionStorage.getItem("crrpg") !== null) {
          currentPage = Number(sessionStorage.getItem("crrpg"));
        }
      }
    }

    function updatePages() {
      const pagesContainer = document.querySelector('.eg-pages'); // Container for page numbers
      const prevButton = document.querySelector('.eg-prev'); // Previous button
      const nextButton = document.querySelector('.eg-next'); // Next button
      if (pagesContainer && prevButton && nextButton) {
        let startPage = Math.max(1, currentPage - 2); // Start page number
        let endPage = Math.min(totalPages, startPage + 4); // End page number

        let pagesHtml = '';
        for (let i = startPage; i <= endPage; i++) {
          let dataNum = (i - 1) * 24;
          pagesHtml += `<button class="eg-page ${i === currentPage ? 'active' : ''}" data-num="${dataNum}">${i}</button>`;
        }
        pagesContainer.innerHTML = pagesHtml;

        prevButton.disabled = currentPage === 1;
        nextButton.disabled = currentPage === totalPages;
        document.querySelectorAll(".eg-page").forEach(btn => {
          btn.addEventListener("click", function () {
            currentPage = parseInt(this.textContent);
            if (this.previousElementSibling) {
              generatePLPURL(Number(this.getAttribute("data-num")));
            } else {
              generatePLPURL(0);
            }
            updatePages();
          });
        });
      }
      prevButton.addEventListener('click', function () {
        if (currentPage > 1) {
          currentPage--;
          prePage();
        }
      });
      nextButton.addEventListener("click", function () {
        if (currentPage < totalPages) {
          currentPage++;
          nextPage();
        }
      });
    }

    const nextPage = () => {
      if (document.querySelector(".eg-page.active")) {
        let activePage = document.querySelector(".eg-page.active");
        let pageNum = activePage.nextElementSibling.getAttribute("data-num");
        sessionStorage.setItem("crrpg", currentPage);
        generatePLPURL(Number(pageNum));
      }
    }

    const prePage = () => {
      if (document.querySelector(".eg-page.active")) {
        let activePage = document.querySelector(".eg-page.active");
        if (activePage.previousElementSibling) {
          let pageNum = activePage.previousElementSibling.getAttribute("data-num");
          console.log("This is prev ", pageNum);
          sessionStorage.setItem("crrpg", currentPage);
          generatePLPURL(Number(pageNum));
        }
      }
    }

    const send = XMLHttpRequest.prototype.send
    XMLHttpRequest.prototype.send = function () {
      this.addEventListener('load', function () {
        if ((this.responseURL.indexOf("/Search-UpdateGrid") !== -1) || (this.responseURL.indexOf("/Search-ShowAjax") !== -1)) {
          currentPage = 1;
          sessionStorage.setItem("crrpg", currentPage);
          waitForElement('#search-result-count-label', init, 500, 15000);
        } else if (this.responseURL.indexOf("start") !== -1) {
          waitForElement('#search-result-count-label', init, 500, 15000);
        }
      })
      return send.apply(this, arguments)
    }

    const generatePLPURL = (newStartPoint) => {
      let url;
      url = window.location.href;
      // search for the pattern
      let pattern = /start=\d+&sz=\d+/;
      let match = url.match(pattern);
      if (match) {
        // replace start and sz values with desired values
        url = url.replace(pattern, `start=${newStartPoint}&sz=${newStartPoint + 24}`);
      } else {
        url = window.location.href + `?start=${newStartPoint}&sz=${newStartPoint + 24}&view=product`;
      }
      console.log(url);
      getPlpData(url, newStartPoint + 24);
    }

    const getPlpData = (url, newStartPoint) => {
      document.body.insertAdjacentHTML("beforeend", egLoader);
      let xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
          let data = this.responseText;
          let el = document.createElement("div");
          el.innerHTML = data;
          el.querySelector("#product-search-results div:first-child #search-result-count-label").classList.remove("d-none");
          el.querySelector("#product-search-results .js-selected-filter").classList.remove("d-none");
          let searchEl = el.querySelector("#product-search-results");
          if (searchEl) {
            document.querySelector("#product-search-results").innerHTML = searchEl.innerHTML;
            // document.querySelector("#product-search-results div:first-child #search-result-count-label").innerText = "Showing " + newStartPoint + " of " + document.querySelector("#product-search-results div:first-child #search-result-count-label").getAttribute("data-total-results");
            console.log("data updated");
            document.querySelector(".eg-loader").remove();
          }
        }
      };
      xhttp.open("GET", url, true);
      xhttp.send();
    }

    waitForElement('#search-result-count-label', init, 50, 15000);
    


function addCss(targetElem) {
    var link = document.createElement("style"),
        styles = `.eg-pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 20px 0;
        }
        
        .show-more button {
            display: none !important;
        }
        
        .eg-pages {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .eg-page {
            background-color: white;
            border: none;
            padding: 8px 16px;
            margin: 0 4px;
            cursor: pointer;
        }
        
        .eg-page:hover {
            background-color: #4e616a;
            color: white;
        }
        
        .eg-page.active {
            background-color: #4e616a;
            color: #fff;
        }
        
        .eg-prev,
        .eg-next {
            background-color: #4e616a;
            border: none;
            color: #fff;
            padding: 8px 16px;
            margin: 0 4px;
            cursor: pointer;
        }
        
        .eg-prev[disabled],
        .eg-next[disabled] {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        @media(min-width:768px) {
            html body .eg-loader {
                position: fixed !important;
            }
        }
        
        @media(max-width:460px) {
            .eg-pagination {
                font-size: 60% !important;
            }
        
            .eg-pagination button {
                padding: 6px 13px !important;
            }
        
            .product-search-grid {
                margin-left: 0 !important;
                margin-right: 0 !important;
            }
        }`;

    link.innerHTML = styles;

    targetElem = targetElem || document.querySelector("head");

    targetElem.appendChild(link);
}
  } catch (e) {
    if (debug) console.log(e, "error in Test" + variation_name);
  }
})();


Editor is loading...