-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared-form.js
More file actions
795 lines (704 loc) · 31.7 KB
/
Copy pathshared-form.js
File metadata and controls
795 lines (704 loc) · 31.7 KB
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
// shared-form.js — shared check-in form logic for index.html and kiosk.html
// Plain vanilla JS, no modules. Exposes window.initCheckinForm.
// All dynamic HTML is built using escapeHtml() on every interpolated value (XSS-safe).
//
// Usage:
// initCheckinForm({ formId: 'checkin-form', isKiosk: false })
// initCheckinForm({ formId: 'checkin-form', isKiosk: true, resetTimeoutMs: 15000 })
(function(global) {
'use strict';
// ===== CONSTANTS =====
var FORM_ENDPOINT = '/api/checkin';
var FORM_TIMEOUT_MS = 12000;
var MAX_LOCAL_ENTRIES = 25;
var LOCAL_ENTRY_TTL_MS = 7 * 24 * 60 * 60 * 1000;
var DEFAULT_TEAM_MEMBERS = [
{ name: 'Carter Helms', title: 'Team Chair', profession: 'Property Restoration', company: 'Franco Restorations', website: 'https://carterhelms.com', leader: true },
{ name: 'Craig Morrill', title: 'Vice Chair', profession: 'Financial Advisor', company: 'Summit Global Investments', website: 'https://sgiam.com', leader: true },
{ name: 'Will Sigmon', title: 'Team Admin', profession: 'Software & Creative', company: 'Will Sigmon Media Co.', website: 'https://willsigmon.media', leader: true },
{ name: 'Rusty Sutton', title: 'Team Marketing Specialist', profession: 'Digital Marketing', company: 'MonkeyFans Creative', website: 'https://monkeyfansraleigh.com/about', leader: false, specialTitle: true },
{ name: 'Robert Courts', title: 'Mortgage Lending', company: 'Advantage Lending', website: 'https://advantagelending.com/mortgage-loan-services', leader: false },
{ name: 'Dana Walsh', title: 'Magazine Publisher', company: 'Stroll Magazine', website: 'https://strollmag.com/locations/hayes-barton-nc', leader: false },
{ name: 'Roni Payne', title: 'Accounting / Tax', company: 'R. Payne Financial & Tax Solutions', website: 'https://rpayne.org/about', leader: false },
{ name: 'Shannida Ramsey', title: 'Property Maintenance', company: 'Ram-Z Services LLC', website: 'https://ramzservices.com', leader: false },
{ name: 'David Mercado', title: 'HOA Management', company: 'William Douglas Management', website: 'https://wmdouglas.com/raleigh-hoa-management', leader: false },
{ name: 'Erika Beckett', title: 'Pet Sitting', company: 'Erika Beckett Pet Sitting', website: '', leader: false },
{ name: 'Sue Kerata', title: 'Realtor', company: 'Century 21 Triangle Group', website: 'https://suekhomes.com', leader: false }
];
var INDUSTRIES = [
'Accounting', 'Architecture', 'Auto Sales', 'Banking', 'Business Consulting',
'Chiropractic', 'Commercial Real Estate', 'Construction', 'Copywriting',
'Cyber Security', 'Dental', 'Education', 'Electrical', 'Event Planning',
'Financial Planning', 'Fitness & Wellness', 'Graphic Design', 'Healthcare',
'Home Inspection', 'Home Services', 'HVAC', 'Insurance', 'Interior Design',
'IT Services', 'Landscaping', 'Legal', 'Lending & Mortgage', 'Marketing',
'Massage Therapy', 'Media & Video', 'Mental Health', 'Nonprofit',
'Nutrition', 'Painting', 'Pest Control', 'Pet Services', 'Photography',
'Physical Therapy', 'Plumbing', 'Printing', 'Property Management',
'Property Restoration', 'Publishing', 'Real Estate', 'Recruiting',
'Roofing', 'Solar Energy', 'Staffing', 'Tax Preparation', 'Technology',
'Travel', 'Veterinary', 'Wealth Management', 'Web Development'
];
// ===== UTILITY =====
// escapeHtml is applied to every dynamic value before building markup strings.
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function keepLatestLocalEntries(entries) {
var now = Date.now();
return entries.filter(function(entry) {
if (!entry || entry.synced) return false;
var savedAt = Date.parse(entry.timestamp || '');
return !isNaN(savedAt) && (now - savedAt) < LOCAL_ENTRY_TTL_MS;
}).slice(-MAX_LOCAL_ENTRIES);
}
function fetchWithTimeout(url, options, timeoutMs) {
if (typeof AbortController === 'undefined') {
return fetch(url, options);
}
var controller = new AbortController();
var timeoutId = setTimeout(function() { controller.abort(); }, timeoutMs);
var requestOptions = Object.assign({}, options, { signal: controller.signal });
return fetch(url, requestOptions).finally(function() { clearTimeout(timeoutId); });
}
// ===== LOCAL BACKUP =====
function saveFailedLocal(data) {
try {
var entries = JSON.parse(localStorage.getItem('heatwave_entries') || '[]');
var savedEntry = Object.assign({}, data, {
timestamp: new Date().toISOString(),
synced: false,
reason: 'sync-failed'
});
entries.push(savedEntry);
var localEntries = keepLatestLocalEntries(entries);
if (localEntries.length) {
localStorage.setItem('heatwave_entries', JSON.stringify(localEntries));
} else {
localStorage.removeItem('heatwave_entries');
}
return savedEntry;
} catch(e) { return null; }
}
function pruneLocalEntries() {
try {
var entries = JSON.parse(localStorage.getItem('heatwave_entries') || '[]');
var localEntries = keepLatestLocalEntries(entries);
if (localEntries.length) {
localStorage.setItem('heatwave_entries', JSON.stringify(localEntries));
} else {
localStorage.removeItem('heatwave_entries');
}
} catch(e) { /* storage unavailable */ }
}
function setLocalEntries(entries) {
try {
var localEntries = keepLatestLocalEntries(entries || []);
if (localEntries.length) {
localStorage.setItem('heatwave_entries', JSON.stringify(localEntries));
} else {
localStorage.removeItem('heatwave_entries');
}
return localEntries;
} catch(e) { return []; }
}
function getLocalEntries() {
pruneLocalEntries();
try { return JSON.parse(localStorage.getItem('heatwave_entries') || '[]'); }
catch(e) { return []; }
}
function exportCSV() {
var entries = getLocalEntries();
if (!entries.length) { alert('No local entries saved.'); return; }
var header = 'Timestamp,First Name,Last Name,Profession,Company Name,Phone,Email,Guest Of,Ideal Referral\n';
var rows = entries.map(function(e) {
return [e.timestamp, e.firstName, e.lastName, e.profession, e.companyName, e.phone, e.email, e.guestOf, e.idealReferral]
.map(function(v) { return '"' + (v || '').replace(/"/g, '""') + '"'; }).join(',');
}).join('\n');
var blob = new Blob([header + rows], { type: 'text/csv' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'heatwave-entries-' + new Date().toISOString().slice(0, 10) + '.csv';
a.click();
}
global.exportCSV = exportCSV;
global.getLocalEntries = getLocalEntries;
// ===== CONFETTI =====
function launchConfetti(canvas) {
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var particles = [];
var colors = ['#E8580C', '#FF6A1E', '#f0e6dc', '#C44A0A', '#FFB347', '#F5A623'];
for (var i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: -20 - Math.random() * 200,
w: 4 + Math.random() * 6,
h: 4 + Math.random() * 6,
vx: (Math.random() - 0.5) * 4,
vy: 2 + Math.random() * 4,
rot: Math.random() * 360,
rotSpeed: (Math.random() - 0.5) * 8,
color: colors[Math.floor(Math.random() * colors.length)],
opacity: 1
});
}
var startTime = Date.now();
function animate() {
var elapsed = Date.now() - startTime;
if (elapsed > 3500) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
return;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(function(p) {
p.x += p.vx;
p.y += p.vy;
p.vy += 0.1;
p.rot += p.rotSpeed;
if (elapsed > 2500) {
p.opacity = Math.max(0, 1 - (elapsed - 2500) / 1000);
}
ctx.save();
ctx.globalAlpha = p.opacity;
ctx.translate(p.x, p.y);
ctx.rotate(p.rot * Math.PI / 180);
ctx.fillStyle = p.color;
ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
ctx.restore();
});
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}
// ===== INIT =====
/**
* Wire up the check-in form.
* @param {Object} config
* @param {string} config.formId - id of the <form> element (default: 'checkin-form')
* @param {boolean} [config.isKiosk] - true: auto-reset, welcome toast, personalized success title
* @param {number} [config.resetTimeoutMs] - ms before auto-reset after success (kiosk only, default 15000)
* @param {Function} [config.onReset] - called after reset; use for page-specific UI teardown
* @param {Function} [config.onSuccess] - called after success shown; receives {localOnly, reason}
* @param {Function} [config.onMembersLoaded] - called when live roster loads; receives updated TEAM_MEMBERS
*/
function initCheckinForm(config) {
var isKiosk = !!(config && config.isKiosk);
var resetTimeoutMs = (config && config.resetTimeoutMs) || 15000;
var onReset = (config && typeof config.onReset === 'function') ? config.onReset : null;
var onSuccess = (config && typeof config.onSuccess === 'function') ? config.onSuccess : null;
var onMembersLoaded = (config && typeof config.onMembersLoaded === 'function') ? config.onMembersLoaded : null;
var formId = (config && config.formId) || 'checkin-form';
var TEAM_MEMBERS = DEFAULT_TEAM_MEMBERS.slice();
// ===== DOM REFS =====
var form = document.getElementById(formId);
if (!form) return;
var submitBtn = document.getElementById('submit-btn');
var successScreen = document.getElementById('success-screen');
var successTitle = document.getElementById('success-title');
var successSubtitle = document.getElementById('success-subtitle');
var resetBtn = document.getElementById('reset-btn');
var confettiCanvas = document.getElementById('confetti-canvas');
var companyWebsite = document.getElementById('companyWebsite');
var guestPicker = document.getElementById('guestOf-picker');
var guestQuickPicks = document.getElementById('guestOf-quick');
var guestSearchInput = document.getElementById('guestOfSearch');
var guestResults = document.getElementById('guestOf-results');
var guestOfHidden = document.getElementById('guestOf');
var professionInput = document.getElementById('profession');
var professionResults = document.getElementById('profession-results');
var kioskToast = document.getElementById('kiosk-toast');
var toastNameEl = document.getElementById('toast-name');
var kioskFormHeader = document.querySelector('.kiosk-form-header');
var defaultSuccessTitle = 'Welcome to the Heatwave!';
var defaultSuccessSubtitle = 'Your registration has been submitted. We look forward to connecting with you.';
var localOnlySuccessTitle = 'Saved on this device';
var localOnlySuccessSubtitle = 'Google Sheets is not connected yet, so this check-in is stored locally on this device only.';
var syncFailedSuccessSubtitle = 'We saved this check-in on this device, but the Google Sheets sync did not complete.';
var submitFailedTitle = 'We could not confirm your check-in';
var submitFailedSubtitle = 'This browser could not save a local backup, and the network sync did not complete. Please try again or ask the host to retry.';
var fields = ['firstName', 'lastName', 'profession', 'phone', 'email', 'guestOf'];
var optionalFields = ['companyName', 'idealReferral'];
var allFields = fields.concat(optionalFields);
var toastTimer = null;
var autoResetTimer = null;
function ensureFormStatus() {
var existing = document.getElementById('form-status');
if (existing) return existing;
var status = document.createElement('div');
status.id = 'form-status';
status.className = 'sr-only';
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'assertive');
status.setAttribute('aria-atomic', 'true');
form.insertBefore(status, form.firstChild);
return status;
}
var formStatus = ensureFormStatus();
function announceFormStatus(message) {
if (!formStatus) return;
formStatus.textContent = '';
window.setTimeout(function() {
formStatus.textContent = message || '';
}, 10);
}
function createPendingRecovery() {
var panel = document.createElement('div');
panel.className = 'pending-checkins';
panel.id = 'pending-checkins';
panel.hidden = true;
panel.innerHTML =
'<div class="pending-checkins__copy">' +
'<strong id="pending-checkins-title">Pending local check-ins</strong>' +
'<span id="pending-checkins-detail">Saved on this device until the connection comes back.</span>' +
'</div>' +
'<div class="pending-checkins__actions">' +
'<button type="button" class="pending-checkins__button" id="pending-checkins-retry">Retry sync</button>' +
'<button type="button" class="pending-checkins__button pending-checkins__button--ghost" id="pending-checkins-export">Export CSV</button>' +
'</div>';
if (form.parentNode) {
form.parentNode.insertBefore(panel, form.nextSibling);
}
return panel;
}
var pendingPanel = createPendingRecovery();
var pendingTitle = document.getElementById('pending-checkins-title');
var pendingDetail = document.getElementById('pending-checkins-detail');
var pendingRetryBtn = document.getElementById('pending-checkins-retry');
var pendingExportBtn = document.getElementById('pending-checkins-export');
function updatePendingRecovery(message) {
var entries = getLocalEntries();
if (!pendingPanel) return;
pendingPanel.hidden = entries.length === 0;
if (pendingTitle) {
pendingTitle.textContent = entries.length === 1
? '1 pending local check-in'
: entries.length + ' pending local check-ins';
}
if (pendingDetail) {
pendingDetail.textContent = message || 'Saved on this device. Retry sync before clearing browser data.';
}
}
function retryPendingCheckins() {
var entries = getLocalEntries();
if (!entries.length) {
updatePendingRecovery('No local check-ins are waiting.');
return;
}
if (pendingRetryBtn) {
pendingRetryBtn.disabled = true;
pendingRetryBtn.textContent = 'Syncing…';
}
var remaining = [];
var syncedCount = 0;
entries.reduce(function(chain, entry) {
return chain.then(function() {
return fetchWithTimeout(FORM_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body: new URLSearchParams(Object.assign({}, entry, { companyWebsite: '' })).toString()
}, FORM_TIMEOUT_MS).then(function(response) {
if (!response.ok) throw new Error('pending-sync-failed');
return response.json();
}).then(function(result) {
if (!result || result.status !== 'ok') throw new Error('pending-sync-failed');
syncedCount += 1;
}).catch(function() {
remaining.push(entry);
});
});
}, Promise.resolve()).then(function() {
setLocalEntries(remaining);
updatePendingRecovery(syncedCount
? ('Synced ' + syncedCount + ' saved check-in' + (syncedCount === 1 ? '.' : 's.'))
: 'Sync still failed. Export CSV if the host needs to recover these manually.');
announceFormStatus(pendingDetail ? pendingDetail.textContent : '');
}).finally(function() {
if (pendingRetryBtn) {
pendingRetryBtn.disabled = false;
pendingRetryBtn.textContent = 'Retry sync';
}
});
}
if (pendingRetryBtn) pendingRetryBtn.addEventListener('click', retryPendingCheckins);
if (pendingExportBtn) pendingExportBtn.addEventListener('click', exportCSV);
updatePendingRecovery();
function bindFieldAccessibility() {
allFields.forEach(function(name) {
var errorEl = document.getElementById(name + '-error');
if (!errorEl) return;
errorEl.setAttribute('role', 'alert');
var input = name === 'guestOf' ? guestSearchInput : document.getElementById(name);
if (!input) return;
input.setAttribute('aria-describedby', errorEl.id);
input.setAttribute('aria-invalid', 'false');
});
}
bindFieldAccessibility();
window.addEventListener('resize', function() {
if (confettiCanvas) {
confettiCanvas.width = window.innerWidth;
confettiCanvas.height = window.innerHeight;
}
});
// ===== PROFESSION AUTOCOMPLETE =====
function getProfessionMatches(query) {
var q = query.trim().toLowerCase();
if (!q) return [];
return INDUSTRIES.filter(function(i) { return i.toLowerCase().indexOf(q) !== -1; }).slice(0, 6);
}
function renderProfessionResults() {
if (!professionInput || !professionResults) return;
var matches = getProfessionMatches(professionInput.value);
if (!matches.length || professionInput.value.trim().toLowerCase() === matches[0].toLowerCase()) {
professionResults.innerHTML = '';
return;
}
professionResults.innerHTML = matches.map(function(industry) {
var s = escapeHtml(industry);
return '<button type="button" class="profession-result" data-value="' + s + '">' + s + '</button>';
}).join('');
}
if (professionInput && professionResults) {
professionInput.addEventListener('input', function() { renderProfessionResults(); });
professionInput.addEventListener('focus', function() {
if (professionInput.value.trim()) renderProfessionResults();
});
professionInput.addEventListener('blur', function() {
window.setTimeout(function() { professionResults.innerHTML = ''; }, 120);
});
professionResults.addEventListener('click', function(event) {
var button = event.target.closest('.profession-result');
if (!button) return;
professionInput.value = button.getAttribute('data-value');
professionResults.innerHTML = '';
professionInput.blur();
validateField('profession');
});
}
// ===== GUEST OF PICKER =====
function normalizeGuestValue(value) {
return String(value || '').trim().toLowerCase();
}
function findGuestMember(value) {
var norm = normalizeGuestValue(value);
if (!norm) return null;
return TEAM_MEMBERS.find(function(m) { return normalizeGuestValue(m.name) === norm; }) || null;
}
function syncGuestQuickPicks() {
if (!guestQuickPicks) return;
var selected = guestQuickPicks.getAttribute('data-selected-option') || '';
guestQuickPicks.querySelectorAll('.guest-chip').forEach(function(btn) {
btn.classList.toggle('active', btn.getAttribute('data-value') === selected);
});
}
function renderGuestQuickPicks() {
if (!guestQuickPicks) return;
var chips = isKiosk
? TEAM_MEMBERS
: TEAM_MEMBERS.filter(function(m) { return m.leader && !m.specialTitle; });
guestQuickPicks.innerHTML = chips.map(function(m) {
var extra = (isKiosk && m.leader) ? ' guest-chip--leader' : '';
var s = escapeHtml(m.name);
return '<button type="button" class="guest-chip' + extra + '" data-value="' + s + '">' + s + '</button>';
}).join('') + '<button type="button" class="guest-chip guest-chip--other" data-value="Other">Someone Else</button>';
syncGuestQuickPicks();
}
function getGuestMatches(query) {
var norm = normalizeGuestValue(query);
if (!norm) return [];
return TEAM_MEMBERS.filter(function(m) {
return [m.name, m.title, m.company].some(function(p) {
return normalizeGuestValue(p).indexOf(norm) !== -1;
});
}).slice(0, 6);
}
function renderGuestResults() {
if (!guestSearchInput || !guestResults || !guestOfHidden) return;
var query = guestSearchInput.value.trim();
if (!query) { guestResults.innerHTML = ''; return; }
var selected = guestOfHidden.value;
guestResults.innerHTML = getGuestMatches(query).map(function(m) {
var cls = m.name === selected ? ' active' : '';
var sn = escapeHtml(m.name), st = escapeHtml(m.title), sc = escapeHtml(m.company || '');
return '<button type="button" class="guest-result' + cls + '" data-value="' + sn + '">' +
'<span class="guest-result-name">' + sn + '</span>' +
'<span class="guest-result-meta">' + st + ' • ' + sc + '</span>' +
'</button>';
}).join('');
}
function setGuestSelection(value, options) {
if (!guestOfHidden || !guestSearchInput || !guestQuickPicks) return;
var next = String(value || '').trim();
var match = findGuestMember(next);
var isCustom = !!(next && !match);
guestOfHidden.value = match ? match.name : next;
if (!options || !options.keepTypedValue) guestSearchInput.value = guestOfHidden.value;
guestQuickPicks.setAttribute('data-selected-option',
match && match.leader ? match.name : (isCustom ? 'Other' : ''));
syncGuestQuickPicks();
renderGuestResults();
validateField('guestOf');
}
renderGuestQuickPicks();
fetchWithTimeout('/api/members', { method: 'GET' }, 5000)
.then(function(r) { return r.json(); })
.then(function(data) {
if (data.status !== 'ok' || !Array.isArray(data.members) || !data.members.length) return;
TEAM_MEMBERS = data.members;
renderGuestQuickPicks();
if (onMembersLoaded) onMembersLoaded(TEAM_MEMBERS);
})
.catch(function() { /* static fallback already rendered */ });
if (guestQuickPicks) {
guestQuickPicks.addEventListener('click', function(event) {
var btn = event.target.closest('.guest-chip');
if (!btn) return;
var val = btn.getAttribute('data-value');
if (val === 'Other') {
guestQuickPicks.setAttribute('data-selected-option', 'Other');
guestOfHidden.value = guestSearchInput.value.trim();
syncGuestQuickPicks();
guestSearchInput.focus();
validateField('guestOf');
return;
}
setGuestSelection(val);
});
}
if (guestSearchInput) {
guestSearchInput.addEventListener('focus', function() { renderGuestResults(); });
guestSearchInput.addEventListener('input', function() {
setGuestSelection(this.value, { keepTypedValue: true });
});
guestSearchInput.addEventListener('blur', function() {
window.setTimeout(function() {
guestResults.innerHTML = '';
setGuestSelection(guestSearchInput.value);
}, 120);
});
}
if (guestResults) {
guestResults.addEventListener('click', function(event) {
var btn = event.target.closest('.guest-result');
if (!btn) return;
setGuestSelection(btn.getAttribute('data-value'));
guestResults.innerHTML = '';
guestSearchInput.blur();
});
}
// ===== VALIDATION =====
function validateField(name) {
var input = document.getElementById(name);
var errorEl = document.getElementById(name + '-error');
var valid = true;
if (name === 'guestOf') {
valid = !!(guestOfHidden && guestOfHidden.value.trim());
if (guestPicker) guestPicker.classList.toggle('error', !valid);
if (guestSearchInput) guestSearchInput.classList.toggle('error', !valid);
if (guestSearchInput) guestSearchInput.setAttribute('aria-invalid', valid ? 'false' : 'true');
if (errorEl) errorEl.classList.toggle('visible', !valid);
return valid;
}
if (!input) return true;
if (input.type === 'hidden') {
valid = !!input.value.trim();
if (errorEl) errorEl.classList.toggle('visible', !valid);
return valid;
}
if (optionalFields.indexOf(name) !== -1 && !input.value.trim()) {
input.classList.remove('error');
input.setAttribute('aria-invalid', 'false');
if (errorEl) errorEl.classList.remove('visible');
return true;
}
if (!input.value.trim()) valid = false;
if (name === 'email' && input.value.trim()) {
valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value.trim());
}
if (valid) {
input.classList.remove('error');
input.setAttribute('aria-invalid', 'false');
if (errorEl) errorEl.classList.remove('visible');
} else {
input.classList.add('error');
input.setAttribute('aria-invalid', 'true');
if (errorEl) errorEl.classList.add('visible');
}
return valid;
}
function validateAll() {
var ok = true;
fields.forEach(function(name) { if (!validateField(name)) ok = false; });
return ok;
}
allFields.forEach(function(name) {
if (name === 'guestOf') return;
var input = document.getElementById(name);
if (!input || input.type === 'hidden') return;
input.addEventListener('blur', function() {
if (input.value.trim() || fields.indexOf(name) !== -1) validateField(name);
});
input.addEventListener('change', function() { validateField(name); });
input.addEventListener('input', function() {
if (input.classList.contains('error')) validateField(name);
});
});
// ===== SUCCESS / ERROR =====
function hideForm() {
form.style.display = 'none';
if (kioskFormHeader) kioskFormHeader.style.display = 'none';
}
function showWelcomeToast(firstName) {
if (!kioskToast || !toastNameEl || !firstName) return;
toastNameEl.textContent = 'WELCOME, ' + firstName.toUpperCase() + '!';
kioskToast.classList.add('visible');
clearTimeout(toastTimer);
toastTimer = setTimeout(function() { kioskToast.classList.remove('visible'); }, 8000);
}
function showSuccess(options) {
var localOnly = !!(options && options.localOnly);
var reason = options && options.reason;
var firstName = (document.getElementById('firstName').value || '').trim();
submitBtn.classList.remove('loading');
submitBtn.disabled = false;
if (isKiosk) {
successTitle.textContent = localOnly
? localOnlySuccessTitle
: ('Welcome, ' + (firstName || 'Guest') + '!');
successSubtitle.textContent = localOnly
? (reason === 'sync-failed' ? syncFailedSuccessSubtitle : localOnlySuccessSubtitle)
: 'You\u2019re all set. Grab a seat, introduce yourself to someone new, and get ready \u2014 we kick off at 4:00!';
} else {
successTitle.textContent = localOnly ? localOnlySuccessTitle : defaultSuccessTitle;
successSubtitle.textContent = localOnly
? (reason === 'sync-failed' ? syncFailedSuccessSubtitle : localOnlySuccessSubtitle)
: defaultSuccessSubtitle;
}
hideForm();
successScreen.style.display = 'flex';
successScreen.setAttribute('tabindex', '-1');
try { successScreen.focus({ preventScroll: true }); }
catch(e) { successScreen.focus(); }
if (confettiCanvas) launchConfetti(confettiCanvas);
announceFormStatus(successTitle.textContent + ' ' + successSubtitle.textContent);
if (isKiosk) {
showWelcomeToast(firstName);
clearTimeout(autoResetTimer);
autoResetTimer = setTimeout(function() {
if (resetBtn) resetBtn.click();
}, resetTimeoutMs);
}
if (onSuccess) onSuccess({ localOnly: localOnly, reason: reason });
}
function showSubmissionIssue() {
submitBtn.classList.remove('loading');
submitBtn.disabled = false;
successTitle.textContent = submitFailedTitle;
successSubtitle.textContent = submitFailedSubtitle;
hideForm();
successScreen.style.display = 'flex';
successScreen.setAttribute('tabindex', '-1');
try { successScreen.focus({ preventScroll: true }); }
catch(e) { successScreen.focus(); }
announceFormStatus(successTitle.textContent + ' ' + successSubtitle.textContent);
}
// ===== SUBMIT =====
form.addEventListener('submit', function(event) {
event.preventDefault();
if (submitBtn && submitBtn.disabled) return;
try {
if (!validateAll()) {
var firstError = form.querySelector('.field-input.error');
announceFormStatus('Please fix the highlighted fields.');
if (firstError) firstError.focus();
return;
}
if (submitBtn) {
submitBtn.classList.add('loading');
submitBtn.disabled = true;
}
var entry = {};
allFields.forEach(function(name) {
var input = document.getElementById(name);
entry[name] = input ? input.value.trim() : '';
});
fetchWithTimeout(FORM_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body: new URLSearchParams(Object.assign({}, entry, {
companyWebsite: companyWebsite ? companyWebsite.value.trim() : ''
})).toString()
}, FORM_TIMEOUT_MS).then(function(response) {
if (!response.ok) throw new Error('submit-failed');
return response.json();
}).then(function(result) {
if (!result || result.status !== 'ok') throw new Error('submit-failed');
pruneLocalEntries();
showSuccess();
}).catch(function() {
var savedEntry = saveFailedLocal(entry);
if (savedEntry) {
updatePendingRecovery('Saved locally after sync failed. Retry sync before clearing browser data.');
showSuccess({ localOnly: true, reason: 'sync-failed' });
return;
}
showSubmissionIssue();
});
} catch(err) {
if (submitBtn) {
submitBtn.classList.remove('loading');
submitBtn.disabled = false;
}
announceFormStatus('Something went wrong before we could submit. Please try again.');
}
});
// ===== RESET =====
function doReset() {
clearTimeout(autoResetTimer);
if (kioskToast) kioskToast.classList.remove('visible');
successScreen.style.display = 'none';
form.style.display = 'flex';
if (kioskFormHeader) kioskFormHeader.style.display = 'block';
form.reset();
if (guestOfHidden) guestOfHidden.value = '';
if (guestSearchInput) guestSearchInput.value = '';
if (guestResults) guestResults.innerHTML = '';
if (guestQuickPicks) guestQuickPicks.setAttribute('data-selected-option', '');
if (companyWebsite) companyWebsite.value = '';
successTitle.textContent = defaultSuccessTitle;
successSubtitle.textContent = defaultSuccessSubtitle;
updatePendingRecovery();
allFields.forEach(function(name) {
var input = document.getElementById(name);
var errorEl = document.getElementById(name + '-error');
if (input) {
input.value = '';
input.classList.remove('error');
input.setAttribute('aria-invalid', 'false');
}
if (errorEl) errorEl.classList.remove('visible');
});
syncGuestQuickPicks();
if (guestPicker) guestPicker.classList.remove('error');
if (guestSearchInput) {
guestSearchInput.classList.remove('error');
guestSearchInput.setAttribute('aria-invalid', 'false');
}
announceFormStatus('');
var firstEl = document.getElementById('firstName');
if (firstEl) firstEl.focus();
if (onReset) onReset();
}
if (resetBtn) {
resetBtn.addEventListener('click', doReset);
}
}
global.initCheckinForm = initCheckinForm;
})(window);