PageSourceSearch

https://www.brandsmartusa.com/cdn/shop/t/5/assets/store-selector.js?v=75465052521961160401790868989

js brandsmartusa.com collected 2026-10-03 23:55:45 UTC 53,558 bytes, 91 lines download raw bytes

1(()=>{"use strict";const escapeHtml=s=>s==null?"":String(s).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),STORE_LOCATOR_ICON_SVG='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" class="store-selector-icon" aria-hidden="true" focusable="false"><path d="M13.5 3.5H2.83337" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="square"/><path d="M2.16675 7.5V14.5C2.16675 15.0523 2.61446 15.5 3.16675 15.5H7.16675C7.71903 15.5 8.16675 15.0523 8.16675 14.5V12.5C8.16675 11.9477 8.61446 11.5 9.16675 11.5H10.5001C11.0524 11.5 11.5001 11.9477 11.5001 12.5V14.5C11.5001 15.0523 11.9478 15.5 12.5001 15.5H13.1667C13.719 15.5 14.1667 15.0523 14.1667 14.5V7.5" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="square"/><path d="M13.5 3.16667C13.5 3.38304 13.5702 3.59357 13.7 3.76667L15.3 5.9C15.4299 6.0731 15.5 6.28363 15.5 6.5C15.5 7.05229 15.0523 7.5 14.5 7.5H1.83337C1.28109 7.5 0.833374 7.05229 0.833374 6.5C0.833374 6.28363 0.903552 6.0731 1.03337 5.9L2.63337 3.76667C2.7632 3.59357 2.83337 3.38304 2.83337 3.16667V1.83334C2.83337 1.28105 3.28109 0.833336 3.83337 0.833336H12.5C13.0523 0.833336 13.5 1.28105 13.5 1.83334V3.16667Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="square"/><path d="M6.16675 9.5H4.16675V11.5H6.16675V9.5Z" fill="currentColor"/></svg>',haversineMeters=(lat1,lon1,lat2,lon2)=>{const toRad=d=>d*Math.PI/180,dLat=toRad(lat2-lat1),dLon=toRad(lon2-lon1),a=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.sin(dLon/2)*Math.sin(dLon/2);return 12742e3*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))},richTextTextNodeToHtml=node=>{if(!node||node.type!=="text")return"";let t=escapeHtml(node.value||"");return node.italic&&(t=`<em>${t}</em>`),node.bold&&(t=`<strong>${t}</strong>`),node.underline&&(t=`<u>${t}</u>`),node.strikethrough&&(t=`<s>${t}</s>`),t},richTextChildrenToHtml=children=>{if(!children?.length)return"";let html="";for(const child of children)if(child.type==="text")html+=richTextTextNodeToHtml(child);else if(child.type==="paragraph"){const inner=richTextChildrenToHtml(child.children),ch=child.children;Array.isArray(ch)&&ch.length===1&&ch[0]?.type==="heading"?html+=inner:inner&&(html+=`<p>${inner}</p>`)}else if(child.type==="heading"){const lvl=Math.min(6,Math.max(1,parseInt(String(child.level),10)||3));html+=`<h${lvl}>${richTextChildrenToHtml(child.children)}</h${lvl}>`}else if(child.type==="list"){const tag=child.listType==="ordered"?"ol":"ul";html+=`<${tag}>${richTextChildrenToHtml(child.children)}</${tag}>`}else if(child.type==="list-item")html+=`<li>${richTextChildrenToHtml(child.children)}</li>`;else if(child.type==="link"){const href=escapeHtml(child.url||"#"),titleAttr=typeof child.title=="string"&&child.title.trim()?` title="${escapeHtml(child.title.trim())}"`:"",blank=child.target==="_blank"?' target="_blank" rel="noopener noreferrer"':' rel="noopener noreferrer"';html+=`<a href="${href}"${titleAttr}${blank}>${richTextChildrenToHtml(child.children)}</a>`}else child.type==="bold"?html+=`<strong>${richTextChildrenToHtml(child.children)}</strong>`:child.type==="italic"?html+=`<em>${richTextChildrenToHtml(child.children)}</em>`:child.type==="blockquote"?html+=`<blockquote>${richTextChildrenToHtml(child.children)}</blockquote>`:child.type==="line-break"||child.type==="linebreak"||child.type==="break"?html+="<br>":child?.children?.length&&(html+=richTextChildrenToHtml(child.children));return html},convertRichMetafieldValue=value=>{if(value==null||value==="")return"";try{const j=JSON.parse(value);if(j?.type==="root"&&j.children)return richTextChildrenToHtml(j.children)}catch{}return escapeHtml(value).replace(/\n/g,"<br>")},metafieldByKey=(location,key)=>{const list=location.metafields;return list?.length&&list.find(m=>m?.key===key)||null},locationPageUrlFromLocation=location=>{const ref=metafieldByKey(location,"location_url")?.reference;if(!ref||typeof ref!="object")return"";const direct=ref.onlineStoreUrl||ref.url;if(typeof direct=="string"&&direct.trim())return direct.trim();const h=typeof ref.handle=="string"?ref.handle.trim():"";return h&&ref.__typename==="Page"?`${String(window.Shopify?.routes?.root||"/").replace(/\/?$/,"")||""}/pages/${encodeURIComponent(h)}`:""},storefrontFetch=(query,variables)=>{const token=typeof window.storefront?.token=="string"?window.storefront.token.trim():"";return!window.storefront?.url||!token?Promise.resolve(null):fetch(window.storefront.url,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":token},body:JSON.stringify({query,variables:variables||{}})}).then(async r=>{let json=null;try{json=await r.json()}catch(e){return console.warn("[store-selector] Storefront response was not JSON",e),null}return r.ok?(json.errors?.length&&console.warn("[store-selector] GraphQL errors",json.errors),!json.data&&json.errors?.length?null:json.data||null):(console.warn("[store-selector] Storefront HTTP",r.status,json),null)}
1).catch(e=>(console.warn("[store-selector]",e),null))},locationsQuery=ns=>{const safe=String(ns||"custom").replace(/[^a-zA-Z0-9_]/g,"");return`query StoreSelectorLocations {
2      locations(first: 50) {
3        nodes {
4          id
5          name
6          address {
7            address1
8            address2
9            city
10            province
11            provinceCode
12            zip
13            phone
14            country
15            latitude
16            longitude
17          }
18          mf_email: metafield(namespace: "${safe}", key: "store_email") {
19            namespace
20            key
21            value
22            type
23          }
24          mf_instagram: metafield(namespace: "${safe}", key: "store_instagram") {
25            namespace
26            key
27            value
28            type
29          }
30          mf_hours: metafield(namespace: "${safe}", key: "store_hours") {
31            namespace
32            key
33            value
34            type
35          }
36          mf_location_hours: metafield(namespace: "${safe}", key: "location_hours") {
37            namespace
38            key
39            value
40            type
41          }
42          mf_location_url: metafield(namespace: "${safe}", key: "location_url") {
43            namespace
44            key
45            type
46            reference {
47              ... on Page {
48                __typename
49                handle
50                onlineStoreUrl
51              }
52            }
53          }
54        }
55      }
56    }`},normalizeLocationNode=node=>{if(!node||typeof node!="object"||Array.isArray(node.metafields))return node;const mfs=[node.mf_email,node.mf_instagram,node.mf_hours,node.mf_location_hours,node.mf_location_url].filter(
56Boolean),{mf_email,mf_instagram,mf_hours,mf_location_hours,mf_location_url,...rest}=node;return{...rest,metafields:mfs}},locationsQueryCoreOnly=()=>`query StoreSelectorLocationsCore {
57    locations(first: 50) {
58      nodes {
59        id
60        name
61        address {
62          address1
63          address2
64          city
65          province
66          provinceCode
67          zip
68          phone
69          country
70          latitude
71          longitude
72        }
73      }
74    }
75  }`,variantsByIdsQuery=()=>`query StoreSelectorVariants($ids: [ID!]!) {
76      nodes(ids: $ids) {
77        ... on ProductVariant {
78          id
79          title
80          product { title }
81          requiresShipping
82          storeAvailability(first: 50) {
83            nodes {
84              available
85              location { id }
86            }
87          }
88        }
89      }
90    }`,toVariantGids=ids=>{const out=[],seen={};for(const raw of ids){if(raw==null)continue;const n=String(raw).replace(/\D/g,"");!n||seen[n]||(seen[n]=1,out.push(`gid://shopify/ProductVariant/${n}`))}return out},getCart=()=>{let url=`${(window.Shopify?.routes?.root||"/").replace(/\/?$/,"/")}cart.js`;return window.routes?.cart_url&&(url=`${window.routes.cart_url.replace(/\/?$/,"")}.js`),fetch(url,{credentials:"same-origin"}).then(r=>r.json())},cartUpdateJsUrl=()=>{const base=window.Shopify?.routes?.root||"/";return window.routes?.cart_url?`${window.routes.cart_url.replace(/\/?$/,"")}/update.js`:`${base.replace(/\/?$/,"/")}cart/update.js`},sanitizeCartAttributeString=v=>v==null?"":String(v).replace(/\s+/g," ").trim(),compactLocationForCartAttribute=location=>{if(!location||typeof location!="object")return null;const a=location.address||{};return{id:location.id,name:sanitizeCartAttributeString(location.name),address1:sanitizeCartAttributeString(a.address1),address2:sanitizeCartAttributeString(a.address2),city:sanitizeCartAttributeString(a.city),province:sanitizeCartAttributeString(a.province),provinceCode:sanitizeCartAttributeString(a.provinceCode),zip:sanitizeCartAttributeString(a.zip),country:sanitizeCartAttributeString(a.country),phone:sanitizeCartAttributeString(a.phone)}},PREFERRED_PICKUP_LOCATION_CART_KEY="preferred_pickup_location_id",verifyCartLocationAttributes=compact=>{const wantId=String(compact.id).trim();return getCart().then(cart=>{const a=cart.attributes||{};if(String(a[PREFERRED_PICKUP_LOCATION_CART_KEY]||"").trim()!==wantId)return!1;try{const o=JSON.parse(a.selected_location||"{}");return String(o?.id||"").trim()===wantId}catch{return!1}})},postLocationAttributesToCart=(compact,payload)=>getCart().then(cart=>{const attrs={...cart.attributes||{}};return attrs.selected_location=payload,attrs[PREFERRED_PICKUP_LOCATION_CART_KEY]=String(compact.id),fetch(cartUpdateJsUrl(),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"same-origin",body:JSON.stringify({attributes:attrs})})}),syncSelectedLocationToCart=location=>{if(window.storeSelector?.persistSelectedStoreToCart===!1)return Promise.resolve();let compact=compactLocationForCartAttribute(location);if(!compact?.id)return Promise.resolve();let payload=JSON.stringify(compact);const maxLen=4500;for(;payload.length>maxLen;)if(compact={id:compact.id,name:(compact.name||"").slice(0,120)},payload=JSON.stringify(compact),payload.length>maxLen){compact={id:compact.id},payload=JSON.stringify(compact);break}const runOnce=()=>postLocationAttributesToCart(compact,payload).then(res=>{if(!res.ok)throw new Error(`cart/update.js ${res.status}`)});return runOnce().then(()=>verifyCartLocationAttributes(compact)).then(ok=>{if(!ok)return runOnce()}).then(()=>verifyCartLocationAttributes(compact)).then(ok=>{ok||console.warn("[store-selector] Cart attributes did not match after sync; check Network tab for /cart/update.js")}).catch(e=>{console.warn("[store-selector] Could not save selected location to cart attributes",e)})},syncPreferredPickupToCartFromLocalStorage=()=>{if(window.storeSelector?.persistSelectedStoreToCart===!1)return Promise.resolve();let location=null;try{const raw=window.localStorage.getItem("selected-location");if(!raw)return Promise.resolve();location=JSON.parse(raw)}catch{return Promise.resolve()}if(!location||typeof location!="object"||!location.id)return Promise.resolve();const gid=String(location.id);return getCart().then(cart=>{const attrs=cart.attributes||{},pref=String(attrs[PREFERRED_PICKUP_LOCATION_CART_KEY]||"").trim(),gidNorm=String(gid).trim();let innerIdMatches=!1;if(attrs.selected_location)try{const o=JSON.parse(attrs.selected_location);innerIdMatches=String(o?.id||"").trim()===gidNorm}catch{innerIdMatches=!1}if(!(pref===gidNorm&&innerIdMatches))return syncSelectedLocationToCart(location)}).catch(()=>{})},flushCartLocationFromLocalStorageToCart=()=>{if(window.storeSelector?.persistSelectedStoreToCart===!1)return Promise.resolve();let location=null;try{const raw=window.localStorage.getItem("selected-location");if(!raw)return Promise.resolve();location=JSON.parse(raw)}catch{return Promise.resolve()}return!location||typeof location!="object"||!location.id?Promise.resolve():syncSelectedLocationToCart(location)};typeof window<"u"&&(window.storeSelectorSyncPreferredPickupFromStorage=syncPreferredPickupToCartFromLocalStorage,window.storeSelectorFlushCartLocationFromStorageForCheckout=flushCartLocationFromLocalStorageToCart);
90let _storeSelectorBypassCheckoutCapture=!1;typeof document<"u"&&document.addEventListener("submit",e=>{if(_storeSelectorBypassCheckoutCapture)return;const form=e.target;if(!(form instanceof HTMLFormElement)||window.storeSelector?.persistSelectedStoreToCart===!1||!form.querySelector('[name="checkout"]'))return;let hasLocation=!1;try{const raw=window.localStorage.getItem("selected-location");if(raw){const loc=JSON.parse(raw);hasLocation=!!(loc&&typeof loc=="object"&&loc.id)}}catch{hasLocation=!1}if(!hasLocation)return;const fid=form.getAttribute("id"),rawSubmitter=e.submitter,submitter=rawSubmitter instanceof HTMLElement&&(form.contains(rawSubmitter)||fid&&rawSubmitter.getAttribute("form")===fid&&rawSubmitter.getAttribute("name")==="checkout")?rawSubmitter:null;e.preventDefault(),e.stopImmediatePropagation(),flushCartLocationFromLocalStorageToCart().catch(()=>{}).finally(()=>{_storeSelectorBypassCheckoutCapture=!0;try{const btn=submitter||form.querySelector('button[type="submit"][name="checkout"], input[type="submit"][name="checkout"]');btn&&typeof form.requestSubmit=="function"?form.requestSubmit(btn):typeof form.requestSubmit=="function"?form.requestSubmit():HTMLFormElement.prototype.submit.call(form)}catch{HTMLFormElement.prototype.submit.call(form)}finally{_storeSelectorBypassCheckoutCapture=!1}})},!0);let storeSelectorVisibilityFlushTimer=0;if(typeof window<"u"&&window.addEventListener("pageshow",()=>{window.storeSelector?.persistSelectedStoreToCart!==!1&&syncPreferredPickupToCartFromLocalStorage()}),typeof document<"u"){const flushCartFromLsDebounced=()=>{window.storeSelector?.persistSelectedStoreToCart!==!1&&(window.clearTimeout(storeSelectorVisibilityFlushTimer),storeSelectorVisibilityFlushTimer=window.setTimeout(()=>{syncPreferredPickupToCartFromLocalStorage()},250))};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&flushCartFromLsDebounced()})}const STORE_SELECTOR_PASSIVE_GEO_KEY="store-selector-passive-geo",STORE_SELECTOR_PASSIVE_GEO_MAX_MS=300*1e3,STORE_SELECTOR_IP_GEO_KEY="store-selector-ip-geo",STORE_SELECTOR_IP_GEO_MAX_MS=1440*60*1e3,formatMilesFromMeters=meters=>{if(meters==null||!Number.isFinite(meters)||meters<0)return"";const mi=meters/1609.344;return mi<.05?"0.1 mi":`${mi<10?mi.toFixed(1):String(Math.round(mi))} mi`},parseUserLocationCoords=()=>{try{const raw=window.localStorage.getItem("user-location");if(!raw)return null;const u=JSON.parse(raw),lat=parseFloat(u.latitude),lng=parseFloat(u.longitude);return Number.isNaN(lat)||Number.isNaN(lng)?null:{lat,lng}}catch{return null}},parsePassiveGeoCoords=()=>{try{const raw=window.sessionStorage.getItem(STORE_SELECTOR_PASSIVE_GEO_KEY);if(!raw)return null;const o=JSON.parse(raw),at=typeof o.at=="number"?o.at:0;if(Date.now()-at>STORE_SELECTOR_PASSIVE_GEO_MAX_MS)return null;const lat=parseFloat(o.latitude),lng=parseFloat(o.longitude);return Number.isNaN(lat)||Number.isNaN(lng)?null:{lat,lng}}catch{return null}},parseIpGeoCoords=()=>{try{const raw=window.sessionStorage.getItem(STORE_SELECTOR_IP_GEO_KEY);if(!raw)return null;const o=JSON.parse(raw),at=typeof o.at=="number"?o.at:0;if(Date.now()-at>STORE_SELECTOR_IP_GEO_MAX_MS)return null;const lat=parseFloat(o.latitude),lng=parseFloat(o.longitude);return Number.isNaN(lat)||Number.isNaN(lng)?null:{lat,lng}}catch{return null}},referenceCoordsForStoreDistance=()=>parseUserLocationCoords()||parsePassiveGeoCoords()||parseIpGeoCoords(),distanceMetersFromUserLocation=location=>{const ref=referenceCoordsForStoreDistance();if(!ref)return null;try{const a=location?.address||{},lat2=parseFloat(a.latitude),lng2=parseFloat(a.longitude);return Number.isNaN(lat2)||Number.isNaN(lng2)?null:haversineMeters(ref.lat,ref.lng,lat2,lng2)}catch{return null}},formatPhoneNumber=phoneNumberString=>{const match=`${phoneNumberString}`.replace(/\D/g,"").match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);return match?`${match[1]?"+1 ":""}${match[2]}-${match[3]}-${match[4]}`:phoneNumberString},strCfg=(key,fallback)=>{const o=window.storeSelector||{};return o[key]!=null&&o[key]!==""?o[key]:fallback},cleanStoreName=name=>{const n=String(name||"").replace(/_\d+$/,"").trim();return/^Lauderhill Clearance$/i.test(n)?"Clearance Outlet":n},storeDisplayLabel=location=>{const cleaned=cleanStoreName(location?.name);if(cleaned)return cleaned;const a=location?.address||{},city=String(a.city||"").trim(),region=String(a.provinceCode||a.province||"").trim();
90return[city,region].filter(Boolean).join(", ")},storeSelectorMinDistanceMeters=(userLat,userLng,locations)=>{let min=1/0;if(!locations?.length)return min;for(const loc of locations){const a=loc.address;if(!a)continue;const la=parseFloat(a.latitude),lo=parseFloat(a.longitude);if(Number.isNaN(la)||Number.isNaN(lo))continue;const d=haversineMeters(userLat,userLng,la,lo);d<min&&(min=d)}return min};let passiveGeoRequestInFlight=!1,ipGeoRequestInFlight=!1;function beginIpGeoIfProximityGate(){if(window.storeSelector?.proximityGateEnabled===!0&&!(parseUserLocationCoords()||parsePassiveGeoCoords())){if(parseIpGeoCoords()){updateStoreSelectorHeaderVisibility();return}ipGeoRequestInFlight||typeof fetch=="function"&&(ipGeoRequestInFlight=!0,fetch("https://ipwho.is/",{method:"GET",credentials:"omit",cache:"no-store"}).then(r=>r.ok?r.json():Promise.reject(new Error(String(r.status)))).then(data=>{if(ipGeoRequestInFlight=!1,!data||data.success===!1)return;const lat=parseFloat(data.latitude),lng=parseFloat(data.longitude);if(!(Number.isNaN(lat)||Number.isNaN(lng))){try{window.sessionStorage.setItem(STORE_SELECTOR_IP_GEO_KEY,JSON.stringify({latitude:lat,longitude:lng,at:Date.now()}))}catch{}updateStoreSelectorHeaderVisibility(),document.dispatchEvent(new CustomEvent("buildLocationsList",{bubbles:!0,detail:{skipInventoryRefresh:!0}}))}}).catch(()=>{ipGeoRequestInFlight=!1}))}}function beginPassiveGeoIfNoUserLocation(){if(!(typeof navigator>"u"||!navigator.geolocation)&&!parseUserLocationCoords()&&!(parsePassiveGeoCoords()||parseIpGeoCoords())&&!passiveGeoRequestInFlight){try{const raw=window.sessionStorage.getItem(STORE_SELECTOR_PASSIVE_GEO_KEY);if(raw){const o=JSON.parse(raw);if(typeof o?.at=="number"&&Date.now()-o.at<STORE_SELECTOR_PASSIVE_GEO_MAX_MS)return}}catch{}passiveGeoRequestInFlight=!0,navigator.geolocation.getCurrentPosition(pos=>{passiveGeoRequestInFlight=!1;try{window.sessionStorage.setItem(STORE_SELECTOR_PASSIVE_GEO_KEY,JSON.stringify({latitude:pos.coords.latitude,longitude:pos.coords.longitude,at:Date.now()}))}catch{}document.dispatchEvent(new CustomEvent("buildLocationsList",{bubbles:!0,detail:{skipInventoryRefresh:!0}})),updateStoreSelectorHeaderVisibility()},()=>{passiveGeoRequestInFlight=!1},{enableHighAccuracy:!1,timeout:12e3,maximumAge:12e4})}}const updateStoreSelectorHeaderVisibility=()=>{const wraps=document.querySelectorAll("[data-store-selector-header-toggle]");if(!wraps.length)return;const proximityOnly=window.storeSelector?.proximityGateEnabled===!0,el=document.querySelector("store-selector"),locations=Array.isArray(el?.locations)?el.locations:[],maxM=window.storeSelector?.headerToggleMaxMeters>0?window.storeSelector.headerToggleMaxMeters:160934.4,ref=referenceCoordsForStoreDistance(),lat=ref?ref.lat:NaN,lng=ref?ref.lng:NaN;let show=!1;if(!proximityOnly)show=!0;else if(!locations.length)show=!1;else if(!Number.isNaN(lat)&&!Number.isNaN(lng)){const minD=storeSelectorMinDistanceMeters(lat,lng,locations);minD===1/0?show=!1:show=minD<=maxM}else show=!1;wraps.forEach(w=>{show?(w.hidden=!1,w.removeAttribute("hidden")):(w.hidden=!0,w.setAttribute("hidden","")),w.setAttribute("aria-hidden",show?"false":"true"),w.classList.toggle("store-selector-header-wrap--visible",show)}),show&&document.querySelectorAll("store-selector-toggle").forEach(toggle=>{typeof toggle.updateButtonText=="function"&&toggle.updateButtonText()}),proximityOnly&&locations.length>0&&!referenceCoordsForStoreDistance()&&(beginPassiveGeoIfNoUserLocation(),beginIpGeoIfProximityGate())};window.updateStoreSelectorHeaderVisibility=updateStoreSelectorHeaderVisibility,window.addEventListener("load",()=>{updateStoreSelectorHeaderVisibility()});const onDomReady=fn=>{document.readyState==="loading"?document.addEventListener("DOMContentLoaded",fn):fn()};typeof window<"u"&&typeof window.gm_authFailure!="function"&&(window.gm_authFailure=function(){console.warn("[store-selector] Google Maps could not authenticate this page. In Google Cloud Console: enable billing on the project; enable Maps JavaScript API and Places API; under API key restrictions allow HTTP referrers for your storefront (e.g. https://your-domain.com/* and https://*.myshopify.com/*). Theme setting: Store selector \u2192 Google Maps API key.")});let _storeSelectorGmapsScriptPromise=null;function ensureStoreSelectorGoogleMapsScript(){if(typeof window>"u"||window.google?.maps)return Promise.resolve();const key=typeof window.storeSelector?.googleMapsKey=="string"?window.storeSelector.googleMapsKey.trim():"";return key?_storeSelectorGmapsScriptPromise||(_storeSelectorGmapsScriptPromise=new Promise(resolve=>
90{const existing=document.querySelector("script[data-store-selector-google-maps]");if(existing){if(window.google?.maps){queueMicrotask(resolve);return}existing.addEventListener("load",()=>resolve(),{once:!0}),existing.addEventListener("error",()=>resolve(),{once:!0});return}const s=document.createElement("script");s.async=!0,s.defer=!0,s.dataset.storeSelectorGoogleMaps="",s.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(key)}&libraries=places`,s.onload=()=>resolve(),s.onerror=()=>{console.warn("[store-selector] Google Maps script failed to load (network, CSP, or blocked URL)."),s.remove(),_storeSelectorGmapsScriptPromise=null,resolve()},document.head.appendChild(s)}),_storeSelectorGmapsScriptPromise):Promise.resolve()}const formatAddressForStoreGeocode=address=>!address||typeof address!="object"?"":[address.address1,address.address2,address.city,address.provinceCode||address.province,address.zip,address.country].filter(p=>p!=null&&String(p).trim()!=="").join(", ").trim(),googleMapsSearchUrlFromAddress=address=>{const q=formatAddressForStoreGeocode(address);return q?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(q)}`:""},locationMissingLatLng=location=>{const a=location?.address||{},la=parseFloat(a.latitude),lo=parseFloat(a.longitude);return Number.isNaN(la)||Number.isNaN(lo)};function enrichLocationsWithGeocodedAddresses(locations){if(!Array.isArray(locations)||!locations.length)return Promise.resolve();const toGeocode=locations.filter(loc=>locationMissingLatLng(loc)&&formatAddressForStoreGeocode(loc.address).length>0);return toGeocode.length?ensureStoreSelectorGoogleMapsScript().then(()=>{if(!window.google?.maps?.Geocoder)return;const geocoder=new google.maps.Geocoder;return toGeocode.reduce((chain,loc)=>chain.then(()=>new Promise(resolve=>{const q=formatAddressForStoreGeocode(loc.address);if(!q){resolve();return}geocoder.geocode({address:q},(results,status)=>{try{if(status==="OK"&&results?.[0]?.geometry?.location){const ll=results[0].geometry.location;loc.address||(loc.address={}),loc.address.latitude=ll.lat(),loc.address.longitude=ll.lng()}}catch{}resolve()})})),Promise.resolve())}).catch(()=>{}):Promise.resolve()}if(!window.customElements.get("store-selector")){class StoreSelector extends HTMLElement{constructor(){super(),this.locations=[],this.input=null,this.currentLocationButton=null,this.useCurrentLocationText=null,this.locationsCount=null,this.locationsCountText=null,this.locationsList=null,this._searchBasicsBound=!1,this._placesAutocomplete=null,this._searchFilter="",this._drawerListSnapshot=null,this._autoSelectingNearestLocation=!1}clearDrawerListSnapshot(){this._drawerListSnapshot=null}_applyLocationsListDom(selectedLocation,locationDistances,productVariant,cartVariantInventoryLevels){if(!this.locationsList){this.buildLocationsCount();return}this.locationsList.innerHTML="";const ref=referenceCoordsForStoreDistance(),ordered=[];locationDistances?locationDistances.forEach(ld=>{const matchingLocation=this.locations.find(l=>l.id===ld.id);matchingLocation&&ordered.push({location:matchingLocation,distance:ld.distance})}):this.locations.forEach((location,index)=>{if(!location||!this.locationMatchesSearchFilter(location))return;const a=location.address||{},lat=parseFloat(a.latitude),lng=parseFloat(a.longitude),distance=ref&&!Number.isNaN(lat)&&!Number.isNaN(lng)?haversineMeters(ref.lat,ref.lng,lat,lng):null;ordered.push({location,distance,index})}),ordered.filter(item=>this.locationMatchesSearchFilter(item.location)).sort((a,b)=>{const ad=a.distance,bd=b.distance,aKnown=Number.isFinite(ad),bKnown=Number.isFinite(bd);return aKnown&&bKnown?ad-bd:aKnown?-1:bKnown?1:(a.index??0)-(b.index??0)}).forEach(item=>{this.addLocation(item.location,selectedLocation,productVariant,cartVariantInventoryLevels,item.distance)}),this.buildLocationsCount()}locationMatchesSearchFilter(location){const q=(this._searchFilter||"").trim().toLowerCase();if(!q)return!0;const name=(location?.name||"").toLowerCase(),a=location?.address||{};return[name,a.address1,a.address2,a.city,a.province,a.provinceCode,a.zip,a.country].filter(
90Boolean).join(" ").toLowerCase().includes(q)}clearAddressSearch(){this.clearAddressSearchError(),this._searchFilter="",this.input&&(this.input.value="");try{window.localStorage.removeItem("user-location"),window.localStorage.removeItem("location-distances")}catch{}document.dispatchEvent(new Event("calculateDistances")),this.buildLocationsCount(),this.buildLocationsList(),updateStoreSelectorHeaderVisibility()}clearAddressSearchError(){this.searchErrorEl&&(this.searchErrorEl.textContent="",this.searchErrorEl.hidden=!0),this.input&&(this.input.removeAttribute("aria-invalid"),this.input.removeAttribute("aria-describedby"))}reportAddressSearchError(message,detail={}){const msg=typeof message=="string"&&message.trim()!==""?message:strCfg("addressGeocodeFailed","Could not resolve that address."),payload={bubbles:!0,composed:!0,detail:{message:msg,input:this.input,...detail}};document.dispatchEvent(new CustomEvent("store-selector:address-search-error",payload)),document.dispatchEvent(new CustomEvent("storeSelectorError",payload)),this.searchErrorEl&&(this.searchErrorEl.textContent=msg,this.searchErrorEl.hidden=!1),this.input&&(this.input.setAttribute("aria-invalid","true"),this.input.setAttribute("aria-describedby","store-selector-search-error"))}submitAddressSearch(){this.clearAddressSearchError();const q=(this.input?.value||"").trim();if(!q)return;const key=typeof window.storeSelector?.googleMapsKey=="string"?window.storeSelector.googleMapsKey.trim():"",done=(lat,lng,name)=>{this.clearAddressSearchError(),this._searchFilter="",window.localStorage.setItem("user-location",JSON.stringify({latitude:lat,longitude:lng,name:name||q})),this.input&&(this.input.value=name||q),document.dispatchEvent(new Event("calculateDistances"))};if(window.google?.maps?.Geocoder){new google.maps.Geocoder().geocode({address:q},(results,status)=>{if(status!=="OK"||!results?.[0]?.geometry?.location){console.warn("[store-selector] Geocode",status,results),this.reportAddressSearchError(strCfg("addressGeocodeFailed","Could not find that address. Try again."),{reason:"geocode",geocodeStatus:status});return}const loc=results[0].geometry.location;done(loc.lat(),loc.lng(),results[0].formatted_address||results[0].name||q)});return}if(key){this.loadGoogleMaps(()=>{if(window.google?.maps?.Geocoder){this.submitAddressSearch();return}this.reportAddressSearchError(strCfg("addressMapsLoadFailed","Maps could not load. Check your connection or API key."),{reason:"maps_load"})});return}this.reportAddressSearchError(strCfg("addressSearchRequiresMaps","Add a Google Maps API key in theme settings to search by address, or pick a store from the list."),{reason:"no_maps_key"})}bindSearchBasicsOnce(){if(this._searchBasicsBound)return;this._searchBasicsBound=!0;const clearBtn=this.querySelector("[data-store-selector-clear]");clearBtn&&clearBtn.addEventListener("click",()=>this.clearAddressSearch());const applyBtn=this.querySelector("[data-store-selector-apply]");if(applyBtn&&applyBtn.addEventListener("click",()=>this.submitAddressSearch()),this.input){let debounceTimer;this.input.addEventListener("input",()=>{this.clearAddressSearchError(),clearTimeout(debounceTimer),debounceTimer=setTimeout(()=>{this._searchFilter=this.input.value,this.buildLocationsList()},200)}),this.input.addEventListener("keydown",e=>{e.key==="Enter"&&(e.preventDefault(),this.submitAddressSearch())})}}ensureGooglePlacesAutocomplete(){this._placesAutocomplete||!window.storeSelector?.googleMapsKey||this.input&&this.loadGoogleMaps(()=>{if(!window.google?.maps?.places||!this.input)return;const country=window.storeSelector?.autocompleteCountry||"US";this._placesAutocomplete=new google.maps.places.Autocomplete(this.input,{componentRestrictions:{country:String(country).toLowerCase()},fields:["address_components","geometry","name","formatted_address"],strictBounds:!1}),google.maps.event.addListener(this._placesAutocomplete,"place_changed",()=>{const place=this._placesAutocomplete.getPlace();place.geometry?.location&&(this.clearAddressSearchError(),window.localStorage.setItem("user-location",JSON.stringify({latitude:place.geometry.location.lat(),longitude:place.geometry.location.lng(),name:place.formatted_address||place.name||this.input.value||""})),this.input&&(this.input.value=place.formatted_address||place.name||this.input.value||""),this._searchFilter="",document.dispatchEvent(new Event("calculateDistances")))})})}scheduleSearchUiInit(){window.setTimeout(()=>{this.ensureGooglePlacesAutocomplete()},150)}connectedCallback(){this.input=this.querySelector("[data-store-selector-input]"),this.currentLocationButton=this.querySelector("[data-store-selector-use-current-location]"),this.useCurrentLocationText=this.querySelector("[data-store-selector-use-current-location-text]"),this.locationsCountRow=this.querySelector("[data-store-selector-count-row]"),this.locationsCount=this.querySelector("[data-store-selector-count]"),this.locationsCountText=this.querySelector("[data-store-selector-count-text]"),this.locationsList=this.querySelector("[data-store-selector-locations-list]"),this.emptyNearbyEl=this.querySelector("[data-store-selector-empty-nearby]"),this.emptyNearbyText=this.querySelector("[data-store-selector-empty-nearby-text]"),this.searchErrorEl=this.querySelector("[data-store-selector-search-error]"),this.bindSearchBasicsOnce(),this._onGeolocateClick=e=>{e.preventDefault(),this.getCurrentLocation(!1)},this._onGeolocateKeydown=e=>{e.key!==" "&&e.key!=="Spacebar"||(e.preventDefault(),this.getCurrentLocation(!1))},this.currentLocationButton&&(this.currentLocationButton.addEventListener("click",this._onGeolocateClick),this.currentLocationButton.addEventListener("keydown",this._onGeolocateKeydown)),this._onCalc=()=>{this.refreshDistanceOrdering(),this.useCurrentLocationText&&(this.useCurrentLocationText.innerText=strCfg("useCurrentLocation",""))},this._onOpen=()=>this.open(),this._onBuild=e=>{e?.detail?.skipInventoryRefresh||this.clearDrawerListSnapshot(),this.buildLocationsList()},this._onListCart=()=>{this.clearDrawerListSnapshot(),syncPreferredPickupToCartFromLocalStorage(),this.buildLocationsList()},this._onProductVariants=()=>{this.clearDrawerListSnapshot(),this.buildLocationsList()},this._onListClick=event=>this._handleListClick(event),document.addEventListener("calculateDistances",this._onCalc),document.addEventListener("openStoreSelector",this._onOpen),document.addEventListener("buildLocationsList",this._onBuild),window.addEventListener("listCart",this._onListCart),window.addEventListener("productVariants",this._onProductVariants),this.addEventListener("click",this._onListClick),onDomReady(()=>{beginPassiveGeoIfNoUserLocation(),beginIpGeoIfProximityGate(),syncPreferredPickupToCartFromLocalStorage(),this.getLocations()})}disconnectedCallback(){this.currentLocationButton&&(this._onGeolocateClick&&this.currentLocationButton.removeEventListener("click",this._onGeolocateClick),this._onGeolocateKeydown&&this.currentLocationButton.removeEventListener("keydown",this._onGeolocateKeydown)),document.removeEventListener("calculateDistances",this._onCalc),document.removeEventListener("openStoreSelector",this._onOpen),document.removeEventListener("buildLocationsList",this._onBuild),window.removeEventListener("listCart",this._onListCart),window.removeEventListener("productVariants",this._onProductVariants),this.removeEventListener("click",this._onListClick)}_handleListClick(event){showBMLoader();const btn=event.target.closest("[data-store-selector-store-select]");if(!btn||!this.contains(btn))return;const id=btn.getAttribute("data-location-id"),loc=this.locations.find(l=>l.id===id);if(!loc)return;
90this.selectLocation(loc),window._zetaFired??=new Set;const customerFields={};window.customerData?.isLoggedIn&&(window.customerData.customerId&&(customerFields.customerID=window.customerData.customerId),window.customerData.customerEmail&&(customerFields.customerEmail=window.customerData.customerEmail)),bt("track","select_store",{id:loc.id,name:loc.name,address:loc.address?`${loc.address.address1||""} ${loc.address.city||""} ${loc.address.provinceCode||""} ${loc.address.zip||""}`.trim():"",...customerFields});const psd=document.querySelector("product-shipping-details");psd&&typeof psd.checkBopisLocation=="function"&&(psd.checkBopisLocation(),psd.checkInventory()),setTimeout(()=>{hideBMLoader()},1500)}async _autoSelectNearestLocationIfNeeded(){if(this._autoSelectingNearestLocation)return!1;let selectedLocation=null;try{selectedLocation=window.localStorage.getItem("selected-location")?JSON.parse(window.localStorage.getItem("selected-location")):null}catch{}if(selectedLocation?.id||!this.locations?.length)return!1;const ref=referenceCoordsForStoreDistance();if(!ref)return!1;let nearestLocation=null,nearestDistance=1/0;for(const location of this.locations){const a=location.address||{},lat=parseFloat(a.latitude),lng=parseFloat(a.longitude);if(Number.isNaN(lat)||Number.isNaN(lng))continue;const d=haversineMeters(ref.lat,ref.lng,lat,lng);d<nearestDistance&&(nearestDistance=d,nearestLocation=location)}if(!nearestLocation)return!1;this._autoSelectingNearestLocation=!0;try{return await this.selectLocation(nearestLocation),!0}finally{this._autoSelectingNearestLocation=!1}}getLocations(){const ns=window.storeSelector?.metafieldNamespace||"custom",finish=data=>{try{const raw=data?.locations?.nodes,apiList=raw?.length?raw.map(normalizeLocationNode):[],hadApi=apiList.length>0;this.locations=apiList,data?.locations?!hadApi&&!this.locations.length&&console.info("[store-selector] No pickup locations from Storefront. Enable local pickup on at least one location (Shopify Admin \u2192 Settings \u2192 Locations) and confirm the Storefront token includes unauthenticated_read_product_pickup_locations."):console.warn("[store-selector] Storefront returned no locations data. Confirm the app token includes unauthenticated_read_product_pickup_locations, the API version matches your shop, and check GraphQL/HTTP messages logged above.")}catch(e){console.warn("[store-selector] Failed to process locations response",e),this.locations=[]}enrichLocationsWithGeocodedAddresses(this.locations).finally(()=>{this.refreshDistanceOrdering()})};return storefrontFetch(locationsQuery(ns)).then(data=>data?.locations?.nodes?.length||data?.locations?finish(data):storefrontFetch(locationsQueryCoreOnly()).then(finish))}loadGoogleMaps(cb){ensureStoreSelectorGoogleMapsScript().then(()=>{if(typeof cb=="function")try{cb()}catch(e){console.warn("[store-selector] Google Maps callback error",e)}})}syncSearchInputFromStorage(){let userLocation=null;try{userLocation=window.localStorage.getItem("user-location")?JSON.parse(window.localStorage.getItem("user-location")):null}catch{}this.input&&userLocation&&(this.input.value=userLocation.name||"")}calculateLocationDistances(){const raw=window.localStorage.getItem("user-location");if(!raw){updateStoreSelectorHeaderVisibility();return}let userLocation;try{userLocation=JSON.parse(raw)}catch{updateStoreSelectorHeaderVisibility();return}const lat=parseFloat(userLocation.latitude),lng=parseFloat(userLocation.longitude);if(Number.isNaN(lat)||Number.isNaN(lng)){updateStoreSelectorHeaderVisibility();return}const locationDistances=this.locations.map(location=>{const la=location.address||{},lat2=parseFloat(la.latitude),lng2=parseFloat(la.longitude),distance=Number.isNaN(lat2)||Number.isNaN(lng2)?1/0:haversineMeters(lat,lng,lat2,lng2);return{id:location.id,distance}});locationDistances.sort((a,b)=>parseFloat(a.distance)-parseFloat(b.distance)),window.localStorage.setItem("location-distances",JSON.stringify(locationDistances)),updateStoreSelectorHeaderVisibility()}refreshDistanceOrdering(){try{this.calculateLocationDistances()}catch{updateStoreSelectorHeaderVisibility()}this.buildLocationsCount(),this.buildLocationsList()}buildLocationsCount(){let locationDistances=null,userLocation=null;try{locationDistances=window.localStorage.getItem("location-distances")?JSON.parse(window.localStorage.getItem("location-distances")):null}catch{}try{userLocation=window.localStorage.getItem("user-location")?JSON.parse(window.localStorage.getItem("user-location")):null}catch{}const searchActive=(this._searchFilter||"").trim().length>0,usedProximityCount=!!(locationDistances?.length&&this.locations?.length);let count=0;
90if(usedProximityCount)for(const ld of locationDistances){const loc=this.locations.find(l=>l.id===ld.id);loc&&this.locationMatchesSearchFilter(loc)&&(count+=1)}else this.locations?.length&&(count=this.locations.filter(l=>this.locationMatchesSearchFilter(l)).length);this.locationsCount&&(this.locationsCount.textContent=String(count)),this.locationsCountText&&(searchActive?this.locationsCountText.textContent=strCfg("matchingSearchSuffix","MATCHING STORES"):userLocation?.name?.trim()?this.locationsCountText.textContent=`${strCfg("storesNearLabel","NEAR")} ${userLocation.name.trim()}`:this.locationsCountText.textContent=strCfg("totalStoresSuffix","TOTAL STORES")),this.locationsCountRow&&(this.locationsCountRow.hidden=!1),this.emptyNearbyEl&&(this.emptyNearbyEl.hidden=!0)}buildLocationsList(){if(this._autoSelectingNearestLocation)return Promise.resolve();let selectedLocation=null,locationDistances=null;try{selectedLocation=window.localStorage.getItem("selected-location")?JSON.parse(window.localStorage.getItem("selected-location")):null}catch{}try{window.localStorage.getItem("user-location")||window.localStorage.getItem("location-distances")&&window.localStorage.removeItem("location-distances")}catch{}try{locationDistances=window.localStorage.getItem("location-distances")?JSON.parse(window.localStorage.getItem("location-distances")):null}catch{}return this._drawerListSnapshot?this._autoSelectNearestLocationIfNeeded().then(didAutoSelect=>{didAutoSelect||this._applyLocationsListDom(selectedLocation,locationDistances,this._drawerListSnapshot.productVariant,this._drawerListSnapshot.cartVariantInventoryLevels)}):getCart().catch(()=>({items:[]})).then(cart=>{const variantIds=(cart.items||[]).map(item=>item.variant_id!=null?item.variant_id:item.id),gids=toVariantGids(variantIds),productVariantPromise=window.location.pathname.includes("/products/")?(()=>{const inp=document.querySelector('input.product-variant-id[name="id"]')||document.querySelector('form[id^="main-product-form"] input[name="id"]');if(!inp?.value)return Promise.resolve(null);const one=toVariantGids([inp.value]);return one.length?storefrontFetch(variantsByIdsQuery(),{ids:one}):Promise.resolve(null)})():Promise.resolve(null),cartLevelsPromise=gids.length>0?storefrontFetch(variantsByIdsQuery(),{ids:gids}):Promise.resolve(null);return Promise.all([productVariantPromise,cartLevelsPromise]).then(results=>{const[productVariant,cartVariantInventoryLevels]=results;return this._drawerListSnapshot={productVariant,cartVariantInventoryLevels},this._autoSelectNearestLocationIfNeeded().then(didAutoSelect=>{didAutoSelect||this._applyLocationsListDom(selectedLocation,locationDistances,productVariant,cartVariantInventoryLevels)})})})}addLocation(location,selectedLocation,productVariant,cartVariantInventoryLevels,distanceMeters){const cfg=window.storeSelector||{},inStockItems=[],outOfStockItems=[];let productAvailable=!1,productTitle="";const pvNode=productVariant?.nodes?.[0]||null;if(pvNode){productTitle=pvNode.title?.includes("Default Title")&&pvNode.product?.title?pvNode.product.title:pvNode.title;const sa=pvNode.storeAvailability?.nodes;if(sa){for(const node of sa)if(node.location?.id===location.id&&node.available){productAvailable=!0;break}}}cartVariantInventoryLevels?.nodes&&cartVariantInventoryLevels.nodes.forEach(variant=>{const nodes=variant.storeAvailability?.nodes;if((!nodes||nodes.length===0)&&!variant.requiresShipping)return;let matchingLocation=null;if(nodes&&nodes.length>0){for(const n of nodes)if(n.location?.id===location.id){matchingLocation=n;break}}matchingLocation&&(matchingLocation.available?inStockItems.push(matchingLocation):outOfStockItems.push(matchingLocation))});const locationEmail=metafieldByKey(location,"store_email"),locationInstagram=metafieldByKey(location,"store_instagram"),locationHours=metafieldByKey(location,"store_hours"),locationHoursRich=metafieldByKey(location,"location_hours"),addr=location.address||{},addrLine=[addr.address1?`${addr.address1},`:"",addr.address2?`${addr.address2},`:"",addr.city?`${addr.city},`:"",addr.province?`${addr.province},`:"",addr.zip||""].join(" ").replace(/\s+/g," ").trim(),distLabel=formatMilesFromMeters(distanceMeters),isSel=selectedLocation?.id===location.id,wrap=document.createElement("div");wrap.className=`store-selector__card${isSel?" is-selected":""}`,wrap.setAttribute("data-store-selector-location","");let html="";const titleText=escapeHtml(storeDisplayLabel(location)),detailUrl=locationPageUrlFromLocation(location);if(html+=detailUrl?`<h3 class="store-selector__card-title"><a class="store-selector__card-title-link" href="${escapeHtml(detailUrl)}">${titleText}</a></h3>`:`<h3 class="store-selector__card-title">${titleText}</h3>`,distLabel){const distText=strCfg("distanceFromLocation","{distance} away").replace(/\{distance\}/g,distLabel);html+=`<p class="store-selector__card-distance">${escapeHtml(distText)}</p>`}const isInValidCart=outOfStockItems.length>=1||inStockItems.length===0;let messageDisabled;if(outOfStockItems.length+inStockItems.length>0?messageDisabled=!!(pvNode&&!productAvailable||isInValidCart):messageDisabled=!!(pvNode&&!productAvailable),pvNode&&(html+=`<p class="store-selector__card-note store-selector__card-note--product-${messageDisabled?"unavailable":"available"}"><span class="store-selector__card-note-mark">${messageDisabled?"\u2717":"\u2713"}</span><span>${escapeHtml(productTitle||"")}  <span class="availability-status-${escapeHtml(messageDisabled?cfg.unavailable||"":cfg.available||"")}">${escapeHtml(productAvailable?cfg.available||"":cfg.unavailable||"")}</span></span></p>`),cartVariantInventoryLevels?.nodes?.length){const total=cartVariantInventoryLevels.nodes.length,bad=outOfStockItems.length>=1||inStockItems.length===0;html+=`<p class="store-selector__card-note store-selector__card-note--cart-${messageDisabled?"unavailable":"available"}"><span class="store-selector__card-note-mark">${messageDisabled?"\u2717":"\u2713"}</span><span>${escapeHtml(messageDisabled?"Some items in your bag are unavailable at this Store":"All items in your bag are available at this Store")}</span></p>`}const contactBits=[];if(addrLine){const mapsUrl=googleMapsSearchUrlFromAddress(addr),safeLine=escapeHtml(addrLine),addrVal=mapsUrl?`<a class="store-selector__card-address-link" href="${escapeHtml(mapsUrl)}" target="_blank" rel="noopener noreferrer">${safeLine}</a>`:safeLine;contactBits.push(`<div class="store-selector__card-row"><span class="store-selector__card-ico">
90${STORE_LOCATOR_ICON_SVG}</span><span class="store-selector__card-val">${addrVal}</span></div>`)}if(locationHoursRich?.value){const hoursRichHtml=convertRichMetafieldValue(locationHoursRich.value);hoursRichHtml&&contactBits.push(`<div class="store-selector__card-row store-selector__card-row--location-hours"><span class="store-selector__card-ico" aria-hidden="true"></span><div class="store-selector__card-val store-selector__card-val--richtext">${hoursRichHtml}</div></div>`)}if(addr.phone){const tel=String(addr.phone).replace(/\s+/g,""),phoneLabel=escapeHtml(formatPhoneNumber(String(addr.phone).replace("+1",""))||addr.phone);contactBits.push(`<div class="store-selector__card-row"><span class="store-selector__card-ico"><i class="icon-phone" aria-hidden="true"></i></span><span class="store-selector__card-val"><a href="tel:${escapeHtml(tel)}">${phoneLabel}</a></span></div>`)}if(locationEmail?.value){const em=String(locationEmail.value).trim(),safeText=escapeHtml(em),mailHref=escapeHtml(encodeURI(`mailto:${em}`));contactBits.push(`<div class="store-selector__card-row"><span class="store-selector__card-ico"><i class="icon-envelope" aria-hidden="true"></i></span><span class="store-selector__card-val"><a href="${mailHref}">${safeText}</a></span></div>`)}if(locationInstagram?.value){const ig=String(locationInstagram.value).replace(/^@/,""),igSafe=escapeHtml(ig);contactBits.push(`<div class="store-selector__card-row"><span class="store-selector__card-ico"><i class="icon-instagram" aria-hidden="true"></i></span><span class="store-selector__card-val"><a href="https://www.instagram.com/${igSafe}" target="_blank" rel="noopener noreferrer">@${igSafe}</a></span></div>`)}contactBits.length&&(html+=`<div class="store-selector__card-contact">${contactBits.join("")}</div>`),locationHours?.value&&(html+=`<details class="store-selector__hours"><summary class="store-selector__hours-summary"><span class="store-selector__hours-summary-text">${escapeHtml(cfg.storeHours||"Hours")}</span><i class="icon-chevron-down store-selector__hours-chev" aria-hidden="true"></i></summary><div class="store-selector__hours-body">${convertRichMetafieldValue(locationHours.value)}</div></details>`);const pickLabel=isSel?cfg.selected||"Selected":cfg.selectStore||cfg.select||"Select",isCartInValid=outOfStockItems.length>=1||inStockItems.length===0;let pickDisabled;outOfStockItems.length+inStockItems.length>0?pickDisabled=!!(pvNode&&!productAvailable||isCartInValid):pickDisabled=!!(pvNode&&!productAvailable);const body=document.createElement("div");body.className="store-selector__card-body",body.innerHTML=html;const pickBtn=document.createElement("button");pickBtn.type="button",pickBtn.className=`store-selector__pick${isSel?" store-selector__pick--selected":""}${pickDisabled?" store-selector__pick--disabled":""}`,pickBtn.setAttribute("data-store-selector-store-select",""),pickBtn.setAttribute("data-location-id",String(location.id)),pickDisabled&&(pickBtn.disabled=!0,pickBtn.setAttribute("aria-disabled","true")),pickBtn.textContent=pickLabel,wrap.appendChild(body),wrap.appendChild(pickBtn),this.locationsList.appendChild(wrap)}getCurrentLocation(silent){const isSilent=!!silent;if(!navigator.geolocation){isSilent||window.alert(strCfg("geolocationNotSupported","Geolocation not supported"));return}this.useCurrentLocationText&&!isSilent&&(this.useCurrentLocationText.innerText=strCfg("loading","\u2026"));const geoOpts={enableHighAccuracy:!1,timeout:18e3,maximumAge:6e4};navigator.geolocation.getCurrentPosition(pos=>this.showPosition(pos),err=>this.handleGeolocationError(err,isSilent),geoOpts)}showPosition(position){const lat=position.coords.latitude,lng=position.coords.longitude,input=document.querySelector("[data-store-selector-input]"),save=name=>{window.localStorage.setItem("user-location",JSON.stringify({latitude:lat,longitude:lng,name:name||strCfg("currentLocationLabel","Current location")})),input&&(input.value=name||strCfg("currentLocationLabel","")),document.dispatchEvent(new Event("calculateDistances"))};if(window.google?.maps){new google.maps.Geocoder().geocode({location:{lat,lng}},(results,status)=>{status==="OK"&&results?.[0]?save(results[0].formatted_address):save(strCfg("currentLocationLabel",""))});return}if(!window.storeSelector?.googleMapsKey){save(strCfg("currentLocationLabel",""));return}this.loadGoogleMaps(()=>{window.google?.maps?this.showPosition(position):save(strCfg("currentLocationLabel",""))})}handleGeolocationError(error,silent){if(error?.code===error.PERMISSION_DENIED)try{sessionStorage.setItem("store_selector_geo_denied","1")}catch{}if(silent){updateStoreSelectorHeaderVisibility();return}const useCurrentLocationText=document.querySelector("[data-store-selector-use-current-location-text]");let msg=strCfg("geolocationUnknownError","");error?.code===error.PERMISSION_DENIED?msg=strCfg("geolocationPermissionDenied",msg):error?.code===error.POSITION_UNAVAILABLE?msg=strCfg("geolocationPositionUnavailable",msg):error?.code===error.TIMEOUT&&(msg=strCfg("geolocationTimeout",msg)),useCurrentLocationText&&msg&&(useCurrentLocationText.innerText=msg),updateStoreSelectorHeaderVisibility()}setCartAttributeWithFormData(formData){return fetch(`${window.Shopify.routes.root}cart/update.js`,{method:"POST",body:formData}).then(response=>{if(!response.ok)throw new Error(`Cart update failed with status ${response.status}`);return response.json()})}async selectLocation(location){window.localStorage.setItem("selected-location",JSON.stringify(location));try{await syncSelectedLocationToCart(location)}catch{}try{const formData=new FormData,addr=location.address||{},addrLine=[addr.address1?`${addr.address1},`:"",addr.address2?`${addr.address2},`:"",addr.city?`${addr.city},`:"",addr.province?`${addr.province},`:"",addr.zip||""].join(" ").replace(/\s+/g," ").trim(),safeLine=escapeHtml(addrLine);formData.append("attributes[bm_store_location_address]",safeLine),formData.append("attributes[bm_store_location_zip]",location.address.zip),this.setCartAttributeWithFormData(formData)}catch{}document.dispatchEvent(new CustomEvent("store-selector:selected-location",{bubbles:!0,detail:{location}})),document.querySelectorAll("store-selector-toggle").forEach(toggle=>{typeof toggle.updateButtonText=="function"&&toggle.updateButtonText()}),this.buildLocationsList(),this.close(),typeof window.storeSelectorOnLocationSelected=="function"&&window.storeSelectorOnLocationSelected(location)}close(){document.documentElement.classList.remove("store-selector-drawer-open"),document.body.classList.remove("overflow-hidden"),this.classList.remove("active"),this.setAttribute("aria-hidden","true");const aside=document.getElementById("store-locator");aside?.classList.contains("toggle")&&(typeof hidePanels=="function"?hidePanels():(aside.classList.remove("toggle"),aside.setAttribute("aria-hidden","true"),document.querySelector(".m6pn.toggle")||document.documentElement.classList.remove("m6pn-open","m6cp-open","f8fl-open")))}requestPassiveGeoForDistancesIfNeeded(){beginPassiveGeoIfNoUserLocation()}open(){if(syncPreferredPickupToCartFromLocalStorage(),this.setAttribute("aria-hidden","false"),typeof openPanel=="function")openPanel
90("store-locator");else{const aside=document.getElementById("store-locator");aside&&(document.querySelectorAll(".m6pn").forEach(el=>{el.classList.remove("toggle"),el.setAttribute("aria-hidden","true")}),aside.classList.add("toggle"),aside.setAttribute("aria-hidden","false"),document.documentElement.classList.add("has-panels","m6pn-open"))}this.requestPassiveGeoForDistancesIfNeeded(),this.classList.contains("loaded")?this.syncSearchInputFromStorage():(this.syncSearchInputFromStorage(),this.buildLocationsCount(),this.buildLocationsList(),this.classList.add("loaded")),this.scheduleSearchUiInit(),document.documentElement.classList.add("store-selector-drawer-open")}}window.customElements.define("store-selector",StoreSelector)}if(!window.customElements.get("store-selector-toggle")){class StoreSelectorToggle extends HTMLElement{constructor(){super(),this.button=null,this.selectedLocationText=null,this._open=null}connectedCallback(){this.button=this.querySelector("button"),this.selectedLocationText=this.querySelector("[data-selected-location]"),this._open=()=>document.dispatchEvent(new Event("openStoreSelector")),this.button&&this.button.addEventListener("click",this._open),this.updateButtonText()}disconnectedCallback(){this.button&&this._open&&this.button.removeEventListener("click",this._open)}updateButtonText(){let selectedLocation=null;try{selectedLocation=window.localStorage.getItem("selected-location")?JSON.parse(window.localStorage.getItem("selected-location")):null}catch{}const cta=this.querySelector("[data-store-selector-cta]"),ctaText=window.storeSelector?.selectYourStore&&String(window.storeSelector.selectYourStore).trim()?window.storeSelector.selectYourStore:"Select your store";if(cta&&(selectedLocation?cta.classList.add("hidden"):(cta.classList.remove("hidden"),cta.textContent=ctaText)),!this.selectedLocationText)return;if(!selectedLocation){this.selectedLocationText.textContent="";return}const a=selectedLocation.address||{},line=`${a.city||""}${a.provinceCode?`, ${a.provinceCode}`:a.province?`, ${a.province}`:""}`;this.selectedLocationText.textContent=line.trim()||selectedLocation.name||""}}window.customElements.define("store-selector-toggle",StoreSelectorToggle)}})();
91//# sourceMappingURL=/cdn/shop/t/5/assets/store-selector.js.map?v=75465052521961160401790868989

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.