Repository navigation
Expand file tree
/
Copy pathscripts.js
More file actions
3836 lines (3429 loc) · 201 KB
/
Copy pathscripts.js
File metadata and controls
3836 lines (3429 loc) · 201 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
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
window.APP_CURRENCY = (document.cookie.match(/(?:^|; )egds_currency=([^;]*)/) || [])[1] || 'USD';
window.APP_LANGUAGE = 'en-US'; // Default Language
// Global definition to ensure it works regardless of load order or other script failures
let _dealModalCloseTimer = null;
window.openDealModal = function (city, code) {
console.log("Opening Deal Modal (Exclusive) for:", city, code);
const dealModal = document.getElementById('deal-modal');
if (!dealModal) {
console.error("Deal modal element not found!");
return;
}
// Cancel any pending close animation to prevent race condition
if (_dealModalCloseTimer) {
clearTimeout(_dealModalCloseTimer);
_dealModalCloseTimer = null;
}
const modalDestName = document.getElementById('deal-modal-dest-name');
const modalDestInput = document.getElementById('modal-dest');
const modalBackdrop = document.getElementById('deal-modal-backdrop');
const modalContent = document.getElementById('deal-modal-content');
if (modalDestName) modalDestName.textContent = city;
if (modalDestInput) {
modalDestInput.value = city;
modalDestInput.dataset.code = code;
}
// Re-initialize flatpickr if needed
const modalDates = document.getElementById('modal-dates');
if (modalDates && window.flatpickr) {
if (!modalDates._flatpickr) {
EngineConfig.bindPicker(modalDates, PACKAGE_CONFIG_ID, { mode: "range" });
}
const fp = modalDates._flatpickr;
if (fp) {
const d1 = new Date(); d1.setDate(d1.getDate() + 28);
// Never pre-fill a date the engine's booking cutoff forbids.
const floor = fp.config && fp.config.minDate;
if (floor && d1 < floor) d1.setTime(floor.getTime());
const d2 = new Date(d1); d2.setDate(d1.getDate() + 7);
fp.setDate([d1, d2]);
}
}
// Lock body scroll — overflow:hidden on both html & body prevents
// background scroll on all browsers including iOS Safari, without
// the visual jump caused by position:fixed
document.documentElement.classList.add('modal-open');
// Force visible
dealModal.style.display = 'block';
dealModal.classList.remove('hidden');
// Use double-rAF to guarantee the browser has painted display:block
// before starting opacity/scale transitions (10ms setTimeout is unreliable on mobile)
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (modalBackdrop) modalBackdrop.classList.remove('opacity-0');
if (modalContent) modalContent.classList.remove('opacity-0', 'scale-95');
});
});
};
// Close logic
window.closeDealModal = function () {
const dealModal = document.getElementById('deal-modal');
const modalBackdrop = document.getElementById('deal-modal-backdrop');
const modalContent = document.getElementById('deal-modal-content');
if (modalBackdrop) modalBackdrop.classList.add('opacity-0');
if (modalContent) modalContent.classList.add('opacity-0', 'scale-95');
// Unlock body scroll
document.documentElement.classList.remove('modal-open');
if (dealModal) {
_dealModalCloseTimer = setTimeout(() => {
dealModal.classList.add('hidden');
dealModal.style.display = ''; // Reset inline style
_dealModalCloseTimer = null;
}, 300);
}
};
// iOS/Safari bfcache (back-forward cache) restoration.
//
// When a user submits a search, navigates to results, and hits back,
// Safari restores the previous page from bfcache instead of re-running
// page scripts. The DOM is snapshot-restored verbatim — meaning:
// (a) Recent-searches strip keeps its prior `.hidden` class even
// though the cookie now has entries (would require re-render).
// (b) Visible input values appear filled, but internal state
// (dataset.code, flatpickr instances, pax managers) is stale,
// causing "incomplete" red-ring validation errors on resubmit.
//
// A full reload on bfcache restore rebuilds a consistent state in one
// shot — simpler and more reliable than surgically re-syncing each
// widget's internal state with its DOM shell.
window.addEventListener('pageshow', (event) => {
if (event.persisted || (performance.getEntriesByType('navigation')[0] || {}).type === 'back_forward') {
window.location.reload();
}
});
document.addEventListener('DOMContentLoaded', () => {
const closeBtn = document.getElementById('deal-close-btn');
const modalBackdrop = document.getElementById('deal-modal-backdrop');
if (closeBtn) closeBtn.onclick = closeDealModal;
if (modalBackdrop) modalBackdrop.onclick = closeDealModal;
// Initialize Lucide Icons
lucide.createIcons();
// Add 'loaded' class for animations
setTimeout(() => {
document.body.classList.add('loaded');
}, 100);
// --- Hero Carousel ---
const slides = document.querySelectorAll('.hero-slide');
const dots = document.querySelectorAll('.carousel-dot');
let currentSlide = 0;
let slideInterval;
const updateCarousel = (index) => {
// Pages without a carousel (e.g. the editorial home-v3 hero)
// share this file, so bail rather than index into an empty list.
if (!slides.length || !dots.length) return;
// Update slides
slides.forEach(s => s.classList.remove('active'));
slides[index].classList.add('active');
// Update dots
dots.forEach(d => {
d.classList.remove('active', 'bg-white', 'w-8');
d.classList.add('bg-white/40', 'w-2.5');
});
const activeDot = dots[index];
activeDot.classList.remove('bg-white/40', 'w-2.5');
activeDot.classList.add('active', 'bg-white', 'w-8');
currentSlide = index;
};
const startSlideShow = () => {
if (!slides.length) return;
if (slideInterval) clearInterval(slideInterval);
slideInterval = setInterval(() => {
const next = (currentSlide + 1) % slides.length;
updateCarousel(next);
}, 6000);
};
// Initialize
startSlideShow();
// Click Handlers
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
updateCarousel(index);
startSlideShow(); // Reset timer
});
});
// --- Mobile Menu Toggle ---
const mobileBtn = document.getElementById('mobile-menu-btn');
const mobileMenu = document.getElementById('mobile-menu');
let isMenuOpen = false;
if (mobileBtn && mobileMenu) {
mobileBtn.addEventListener('click', () => {
isMenuOpen = !isMenuOpen;
if (isMenuOpen) {
mobileMenu.classList.remove('translate-x-full');
mobileBtn.innerHTML = '<i data-lucide="x" class="w-7 h-7"></i>';
mobileBtn.classList.remove('text-white');
mobileBtn.classList.add('text-brand-primary');
document.body.style.overflow = 'hidden';
} else {
mobileMenu.classList.add('translate-x-full');
mobileBtn.innerHTML = '<i data-lucide="menu" class="w-7 h-7"></i>';
mobileBtn.classList.add('text-white');
mobileBtn.classList.remove('text-brand-primary');
document.body.style.overflow = '';
}
lucide.createIcons();
});
}
// --- Sticky Search Logic ---
const header = document.getElementById('main-header');
const searchContainerWrapper = document.getElementById('search-container-wrapper');
const searchPanel = document.getElementById('search-panel');
const searchInputsContainer = document.getElementById('search-inputs-container');
const searchTabsContainer = document.getElementById('search-tabs-container');
// ─── Sticky/collapse is a DESKTOP-ONLY behavior ──────────────────────
// On mobile, the sticky-collapsed search bar fights with:
// - iOS focus auto-scroll on input tap
// - layout shifts from opening/closing popovers (rooms, travelers)
// - restoring a recent-search chip (form content swaps height)
// - the virtual keyboard showing/hiding
//
// Every one of those can trip the sticky threshold unexpectedly and
// collapse the widget mid-interaction. No amount of focus/grace
// guarding fully covers all cases because the scroll itself is
// genuine — caused by the page reflowing, not by the user.
//
// Simplest durable fix: disable sticky/collapse below the lg
// breakpoint (1024px). Desktop keeps the full behavior.
const isDesktop = () => window.matchMedia('(min-width: 1024px)').matches;
if (header && searchContainerWrapper && searchPanel && isDesktop()) {
const headerHeight = header.offsetHeight;
let isSticky = false;
let isExpanded = false;
const applySticky = () => {
searchPanel.classList.add('is-sticky', 'is-collapsed');
searchPanel.classList.remove('max-w-4xl', 'rounded-2xl', 'shadow-elegant-xl', 'bg-white/10', 'backdrop-blur-md', 'border-white/30', 'p-2', 'lg:p-4');
searchPanel.classList.add('max-w-full', 'rounded-b-2xl', 'border-t', 'border-gray-100', 'py-3', 'px-4', 'lg:px-6');
searchContainerWrapper.classList.remove('px-4', 'lg:px-6', 'pb-6');
updateTabStyles(true);
};
const removeSticky = () => {
searchPanel.classList.remove('is-sticky', 'is-collapsed');
searchPanel.classList.add('max-w-4xl', 'rounded-2xl', 'shadow-elegant-xl', 'bg-white/10', 'backdrop-blur-md', 'border-white/30', 'p-2', 'lg:p-4');
searchPanel.classList.remove('max-w-full', 'rounded-b-2xl', 'border-t', 'border-gray-100', 'py-3', 'px-4', 'lg:px-6');
searchContainerWrapper.classList.add('px-4', 'lg:px-6', 'pb-6');
isExpanded = false;
updateTabStyles(false);
};
const updateTabStyles = (sticky) => {
const tabs = searchTabsContainer.querySelectorAll('.search-tab');
tabs.forEach(tab => {
if (!tab.classList.contains('active')) {
if (sticky) {
tab.classList.remove('text-white/90', 'hover:text-white', 'hover:bg-white/10');
tab.classList.add('text-gray-500', 'hover:text-brand-primary', 'hover:bg-gray-50');
} else {
tab.classList.add('text-white/90', 'hover:text-white', 'hover:bg-white/10');
tab.classList.remove('text-gray-500', 'hover:text-brand-primary', 'hover:bg-gray-50');
}
}
});
};
// ─── Widget-active lock ──────────────────────────────────────────
// The sticky/collapse transitions must FREEZE while the user is
// actively interacting with the widget, otherwise:
// - iOS auto-scrolls on input focus → trips the sticky threshold
// → collapses the form mid-tap.
// - focusout fires when tapping an autocomplete result (the
// result <div> isn't focusable) → collapses while the user
// is selecting.
//
// "Active" = any of:
// (a) focus is inside a panel input
// (b) an autocomplete dropdown is visible
// (c) a traveler-popover / custom-options dropdown is open
// (d) within a 400ms grace window after any of the above ended
// (tap → focus transfer → dropdown settles)
const hasVisibleChild = (selector) => {
const nodes = searchPanel.querySelectorAll(selector);
for (const n of nodes) {
if (!n.classList.contains('hidden') && n.offsetParent !== null) return true;
}
return false;
};
const isWidgetActive = () => {
const ae = document.activeElement;
const focusInside = ae && searchPanel.contains(ae) &&
(ae.tagName === 'INPUT' || ae.tagName === 'TEXTAREA' || ae.tagName === 'SELECT');
if (focusInside) return true;
if (hasVisibleChild('.autocomplete-results')) return true;
if (hasVisibleChild('.traveler-popover')) return true;
if (hasVisibleChild('.custom-options')) return true;
return false;
};
let graceUntil = 0;
const markActivity = () => { graceUntil = Date.now() + 400; };
const inGrace = () => Date.now() < graceUntil;
const reconcileSticky = () => {
if (isWidgetActive() || inGrace()) return;
const triggerPoint = searchContainerWrapper.offsetTop - headerHeight;
if (window.scrollY > triggerPoint) {
if (!isSticky) { isSticky = true; applySticky(); }
} else {
if (isSticky) { isSticky = false; removeSticky(); }
}
};
window.addEventListener('scroll', () => {
if (isWidgetActive()) { markActivity(); return; }
if (inGrace()) return;
reconcileSticky();
}, { passive: true });
// When focus leaves a panel input (including tapping on a
// non-focusable dropdown item), start grace and check later —
// never immediately collapse.
document.addEventListener('focusout', (e) => {
if (!searchPanel.contains(e.target)) return;
markActivity();
setTimeout(reconcileSticky, 450);
});
// When the user focuses into a panel input, lock expanded state
// even if we're already sticky. Removing .is-collapsed lets the
// user see the inputs instead of the collapsed tab bar.
document.addEventListener('focusin', (e) => {
if (!searchPanel.contains(e.target)) return;
markActivity();
if (searchPanel.classList.contains('is-sticky')) {
isExpanded = true;
searchPanel.classList.remove('is-collapsed');
searchPanel.classList.remove('py-3');
searchPanel.classList.add('py-4');
}
});
// Expand on tab click when sticky
if (searchTabsContainer) {
searchTabsContainer.addEventListener('click', (e) => {
const clickedTab = e.target.closest('.search-tab');
if (clickedTab && isSticky) {
isExpanded = true;
searchPanel.classList.remove('is-collapsed');
searchPanel.classList.remove('py-3');
searchPanel.classList.add('py-4');
}
});
}
// Collapse on outside click when sticky
document.addEventListener('click', (e) => {
if (isSticky && isExpanded) {
const isClickInside = searchPanel.contains(e.target);
if (!isClickInside) {
isExpanded = false;
searchPanel.classList.add('is-collapsed');
searchPanel.classList.add('py-3');
searchPanel.classList.remove('py-4');
}
}
});
}
// --- Search Tab Switching ---
const tabs = document.querySelectorAll('.search-tab');
// Scope to #search-panel only — do NOT select the modal's .search-form
const forms = document.querySelectorAll('#search-panel .search-form');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = tab.dataset.target;
const searchPanel = document.getElementById('search-panel');
const isSticky = searchPanel.classList.contains('is-sticky');
tabs.forEach(t => {
// Reset all tabs
t.classList.remove('active', 'bg-white', 'shadow-elegant', 'text-brand-primary', 'ring-1', 'ring-black/5');
if (isSticky) {
t.classList.add('text-gray-500', 'hover:text-brand-primary', 'hover:bg-gray-50');
t.classList.remove('text-white/90', 'hover:text-white', 'hover:bg-white/10');
} else {
t.classList.add('text-white/90', 'hover:text-white', 'hover:bg-white/10');
t.classList.remove('text-gray-500', 'hover:text-brand-primary', 'hover:bg-gray-50');
}
});
// Activate clicked tab
tab.classList.add('active', 'bg-white', 'shadow-elegant', 'text-brand-primary', 'ring-1', 'ring-black/5');
tab.classList.remove('text-white/90', 'text-gray-500', 'hover:bg-white/10', 'hover:bg-gray-50', 'hover:text-white', 'hover:text-brand-primary');
forms.forEach(form => form.classList.add('hidden'));
const targetForm = document.getElementById(`${target}-form`);
if (targetForm) targetForm.classList.remove('hidden');
});
});
// Popovers are handled by homepage_logic_integrated.js
// --- Currency Dropdown Logic ---
const currencyCurrencies = ['AED', 'AUD', 'EUR', 'GBP', 'INR', 'JPY', 'MYR', 'NZD', 'SAR', 'SGD', 'TRY', 'USD', 'VND'];
const currencyTriggerDesktop = document.getElementById('currency-trigger-desktop');
const currencyMenuDesktop = document.getElementById('currency-menu-desktop');
const currencyTriggerMobile = document.getElementById('currency-trigger-mobile');
const currencyMenuMobile = document.getElementById('currency-menu-mobile');
function setCurrency(code) {
window.APP_CURRENCY = code;
document.cookie = 'egds_currency=' + code + '; path=/; max-age=31536000; SameSite=Lax';
// Update Displays
const dDesk = document.getElementById('currency-display-desktop');
const dMob = document.getElementById('currency-display-mobile');
if (dDesk) dDesk.textContent = code;
if (dMob) dMob.textContent = code;
// Visual Feedback (Desktop)
if (currencyMenuDesktop) {
currencyMenuDesktop.querySelectorAll('.currency-item').forEach(el => {
if (el.dataset.val === code) el.classList.add('bg-brand-surface', 'text-brand-primary', 'font-bold');
else el.classList.remove('bg-brand-surface', 'text-brand-primary', 'font-bold');
});
}
// Visual Feedback (Mobile)
if (currencyMenuMobile) {
currencyMenuMobile.querySelectorAll('.currency-item-mobile').forEach(el => {
if (el.dataset.val === code) el.classList.add('border-brand-primary', 'text-brand-primary', 'bg-brand-surface');
else el.classList.remove('border-brand-primary', 'text-brand-primary', 'bg-brand-surface');
});
}
// Close Desktop Menu
if (currencyMenuDesktop) currencyMenuDesktop.classList.add('hidden');
}
// Init Desktop Menu
if (currencyMenuDesktop) {
const listContainer = currencyMenuDesktop.querySelector('.currency-list');
listContainer.innerHTML = '';
currencyCurrencies.forEach(c => {
const item = document.createElement('div');
item.className = 'currency-item px-4 py-2 hover:bg-brand-surface cursor-pointer text-sm font-medium text-brand-text transition-colors flex justify-between items-center';
if (c === window.APP_CURRENCY) item.classList.add('bg-brand-surface', 'text-brand-primary', 'font-bold');
item.textContent = c;
item.dataset.val = c;
item.onclick = (e) => { e.stopPropagation(); setCurrency(c); };
listContainer.appendChild(item);
});
// Toggle (and close language dropdown)
if (currencyTriggerDesktop) {
currencyTriggerDesktop.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (langMenuDesk) langMenuDesk.classList.add('hidden');
currencyMenuDesktop.classList.toggle('hidden');
});
}
}
// Init Mobile Menu
if (currencyMenuMobile) {
currencyMenuMobile.innerHTML = '';
currencyCurrencies.forEach(c => {
const item = document.createElement('div');
item.className = 'currency-item-mobile py-2 px-3 text-center border border-gray-200 rounded-lg text-sm font-medium hover:border-brand-primary hover:text-brand-primary cursor-pointer transition-colors';
if (c === window.APP_CURRENCY) item.classList.add('border-brand-primary', 'text-brand-primary', 'bg-brand-surface');
item.textContent = c;
item.dataset.val = c;
item.onclick = (e) => { e.stopPropagation(); setCurrency(c); };
currencyMenuMobile.appendChild(item);
});
if (currencyTriggerMobile) {
currencyTriggerMobile.addEventListener('click', (e) => {
// Close language mobile menu
if (langMenuMob && !langMenuMob.classList.contains('hidden')) {
langMenuMob.classList.add('hidden');
const langChev = document.getElementById('lang-chevron-mobile');
if (langChev) langChev.classList.remove('rotate-180');
}
const chevron = document.getElementById('currency-chevron-mobile');
currencyMenuMobile.classList.toggle('hidden');
if (chevron) chevron.classList.toggle('rotate-180');
});
}
}
// Restore saved currency on load
if (window.APP_CURRENCY && window.APP_CURRENCY !== 'USD') {
setCurrency(window.APP_CURRENCY);
}
// --- Language Dropdown Logic ---
const appLanguages = [
{ code: 'en-US', label: 'EN', flag: 'us' },
{ code: 'de-DE', label: 'DE', flag: 'de' },
{ code: 'ru-RU', label: 'RU', flag: 'ru' },
{ code: 'ja-JP', label: 'JP', flag: 'jp' }
];
const langTriggerDesk = document.getElementById('lang-trigger-desktop');
const langMenuDesk = document.getElementById('lang-menu-desktop');
const langTriggerMob = document.getElementById('lang-trigger-mobile');
const langMenuMob = document.getElementById('lang-menu-mobile');
function setLanguage(langObj) {
window.APP_LANGUAGE = langObj.code;
// Update Displays
const updateDisplay = (prefix) => {
const label = document.getElementById(`${prefix}-label`);
const flag = document.getElementById(`${prefix}-flag`);
if (label) label.textContent = langObj.label;
if (flag) flag.src = `https://flagcdn.com/w20/${langObj.flag}.png`;
};
updateDisplay('lang-display-desktop');
updateDisplay('lang-display-mobile');
// Visual Feedback
const updateActive = (menu, itemClass, activeClass) => {
if (!menu) return;
menu.querySelectorAll(itemClass).forEach(el => {
if (el.dataset.code === langObj.code) el.classList.add(...activeClass.split(' '));
else el.classList.remove(...activeClass.split(' '));
});
};
if (langMenuDesk) updateActive(langMenuDesk, '.lang-item', 'bg-brand-surface text-brand-primary font-bold');
if (langMenuMob) updateActive(langMenuMob, '.lang-item-mobile', 'border-brand-primary text-brand-primary bg-brand-surface');
// Close Menu
if (langMenuDesk) langMenuDesk.classList.add('hidden');
}
// Init Desktop Lang Menu
if (langMenuDesk) {
const list = langMenuDesk.querySelector('.lang-list');
list.innerHTML = '';
appLanguages.forEach(l => {
const item = document.createElement('div');
item.className = 'lang-item px-4 py-2 hover:bg-brand-surface cursor-pointer text-sm font-medium text-brand-text transition-colors flex items-center gap-3';
if (l.code === window.APP_LANGUAGE) item.classList.add('bg-brand-surface', 'text-brand-primary', 'font-bold');
item.dataset.code = l.code;
item.innerHTML = `
<img src="https://flagcdn.com/w20/${l.flag}.png" class="w-5 h-auto rounded shadow-sm">
<span>${l.label}</span>
`;
item.onclick = (e) => { e.stopPropagation(); setLanguage(l); };
list.appendChild(item);
});
if (langTriggerDesk) {
langTriggerDesk.addEventListener('click', (e) => {
e.preventDefault(); e.stopPropagation();
if (currencyMenuDesktop) currencyMenuDesktop.classList.add('hidden');
langMenuDesk.classList.toggle('hidden');
});
}
}
// Init Mobile Lang Menu
if (langMenuMob) {
langMenuMob.innerHTML = '';
appLanguages.forEach(l => {
const item = document.createElement('div');
item.className = 'lang-item-mobile py-2 px-3 flex items-center justify-center gap-2 border border-gray-200 rounded-lg text-sm font-medium hover:border-brand-primary hover:text-brand-primary cursor-pointer transition-colors';
if (l.code === window.APP_LANGUAGE) item.classList.add('border-brand-primary', 'text-brand-primary', 'bg-brand-surface');
item.dataset.code = l.code;
item.innerHTML = `
<img src="https://flagcdn.com/w20/${l.flag}.png" class="w-4 h-auto rounded shadow-sm">
<span>${l.label}</span>
`;
item.onclick = (e) => { e.stopPropagation(); setLanguage(l); };
langMenuMob.appendChild(item);
});
if (langTriggerMob) {
langTriggerMob.addEventListener('click', () => {
// Close currency mobile menu
if (currencyMenuMobile && !currencyMenuMobile.classList.contains('hidden')) {
currencyMenuMobile.classList.add('hidden');
const currChev = document.getElementById('currency-chevron-mobile');
if (currChev) currChev.classList.remove('rotate-180');
}
const chev = document.getElementById('lang-chevron-mobile');
langMenuMob.classList.toggle('hidden');
if (chev) chev.classList.toggle('rotate-180');
});
}
}
// --- Close all desktop dropdowns on outside click ---
document.addEventListener('click', (e) => {
if (currencyMenuDesktop && currencyTriggerDesktop &&
!currencyTriggerDesktop.contains(e.target) && !currencyMenuDesktop.contains(e.target)) {
currencyMenuDesktop.classList.add('hidden');
}
if (langMenuDesk && langTriggerDesk &&
!langTriggerDesk.contains(e.target) && !langMenuDesk.contains(e.target)) {
langMenuDesk.classList.add('hidden');
}
});
});
// ================= CONFIGURATION =================
const API_BASE_URL = 'https://demo.apps.easygds.com/api';
const SESSION_ID = 'demo_session_dynamic_homepage_' + Math.floor(Math.random() * 10000);
// Product IDs — these double as the keys the engine publishes its search
// rules under (see engine-config.js / GET /packages/list).
const FLIGHT_CONFIG_ID = '3dca0e8c-b1ec-4fef-913e-09b577956c6d';
const HOTEL_CONFIG_ID = '4a5c9770-f901-4b96-8673-ecdc5ee49102';
const PACKAGE_CONFIG_ID = 'aaa34775-f480-477c-a656-f7a9a07ce605';
const TRANSFER_CONFIG_ID = '7bf47e3c-8951-4016-9190-d813047b3939';
const TOUR_CONFIG_ID = 'ddd85aba-76ad-47f0-abd4-a36d7767b624';
// ================= ENGINE PAX CLAMPING =================
/* Engine rules arrive after first paint (or instantly, from cache). By the time
* they land the user may already hold more travellers than the new cap allows —
* the room selectors are unbounded until a limit exists — so an EngineConfig
* update has to reduce an over-limit selection, not merely redraw the + buttons.
*
* Both shapes of selector funnel into EngineConfig.clampPax, which owns the
* reduction order (infants, then children, then adults) and the "never below the
* floor" rule. These two adapters only translate each selector's own state shape
* to and from plain counts.
*
* Everything here is defensive: it runs inside an EngineConfig listener, where a
* throw would take the remaining listeners — and the widget — down with it. */
/* Counter selectors (flights, tours): { adt, chd, inf, chdAges }.
* Returns true when something moved, so the caller re-renders only then. */
const clampCounterPax = (state, configId, fallbackTotal, countInfants) => {
try {
const next = EngineConfig.clampPax(state, EngineConfig.rulesFor(configId), fallbackTotal, countInfants, { adt: 1 });
if (!next.changed) return false;
state.adt = next.adt; state.chd = next.chd; state.inf = next.inf;
// Client-side rule — the engine publishes no infant-per-adult ratio.
if (state.inf > state.adt) state.inf = state.adt;
// chdAges holds one age per child; keep it the same length as the count.
if (!Array.isArray(state.chdAges)) state.chdAges = [];
while (state.chdAges.length > state.chd) state.chdAges.pop();
while (state.chdAges.length < state.chd) state.chdAges.push(5);
return true;
} catch (e) {
console.warn('[EngineConfig] pax clamp failed', e);
return false;
}
};
/* Trim a party spread across rooms by the given per-type amounts, taking from
* the trailing rooms first and leaving every room its one adult. */
const shedFromRooms = (rooms, dropInf, dropChd, dropAdt) => {
for (let i = rooms.length - 1; i >= 0 && dropInf > 0; i--) {
const take = Math.min(rooms[i].infants || 0, dropInf);
rooms[i].infants = (rooms[i].infants || 0) - take;
dropInf -= take;
}
for (let i = rooms.length - 1; i >= 0 && dropChd > 0; i--) {
// children holds ages, so drop entries rather than decrement a number.
const take = Math.min(rooms[i].children.length, dropChd);
if (take > 0) rooms[i].children.splice(rooms[i].children.length - take, take);
dropChd -= take;
}
for (let i = rooms.length - 1; i >= 0 && dropAdt > 0; i--) {
const take = Math.min(Math.max(0, (rooms[i].adults || 0) - 1), dropAdt);
rooms[i].adults = (rooms[i].adults || 0) - take;
dropAdt -= take;
}
};
/* Room selectors (package, hotel, deal modal): [{ adults, children:[ages], infants }].
* Engine limits are party-wide, not per room. Excess rooms are dropped from the
* end (nothing is merged), and because every room keeps one adult, a cap that
* leaves room for fewer adults than there are rooms has to take rooms with it.
* Returns true when something moved. */
const clampRoomPax = (rooms, configId) => {
try {
if (!Array.isArray(rooms) || !rooms.length) return false;
const rules = EngineConfig.rulesFor(configId);
let changed = false;
rooms.forEach(r => { if (!Array.isArray(r.children)) r.children = []; });
const totals = () => rooms.reduce((t, r) => ({
adt: t.adt + (r.adults || 0),
chd: t.chd + r.children.length,
inf: t.inf + (r.infants || 0)
}), { adt: 0, chd: 0, inf: 0 });
const maxRooms = rules.maxRooms;
if (maxRooms !== null && maxRooms !== undefined && isFinite(maxRooms)) {
const keep = Math.max(1, Math.floor(maxRooms));
if (rooms.length > keep) { rooms.splice(keep); changed = true; }
}
// How many adults may survive at all decides how many rooms may survive,
// so probe with a floor of one adult overall before fixing the floor.
const probe = EngineConfig.clampPax(totals(), rules, null, true, { adt: 1 });
if (probe.adt < rooms.length) { rooms.splice(Math.max(1, probe.adt)); changed = true; }
// Now the real floor: one adult per surviving room.
const before = totals();
const target = EngineConfig.clampPax(before, rules, null, true, { adt: rooms.length });
if (target.changed) {
shedFromRooms(rooms, before.inf - target.inf, before.chd - target.chd, before.adt - target.adt);
changed = true;
}
return changed;
} catch (e) {
console.warn('[EngineConfig] room pax clamp failed', e);
return false;
}
};
// ================= UTILITIES =================
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function getDefaultDates() {
const start = new Date();
start.setDate(start.getDate() + 6); // 6 days out
const end = new Date();
end.setDate(end.getDate() + 9); // 3-day trip
const fmt = (d) => d.toISOString().split('T')[0];
return { startStr: fmt(start), endStr: fmt(end) };
}
// ================= RECENT SEARCHES (Cookie Manager) =================
const RecentSearches = {
COOKIE: 'egds_recent_searches',
MAX: 5,
_read() {
const m = document.cookie.match(new RegExp('(?:^|; )' + this.COOKIE + '=([^;]*)'));
if (!m) return [];
try { return JSON.parse(decodeURIComponent(m[1])); } catch { return []; }
},
_write(arr) {
const v = encodeURIComponent(JSON.stringify(arr));
document.cookie = this.COOKIE + '=' + v + '; path=/; max-age=2592000; SameSite=Lax';
},
getAll() { return this._read(); },
add(entry) {
let arr = this._read();
// Dedupe by tab + origin + dest + dates
arr = arr.filter(e => !(e.tab === entry.tab && e.o === entry.o && e.d === entry.d && e.dd === entry.dd && e.rd === entry.rd));
arr.unshift(entry);
if (arr.length > this.MAX) arr = arr.slice(0, this.MAX);
this._write(arr);
},
remove(index) {
const arr = this._read();
arr.splice(index, 1);
this._write(arr);
},
clearAll() { this._write([]); }
};
async function fetchLocations(query, type, countryCode, placeId) {
const url = new URL(`${API_BASE_URL}/places`);
url.searchParams.append("search_text", query);
url.searchParams.append("language_code", "en-US");
// Dynamic types based on input data-type
let typeParam = "country,airport,administrative_area_level_4,administrative_area_level_3";
if (type === 'airport_code') {
typeParam = "airport"; // Strict filtering for flights/packages
} else if (type === 'hotel') {
typeParam = "hotel"; // Strict filtering for transfer dropoff (properties only)
}
url.searchParams.append("types", typeParam);
if (countryCode) {
url.searchParams.append("country_code", countryCode);
}
if (placeId) {
url.searchParams.append("place_id", placeId);
}
url.searchParams.append("has_code", "false");
// More results for airport searches to accommodate multi-airport city grouping
url.searchParams.append("per_page", (type === 'airport_code' || type === 'any' || type === 'tour_region') ? "30" : "20");
url.searchParams.append("page", "1");
// Handle specific type logic for properties (hotels)
if (type === 'tour_region' || type === 'airport_code') {
url.searchParams.append("with_properties", "false");
} else {
// For hotels or generic search, we might want properties
url.searchParams.append("with_properties", "true");
}
try {
const res = await fetch(url);
if (!res.ok) throw new Error("API Request Failed");
const data = await res.json();
let results = [];
if (Array.isArray(data)) {
// ... existing array handling ...
results = data.map(item => ({
name: item.name,
code: item.code || item.id,
type: 'airport_code',
id: item.id,
city: item.location?.city_code || item.city,
country: item.country,
ancestors: item.ancestors || [],
duffelId: item.duffel_id || null,
icon: '✈️'
}));
} else {
// Object response
const places = (data.places || []).map(p => ({
name: p.long_name || p.name,
code: p.code || p.id,
type: p.type === 'airport' ? 'airport_code' : 'place_id',
rawType: p.type,
id: p.id,
city: p.name,
cityCode: p.location?.city_code || null,
country: p.location?.country_code,
ancestors: p.ancestors || [],
duffelId: p.duffel_id || null,
icon: p.type === 'airport' ? '✈️' : '📍'
}));
const props = (data.properties || []).map(p => ({
name: p.name,
code: p.hotel_id || p.id,
type: 'hotel',
id: p.id,
city: p.city_name || p.city || p.location?.city_name || p.location?.city_code || p.location?.name || '',
country: p.country_code || p.location?.country_code || '',
ancestors: p.ancestors || p.places || [],
stars: p.star || 0,
icon: '🏨'
}));
results = [...places, ...props];
}
// Client-side filtering: API seems to ignore country_code
if (countryCode) {
results = results.filter(r => r.country === countryCode);
}
// Filter non-commercial airports (e.g. QEF-Frankfurt Egelsbach) from
// airport-only queries. Only keep airports bookable via Duffel.
if (type === 'airport_code') {
results = results.filter(r => r.duffelId);
}
return results;
} catch (e) {
console.warn("API Error:", e);
return [];
}
}
// ─── Supplementary Property Name Search ─────────────────────────────────────
// The /api/places endpoint matches search_text against location names, so
// queries like "hilton london" return destinations but zero hotel properties.
// The /api/properties endpoint searches property names directly and handles
// brand + city queries correctly (e.g. "hilton london" → 17 Hilton London hotels).
async function fetchProperties(query, countryCode) {
const url = new URL(`${API_BASE_URL}/properties`);
url.searchParams.append("search_text", query);
url.searchParams.append("language_code", "en-US");
url.searchParams.append("per_page", "10");
url.searchParams.append("page", "1");
try {
const res = await fetch(url);
if (!res.ok) throw new Error("Properties API Failed");
const data = await res.json();
const raw = data.result || [];
let results = raw.map(p => {
// Extract human-readable city from street_address
// e.g. "225 Edgware Road, London, England, W2 1JU, GB" → "London"
const addrParts = (p.street_address || '').split(', ');
const cityFromAddr = addrParts.length >= 3 ? addrParts[1] : '';
return {
name: p.name,
code: p.expedia_id || p.id,
type: 'hotel',
id: p.id,
city: cityFromAddr || p.location?.city_code || '',
country: p.location?.country_code || '',
ancestors: p.places || [],
stars: p.star || 0,
icon: '🏨'
};
});
// Client-side country filter (same as fetchLocations)
if (countryCode) {
results = results.filter(r => r.country === countryCode);
}
return results;
} catch (e) {
console.warn("Properties API Error:", e);
return [];
}
}
function getPlaceIdFromAncestors(ancestors) {
if (!ancestors || !Array.isArray(ancestors)) return null;
const findId = (t) => ancestors.find(a => a.type === t)?.id;
return findId('country') || findId('city') || findId('multi_city_vicinity') || findId('province_state');
}
// ─── Autocomplete Grouping & Sorting ───────────────────────────────────────
function groupResults(results, fieldType, query) {
const q = (query || '').trim().toLowerCase();
if (fieldType === 'airport_code') {
return groupAirportResults(results, q);
} else if (fieldType === 'any') {
return groupHotelDestResults(results, q);
} else if (fieldType === 'hotel') {
return groupTransferHotelResults(results);
} else if (fieldType === 'tour_region') {
return groupTourResults(results, q);
}
// Default: single section, no headers
return [{ label: null, items: results.map(r => ({ ...r, indent: 0 })) }];
}
// Airport passenger traffic rank — top ~200 airports worldwide by annual passengers.
// Used to sort airports within multi-airport cities by importance (lower rank = busier).
// Source: ACI World / publicly available airport traffic statistics.
const AIRPORT_TRAFFIC_RANK = {
// Rank 1-20: Global mega-hubs
ATL: 1, DXB: 2, DFW: 3, LHR: 4, HND: 5,
DEN: 6, IST: 7, LAX: 8, ORD: 9, CDG: 10,
DEL: 11, JFK: 12, AMS: 13, SIN: 14, CAN: 15,
FRA: 16, ICN: 17, PVG: 18, SEA: 19, PEK: 20,
// Rank 21-50: Major international hubs
BKK: 21, SFO: 22, MUC: 23, MAD: 24, BCN: 25,
MEX: 26, KUL: 27, BOM: 28, DOH: 29, SYD: 30,
EWR: 31, CGK: 32, YYZ: 33, JED: 34, LAS: 35,
CLT: 36, MIA: 37, MCO: 38, SAW: 39, FCO: 40,
PHX: 41, IAH: 42, SZX: 43, CTU: 44, TPE: 45,
LGW: 46, BLR: 47, MSP: 48, DTW: 49, NRT: 50,
// Rank 51-100: Major national/regional airports
MNL: 51, HKG: 52, BOS: 53, FLL: 54, SHA: 55,
MEL: 56, DME: 57, SVO: 58, OSL: 59, VIE: 60,
ZRH: 61, CPH: 62, DUS: 63, MAN: 64, DUB: 65,
BRU: 66, HEL: 67, LIS: 68, ARN: 69, ATH: 70,
PMI: 71, AGP: 72, ORY: 73, ALC: 74, EDI: 75,
GLA: 76, HAM: 77, STN: 78, WAW: 79, PRG: 80,
BUD: 81, OTP: 82, BGY: 83, CIA: 84, TXL: 85,
BER: 86, SXF: 87, LTN: 88, LCY: 89, BHX: 90,
NCL: 91, BFS: 92, LBA: 93, EMA: 94, STR: 95,
CGN: 96, TLS: 97, NCE: 98, LYS: 99, MRS: 100,
// Rank 101-150: Secondary hubs & busy regionals
GIG: 101, GRU: 102, EZE: 103, BOG: 104, SCL: 105,
LIM: 106, PTY: 107, SJO: 108, CUN: 109, SJU: 110,
AUH: 111, SHJ: 112, DWC: 113, RUH: 114, DMM: 115,
BAH: 116, MCT: 117, AMM: 118, CAI: 119, CMN: 120,
JNB: 121, CPT: 122, NBO: 123, ADD: 124, LOS: 125,
ACC: 126, DAR: 127, MRU: 128, HYD: 129, MAA: 130,
CCU: 131, COK: 132, GOI: 133, AMD: 134, PNQ: 135,
DMK: 136, HKT: 137, CNX: 138, SGN: 139, HAN: 140,
CXR: 141, DAD: 142, REP: 143, PNH: 144, RGN: 145,
MLE: 146, CMB: 147, KTM: 148, ISB: 149, KHI: 150,
// Rank 151-200: Tertiary airports & multi-city fills
AKL: 151, CHC: 152, WLG: 153, BNE: 154, PER: 155,
ADL: 156, OOL: 157, CNS: 158, CBR: 159, HBA: 160,
NAN: 161, PPT: 162, SUV: 163, KIX: 164, NGO: 165,
FUK: 166, CTS: 167, ITM: 168, OKA: 169, GMP: 170,
PUS: 171, CJU: 172, MFM: 173, TSA: 174, RMQ: 175,
KHH: 176, PKX: 177, XIY: 178, CKG: 179, KMG: 180,
BEG: 181, SEN: 182, BQH: 183, ABZ: 184, INV: 185, SOU: 186,
EXT: 187, CWL: 188, JER: 189, GCI: 190, IOM: 191,
HHN: 192, MXP: 193, VCE: 194, NAP: 195, PSA: 196,
BLQ: 197, TRN: 198, CTA: 199, PMO: 200, BRI: 201, OLB: 202
};
// Destination popularity rank — top ~2,000 destinations worldwide.
// Composite of GeoNames population + Wikidata sitelink count (global prominence).
// Generated by: node scripts/generate-destination-ranks.js
// Generated on: 2026-02-19
// Lower rank = more popular destination. Key format: "asciiname:CC"
const DESTINATION_POPULARITY_RANK = {
// Rank 1-50: Global mega-destinations
"beijing:CN": 1, "moscow:RU": 2, "istanbul:TR": 3, "london:GB": 4, "tokyo:JP": 5,
"new york city:US": 6, "sicily:IT": 7, "cape town:ZA": 8, "ho chi minh city:VN": 9, "shanghai:CN": 10,
"bogota:CO": 11, "mexico city:MX": 12, "cairo:EG": 13, "seoul:KR": 14, "jakarta:ID": 15,
"saint petersburg:RU": 16, "tuscany:IT": 17, "santiago:CL": 18, "baghdad:IQ": 19, "sydney:AU": 20,
"bangkok:TH": 21, "berlin:DE": 22, "mumbai:IN": 23, "tehran:IR": 24, "los angeles:US": 25,
"dhaka:BD": 26, "kinshasa:CD": 27, "lima:PE": 28, "nairobi:KE": 29, "karachi:PK": 30,
"delhi:IN": 31, "buenos aires:AR": 32, "rome:IT": 33, "ankara:TR": 34, "kyiv:UA": 35,
"chicago:US": 36, "kabul:AF": 37, "havana:CU": 38, "hanoi:VN": 39, "paris:FR": 40,