forked from davidnuescheler/n2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
1948 lines (1686 loc) · 64.8 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------
general purpose helix pages / display scripts
--------- */
(() => {
const scrani = (() => {
const scrani = {
// config
animations: [
{selector: "body>main>div", animation:"eager-appear"},
],
scrollY: -1,
scrollYBottom: 0,
}
// setup
scrani.setup = () => {
for (let i=0; i<scrani.animations.length; i++) {
a = scrani.animations[i];
a.elems=document.querySelectorAll(a.selector);
}
}
// update single element
scrani.updateElement = (el, animation) => {
let progress=0.0;
const offsetTop = el.getBoundingClientRect().top+window.pageYOffset;
if (scrani.scrollY > offsetTop) {
progress=1.0;
} else if (scrani.scrollYBottom < offsetTop) {
progress=0.0;
} else {
progress=1.0-(offsetTop - scrani.scrollY)/window.innerHeight;
}
// HACK: manually specified animation
progress=progress*2;
if (progress>1) progress=1;
if (animation == "eager-appear") {
const transY=100-progress*100;
const opacity=progress;
el.style=`opacity: ${opacity}; transform: translateY(${transY}px)`;
}
if (animation == "wipe") {
const right=Math.round(100-progress*100);
el.style=`clip-path: inset(0 ${right}% 0 0); -webkit-clip-path: inset(0 ${right}% 0 0)`;
}
}
// update to get called by requestAnimationFrame
scrani.update = (scrollY) => {
if (scrollY == scrani.scrollY) return;
scrani.scrollY = scrollY;
scrani.scrollYBottom = scrollY+window.innerHeight;
for (let i=0; i<scrani.animations.length;i++) {
const a = scrani.animations[i];
for (let j=0; j<a.elems.length;j++) {
scrani.updateElement(a.elems[j], a.animation);
}
}
}
//to be called onload
scrani.onload = () => {
scrani.setup();
const repaint = () => {
scrani.update(window.scrollY)
window.requestAnimationFrame(repaint)
}
window.requestAnimationFrame(repaint);
}
return (scrani)
})();
window.scrani = scrani;
})();
function classify() {
document.querySelectorAll("main h1").forEach((e) => {
var label=stripName(e.textContent);
e.parentElement.classList.add(label);
})
document.querySelectorAll("div.image").forEach((e, i) => {
e.classList.add(i%2?"right":"left");
})
document.querySelector("main").classList.add("appear");
}
function wrapMenus() {
hWrap(document.querySelector("main div.menu"),5);
var h1=document.querySelector("main div.menu h1");
document.querySelector("main div.menu").insertBefore(h1.cloneNode(true), document.querySelector("main div.menu>div"));
h1.parentNode.removeChild(h1);
}
function hWrap(el, maxlevel) {
var level=0;
var newlevel=0;
var wrapped=document.createElement('div');
var currentParent=wrapped;
Array.from(el.children).forEach((e) => {
if (e.tagName.substr(0,1) == "H") {
newlevel=+e.tagName.substr(1,1);
if (newlevel<maxlevel) {
if (newlevel<=level) {
while (newlevel<=level) {
currentParent=currentParent.parentElement;
level--;
}
}
if (newlevel>level) {
while (newlevel>level) {
var div=document.createElement('div');
if ((newlevel==level+1) && newlevel>1) div.className = e.id;
currentParent.appendChild(div);
currentParent=div;
level++;
}
}
}
}
currentParent.appendChild(e.cloneNode(true));
})
el.innerHTML="";
el.appendChild(wrapped.firstChild);
};
async function fetchJSON(url) {
let response=await fetch(url);
let json={};
if (response.ok) {
json = await response.json();
}
return (json)
}
function fixIcons() {
document.querySelectorAll("use").forEach (async (e) => {
var a=e.getAttribute("href");
var name=a.split("/")[2].split(".")[0];
if (name == 'participant' || name == 'donations') {
var json=await fetchJSON('/blm-fundraiser-data-new.json');
html='';
json.forEach((r) => {
var text=r[name];
var link=r[name+'-link']
var desc=r[name+'-description']
if (text) {
if (link) {
html+=`<p><a href="${link}"><b>${text}</b></a>`;
if (desc) html+=`<br>${desc}`;
html+=`</p>`;
} else {
html+=`<p><b>${text}</b>`;
if (desc) html+=`<br>${desc}`;
html+=`</p>`;
}
}
})
var div=document.createElement('div');
div.innerHTML=html;
e.parentNode.parentNode.replaceChild(div,e.parentNode);
}
if (name == 'lab-cone') {
var $div=document.createElement('div');
$div.id='labconepreview';
e.parentNode.parentNode.replaceChild($div, e.parentNode);
setTimeout(randomizeLabCone, 1000);
} else {
e.setAttribute("href", `/icons.svg#${name}`);
if (e.parentNode.parentNode.tagName=='A') {
e.parentNode.parentNode.classList.add('noborder');
}
}
});
}
function cloneMenuSwiper() {
var menu=document.querySelector("div.menu");
var mobilemenu=menu.cloneNode(true);
mobilemenu.querySelector(":scope>div").className="locations-menus";
var titleswitcher=document.createElement('div');
titleswitcher.className="locations";
mobilemenu.querySelectorAll("h2").forEach((e) => {
titleswitcher.appendChild(e.cloneNode(true));
e.parentNode.removeChild(e);
});
mobilemenu.insertBefore(titleswitcher, mobilemenu.firstChild);
menu.classList.add("desktop");
menu.parentNode.insertBefore(mobilemenu,menu.nextSibling);
}
var menuLocation="store";
var menuOffset=0;
function setMenuLocation(e) {
}
function bindInputs(inputs) {
inputs.forEach((e) => {
e.value=localStorage.getItem(e.id);
e.addEventListener('change', (event) => {
localStorage.setItem(event.target.id, event.target.value);
})
})
}
function updateMenuDisplay() {
var vw=window.innerWidth;
var p=(vw-375)/375;
console.log(`p: ${p}`);
p=Math.max(p,0);
p=Math.min(p,1);
console.log(`p: ${p}`);
var pink=[252,216,199];
var blue=[0,1,253];
var r=pink[0]*(1-p)+blue[0]*(p);
var g=pink[1]*(1-p)+blue[1]*(p);
var b=pink[2]*(1-p)+blue[2]*(p);
document.querySelector(".locations-menus .lab").style=`color:rgba(${r},${g},${b},1)`;
document.querySelector(".locations #lab").style=`color:rgba(${r},${g},${b},1)`;
}
function isAndroid() {
var os="";
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
os="android";
}
console.log(os);
return (os=="android");
}
function resizeImages() {
document.querySelectorAll('main div img').forEach((i) => {
var s = i.getAttribute('src');
if (s.indexOf('/hlx_')==0) {
i.setAttribute('src',s+'?width=256')
}
})
}
function fixSmsUrls() {
document.querySelectorAll("main a").forEach((e) => {
var href=e.getAttribute("href");
console.log(href);
if (href && href.indexOf("https://sms.com")==0) {
var smshref="sms:/"+href.substr(15);
if (isAndroid()) {
var s=smshref.split("&body");
smshref=s[0]+"?body"+s[1];
}
e.setAttribute("href",smshref);
}
})
}
function setColors() {
let root = document.documentElement;
document.querySelectorAll('code').forEach(($code) => {
$code.innerText.split('\n').forEach((line)=>{
var splits=line.split(':');
if (splits[1])
if (splits[0].startsWith('--')) {
root.style.setProperty(splits[0].trim(), splits[1].trim());
} else if (splits[0].trim() == 'class') {
$code.parentNode.parentNode.classList.add(splits[1].trim());
}
})
})
}
function highlightNav() {
var currentPath=window.location.pathname.split('.')[0];
document.querySelectorAll('header>ul>li>a').forEach((e) => {
var href=e.getAttribute('href').split('.')[0];
if (currentPath==href) e.parentNode.classList.add('selected');
})
}
function setLocation() {
if (window.location.pathname.indexOf('/lab')==0) {
storeLocation='lab';
} else {
storeLocation='store';
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function generateId () {
var id="";
var chars="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i=0;i<4;i++) {
id+=chars.substr(Math.floor(Math.random()*chars.length),1);
}
return id;
}
/* ------
pim and catalog management handling
--------- */
function indexCatalog() {
catalog={
byId: {},
items: [],
categories: [],
discounts: {}
};
catalog_raw.forEach((e) => {
if (!catalog.byId[e.id]) catalog.byId[e.id]=e;
if (e.type=="ITEM") {
catalog.items.push(e);
if (e.item_data.variations) e.item_data.variations.forEach((v) => {
catalog.byId[v.id]=v;
})
}
if (e.type=="MODIFIER_LIST") {
if (e.modifier_list_data.modifiers) e.modifier_list_data.modifiers.forEach((m) => {
m.modifier_data.modifier_list_id=e.id;
console.log(m.modifier_data.modifier_list_id);
catalog.byId[m.id]=m;
})
}
if (e.type=="DISCOUNT") {
if (e.discount_data.name) {
catalog.discounts[e.discount_data.name.toLowerCase()]={ id: e.id };
}
}
if (e.type=="CATEGORY") {
catalog.categories.push(e);
}
})
}
/* ------
product config
--------- */
function hideConfig() {
var config=document.getElementById("config");
config.classList.add("hidden");
document.body.classList.remove("noscroll");
}
function isFixedPickup(item) {
if (item.item_data.variations[0].item_variation_data.name.indexOf('day ')>0) {
return true;
}
return false;
}
function getScrollingOffset($sel) {
var selpos = $sel.offsetLeft-$sel.parentNode.firstChild.offsetLeft;
var selwidth = $sel.offsetWidth;
var wrapperwidth=document.querySelector("#config.cone-builder .wrapper").offsetWidth;
var newOffset=-Math.round(selpos+(selwidth-wrapperwidth)/2);
return newOffset;
}
function adjustScrolling($sel) {
var newOffset=getScrollingOffset($sel);
$sel.parentNode.style=`transform: translateX(${newOffset}px)`;
scrollOffsets[$sel.parentNode.parentNode.getAttribute('data-name')]=newOffset;
}
function hasDip() {
const dips=document.querySelector('div[data-name="dip"]');
if (dips) {
const seldip=dips.querySelector('.selected');
const nodip=dips.querySelector('.cb-options span:first-of-type');
const dip=(seldip==nodip)?0:1;
return dip;
}
return (0);
}
function updateNumberOfToppings() {
var dip=hasDip();
title=`pick up to ${dip?2:3} toppings`;
const toppingTitle=document.querySelector('div[data-name="topping"] h4');
toppingTitle.innerHTML=title;
}
function coneBuilderSelect($sel) {
if (($sel.parentNode.parentNode.getAttribute('data-name')=='topping') && ($sel != $sel.parentNode.firstChild)) {
$sel.parentNode.firstChild.classList.remove('selected');
if (!$sel.classList.contains('selected')) {
//check for too many toppings
const numToppings=$sel.parentNode.querySelectorAll('.selected').length;
const dip=hasDip();
if (dip+numToppings>=3) {
alert ('sorry, 2 toppings+dip or 3 toppings without a dip');
} else {
$sel.classList.add('selected');
}
} else {
$sel.classList.remove('selected');
if (!$sel.parentNode.querySelector('.selected'))
$sel.parentNode.firstChild.classList.add('selected');
}
} else {
$sel.parentNode.querySelectorAll("span").forEach(($e) => {
$e.classList.remove('selected');
})
$sel.classList.add('selected');
}
updateNumberOfToppings();
showConfig();
adjustScrolling($sel);
}
function randomizeLabCone() {
var $labcone=document.getElementById('labconepreview');
if ($labcone) {
var $a=document.querySelector('a.labcone');
var itemid=$a.getAttribute('data-id');
var mods=createRandomConfig(itemid);
$labcone.innerHTML=createConeFromConfig(mods);
}
setTimeout(randomizeLabCone,300);
}
function createRandomConfig(itemid) {
var item=catalog.byId[itemid];
var config=[];
item.item_data.modifier_list_info.forEach((ml) => {
var mods=catalog.byId[ml.modifier_list_id].modifier_list_data.modifiers;
var mlname=catalog.byId[ml.modifier_list_id].modifier_list_data.name;
if (mlname.includes('vessel')) {
config.push(mods[0].id);
} else {
config.push(mods[Math.floor(Math.random()*mods.length)].id);
}
})
return (config);
}
function createConeFromConfig(mods) {
var coneconfig={toppings:[]};
mods.forEach((m) => {
var mod=catalog.byId[m];
if (mod && mod.modifier_data) {
var mlname=catalog.byId[mod.modifier_data.modifier_list_id].modifier_list_data.name;
var modname=stripName(mod.modifier_data.name);
if (mlname.includes('topping')) {
coneconfig.toppings.push(modname);
}
else {
if (mlname.includes('vessel')) name='vessel';
if (mlname.includes('flavor')) name='flavor';
if (mlname.includes('dip')) name='dip';
coneconfig[name]=modname;
}
}
});
const postfix='?width=1024&auto=webp';
const flavor=`url(/cone-builder/${coneconfig.flavor}-soft-serve.png${postfix})`;
const vesself=`url(/cone-builder/${coneconfig.vessel}-front.png${postfix})`;
const vesselb=`url(/cone-builder/${coneconfig.vessel}-back.png${postfix})`;
const dip=`url(/cone-builder/${coneconfig.dip}-dip.png${postfix})`;
let toppings='';
coneconfig.toppings.forEach((t, i) => {
let topping=`url(/cone-builder/${t}-topping.png${postfix})`;
if (t.includes('cotton') && coneconfig.vessel.includes('cup')) {
topping=`url(/cone-builder/${t}-topping-cup.png${postfix})`;
};
toppings=`${topping}`+(i?', ':'')+toppings;
})
html=`<div style="background-image: ${vesselb}">
<div style="background-image: ${flavor}">
<div style="background-image: ${dip}">
<div style="background-image: ${toppings}">
<div style="background-image: ${vesself}">
</div>
</div>
</div>
</div>
</div>`;
return html;
}
function coneBuilderFlow() {
return ["variation", "vessel", "flavor", "dip", "topping"];
}
function coneBuilderShow(name) {
var $current=document.querySelectorAll("div.cb-selection").forEach(($e) => {
if ($e.getAttribute('data-name') == name) {
$e.classList.remove('hidden');
$e.classList.add('visible');
adjustScrolling($e.querySelector('.selected'));
} else {
$e.classList.add('hidden');
$e.classList.remove('visible');
}
})
var flow=coneBuilderFlow();
if (name==flow[0]) hide("cb-back");
else show("cb-back");
if (name==flow[flow.length-1]) {
hide("cb-next");
show("cb-addtocart");
} else {
show("cb-next");
hide("cb-addtocart");
}
}
function coneBuilderBack() {
var $current=document.querySelector("div.cb-selection.visible");
var flow=coneBuilderFlow()
var index=flow.indexOf($current.getAttribute('data-name'));
if (index>=1) coneBuilderShow(flow[index-1]);
}
function show(id) {
document.getElementById(id).classList.remove("hidden");
}
function hide(id) {
document.getElementById(id).classList.add("hidden");
}
function coneBuilderNext() {
var $current=document.querySelector("div.cb-selection.visible");
var flow=coneBuilderFlow()
var index=flow.indexOf($current.getAttribute('data-name'));
if (index<flow.length-1) coneBuilderShow(flow[index+1]);
}
function getConeBuilderHTML(item, callout) {
let html='';
html+=`<div class="close" onclick="hideConfig()"><svg class="icon icon-close"><use href="/icons.svg#close"></use></svg></div><div class="wrapper">`;
html+=`<div id="cone-builder">
</div>`;
html+=`<div class="cb-controls"><div class="cb-selections">`;
html+=`<div class="cb-selection visible" data-name="variation" value=""><h4>pick your size</h4><div class="cb-options smooth">`;
item.item_data.variations.forEach((v, i) => {
var price=v.item_variation_data.price_money.amount;
price=price?`<br><span class="price">($${formatMoney(price)})</span>`:'';
html+=`<span data-id="${v.id}" class="${i?"":"selected"}" onclick="coneBuilderSelect(this)">${v.item_variation_data.name}${price}</span>`;
});
html+=`</div></div>`;
if (item.item_data.modifier_list_info) {
item.item_data.modifier_list_info.forEach((m) => {
var ml=catalog.byId[m.modifier_list_id];
var name=ml.modifier_list_data.name;
if (name.includes('vessel')) name='vessel';
if (name.includes('flavor')) name='flavor';
if (name.includes('dip')) name='dip';
if (name.includes('topping')) name='topping';
let title=`pick your ${name}`;
// html+=`<h3>${ml.modifier_list_data.name}</h3>`;
html+=`<div class="cb-selection hidden" data-name="${name}"><h4>${title}</h4><div class="cb-options smooth">`;
ml.modifier_list_data.modifiers.forEach((mod, i) => {
var price=mod.modifier_data.price_money.amount;
price=price?`<br><span class="price">(+$${formatMoney(price)})</span>`:'';
var modname=mod.modifier_data.name.replace('(v)','<svg><use href="/icons.svg#v"></use></svg>');
modname=modname.replace('(gf)','<svg><use href="/icons.svg#gf"></use></svg>');
html+=`<span onclick="coneBuilderSelect(this)" data-id="${mod.id}" class="${i?"":"selected"}">${modname}${price}</span>`;
})
html+=`</div></div>`;
});
}
html+=`</div>
<div class="cb-buttons">
<div id="cb-back" class="hidden" onclick="coneBuilderBack()"><svg class="icon icon-back"><use href="/icons.svg#back"></use></svg></div>
<div id="cb-next" onclick="coneBuilderNext()"><svg class="icon icon-next"><use href="/icons.svg#next"></use></svg></div>
<div id="cb-addtocart" class="hidden" onclick="addConeToCart()"><h3>add to cart</h3></div>
</div>
</div>
</div>`;
return (html);
}
function getConfigHTML(item, callout) {
let html='';
var pickupVars=isFixedPickup(item);
var image="";
if (item.item_data.variations[0].item_variation_data.name.indexOf('day ')>0) {
pickupVars=true;
}
if (item.image_id) {
var imgobj=catalog.byId[item.image_id];
if (imgobj) {
image=imgobj.image_data.url;
}
}
if (image) {
html+=`<img src="${image}">`;
}
html+=`<div class="close" onclick="hideConfig()">X</div><div class="wrapper">`;
if (pickupVars) {
html+=`when would you like to pick this up?`
} else {
html+=`<h3>customize your ${item.item_data.name}</h3>`;
}
html+=callout;
html+=`<select name="variation">`;
item.item_data.variations.forEach((v) => {
html+=`<option value="${v.id}">${v.item_variation_data.name} ($${formatMoney(v.item_variation_data.price_money.amount)})</option>`;
});
html+=`</select>`;
if (item.item_data.modifier_list_info) {
item.item_data.modifier_list_info.forEach((m) => {
var ml=catalog.byId[m.modifier_list_id];
// html+=`<h3>${ml.modifier_list_data.name}</h3>`;
html+=`<div><select name="${ml.modifier_list_data.name}">`;
ml.modifier_list_data.modifiers.forEach((mod) => {
html+=`<option value="${mod.id}">${mod.modifier_data.name} (+$${formatMoney(mod.modifier_data.price_money.amount)})</option>`;
})
html+=`</select></div>`;
});
}
html+=`<button onclick="addConfigToCart()">add to cart</button>
</div>`;
return html;
}
var touchStartX=0;
var touchEndX=0;
var touchSpeed=0;
var scrollOffsets=[];
function scrollSelection(ev) {
var $cbs=ev.target.parentNode.parentNode;
var $options=ev.target.parentNode;
if (ev.type == 'touchstart') {
touchStartX=ev.touches[0].screenX;
$options.classList.remove("smooth");
}
if (ev.type == 'touchmove') {
var delta=0;
delta=touchStartX-ev.touches[0].screenX;
touchSpeed=touchEndX-ev.touches[0].screenX;
touchEndX=ev.touches[0].screenX;
newOffset=scrollOffsets[$cbs.getAttribute('data-name')]-delta;
$options.style=`transform: translateX(${newOffset}px)`;
ev.preventDefault();
}
if (ev.type == 'touchend') {
var delta=touchStartX-touchEndX;
$options.classList.add("smooth");
newOffset=scrollOffsets[$cbs.getAttribute('data-name')]-delta-touchSpeed*10;
var left=getScrollingOffset($options.firstChild);
var right=getScrollingOffset($options.lastChild);
if (newOffset > left) newOffset=left;
if (newOffset < right) newOffset=right;
$options.style=`transform: translateX(${newOffset}px)`;
scrollOffsets[$cbs.getAttribute('data-name')]=newOffset;
}
}
function configItem(item, callout) {
var config=document.getElementById("config");
config.classList.remove("hidden");
document.body.classList.add("noscroll");
var html='';
var name=item.item_data.name;
if (name == "lab cone") {
html=getConeBuilderHTML(item, callout);
config.classList.add('cone-builder');
config.innerHTML=html;
document.querySelectorAll('#config .cb-selection').forEach(($cbs) => {
$cbs.addEventListener('touchstart', scrollSelection, true);
$cbs.addEventListener('touchmove', scrollSelection, true);
$cbs.addEventListener('touchcancel', scrollSelection, true);
$cbs.addEventListener('touchend', scrollSelection, true);
});
updateNumberOfToppings();
showConfig();
adjustScrolling(document.querySelector('#config.cone-builder .cb-options .selected'));
} else {
html=getConfigHTML(item, callout);
config.classList.remove('cone-builder');
config.innerHTML=html;
}
}
function showConfig() {
const cb=document.getElementById("cone-builder");
if (cb) {
var mods=[];
document.querySelectorAll('#config.cone-builder .cb-options .selected').forEach((e) => {
mods.push(e.getAttribute('data-id'));
});
cb.innerHTML=createConeFromConfig(mods);
}
}
/* ------
check-out flow (pickup name, cell, time, store opening hours, payment)
--------- */
function formatTime(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function toNumbersArray(str) {
return (str.split(',').map(e => +e.trim()));
}
function getOpeningHoursConfig() {
var opening=window.labels[storeLocation+'_openinghours'];
var closing=window.labels[storeLocation+'_closinghours']
if (opening) {
storeLocations[storeLocation].openingHours.opening=toNumbersArray(opening);
}
if (closing) {
storeLocations[storeLocation].openingHours.closing=toNumbersArray(closing);
}
return storeLocations[storeLocation].openingHours;
}
function setPickupTimes () {
var date=document.getElementById("pickup-date").value;
var timeSelect=document.getElementById("pickup-time");
var conf=getOpeningHoursConfig();
var now=new Date();
//var now=new Date("2020-04-15T22:51:00-07:00");
var today=now.getFullYear()+"/"+(now.getMonth()+1)+"/"+now.getDate();
var openingTime=new Date(date);
openingTime.setHours(conf.opening[openingTime.getDay()]);
var closingTime=new Date(date);
closingTime.setHours(conf.closing[closingTime.getDay()]);
var startTime;
if (today == date && (now.getTime()>openingTime)) {
startTime=new Date(now.getTime()+(conf.prepTime*60000));
time=new Date(startTime.getTime()+(10*60000-startTime.getTime()%(10*60000)));
timeSelect.innerHTML="";
} else {
var openingTime=new Date(date);
openingTime.setHours(conf.opening[openingTime.getDay()]);
startTime=new Date(openingTime.getTime()+(conf.prepTime*60000));
time=new Date(startTime.getTime());
timeSelect.innerHTML="";
}
while (time<=closingTime) {
var option = document.createElement("option");
option.text = formatTime(time);
option.value=time.toISOString();
timeSelect.add(option);
time=new Date(time.getTime()+10*60000);
}
}
function displayThanks(payment){
var cartEl=document.getElementById("cart");
var $receipt;
cartEl.querySelector(".payment").classList.add("hidden");
if (storeLocations[storeLocation].orderAhead) {
var $thankyou=cartEl.querySelector(".thankyou.order-ahead");
$thankyou.classList.remove("hidden");
$receipt=$thankyou.querySelector('.receipt-link');
} else {
var $thankyou=cartEl.querySelector(".thankyou.callyourname");
$thankyou.classList.remove("hidden");
$receipt=$thankyou.querySelector('.receipt-link');
}
var receiptLink="/receipt"
if (payment) {
receiptLink=payment.receipt_url;
}
$receipt.setAttribute("href", receiptLink);
var textElem=document.getElementById("text-link");
var msg=`hi normal, this is ${order.fulfillments[0].pickup_details.recipient.display_name}, picking up my order in a (describe car)`;
var smshref=`sms://+13852995418/${isAndroid()?"?":"&"}body=${encodeURIComponent(msg)}`;
textElem.setAttribute("href", smshref);
cart.clear();
var summaryEl=document.querySelector("#cart .summary");
summaryEl.innerHTML=`your cart is empty`;
}
function getTip() {
var tipPercentage=+document.getElementById("tip").value;
var tipAmount=Math.round(order.total_money.amount*tipPercentage/100);
return (tipAmount);
}
function setPickupDates () {
//var now=new Date("2020-04-15T22:51:00-07:00");
var now=new Date();
var i=0;
var day=now;
var conf=getOpeningHoursConfig();
var weekdays = ["sun","mon","tue","wed","thu","fri","sat"];
var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
var dateSelect=document.getElementById("pickup-date");
var closedForToday=false;
if (storeLocations[storeLocation].orderAhead) {
while (i<storeLocations[storeLocation].orderAhead) {
if (i==0) {
/* check if we are past cutoff for today */
var closingDate=new Date();
closingDate.setHours(conf.closing[day.getDay()],0,0,0);
if (now>closingDate-conf.lastOrderFromClose*60000) {
day.setDate(day.getDate()+1);
document.querySelector("#cart .info .pickup-time .warning.hidden").classList.remove("hidden");
}
}
if(conf.opening[day.getDay()]) {
var option = document.createElement("option");
option.text = (i==0)?'today':weekdays[day.getDay()]+", "+months[day.getMonth()]+" "+day.getDate();
option.value=day.getFullYear()+"/"+(day.getMonth()+1)+"/"+day.getDate();
dateSelect.add(option);
}
day.setDate(day.getDate()+1);
i++;
}
setPickupTimes();
} else {
var closingDate=new Date();
var openingDate=new Date();
closingDate.setHours(conf.closing[day.getDay()],0,0,0);
openingDate.setHours(conf.opening[day.getDay()],0,0,0);
var option = document.createElement("option");
option.text = 'today';
option.value=day.getFullYear()+"/"+(day.getMonth()+1)+"/"+day.getDate();
dateSelect.add(option);
setPickupTimes();
if (now>closingDate-conf.lastOrderFromClose*60000) {
document.querySelector("#cart .info").classList.add("hidden");
document.querySelector("#cart .warning.toolate").classList.remove("hidden");
}
if (now<openingDate) {
document.querySelector("#cart .info").classList.add("hidden");
document.querySelector("#cart .warning.tooearly").classList.remove("hidden");
}
}
}
var paymentForm;
function initPaymentForm() {
// Create and initialize a payment form object
paymentForm = new SqPaymentForm({
// Initialize the payment form elements
applicationId: "sq0idp-q-NmavFwDX6MRLzzd5q-sg",
locationId: storeLocations[storeLocation].locationId,
inputClass: 'sq-input',
autoBuild: false,
// Customize the CSS for SqPaymentForm iframe elements
inputStyles: [{
fontSize: '16px',
lineHeight: '24px',
padding: '16px',
placeholderColor: '#a0a0a0',
color: getComputedStyle(document.documentElement).getPropertyValue('--text-color').trim(),
backgroundColor: 'transparent',
}],
// Initialize the credit card placeholders
cardNumber: {
elementId: 'sq-card-number',
placeholder: 'Card Number'
},
cvv: {
elementId: 'sq-cvv',
placeholder: 'CVV'
},
expirationDate: {
elementId: 'sq-expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
elementId: 'sq-postal-code',
placeholder: 'Postal'
},
// SqPaymentForm callback functions
callbacks: {
/*
* callback function: cardNonceResponseReceived
* Triggered when: SqPaymentForm completes a card nonce request
*/
cardNonceResponseReceived: function (errors, nonce, cardData) {
if (errors) {
// Log errors from nonce generation to the browser developer console.
console.error('Encountered errors:');
errors.forEach(function (error) {
alert(error.message);
console.error(' ' + error.message);
});
submittingPayment=false;
return;
}
console.log(`The generated nonce is:\n${nonce}`);