window.pdUserSession = {"provider":"bigcommerce","token":"","hint":[],"source":"client"}; pdLog('pdUserSession error:', ["token_missing"]); //************************************************ //********** GLOBAL PD/ONE VARIABLES ************* //************************************************ //************************************************ //************ JS/CSS FILE ROUTINES ************* //************************************************ function pdLoadJsCssFile(filename, filetype){ if (filetype=="js") { var fileref=document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("async",true); fileref.setAttribute("src", filename); } else if (filetype=="css") { var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); } if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref); } function pdLog() { if (window.pdDebug && window.console && console.log) { console.log.apply(console, arguments); } } function pdDebugLog() { if (window.console && console.log) { console.log.apply(console, arguments); } } // Some storefront scripts assume event.target.closest(...) exists, but click targets can be text nodes. if (typeof window !== 'undefined' && window.Node && window.Element && !window.Node.prototype.closest) { window.Node.prototype.closest = function(selector) { if (!selector) return null; if (this.nodeType === 1 && window.Element.prototype.closest) { return window.Element.prototype.closest.call(this, selector); } var parent = this.parentElement || this.parentNode; if (!parent) return null; if (parent.nodeType === 1 && window.Element.prototype.closest) { return window.Element.prototype.closest.call(parent, selector); } return null; }; } //************************************************ //*** UTILITY TO EXECUTE SCRIPTS IN A CONTAINER *** //************************************************ function pdRunScriptsIn(element) { if (!element) return; var targetDocument = element.ownerDocument || document; var targetWindow = targetDocument.defaultView || window; if (!targetWindow.__pdExecutedScriptsSet) targetWindow.__pdExecutedScriptsSet = new Set(); var scripts = element.querySelectorAll('script'); pdLog('pdRunScriptsIn: found', scripts.length, 'script tag(s) inside injected content.'); scripts.forEach(function(originalScript, idx) { var signature = originalScript.src ? 'src:' + originalScript.src : 'inline:' + (originalScript.textContent || '').trim(); if (targetWindow.__pdExecutedScriptsSet.has(signature)) { pdLog('pdRunScriptsIn: skipping already executed script #' + (idx + 1)); originalScript.remove(); return; } // Skip known inline definitions if the global already exists (prevents duplicate var errors) if (!originalScript.src && originalScript.textContent && originalScript.textContent.indexOf('EmailInputManager') !== -1 && typeof targetWindow.EmailInputManager !== 'undefined') { pdLog('pdRunScriptsIn: skipping inline EmailInputManager because it already exists.'); originalScript.remove(); return; } var newScript = targetDocument.createElement('script'); // Preserve external vs inline scripts if (originalScript.src) { newScript.src = originalScript.src; newScript.async = originalScript.async; newScript.defer = originalScript.defer; } else { newScript.textContent = originalScript.textContent; } // Move over type/attrs in case module/type is used if (originalScript.type) newScript.type = originalScript.type; // Append to head to ensure execution in most browsers targetWindow.__pdExecutedScriptsSet.add(signature); (targetDocument.head || targetDocument.documentElement).appendChild(newScript); pdLog('pdRunScriptsIn: executed script #' + (idx + 1) + (originalScript.src ? ' src=' + originalScript.src : ' (inline)')); originalScript.remove(); }); } //************************************************ //*** UTILITY TO NORMALIZE MODULE NAMES ********** //************************************************ function pdNormalizeModuleName(raw) { if (!raw) return ''; var name = String(raw); if (name.indexOf('?') !== -1) name = name.split('?')[0]; if (name.indexOf('&') !== -1) name = name.split('&')[0]; if (name.indexOf('#') !== -1) name = name.split('#')[0]; if (name.indexOf('/') !== -1) { var parts = name.split('/').filter(function(p){ return p; }); var lastMod = parts.find(function(p){ return p.indexOf('mod_') === 0; }); if (lastMod) name = lastMod; else name = parts[parts.length - 1] || name; } return name.trim(); } //************************************************ //*** UTILITY TO PULL MODULE NAME FROM A URL ***** //************************************************ function pdGetModuleFromUrl(url) { try { var parsed = new URL(url, window.location.origin); return pdNormalizeModuleName(parsed.searchParams.get('module') || ''); } catch (e) { return ''; } } //************************************************ //****** PD/ONE FEATURE SPECIFIC CSS/JS ********* //************************************************ pdLoadJsCssFile("https://cdn.practicaldatacore.com/rockbottomgolf/mod_bigcommerce/pdCompiledScript.js?cb=1973187", "js"); pdLoadJsCssFile("https://cdn.practicaldatacore.com/rockbottomgolf/mod_pdOneStyleEditor/pdPublicStyle.css?cb=493296", "css"); //*** CATEGORY ID:**** //*** PRODUCT ID:**** //*** PRODUCT ID LIST CSV:**** function pdGetAccountSearchDocuments() { if (typeof pdShouldInspectAccountUi === 'function' && !pdShouldInspectAccountUi()) return [document]; var docs = []; try { var frames = document.querySelectorAll('#bundle-container iframe.active-frame, #bundle-container iframe'); for (var i = 0; i < frames.length; i++) { try { if (frames[i].contentDocument && frames[i].contentDocument.body) docs.push(frames[i].contentDocument); } catch (e) { pdDebugLog('pdAccountLinks: b2b iframe not accessible', frames[i], e); } } } catch (e) {} if (!pdIsBigCommerceB2BAccountRoute() || !docs.length) docs.push(document); return docs; } function pdFindAccountElementById(id) { var docs = pdGetAccountSearchDocuments(); for (var i = 0; i < docs.length; i++) { try { var element = docs[i].getElementById(id); if (element) return element; } catch (e) {} } return null; } function pdQueryFirstAcrossAccountDocs(selector) { var docs = pdGetAccountSearchDocuments(); for (var i = 0; i < docs.length; i++) { try { var element = docs[i].querySelector(selector); if (element) return element; } catch (e) {} } return null; } function pdGetAccountNavRoot() { if (typeof pdShouldInspectAccountUi === 'function' && !pdShouldInspectAccountUi()) return null; var docs = pdGetAccountSearchDocuments(); var selectors = [ '.navBar.navBar--sub.navBar--account .navBar-section', '.navBar.navBar--sub.navBar--account', '.account-nav', '.b2b-account-nav', '.b2b-side-nav', '.b2b-sidebar nav ul', '.b2b-sidebar nav', '.b2b-sidebar ul', '.b2b-sidebar', '.b3-side-nav', '.b3-nav', '.b3-sidebar nav ul', '.b3-sidebar nav', '.b3-sidebar ul', '.b3-sidebar', '.b2b-portal__nav ul', '.b2b-portal__nav', '.b3-portal__nav ul', '.b3-portal__nav', 'nav.MuiList-root', 'nav[aria-labelledby="nested-list-subheader"]' ]; for (var d = 0; d < docs.length; d++) { for (var i = 0; i < selectors.length; i++) { var navRoot = null; try { navRoot = docs[d].querySelector(selectors[i]); } catch (e) { navRoot = null; } if (navRoot) pdDebugLog('pdAccountLinks: candidate nav root found', selectors[i], navRoot, docs[d] === document ? 'parent-doc' : 'iframe-doc'); if (pdIsAccountNavRoot(navRoot)) { pdDebugLog('pdAccountLinks: using nav root', selectors[i], navRoot); return navRoot; } } } for (var d2 = 0; d2 < docs.length; d2++) { if (pdIsBigCommerceB2BAccountRoute() && docs[d2] === document) continue; var accountLikeLinks = []; try { accountLikeLinks = docs[d2].querySelectorAll('a[href*="account.php?action=order_status"], a[href*="account.php?action=address_book"], a[href*="account.php?action=account_details"], a[href*="#/account"], a[href*="#/order"], a[href*="#/address"], a[href*="#/setting"], a[href*="#/dashboard"], a[href*="#/quote"], a[href*="#/shopping"], a[href*="#/invoice"], a[href*="#/user-management"], a[href*="#/userManagement"], nav li, nav [role="button"], nav button'); } catch (e) { accountLikeLinks = []; } pdDebugLog('pdAccountLinks: global account-like links found', accountLikeLinks.length, docs[d2] === document ? 'parent-doc' : 'iframe-doc'); for (var j = 0; j < accountLikeLinks.length; j++) { var link = accountLikeLinks[j]; var navCandidate = link.closest('ul, nav, aside, [role="navigation"], [class*="nav"], [class*="sidebar"]'); if (navCandidate) pdDebugLog('pdAccountLinks: derived nav candidate from link', link, navCandidate); if (pdIsAccountNavRoot(navCandidate)) { pdDebugLog('pdAccountLinks: using derived nav root from link', link, navCandidate); return navCandidate; } } } var existingRewardsTab = pdFindAccountElementById('pdContent_mod_myRewards'); if (existingRewardsTab) { var existingNavCandidate = existingRewardsTab.closest('ul, nav, aside, [role="navigation"], [class*="nav"], [class*="sidebar"]'); if (existingNavCandidate) pdDebugLog('pdAccountLinks: derived nav candidate from existing rewards tab', existingNavCandidate); if (pdIsAccountNavRoot(existingNavCandidate)) { pdDebugLog('pdAccountLinks: using derived nav root from existing rewards tab', existingNavCandidate); return existingNavCandidate; } } pdDebugLog('pdAccountLinks: no valid nav root found'); return null; } function pdGetBigCommerceB2BHashRoute() { try { var path = (window.location && window.location.pathname) ? window.location.pathname : ''; var hash = (window.location && typeof window.location.hash === 'string') ? window.location.hash : ''; if ((path === '/' || path === '/account.php') && /^#\//.test(hash)) return hash; } catch(e) {} return ''; } function pdIsBigCommerceB2BAccountHash(hashRoute) { if (!hashRoute || !/^#\//.test(hashRoute)) return false; return true; } function pdIsBigCommerceB2BAccountRoute() { var hashRoute = pdGetBigCommerceB2BHashRoute(); if (!hashRoute) return false; return pdIsBigCommerceB2BAccountHash(hashRoute); } function pdIsBigCommerceB2BHashShell() { var hashRoute = pdGetBigCommerceB2BHashRoute(); if (pdIsBigCommerceB2BAccountHash(hashRoute)) { pdDebugLog('pdAccountLinks: B2B detected via hash shell', hashRoute); return true; } return false; } function pdShouldRunAccountLinkInjection() { try { var path = (window.location && window.location.pathname) ? window.location.pathname : ''; if (path === '/account.php' || path === '/wishlist.php') return true; if (/^\/(buy-again|address-book|create-quote|quote-detail|quote|quote-edit|quote-list|quotes-list|dashboard|order-detail|quick-order-pad|shopping-list|shopping-lists|user-management|invoices|invoice-payment|invoice-details|invoice-payment-receipt)\/?$/i.test(path)) return true; if (pdIsBigCommerceB2BAccountRoute()) return true; } catch(e) {} return false; } function pdIsBigCommerceB2BAccountPage() { try { if (window.B3 && window.B3.setting && window.B3.setting.b2b_url) { pdDebugLog('pdAccountLinks: B2B detected via window.B3'); return true; } if (window.b3CheckoutConfig && window.b3CheckoutConfig.routes) { pdDebugLog('pdAccountLinks: B2B detected via window.b3CheckoutConfig'); return true; } if (document.getElementById('bundle-container') || document.getElementById('b2b_loading_overlay')) { pdDebugLog('pdAccountLinks: B2B detected via DOM container'); return true; } if (document.querySelector('script[src*="b2b-buyer-portal"], script[src*="bundleb2b"]')) { pdDebugLog('pdAccountLinks: B2B detected via script tag'); return true; } if (pdIsBigCommerceB2BHashShell()) return true; var path = (window.location && window.location.pathname) ? window.location.pathname : ''; if (/^\/(buy-again|address-book|create-quote|quote-detail|quote|quote-edit|quote-list|quotes-list|dashboard|order-detail|quick-order-pad|shopping-list|shopping-lists|user-management|invoices|invoice-payment|invoice-details|invoice-payment-receipt)\/?$/i.test(path)) { pdDebugLog('pdAccountLinks: B2B detected via pathname', path); return true; } } catch(e) {} pdDebugLog('pdAccountLinks: B2B not detected', window.location ? window.location.pathname + (window.location.hash || '') : ''); return false; } function pdIsAccountNavRoot(root) { if (!root || !root.querySelectorAll) return false; var items = root.matches && (root.matches('a') || root.matches('button') || root.matches('[role="button"]') || root.matches('li')) ? [root] : root.querySelectorAll('a, button, [role="button"], li, span'); if (!items || !items.length) return false; if (root.matches && root.matches('nav.MuiList-root, nav[aria-labelledby="nested-list-subheader"]')) { var muiItems = root.querySelectorAll('li, .MuiListItemButton-root, [role="button"], button'); if (muiItems.length >= 3) return true; } var matchedLabels = 0; for (var i = 0; i < items.length; i++) { var href = items[i].getAttribute ? (items[i].getAttribute('href') || '') : ''; var text = (items[i].textContent || '').replace(/\s+/g, ' ').trim(); if (href.indexOf('account.php?action=order_status') !== -1) return true; if (href.indexOf('account.php?action=address_book') !== -1) return true; if (href.indexOf('account.php?action=account_details') !== -1) return true; if (/^(my orders|orders|order status|shopping lists|quick order|addresses|address book|account settings|settings)$/i.test(text)) matchedLabels++; } return matchedLabels >= 2; } function pdGetAccountNavItem(root, hrefFragment, fallbackSelector) { if (!root) return null; var link = hrefFragment ? root.querySelector('a[href*="' + hrefFragment + '"]') : null; if (link && link.closest) { var item = link.closest('li'); if (item) return item; } var itemCandidates = root.querySelectorAll('li, button, [role="button"], .MuiListItemButton-root'); for (var i = 0; i < itemCandidates.length; i++) { var itemText = (itemCandidates[i].textContent || '').replace(/\s+/g, ' ').trim(); if (hrefFragment === 'account.php?action=order_status' && /^(my orders|orders|order status)$/i.test(itemText)) return itemCandidates[i].closest('li') || itemCandidates[i]; if (hrefFragment === 'account.php?action=address_book' && /^(addresses|address book)$/i.test(itemText)) return itemCandidates[i].closest('li') || itemCandidates[i]; if (hrefFragment === 'account.php?action=account_details' && /^(account settings|settings)$/i.test(itemText)) return itemCandidates[i].closest('li') || itemCandidates[i]; } return fallbackSelector ? root.querySelector(fallbackSelector) : null; } function pdGetAccountNavTemplateItem(root) { if (!root) return null; var preferred = pdGetAccountNavItem(root, 'account.php?action=account_details', null); if (!preferred) preferred = pdGetAccountNavItem(root, 'account.php?action=address_book', null); if (!preferred) { var candidates = root.querySelectorAll('li, .MuiListItemButton-root, [role="button"], button'); for (var i = 0; i < candidates.length; i++) { var text = (candidates[i].textContent || '').replace(/\s+/g, ' ').trim(); if (/^(account settings|settings|addresses|address book)$/i.test(text)) { preferred = candidates[i].closest('li') || candidates[i]; break; } } } if (!preferred) preferred = pdGetAccountNavItem(root, 'account.php?action=order_status', 'li:nth-child(1)'); return preferred; } function pdSetB2BAccountTabActive(tabItem) { if (!tabItem || !tabItem.closest) return; var navRoot = tabItem.closest('nav, ul, [role="navigation"], [class*="nav"], [class*="sidebar"]'); if (!navRoot) return; var items = navRoot.querySelectorAll('li, .MuiListItemButton-root, [role="button"], button'); for (var i = 0; i < items.length; i++) { if (items[i].classList) { items[i].classList.remove('is-active'); items[i].classList.remove('active'); items[i].classList.remove('Mui-selected'); } if (items[i].removeAttribute) { items[i].removeAttribute('aria-current'); items[i].removeAttribute('aria-selected'); } } if (tabItem.classList) { tabItem.classList.add('is-active'); tabItem.classList.add('active'); } tabItem.setAttribute('aria-current', 'page'); var interactive = tabItem.matches('.MuiListItemButton-root, [role="button"], button') ? tabItem : tabItem.querySelector('.MuiListItemButton-root, [role="button"], button'); if (interactive) { if (interactive.classList) interactive.classList.add('Mui-selected'); interactive.setAttribute('aria-selected', 'true'); } } function pdBindB2BInjectedTabHandler(tabItem, module, title, logPrefix) { if (!tabItem || tabItem.__pdB2BHandlerBound === true) return; tabItem.__pdB2BHandlerBound = true; tabItem.setAttribute('data-pd-b2b-handler-bound', 'true'); var clickable = tabItem.querySelector('a, .MuiListItemButton-root, [role="button"], button') || tabItem; if (clickable && clickable.tagName === 'A') { clickable.setAttribute('href', '#'); } tabItem.style.cursor = 'pointer'; tabItem.addEventListener('click', function(e) { if (e) { if (typeof e.preventDefault === 'function') e.preventDefault(); if (typeof e.stopPropagation === 'function') e.stopPropagation(); } pdSetB2BAccountTabActive(tabItem); try { pdOpenAccountModule(module, title); } catch (err) { throw err; } }); } function pdNavCacheGet(key) { try { var raw = window.localStorage ? localStorage.getItem(key) : null; if (!raw) return null; var obj = JSON.parse(raw); if (!obj || !obj.html) return null; if (obj.exp && Date.now() > obj.exp) { localStorage.removeItem(key); return null; } return obj.html; } catch(e) { return null; } } function pdNavCacheSet(key, html, ttlMs) { try { if (!window.localStorage) return; var exp = ttlMs ? (Date.now() + ttlMs) : null; localStorage.setItem(key, JSON.stringify({ html: html, exp: exp })); } catch(e) {} } function pdIsInjectedAccountTab(element) { if (!element || !element.closest) return false; var parentNav = element.closest('ul, nav, .navBar-section, .navBar.navBar--sub.navBar--account, .account-nav, .b2b-account-nav, .b2b-side-nav, .b2b-sidebar, .b3-side-nav, .b3-nav, .b3-sidebar, .b2b-portal__nav, .b3-portal__nav'); return pdIsAccountNavRoot(parentNav); } function pdScheduleAccountLinkInjection() { if (typeof __pdAccountLinkInjectionSchedulerActive !== 'undefined' && __pdAccountLinkInjectionSchedulerActive) { pdDebugLog('pdAccountLinks: scheduler already running'); return; } __pdAccountLinkInjectionSchedulerActive = true; var maxAttempts = pdIsBigCommerceB2BAccountPage() ? 60 : 8; var attempt = 0; var timer = null; var observer = null; var stopped = false; var startTime = Date.now(); var maxRuntimeMs = 3000; var onWindowEvent = function() { if (!stopped) run(); }; var stopScheduler = function(reason, payload) { if (stopped) return; stopped = true; pdDebugLog(reason, payload || {}); __pdAccountLinkInjectionSchedulerActive = false; if (timer) clearTimeout(timer); if (observer) observer.disconnect(); window.removeEventListener('load', onWindowEvent); window.removeEventListener('hashchange', onWindowEvent); }; var run = function() { if (stopped) return; if (!pdShouldRunAccountLinkInjection()) { stopScheduler('pdAccountLinks: skipping nav search on non-account route', window.location ? window.location.pathname + (window.location.hash || '') : ''); return; } if ((Date.now() - startTime) >= maxRuntimeMs) { stopScheduler('pdAccountLinks: stopping scheduler after max runtime', { elapsedMs: Date.now() - startTime, maxRuntimeMs: maxRuntimeMs, attempt: attempt }); return; } attempt++; pdDebugLog('pdAccountLinks: injection attempt', attempt, 'of', maxAttempts, 'url=', window.location ? window.location.pathname + (window.location.hash || '') : ''); try { if (pdIsBigCommerceB2BAccountPage()) pdBindB2BNativeNavRestore(); } catch(e) { pdLog('pdAccountLinks: bind native nav restore error', e); } try { pdInjectAccountLinkModifications(); } catch(e) { pdLog('pdAccountLinks: injection error', e); } var navRoot = pdGetAccountNavRoot(); var rewardsTab = pdFindAccountElementById('pdContent_mod_myRewards'); var olderOrdersTab = pdFindAccountElementById('pdContent_mod_orderHistory'); var deleteAccountTab = pdFindAccountElementById('pdContent_mod_bigcommerce'); var rewardsInNav = pdIsInjectedAccountTab(rewardsTab); var olderOrdersInNav = pdIsInjectedAccountTab(olderOrdersTab); var deleteAccountInNav = pdIsInjectedAccountTab(deleteAccountTab); var done = !!navRoot && (rewardsInNav || olderOrdersInNav || deleteAccountInNav); pdDebugLog('pdAccountLinks: post-injection state', { navRootFound: !!navRoot, done: done, rewards: !!rewardsTab, rewardsInNav: rewardsInNav, olderOrders: !!olderOrdersTab, olderOrdersInNav: olderOrdersInNav, deleteAccount: !!deleteAccountTab, deleteAccountInNav: deleteAccountInNav }); if (rewardsTab && !rewardsInNav) pdDebugLog('pdAccountLinks: rewards tab exists outside account nav', rewardsTab, rewardsTab.parentElement); if ((!pdIsBigCommerceB2BAccountPage() && navRoot) || done || attempt >= maxAttempts) { stopScheduler('pdAccountLinks: stopping scheduler', { navRootFound: !!navRoot, done: done, attempt: attempt, maxAttempts: maxAttempts, isB2B: pdIsBigCommerceB2BAccountPage() }); return; } timer = setTimeout(run, pdIsBigCommerceB2BAccountPage() ? 500 : 250); }; if (typeof MutationObserver !== 'undefined' && document.body) { observer = new MutationObserver(function() { pdDebugLog('pdAccountLinks: mutation observed, scheduling rerun'); if (timer) clearTimeout(timer); timer = setTimeout(run, 100); }); observer.observe(document.body, { childList: true, subtree: true }); pdDebugLog('pdAccountLinks: MutationObserver attached'); } if (document.readyState === 'loading') { pdDebugLog('pdAccountLinks: waiting for DOMContentLoaded'); document.addEventListener('DOMContentLoaded', run); } else { pdDebugLog('pdAccountLinks: document already ready, running now'); run(); } window.addEventListener('load', onWindowEvent); window.addEventListener('hashchange', onWindowEvent); pdDebugLog('pdAccountLinks: load/hashchange listeners attached'); } function pdInjectAccountLinkModifications() { //***** INJECT REWARDS LINK **** var navRoot = pdGetAccountNavRoot(); var navDocument = navRoot && navRoot.ownerDocument ? navRoot.ownerDocument : document; var navTemplateItem = pdGetAccountNavTemplateItem(navRoot); var ordersLink = navRoot ? navRoot.querySelector('a[href*="account.php?action=order_status"]') : null; if (!ordersLink && !navRoot) { ordersLink = pdQueryFirstAcrossAccountDocs('a[href*="account.php?action=order_status"]'); } var navItem = ordersLink && ordersLink.closest ? (ordersLink.closest("li") || ordersLink.closest("[role=button]") || ordersLink.closest("button")) : null; if (!navItem && navRoot) { navItem = pdGetAccountNavItem(navRoot, "account.php?action=order_status", "li:nth-child(1)"); } if (!navItem && navRoot) { var activeItem = navRoot.querySelector("li.is-active"); if (activeItem) { var activeText = (activeItem.textContent || "").replace(/\s+/g, " ").trim(); if (/^(orders|order status)\b/i.test(activeText)) { navItem = activeItem; } } } if (!navItem && navRoot) { var navItems = navRoot.querySelectorAll("li"); for (var i = 0; i < navItems.length; i++) { var itemText = (navItems[i].textContent || "").replace(/\s+/g, " ").trim(); if (/^(orders|order status)\b/i.test(itemText)) { navItem = navItems[i]; break; } } } var existingRewardsTab = pdFindAccountElementById("pdContent_mod_myRewards"); if (existingRewardsTab && !pdIsInjectedAccountTab(existingRewardsTab)) { existingRewardsTab.remove(); existingRewardsTab = null; } var rewardsNavModel = (navRoot && navRoot.matches && navRoot.matches("nav.MuiList-root, nav[aria-labelledby='nested-list-subheader']")) ? "b2b" : "classic"; if (existingRewardsTab && rewardsNavModel === "b2b") { pdBindB2BInjectedTabHandler(existingRewardsTab, "mod_myRewards", "Rewards", "pdRewardsTab"); } var rewardsCacheKey = "pdNavRewards:v5:" + rewardsNavModel; var rewardsCachedHtml = pdNavCacheGet(rewardsCacheKey); if (navItem && !existingRewardsTab && rewardsCachedHtml) { navItem.insertAdjacentHTML("afterend", rewardsCachedHtml); existingRewardsTab = pdFindAccountElementById("pdContent_mod_myRewards"); if (existingRewardsTab) { var cachedLooksB2B = !!existingRewardsTab.querySelector(".MuiListItemButton-root, .MuiTypography-root"); var cachedLooksClassic = !!existingRewardsTab.querySelector("a.navBar-action, a.navPage-subMenu-action"); var cacheMatchesNav = (rewardsNavModel === "b2b" && cachedLooksB2B) || (rewardsNavModel === "classic" && cachedLooksClassic); if (!cacheMatchesNav) { existingRewardsTab.remove(); existingRewardsTab = null; } else { if (rewardsNavModel === "b2b") { pdBindB2BInjectedTabHandler(existingRewardsTab, "mod_myRewards", "Rewards", "pdRewardsTab"); } } } } if (navItem && !existingRewardsTab) { var rewardsItem = (navTemplateItem || navItem).cloneNode(true); rewardsItem.id = "pdContent_mod_myRewards"; if (rewardsItem.classList) { rewardsItem.classList.remove("is-active"); rewardsItem.classList.remove("Mui-selected"); rewardsItem.classList.remove("active"); } rewardsItem.removeAttribute("aria-current"); rewardsItem.removeAttribute("aria-selected"); var rewardsLink = rewardsItem.querySelector("a"); var rewardsLabel = rewardsItem.querySelector(".MuiListItemText-primary, .MuiTypography-root, span"); var selectedChildren = rewardsItem.querySelectorAll(".is-active, .Mui-selected, .active"); for (var s = 0; s < selectedChildren.length; s++) { selectedChildren[s].classList.remove("is-active"); selectedChildren[s].classList.remove("Mui-selected"); selectedChildren[s].classList.remove("active"); selectedChildren[s].removeAttribute("aria-current"); selectedChildren[s].removeAttribute("aria-selected"); } if (!rewardsLink) { if (rewardsLabel) { rewardsLabel.textContent = "Rewards"; rewardsItem.style.cursor = "pointer"; pdBindB2BInjectedTabHandler(rewardsItem, "mod_myRewards", "Rewards", "pdRewardsTab"); } else { rewardsItem.textContent = ""; rewardsLink = navDocument.createElement("a"); var templateLink = navRoot ? navRoot.querySelector("a") : pdQueryFirstAcrossAccountDocs(".navBar-action"); rewardsLink.className = templateLink ? templateLink.className : "navBar-action"; rewardsItem.appendChild(rewardsLink); } } if (rewardsLink) { rewardsLink.href = "https://www.rockbottomgolf.com/account.php?action=order_status&pd_module_content=mod_myRewards"; rewardsLink.textContent = "Rewards"; } if (rewardsNavModel === "b2b") { pdBindB2BInjectedTabHandler(rewardsItem, "mod_myRewards", "Rewards", "pdRewardsTab"); } navItem.insertAdjacentElement("afterend", rewardsItem); try { setTimeout(function(){ var insertedRewards = pdFindAccountElementById("pdContent_mod_myRewards"); var insertedLink = insertedRewards ? insertedRewards.querySelector("a") : null; var href = insertedLink ? insertedLink.getAttribute("href") : ""; var textOk = (insertedLink && (insertedLink.textContent || "").trim() === "Rewards") || (insertedRewards && /rewards/i.test((insertedRewards.textContent || "").trim())); var inAccountNav = insertedRewards && pdIsInjectedAccountTab(insertedRewards); var inFlyout = insertedRewards && insertedRewards.closest && insertedRewards.closest("#navUser-more-panel, .navUser-panel, .navUser-section--panel"); if (insertedRewards && textOk && inAccountNav && !inFlyout) { pdNavCacheSet(rewardsCacheKey, insertedRewards.outerHTML, 10 * 60 * 1000); } }, 0); } catch(e) {} } } pdScheduleAccountLinkInjection();var pdPublicUrl = 'https://myaccount.rockbottomgolf.com/'; var pdUseLegacyRewardsPage = true; var pdRewardsUseShadowDom = true; function pdShouldUseRewards2025() { return !pdUseLegacyRewardsPage; } function insertDivUnderH1(divClass = "inserted-under-h1") { var pageName = window.location.pathname.split("/").pop(); if (pageName !== "login.php" && pageName !== "cart.php" && pageName !== "checkout") return; var params = new URLSearchParams(window.location.search || ""); var action = params.get("action") || "login"; if (pageName === "login.php" && action === "reset_password") return; var bannerHtml = ""; var bannerTemplateData = {"rewardsPercentageBack":2,"pointsAwardedForNewSignUp":"100"}; if (!bannerHtml) return; if (pageName === "login.php" && action === "login" && !true) return; if (pageName === "login.php" && action === "create_account" && !true) return; if (pageName === "cart.php" && !true) return; if (pageName === "checkout" && !true) return; function pdRenderBannerTemplate(template, data) { if (!template || !data) return template || ''; template = template.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g, function(_, key, inner) { var val = data[key]; if (val === undefined || val === null) return ''; if (typeof val === 'number' && val === 0) return ''; if (typeof val === 'string' && val.trim() === '') return ''; return inner; }); template = template.replace(/\{\{(\w+)\}\}/g, function(_, key) { var val = data[key]; return (val === undefined || val === null) ? '' : String(val); }); return template; } bannerHtml = pdRenderBannerTemplate(bannerHtml, bannerTemplateData); var div = document.createElement("div"); div.className = divClass; div.innerHTML = bannerHtml; if (pageName === "checkout") { var checkoutPrimary = document.querySelector(".layout.optimizedCheckout-contentPrimary"); if (checkoutPrimary) { checkoutPrimary.insertAdjacentElement("afterbegin", div); return; } } var h1 = document.querySelector("h1.page-heading"); if (!h1) return; if (pageName === "cart.php") { h1.insertAdjacentElement("afterend", div); return; } if (action === "login") { var loginRow = document.querySelector(".login-row"); if (loginRow) { loginRow.insertAdjacentElement("afterbegin", div); return; } } if (action === "create_account") { var accountBody = document.querySelector(".account-body"); if (accountBody) { accountBody.insertAdjacentElement("afterbegin", div); return; } } h1.insertAdjacentElement("afterend", div); } function pdShouldInspectAccountUi() { try { var path = (window.location && window.location.pathname) ? window.location.pathname : ''; if (path === '/account.php' || path === '/wishlist.php') return true; if (/^\/(buy-again|address-book|create-quote|quote-detail|quote|quote-edit|quote-list|quotes-list|dashboard|order-detail|quick-order-pad|shopping-list|shopping-lists|user-management|invoices|invoice-payment|invoice-details|invoice-payment-receipt)\/?$/i.test(path)) return true; if (typeof pdIsBigCommerceB2BAccountRoute === 'function' && pdIsBigCommerceB2BAccountRoute()) return true; } catch (e) {} return false; } function pdGetAccountIntegrationModel() { if (!pdShouldInspectAccountUi()) return 'classic'; var navRoot = (typeof pdGetAccountNavRoot === 'function') ? pdGetAccountNavRoot() : null; if (navRoot && navRoot.ownerDocument && navRoot.ownerDocument !== document) return 'b2b'; if (navRoot && navRoot.querySelector && navRoot.querySelector('.MuiListItemButton-root, .MuiTypography-root')) return 'b2b'; if (document.querySelector('#bundle-container iframe.active-frame')) return 'b2b'; return 'classic'; } function pdGetAccountContentContainer() { var model = pdGetAccountIntegrationModel(); if (model === 'b2b') { var navRoot = (typeof pdGetAccountNavRoot === 'function') ? pdGetAccountNavRoot() : null; var doc = navRoot && navRoot.ownerDocument ? navRoot.ownerDocument : document; var main = doc.querySelector('#app-mainPage-layout main') || doc.querySelector('#app-mainPage-layout [role="main"]') || doc.querySelector('main.MuiBox-root') || doc.querySelector('main'); if (!main) return null; var host = main.querySelector('#pdB2BAccountContentHost'); if (!host) { host = doc.createElement('div'); host.id = 'pdB2BAccountContentHost'; host.style.display = 'none'; host.setAttribute('data-pd-b2b-host', 'true'); main.appendChild(host); } return host; } return document.querySelector('.account-content'); } function pdGetB2BAccountMainContainer(doc) { doc = doc || document; return doc.querySelector('#app-mainPage-layout main') || doc.querySelector('#app-mainPage-layout [role="main"]') || doc.querySelector('main.MuiBox-root') || doc.querySelector('main'); } function pdActivateB2BAccountContent(title) { var navRoot = (typeof pdGetAccountNavRoot === 'function') ? pdGetAccountNavRoot() : null; var doc = navRoot && navRoot.ownerDocument ? navRoot.ownerDocument : document; var main = pdGetB2BAccountMainContainer(doc); var host = pdGetAccountContentContainer(); var heading = pdGetAccountPageHeading(); if (!main || !host) return host; if (heading && title) { if (!heading.getAttribute('data-pd-original-heading')) { heading.setAttribute('data-pd-original-heading', heading.textContent || ''); } heading.textContent = title; } for (var i = 0; i < main.children.length; i++) { var child = main.children[i]; if (child === host) continue; if (!child.hasAttribute('data-pd-prev-display')) { child.setAttribute('data-pd-prev-display', child.style.display || ''); } child.style.display = 'none'; child.setAttribute('data-pd-b2b-hidden', 'true'); } host.style.display = ''; host.setAttribute('data-pd-active', 'true'); return host; } function pdRestoreB2BAccountContent(doc) { doc = doc || document; var main = pdGetB2BAccountMainContainer(doc); if (!main) return; try { pdResetB2BRewardsState(doc); } catch (e) {} var host = main.querySelector('#pdB2BAccountContentHost'); if (host) { host.style.display = 'none'; host.removeAttribute('data-pd-active'); } for (var i = 0; i < main.children.length; i++) { var child = main.children[i]; if (child === host) continue; if (child.hasAttribute('data-pd-b2b-hidden')) { child.style.display = child.getAttribute('data-pd-prev-display') || ''; child.removeAttribute('data-pd-prev-display'); child.removeAttribute('data-pd-b2b-hidden'); } } var heading = doc.querySelector('h3') || doc.querySelector('h1, h2, h4'); if (heading && heading.hasAttribute('data-pd-original-heading')) { heading.textContent = heading.getAttribute('data-pd-original-heading') || heading.textContent; heading.removeAttribute('data-pd-original-heading'); } var navRoot = doc.querySelector('nav.MuiList-root, nav[aria-labelledby="nested-list-subheader"]'); if (navRoot) { var injectedTabs = navRoot.querySelectorAll('#pdContent_mod_myRewards, #pdContent_mod_orderHistory, #pdContent_mod_bigcommerce'); for (var j = 0; j < injectedTabs.length; j++) { var item = injectedTabs[j]; if (item.classList) { item.classList.remove('is-active'); item.classList.remove('active'); item.classList.remove('Mui-selected'); } item.removeAttribute('aria-current'); item.removeAttribute('aria-selected'); var interactive = item.querySelector('.MuiListItemButton-root, [role="button"], button'); if (interactive && interactive.classList) { interactive.classList.remove('Mui-selected'); interactive.removeAttribute('aria-selected'); } } } } function pdResetB2BRewardsState(doc) { doc = doc || document; var win = doc.defaultView || window; var host = doc.querySelector('#pdB2BAccountContentHost'); if (host) { host.innerHTML = ''; } try { win.pdRewardsShadowRoot = null; } catch (e) {} try { pdRewardsForceLegacy = false; } catch (e) {} try { doc.querySelectorAll('script[data-pd-rewards-ajax="true"]').forEach(function(script) { if (script.parentNode) script.parentNode.removeChild(script); }); } catch (e) {} try { if (win.__pdExecutedScriptsSet && typeof win.__pdExecutedScriptsSet.forEach === 'function') { var rewardsScriptSignatures = []; win.__pdExecutedScriptsSet.forEach(function(signature) { if ( /mod_myRewards/i.test(signature) || /RewardsManager/i.test(signature) || /pdRewards/i.test(signature) || /rewardTabs/i.test(signature) ) { rewardsScriptSignatures.push(signature); } }); for (var i = 0; i < rewardsScriptSignatures.length; i++) { win.__pdExecutedScriptsSet.delete(rewardsScriptSignatures[i]); } } } catch (e) {} } function pdBindB2BNativeNavRestore() { var docs = (typeof pdGetAccountSearchDocuments === 'function') ? pdGetAccountSearchDocuments() : [document]; for (var i = 0; i < docs.length; i++) { var doc = docs[i]; if (!doc || doc === document || !doc.body || doc.body.getAttribute('data-pd-b2b-nav-restore-bound') === 'true') continue; doc.body.setAttribute('data-pd-b2b-nav-restore-bound', 'true'); doc.addEventListener('click', function(e) { if (!e.target || typeof e.target.closest !== 'function') return; var navRoot = this.querySelector('nav.MuiList-root, nav[aria-labelledby="nested-list-subheader"]'); if (!navRoot) return; var clickedItem = e.target.closest('li, .MuiListItemButton-root, [role="button"], button, a'); if (!clickedItem || !navRoot.contains(clickedItem)) return; if (clickedItem.closest('#pdContent_mod_myRewards, #pdContent_mod_orderHistory, #pdContent_mod_bigcommerce')) return; pdRestoreB2BAccountContent(this); }, true); } } var __pdAccountLinkInjectionSchedulerActive = false; var __pdAccountUrlWatcherBound = false; var __pdLastObservedAccountHref = ''; var __pdAccountUrlWatcherTimer = null; function pdCanRunAccountLinkInjectionForCurrentUrl() { if (!pdShouldRunAccountLinkInjection()) return false; if (!pdIsBigCommerceB2BAccountRoute()) return true; try { if (document.getElementById('bundle-container')) return true; if (document.getElementById('b2b_loading_overlay')) return true; if (document.querySelector('#bundle-container iframe.active-frame, #bundle-container iframe')) return true; } catch (e) {} return false; } function pdOnAccountUrlChanged(reason) { var href = window.location ? window.location.href : ''; if (href === __pdLastObservedAccountHref) return; __pdLastObservedAccountHref = href; pdDebugLog('pdAccountLinks: observed url change', reason || '', href); if (__pdAccountUrlWatcherTimer) clearTimeout(__pdAccountUrlWatcherTimer); var attempts = 0; var waitForReadyState = function() { if (href !== (window.location ? window.location.href : '')) { __pdAccountUrlWatcherTimer = null; return; } if (pdCanRunAccountLinkInjectionForCurrentUrl()) { __pdAccountUrlWatcherTimer = null; pdScheduleAccountLinkInjection(); return; } if (pdIsBigCommerceB2BAccountRoute() && attempts < 12) { attempts++; __pdAccountUrlWatcherTimer = setTimeout(waitForReadyState, 150); return; } __pdAccountUrlWatcherTimer = null; }; __pdAccountUrlWatcherTimer = setTimeout(waitForReadyState, 120); } function pdBindAccountUrlWatcher() { if (__pdAccountUrlWatcherBound) return; __pdAccountUrlWatcherBound = true; __pdLastObservedAccountHref = window.location ? window.location.href : ''; var wrapHistoryMethod = function(method) { var original = history[method]; if (!original || original.__pdWrapped) return; var wrapped = function() { var result = original.apply(this, arguments); pdOnAccountUrlChanged(method); return result; }; wrapped.__pdWrapped = true; history[method] = wrapped; }; try { wrapHistoryMethod('pushState'); wrapHistoryMethod('replaceState'); } catch (e) {} window.addEventListener('hashchange', function() { pdOnAccountUrlChanged('hashchange'); }); window.addEventListener('popstate', function() { pdOnAccountUrlChanged('popstate'); }); } function pdGetAccountPageHeading() { var model = pdGetAccountIntegrationModel(); if (model === 'b2b') { var navRoot = (typeof pdGetAccountNavRoot === 'function') ? pdGetAccountNavRoot() : null; var doc = navRoot && navRoot.ownerDocument ? navRoot.ownerDocument : document; return doc.querySelector('h3') || doc.querySelector('h1, h2, h4'); } return document.querySelector('.page-heading'); } function pdCleanupB2BInjectedHeading(accountContent) { if (!accountContent || pdGetAccountIntegrationModel() !== 'b2b') return; var heading = accountContent.querySelector('.page-heading, h1, h2, h3, h4'); if (!heading) return; var parent = heading.parentElement; if (!parent) return; if (heading === accountContent.firstElementChild) { heading.remove(); return; } if ( parent === accountContent && heading.previousElementSibling === null && heading.textContent && heading.textContent.replace(/\s+/g, ' ').trim() !== '' ) { heading.remove(); } } function pdOpenAccountModule(module, title, subNav) { subNav = subNav || ''; var model = pdGetAccountIntegrationModel(); if (model === 'b2b') { if (module === 'mod_myRewards') { try { var navRoot = (typeof pdGetAccountNavRoot === 'function') ? pdGetAccountNavRoot() : null; var doc = navRoot && navRoot.ownerDocument ? navRoot.ownerDocument : document; pdResetB2BRewardsState(doc); } catch (e) {} } pdActivateB2BAccountContent(title); var url = pdPublicUrl + '/' + module + '/' + (subNav ? (subNav + '.php') : 'index.php') + '?module=' + encodeURIComponent(module); if (module === 'mod_myRewards') { pdLoadRewardsLegacyFallback({ method: 'GET', queryString: 'module=' + encodeURIComponent(module) }); } else { pdOneAjaxLinkHandler(url); } return false; } window.top.location.href = pdPublicUrl + '/' + module + '/' + (subNav ? (subNav + '.php') : 'index.php') + '?module=' + encodeURIComponent(module); return false; } function pdInitAccountModuleContent(){ if (pdGetAccountIntegrationModel() !== 'classic') { pdLog('pdPageScript2025: skipping classic account init for B2B model'); insertDivUnderH1(); return; } pdLog('pdPageScript2025: DOMContentLoaded fired'); const urlParams = new URLSearchParams(location.search); var navSection = pdGetAccountNavSection(); var activeNavItem = navSection ? navSection.querySelector('.is-active') : document.querySelector('.navBar-section .is-active'); var prevLinkElem = activeNavItem ? activeNavItem.dataset.pdLinkElem : null; var prevLinkTarget = activeNavItem ? activeNavItem.dataset.pdLinkElemTarget : null; if (prevLinkElem && prevLinkTarget) { var prevTargetElem = document.querySelector(prevLinkTarget); if (prevTargetElem) { prevTargetElem.innerHTML = prevLinkElem; } delete activeNavItem.dataset.pdLinkElem; delete activeNavItem.dataset.pdLinkElemTarget; } if (urlParams.has('pd_module_content')){ pdLog('pdPageScript2025: pd_module_content detected:', urlParams.get('pd_module_content')); pdLog('pdPageScript2025: pd_module_subNav:', urlParams.get('pd_module_subNav')); var module = urlParams.get('pd_module_content'); var subNav = urlParams.get('pd_module_subNav'); var moduleLink = document.querySelector('#pdContent_'+module+' a'); var moduleTitle = moduleLink ? moduleLink.innerHTML : ''; var currentUrl = window.location.href; var currentUrlNoQuery = currentUrl.substring(0, currentUrl.indexOf('?')); pdLog(currentUrlNoQuery); navSection = pdGetAccountNavSection(); activeNavItem = navSection ? navSection.querySelector('.is-active') : document.querySelector('.navBar-section .is-active'); var currentTab = activeNavItem ? activeNavItem.innerHTML : ''; if (activeNavItem && activeNavItem.classList.contains('pdLinkEvent') == false){ if(activeNavItem.querySelector('.navBar-action')){ } else { activeNavItem.innerHTML = ''+currentTab+''; } } if (activeNavItem) { activeNavItem.dataset.pdLinkElemTarget = '#pdContent_'+module; var moduleItem = document.querySelector('#pdContent_'+module); activeNavItem.dataset.pdLinkElem = moduleItem ? moduleItem.innerHTML : ''; } var moduleItem = document.querySelector('#pdContent_'+module); if (moduleItem) { moduleItem.innerHTML = moduleLink ? moduleLink.textContent : ''; } if (activeNavItem) { activeNavItem.classList.remove('is-active'); } if (moduleItem) { moduleItem.classList.add('is-active'); } var pageHeading = document.querySelector('.page-heading'); if (pageHeading) { pageHeading.innerHTML = moduleTitle; } if (subNav !== '' && subNav !== null){ url = pdPublicUrl+'/'+module+'/'+subNav+'.php?module='+module; } else { url = pdPublicUrl+'/'+module+'/index.php?module='+module; } pdLog('pdPageScript2025: calling pdOneAjaxLinkHandler with URL:', url); pdOneAjaxLinkHandler(url); } insertDivUnderH1(); } var __pdAccountNavSection = null; function pdGetAccountNavSection() { if (__pdAccountNavSection && document.contains(__pdAccountNavSection)) { return __pdAccountNavSection; } __pdAccountNavSection = document.querySelector('.navBar-section'); return __pdAccountNavSection; } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', pdInitAccountModuleContent); document.addEventListener('DOMContentLoaded', pdBindAccountUrlWatcher); } else { pdInitAccountModuleContent(); pdBindAccountUrlWatcher(); } document.addEventListener('submit', function(e) { if (!e.target || typeof e.target.closest !== 'function') { return; } var form = e.target.closest('.pdModal form'); if (!form) { return; } e.preventDefault(); e.stopImmediatePropagation(); pdOneAjaxFormHandler(form); }, true); document.addEventListener('submit', function(e) { if (!e.target || typeof e.target.closest !== 'function') { return; } var form = e.target.closest('#pdModuleContent form'); if (!form) { return; } e.preventDefault(); e.stopImmediatePropagation(); pdOneAjaxFormHandler(form); }, true); document.addEventListener('click', function(e) { if (!e.target || typeof e.target.closest !== 'function') { return; } var link = e.target.closest('.pdLinkEvent'); if (!link) { return; } var currentUrl = window.location.href; var navSection = pdGetAccountNavSection(); activeNavItem = navSection ? navSection.querySelector('.is-active') : document.querySelector('.navBar-section .is-active'); var activeNavAction = activeNavItem ? activeNavItem.querySelector('.navBar-action') : null; var currentTab = activeNavAction ? activeNavAction.innerHTML : (activeNavItem ? activeNavItem.innerHTML : ''); pdLog(link.innerHTML); if (activeNavItem && activeNavItem.classList.contains('pdLinkEvent') == false){ activeNavItem.innerHTML = ''+currentTab+''; } if (activeNavItem) { activeNavItem.classList.remove('is-active'); } if (link.parentElement) { link.parentElement.classList.add('is-active'); } var pageHeading = document.querySelector('.page-heading'); if (pageHeading) { var linkText = (link.textContent || '').trim(); pageHeading.textContent = linkText || pageHeading.textContent; } var url = link.getAttribute('href'); e.preventDefault(); e.stopImmediatePropagation(); pdOneAjaxLinkHandler(url); }); document.addEventListener('click', function(e) { if (!e.target || typeof e.target.closest !== 'function') { return; } var link = e.target.closest('a[href*="pd_module_content=mod_myRewards"]'); if (!link) { return; } var pageHeading = document.querySelector('.page-heading'); if (!pageHeading) { return; } var linkText = (link.textContent || '').trim(); if (!linkText) { var rewardsCached = pdNavCacheGet('pdNavRewards:v5'); if (rewardsCached && rewardsCached.title) linkText = rewardsCached.title; } pageHeading.textContent = linkText || pageHeading.textContent; }); document.addEventListener('click', function(e) { if (!e.target || typeof e.target.closest !== 'function') { return; } var link = e.target.closest('#pdModuleContent a'); if (!link) { return; } var url = link.getAttribute('href'); link.setAttribute("href", "#"); e.preventDefault(); pdOneAjaxLinkHandler(url); }); function pdShowRewardsLoadError(message){ var accountContent = pdGetAccountContentContainer(); if (!accountContent) { return; } var safeMessage = message || 'Rewards could not be loaded.'; accountContent.innerHTML = '
' + safeMessage + '
'; } function pdInjectRewardsHtml(html){ var accountContent = pdGetAccountContentContainer(); if (!accountContent) { return false; } var targetDocument = accountContent.ownerDocument || document; var targetWindow = targetDocument.defaultView || window; var useShadowDom = pdRewardsUseShadowDom && pdGetAccountIntegrationModel() !== 'b2b'; if (!useShadowDom) { accountContent.innerHTML = html || ''; try { targetWindow.pdRewardsShadowRoot = null; } catch (e) {} return true; } try { if (typeof html === 'string') { html = html.replace(/:root\s*{/g, ':host {'); } accountContent.innerHTML = '
'; var host = accountContent.querySelector('#pdRewardsShadowHost'); if (!host || !host.attachShadow) { accountContent.innerHTML = html || ''; return true; } var shadowRoot = host.attachShadow({ mode: 'open' }); shadowRoot.innerHTML = html || ''; targetWindow.pdRewardsShadowRoot = shadowRoot; pdLog('pdRewardsShadowDom: injected into shadow root'); return true; } catch (e) { pdLog('pdRewardsShadowDom: failed, falling back to light DOM', e); accountContent.innerHTML = html || ''; try { targetWindow.pdRewardsShadowRoot = null; } catch (err) {} return true; } } var pdRewardsForceLegacy = false; function pdLoadRewardsLegacyFallback(options){ options = options || {}; pdRewardsForceLegacy = true; var url = pdPublicUrl + '/mod_myRewards/index.php?module=mod_myRewards'; var method = (options.method || 'GET').toUpperCase(); var queryString = options.queryString || ''; if (!queryString && options.body) { queryString = options.body.toString(); } if (queryString) { url += (url.indexOf('?') !== -1 ? '&' : '?') + queryString; } pdLog('pdLoadRewardsLegacyFallback:', url, 'method:', method); if (method === 'GET') { pdOneAjaxLinkHandler(url); return; } var fetchOptions = { method: method, credentials: 'include' }; if (options.body) { fetchOptions.headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }; fetchOptions.body = options.body; } fetch(url, fetchOptions) .then(function(response) { return response.text(); }) .then(function(result) { pdLog('pdLoadRewardsLegacyFallback success; length:', (result || '').length); var accountContent = pdGetAccountContentContainer(); if (accountContent) { accountContent.innerHTML = result; pdCleanupB2BInjectedHeading(accountContent); } if (typeof pdRunScriptsIn === 'function' && pdGetAccountIntegrationModel() !== 'b2b') { pdRunScriptsIn(accountContent); } }) .catch(function(errMsg) { pdLog('pdLoadRewardsLegacyFallback error', errMsg && errMsg['statusText'] ? errMsg['statusText'] : errMsg); pdShowRewardsLoadError('Rewards could not be loaded.'); }); } function pdLoadRewards2025Ajax(options){ options = options || {}; var endpoint = pdPublicUrl + '/mod_myRewards/ajax/renderRewardsPage2025.php'; var method = (options.method || 'GET').toUpperCase(); var queryString = options.queryString || ''; if (!queryString && options.body && method === 'GET') { queryString = options.body.toString(); } if (queryString) { endpoint += (endpoint.indexOf('?') !== -1 ? '&' : '?') + queryString; } var pdUserSession = (typeof window !== 'undefined' && window.pdUserSession) ? window.pdUserSession : null; // Force POST when pdUserSession is present and no explicit body is supplied if (pdUserSession && (!options.body || method === 'GET')) { method = 'POST'; } var fetchOptions = { method: method, credentials: 'include', headers: { 'Accept': 'application/json' } }; if (method != 'GET' && options.body) { // Form submission path (URL-encoded) if (pdUserSession && typeof options.body.set === 'function') { try { options.body.set('pdUserSession', JSON.stringify(pdUserSession)); } catch(e) {} } fetchOptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; fetchOptions.body = options.body; } else if (method != 'GET' && pdUserSession) { // Initial load path (JSON body) fetchOptions.headers['Content-Type'] = 'application/json'; fetchOptions.body = JSON.stringify({ pdUserSession: pdUserSession }); } var accountContent = pdGetAccountContentContainer(); if (accountContent) { accountContent.innerHTML = '
Loading rewards...
'; } pdLog('pdLoadRewards2025Ajax:', endpoint, 'method:', method); return fetch(endpoint, fetchOptions) .then(function(response) { if (!response.ok) { throw new Error('HTTP ' + response.status); } return response.json(); }) .then(function(data) { pdLog('pdLoadRewards2025Ajax success; html length:', (data.html || '').length); if (data && data.success === false) { pdShowRewardsLoadError(data.message || 'Rewards could not be loaded.'); return; } if (data.redirectUrl) { window.location.href = data.redirectUrl; return; } pdInjectRewardsHtml(data.html || ''); if (!data.html) { pdLoadRewardsLegacyFallback(options); return; } if (data.js) { var targetContent = pdGetAccountContentContainer(); var targetDocument = targetContent && targetContent.ownerDocument ? targetContent.ownerDocument : document; targetDocument.querySelectorAll('script[data-pd-rewards-ajax="true"]').forEach(function(script) { if (script.parentNode) script.parentNode.removeChild(script); }); var script = targetDocument.createElement('script'); script.type = 'text/javascript'; script.setAttribute('data-pd-rewards-ajax', 'true'); script.text = data.js; (targetDocument.body || targetDocument.documentElement).appendChild(script); } }) .catch(function(errMsg) { pdLog('pdLoadRewards2025Ajax error', errMsg && errMsg['statusText'] ? errMsg['statusText'] : errMsg); pdLoadRewardsLegacyFallback(options); }); } function pdOneAjaxLinkHandler(url){ pdLog('pdOneAjaxLinkHandler entry:', url); pdLog("pdOneAjaxLinkHandler:" + url); var contentElem = document.querySelector('#pdModuleContent'); var dataElem = document.querySelector('#pdModuleData'); var currModule = contentElem ? contentElem.getAttribute('data-currmodule') : null; if (!currModule || currModule === '' || currModule === undefined) { currModule = dataElem ? dataElem.getAttribute('data-currmodule') : null; } currModule = pdNormalizeModuleName(currModule); var externalLink = false; var targetModule = pdGetModuleFromUrl(url); if (!targetModule && currModule) { targetModule = currModule; } if (!targetModule) { // As a last resort, try to parse the path portion (e.g., /mod_myRewards/) try { var tmpUrl = new URL(url, window.location.origin); var parts = tmpUrl.pathname.split('/').filter(function(p){ return p; }); var maybeMod = parts.find(function(p){ return p.indexOf('mod_') === 0; }); if (maybeMod) targetModule = maybeMod; } catch(e) {} } pdLog('pdOneAjaxLinkHandler: targetModule =', targetModule, 'currModule =', currModule); pdLog('pdOneAjaxLinkHandler: targetModule decision point; targetModule=', targetModule); if (targetModule === 'mod_myRewards' && pdGetAccountIntegrationModel() !== 'b2b' && pdShouldUseRewards2025() && !pdRewardsForceLegacy) { var queryString = ''; try { var tmpUrl = new URL(url, window.location.origin); queryString = tmpUrl.search ? tmpUrl.search.substring(1) : ''; } catch(e) {} pdLog('pdOneAjaxLinkHandler: routing to pdLoadRewards2025Ajax with query:', queryString); pdLoadRewards2025Ajax({ method: 'GET', queryString: queryString }); return; } //assume http or https is external link var testUrl = url; var testUrlNoQuery = url.substring(0, testUrl.indexOf('?')); if (testUrlNoQuery !== ''){ if ((url.includes('https://') || url.includes('http://')) && !testUrlNoQuery.includes('mod_')){ externalLink = true; } } if (!externalLink && currModule !== '' && currModule !== undefined) { testUrl = testUrl.replace('https://', ''); testUrl = testUrl.replace('http://', ''); replaceStart = testUrl.indexOf('/'); if (replaceStart == -1){ replaceStart = 0; } testurl = testUrl.substring(replaceStart); //If no 'mod_' present assume reference path to current module and create absolute path if (!url.includes('mod_')){ url = pdPublicUrl+'/'+currModule+'/'+testurl; } //Else assume link to other module and create absolute path else { url = pdPublicUrl+'/'+testurl; } if (currModule) { url += (url.indexOf('?') !== -1 ? '&' : '?') + 'module=' + currModule; } } //Perform ajax if not linking to external site if (!externalLink){ if (url.includes('?')){ url += '&mode=inject'; } else { url += '?mode=inject'; } fetch(url, { method: 'POST', credentials: 'include' }) .then(function(response) { return response.text(); }) .then(function(result) { pdLog('pdOneAjaxLinkHandler success; length:', (result || '').length); var accountContent = pdGetAccountContentContainer(); if (accountContent) { accountContent.innerHTML = result; pdCleanupB2BInjectedHeading(accountContent); } if (targetModule === 'mod_myRewards' && pdGetAccountIntegrationModel() !== 'b2b') { pdLog('pdOneAjaxLinkHandler: running pdRunScriptsIn for mod_myRewards.'); pdRunScriptsIn(accountContent); } }) .catch(function(errMsg) { pdLog('pdOneAjaxLinkHandler error', errMsg && errMsg['statusText']); }); } else { // window.location.href = url; } } function pdOneAjaxFormHandler(form, module){ var dataElem = document.querySelector('#pdModuleData'); var contentElem = document.querySelector('#pdModuleContent'); var currModule = dataElem ? dataElem.getAttribute('data-currmodule') : null; if (currModule == undefined){ currModule = contentElem ? contentElem.getAttribute('data-currmodule') : null; } currModule = pdNormalizeModuleName(currModule); if (currModule === 'mod_myRewards' && pdGetAccountIntegrationModel() !== 'b2b' && pdShouldUseRewards2025()) { var method = (form.getAttribute('method') || 'GET').toUpperCase(); var formParams = new URLSearchParams(new FormData(form)); if (method === 'GET') { pdLoadRewards2025Ajax({ method: 'GET', queryString: formParams.toString() }); } else { pdLoadRewards2025Ajax({ method: method, body: formParams }); } return; } var formData = new FormData(form); pdLog(Array.from(formData.entries())); var method = form.getAttribute('method') || 'GET'; var url = form.getAttribute('action') || ''; replaceStart = url.indexOf('/'); if (replaceStart == -1){ replaceStart = 0; } url = url.substring(replaceStart); url = pdPublicUrl+'/'+currModule+'/'+url+'?module='+currModule; if (url.includes('?')){ url += '&mode=inject'; } else { url += '?mode=inject'; } if (url.includes('?')){ url += '&module='+currModule; } else { url += '?module='+currModule; } var formParams = new URLSearchParams(formData); var fetchUrl = url; var fetchOptions = { method: method.toUpperCase(), credentials: 'include' }; if (fetchOptions.method === 'GET') { if (formParams.toString()) { fetchUrl += (fetchUrl.includes('?') ? '&' : '?') + formParams.toString(); } } else { fetchOptions.headers = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }; fetchOptions.body = formParams; } fetch(fetchUrl, fetchOptions) .then(function(response) { return response.text(); }) .then(function(result) { pdLog('pdOneAjaxFormHandler success; length:', (result || '').length); var moduleContainerSelector = '#pdModuleContent'; var moduleContainer = form.closest(moduleContainerSelector); if (moduleContainer) { moduleContainer.outerHTML = result; } if (currModule === 'mod_myRewards' && pdShouldUseRewards2025() && !pdRewardsForceLegacy) { pdLog('pdOneAjaxFormHandler: running pdRunScriptsIn for mod_myRewards.'); if (pdGetAccountIntegrationModel() !== 'b2b') { pdRunScriptsIn(document.querySelector(moduleContainerSelector)); } } }) .catch(function(errMsg) { pdLog('pdOneAjaxFormHandler error', errMsg); }); }var script = document.createElement('style'); script.setAttribute('type', 'text/css'); script.innerHTML = ``; document.getElementsByTagName('head')[0].appendChild(script); //*** COMPLETION CALLBACK try{pdContentRenderCompleted()}catch(e){}; //*** done.