PageSourceSearch

https://segar.group/Scripts/library.js?v=27.20260916-124&pwaLogin=2

js segar.group collected 2026-10-05 01:53:20 UTC 271,729 bytes, 6,694 lines download raw bytes

1var isMobile = {
2    Android: function () {
3        return navigator.userAgent.match(/Android/i);
4    },
5    BlackBerry: function () {
6        return navigator.userAgent.match(/BlackBerry/i);
7    },
8    iPhone: function () {
9        return navigator.userAgent.match(/iPhone|iPod/i);
10    },
11    iPad: function () {
12        return navigator.userAgent.match(/iPad/i);
13    },
14    iOS: function () {
15        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
16    },
17    Opera: function () {
18        return navigator.userAgent.match(/Opera Mini/i);
19    },
20    Windows: function () {
21        return navigator.userAgent.match(/IEMobile/i);
22    },
23    any: function () {
24        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iPhone() || isMobile.Opera() || isMobile.Windows() || isMobile.iPad());
25    }
26};
27
28var isCheckoutPayLater = false;
29var isGoing = false;
30var langSelect = "en";
31var languageButton = [];
32var languageLabel = [];
33var languageMessage = [];
34var deliveryMethodSession = '';
35var maximumSessionTimeout = -1;// ViewBag.SessionTimeout
36var currentSessionTimeout = -1;
37var menuId = '';
38var menuType = '';
39var urlBodyMain = '';
40var maxtimeout = (2 * 60 * 60 * 1000);
41var isDeliveryMethod = false;
42var siteID = "";
43var stationName = "";
44var arrayPromotionCart = [];
45var isLoadPage = false;
46var currentPromotionId = '';
47var currentPromotionIndex = 0;
48var lessItemInCart = 0;
49var detailPromotionId = '';
50var currentService = -1;
51var isConfirmCancel = false;
52var isSelectTime = false;
53var isAutoRedirect = false;
54var autoRedirectType = 0;
55var enableLimitBySales = false;
56var isBackFromDateModal = false;
57var listLimitedItemPromo = [
58    , '685f1cb1-b4b4-4992-a505-a0d903670e5e' // Sakae Sushi - Oyako Don
59    , '2cea0a53-8dfd-4726-98a7-883166d370de' // Sakae Sushi - Nacho Cheese
60    , '4d83fde5-e4ec-4788-85c3-6eda2fd4e81d' // Sakae Sushi - Spicy Ebi Tanuki
61    , 'ed00920e-b883-422d-bded-7e89345774b7' // Sakae Sushi - Unagi Cream Cheese
62    , 'd8b0ca7e-becd-459c-a386-6b9302b9cb79' // Hei Sushi - Tori Ju
63];
64var listLimitedItemPromoAdded = [];
65var isMainPopUpAllowedShow = false;
66var isChopePopupShow = false;
67var isNotifyBannerAllowedShow = false;
68var isMainPopUpShow = false;
69var isShowPromotionDetail = false;
70var isFirstLoad = false;
71var isFirstSite = true;
72var reloadSessionTimeout = null;
73var processing = null;
74var btnUnavailable = "Unavailable";
75var btnCheckAvailability = "Check Date";
76var currentUnavailableFlag = false;
77var timerCheckAvailability;
78var showProductDetailId = '';
79var isExistedItemHide = false;
80var listProductInvalid = '';
81var isSelectDateTime = false;
82var adjustedDeliveryTime = false;
83var isHideNotifiAdjustedDeliveryTime = false;
84var isOpenDateTime = false;
85var isShowTimeModal = false;
86var isShowDateModal = false;
87var allowOverLimit = false;
88var stepShowCalendar = 0;
89let isUseEventSetupTool = 0;
90
91let listPCUseDB = ["821271"];
92var siteId;
93
94var isAdding = false;
95var isChecking = false;
96var productIdPreOrder = '';
97var collect_datePreOrder = '';
98var collect_timePreOrder = '';
99var totalHoursPreOrder = 0;
100var orderUserStep = 0;
101var standalone = window.navigator.standalone,
102    userAgent = window.navigator.userAgent.toLowerCase(),
103    safari = /safari/.test(userAgent),
104    ios = /iphone|ipod|ipad/.test(userAgent);
105
106var allowChangeService = false;
107var outletIndexChosse = 0;
108var currentOutletIndex = 0;
109var iosHeight = 85;
110var isNeedReloadPage = false;
111
112var isPayLaterRequest = false;
113var previousPopup = '';
114var isAmendMore = false;
115//var topHeaderScroll = 0;
116var windowWidth = $(window).width();
117var validateTimeout = null;
118var buffetId = '';
119var isBuffet = false;
120var isBuffetDetail = false;
121var isGroupOrdering = false;
122var popupLoading;
123var scrollTopMyCart = 0;
124var collapsedInforMyCart = null;
125var gapTimeForMerchant = '';
126if (ios && !standalone && !safari && navigator.userAgent.match(/instagram/i)) {
127    //uiwebview
128    $("html").addClass("padding-top-50");
129}
130else {
131    $("html").removeClass("padding-top-50");
132}
133function reloadpage() {
134    location.reload();
135}
136//function autoResizeDiv() {
137//    $('#navbar-collapse-1 .dropdown .dropdown-menu').css('max-height', ($(window).height() - 100) + 'px');
138//    $('#getz-menu-mainsub-category ul.dropdown-menu-getz').css('max-height', ($(window).height() - 100) + 'px');
139//    var ismobile = false;
140//    try {
141//        var width = $(window).width();
142//        if (isMobile.any() && width < 992) {
143//            ismobile = true;
144//        }
145//        if ($('.floating-category .category-menu-mobile').length > 0 && $('.floating-category .category-menu-mobile').hasClass("position-fixed")) {
146//            $('.floating-category .category-menu-mobile').removeClass("position-fixed");
147//            $('.floating-category .category-menu-mobile').removeAttr("style");
148//            var heightFooter = 0;
149//            var positonFooter = $('#footer').position().top;
150//            if ($(window).scrollTop() + $(window).height() > positonFooter) {
151//                heightFooter = $(window).scrollTop() + $(window).height() - positonFooter;
152//            }
153//            let heightHeader = $("#header .inner").height() + 15;
154//            if (ismobile || $(window).width() < 992) {
155//                heightHeader = $("#header .header__navbar").height();
156//            }
157//            var navwidth = $('.floating-category .category-menu-mobile').width();
158
159//            let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
160//            if (windowHeight < 1) {
161//                windowHeight = $(window).height();
162//            }
163//            let maxHeightCategory = (windowHeight - heightHeader - heightFooter - Math.abs(window.innerHeight - document.documentElement.clientHeight) - $(".homepage-cart-button-display").innerHeight());
164
165//            $('.floating-category .category-menu-mobile').addClass("position-fixed");
166//            $('.floating-category .category-menu-mobile').attr("style", `top: ${heightHeader}px; width: ${navwidth}px; max-height: ${maxHeightCategory}px;`);
167//        }
168
169//        let leftDropdownMenu = 10;
170//        if ($("div[id^='dropdownMenu']").parent() && $("div[id^='dropdownMenu']").parent().position()) {
171//            leftDropdownMenu += $("div[id^='dropdownMenu']").parent().position().left;
172//        }
173
174//        $("div[id^='dropdownMenu'] #accordion").css({ left: -leftDropdownMenu + 'px', width: $(window).width() - 10 + 'px' });
175
176//        $("#getz-menu-mainsub-category .wrapper").css({ height: ($(window).height() - 100) + 'px' });
177
178//    } catch (e) {
179//        console.log(e);
180//    }
181
182//    try {
183//        if (ismobile) {
184//            var w = $('#promotion-detail-title').width() - 40;
185//            $('#d-promotion-detail-title').attr('style', 'max-width:' + w + 'px;');
186//            $('#h-promotion-detail-title').attr('style', 'max-width:' + w + 'px;');
187//        }
188//        else {
189//            $('#d-promotion-detail-title').removeAttr('style');
190//            $('#h-promotion-detail-title').removeAttr('style');
191//        }
192
193//    } catch (e) {
194//        console.log(e);
195//    }
196//}
197
198function showAnnouncementPopup() {
199    if (isMainPopUpAllowedShow == true && isMainPopUpShow && !isChopePopupShow) {
200        setTimeout(function () {
201            $('#announcementpopup').modal('show');
202        }, 300);
203    }
204}
205
206function showStickyAnnouncement() {
207    if (!isChopePopupShow) {
208        $('.tracker-header-announcement').show();
209    }
210};
211var myTimeout = null;
212$(function () {
213    //console.log('lazyLoadingImages', lazyLoadingImages);
214    if (lazyLoadingImages) {
215
216        echo.init({
217            offset: 1000,
218            throttle: 1,
219            unload: false,
220            callback: function (element, op) {
221                try {
222                    if (myTimeout) {
223                        clearTimeout(myTimeout);
224                    }
225                } catch (e) {
226                    console.log(e);
227                }
228                //console.log(element, 'has been', op + 'ed')
229
230                myTimeout = setTimeout(myGreeting, 1500);
231            }
232        });
233
234    }
235});
236function myGreeting() {
237    //console.log('call lazyResizeWidth');
238    myTimeout = null;
239
240    lazyResizeWidth();
241}
242function lazyResizeWidth() {
243    if ($('.row-item-product-floating').length !== 0) {
244        //console.log("fewffwe", $(".row-item-product-floating.loaded").length);
245        //$(".row-item-product-floating.loaded").each(function () {
246        //    var id = $(this).attr('id');
247        //    $("#" + id).removeClass('loaded');
248        //});
249        //if ($(window).width() != windowWidth) {
250        $(".row-item-product-floating").removeClass("loaded");
251        // Update the window width for next time
252        windowWidth = $(window).width();
253        // Otherwise do nothing
254        ResizeRecommendProductFloating();
255        // Do stuff here
256
257        //}
258    }
259}
260$(document).ready(function () {
261    isAdding = false;
262    //window.onresize = autoResizeDiv;
263    //autoResizeDiv();
264
265    //debugger;
266    var shopOnline = new ShopOnline(window, $);
267    //shopOnline.homeSlider();
268    shopOnline.menuSlider();
269    shopOnline.menuSelectSlider();
270    shopOnline.initRightBar();
271    shopOnline.setHeightRightBar();
272    //shopOnline.footerSlider();
273    //shopOnline.fullHeightItem();
274    var cartblockBaner = $('.cart-block li.active');
275    if (cartblockBaner !== null && cartblockBaner.find('a')[0]) {
276        var activeTabName = cartblockBaner.find('a')[0].hash;
277        $('#my-cart-dine-in-ordering').removeClass('invisible');
278        //$('#my-cart-dine-in-ordering p').remove();
279        document.getElementById("header").style = "min-height = 92px";
280        //document.getElementById("my-cart-count").style = "background-color: #fd576a;";
281        $('#header .navbar-header .cart').css('color', '#FFF');
282
283        if (activeTabName === '#tab_Dine_In') {
284            //if (stationName && stationName != '') {
285            //    $('#my-cart-dine-in-ordering').append('<p>' + languageLabel["O_DineinSelfOrderingTable"] + ': ' + stationName + '</p>');
286            //}
287            //else {
288            //    $('#my-cart-dine-in-ordering').append('<p>' + languageLabel["O_DineinSelfOrdering"] + '</p>');
289            //}
290        }
291        else if (activeTabName === '#tab_Pick_Up') {
292            //GETFIX-406  Change copytext for PlatformM
293            var textPickup = '<p>' + languageLabel["O_Pickup"] + '</p>';
294            if (siteID == "af0ec0ff-a539-49ac-bdc5-6557c128a489"
295                || siteID == "2391be96-d5f4-4edd-b5c8-9e9a8a822cd9"
296                || siteID == "d6f9829c-91c9-48bb-8ff7-caf41124be6d"
297                || siteID == "560bf8ac-1452-4f20-9dd4-9cec78b1536d"
298                || siteID == "5f32c4ea-9276-4280-9496-3ee0e940e1f5") {
299                textPickup = '<p>' + languageLabel["O_Takeout"] + '</p>';
300            }
301            //$('#my-cart-dine-in-ordering').append(textPickup);
302        }
303        else if (activeTabName === '#tab_Delivery') {
304            //$('#my-cart-dine-in-ordering').append('<p>' + languageLabel["O_Delivery"] + '</p>');
305        } else {
306            $('#my-cart-dine-in-ordering').addClass('invisible');
307            document.getElementById("header").style = "min-height = 56px";
308            //document.getElementById("my-cart-count").style = "background-color: #FFF;";
309            $('#header .navbar-header .cart').css('color', '#000');
310        }
311    }
312
313    if (typeof $.fn.dropdown === 'function') {
314        $('.dropdown-toggle').dropdown();
315    }
316
317    $("#dropdownMenu1")
318        .on("show.bs.dropdown", function (event) {
319            $("body").css("overflow", "hidden");
320        })
321        .on("hide.bs.dropdown", function (event) {
322            $("body").css("overflow", "");
323        });
324
325    $("#dropdownMenu2")
326        .on("show.bs.dropdown", function (event) {
327            $("body").css("overflow", "hidden");
328        })
329        .on("hide.bs.dropdown", function (event) {
330            $("body").css("overflow", "");
331        });
332
333    fixLogo($(".logo img"));
334
335    $('#q-search').mouseover(function () {
336        $(".q-menu-search").css("display", "block");
337    });
338    $('.q-menu-search').mouseleave(function () {
339        $(".q-menu-search").css("display", "none");
340    });
341    $('#q-menu').mouseleave(function () {
342        $(".q-menu-search").css("display", "none");
343    });
344    var ismobile = false;
345    var width = $(window).width();
346    if (isMobile.any() && width < 992) {
347        ismobile = true;
348    }
349
350    var currentUrl = window.location.href.toLowerCase();
351    if (currentUrl.indexOf('/checkout') > 0) {
352        $('.search-form').addClass("hidden");
353
354        //$('#my-cart-count').removeClass("visible-xs");
355        //$('#my-cart-count').removeClass("visible-sm");
356        //$('#my-cart-count').addClass("hidden");
357        $('#header').find('.mobile-menu').addClass("checkout-header");
358    }
359    else {
360        if (isBuffet && !isBuffetDetail) {
361
362        }
363        else {
364            $('.search-form').removeClass("hidden");
365        }
366        //$('#my-cart-count').removeClass("hidden");
367        //$('#my-cart-count').addClass("visible-xs");
368        //$('#my-cart-count').addClass("visible-sm");
369        $('#header').find('.mobile-menu').removeClass("checkout-header");
370    }
371
372    reloadSessionTimeout = setInterval(fnSessionTimeOut, 60 * 1000);
373
374    $('.custom-model').on('show.bs.modal', function () {
375        $(this).show();
376        setModalMaxHeight(this);
377    });
378
379    //showAnnouncementPopup();
380
381    $(window).scroll(function () {
382        if ($(this).scrollTop() >= 350) {
383
384            $('#scroll-top').removeClass("hidden");
385
386        } else {
387
388            $('#scroll-top').addClass("hidden");
389        }
390    });
391
392    loadImageOriginal(true);
393
394    btnUnavailable = languageLabel["O_SoldOut"];
395    if (!btnUnavailable) {
396        btnUnavailable = "Unavailable";
397    }
398    btnPreorder = languageLabel["O_Preorder"];
399    if (!btnPreorder) {
400        btnPreorder = "Pre-order";
401    }
402    btnCheckAvailability = languageLabel["O_CheckAvailability"];
403    if (!btnCheckAvailability) {
404        btnCheckAvailability = "Check Date";
405    }
406    timerCheckAvailability = setInterval(function () {
407        var btns = $('.unavailableflag');
408        var btnpreorders = $('.preorderflag');
409        currentUnavailableFlag = !currentUnavailableFlag;
410        var classOpening = 'span-showProductDetailId';
411        if (showProductDetailId != '') {
412            classOpening = 'span-' + showProductDetailId;
413        }
414        if (btns && btns.length > 0) {
415            if (currentUnavailableFlag) {
416                for (var i = 0; i < btns.length; i++) {
417                    if (showProductDetailId != '') {
418                        if (!btns[i].hasClass(classOpening)) {
419                            $(btns[i]).text(btnCheckAvailability);
420                        }
421                    }
422                    else {
423                        $(btns[i]).text(btnCheckAvailability);
424                    }
425                }
426            }
427            else {
428                for (var i = 0; i < btns.length; i++) {
429                    if (showProductDetailId != '') {
430                        if (!btns[i].hasClass(classOpening)) {
431                            $(btns[i]).text(btnUnavailable);
432                        }
433                    }
434                    else {
435                        $(btns[i]).text(btnUnavailable);
436                    }
437                }
438            }
439        }
440        //console.log(btnpreorders);
441        setTextForBtn(btns, currentUnavailableFlag, showProductDetailId, btnCheckAvailability, btnUnavailable, classOpening);
442        //setTextForBtn(btnpreorders, currentUnavailableFlag, showProductDetailId, btnCheckAvailability, btnPreorder, classOpening);
443
444    }, 2000);//1 second
445    ResizeCategory(false);
446    var currentUrl = window.location.href.toLowerCase();
447    //if (currentUrl.indexOf('/OrderHistory/'.toLowerCase()) > 0) { }
448    if (currentUrl.indexOf('/recommendations') > 0
449        || currentUrl.indexOf('/category/') > 0
450        || currentUrl.indexOf('/promotion') > 0
451        || currentUrl.indexOf('/hours') > 0
452        || currentUrl.indexOf('/about') > 0
453        || currentUrl.indexOf('/shippinginfo') > 0
454        || currentUrl.indexOf('/returnexchange') > 0
455        || currentUrl.indexOf('/contact') > 0
456        || currentUrl.indexOf('/privacypolicy') > 0
457        || currentUrl.indexOf('/termsconditions') > 0
458        || currentUrl.indexOf('/orderhistory') > 0
459        || currentUrl.indexOf('/ordertracker') > 0
460    ) { }
461    else {
462        if (typeof isMerchantOS === 'undefined') {
463            LoadBannerSlider(shopOnline);
464        }
465
466        var currentWidthSlider = window.innerWidth;
467        $(window).resize(function () {
468            if (typeof isMerchantOS === 'undefined') {
469                if ((window.innerWidth < 992 && currentWidthSlider >= 992)
470                    || (window.innerWidth >= 992 && currentWidthSlider < 992)) {
471
472                    currentWidthSlider = window.innerWidth;
473                    delayTimer(function () {
474                        LoadBannerSlider(shopOnline);
475                    }, 500);
476                }
477            }
478
479            if ($('.modal.popup-full-mobi.in').length > 0) {
480                let windowWidth = $(window).width();
481                let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0
481);
482                if (windowHeight < 1) {
483                    windowHeight = $(window).height();
484                }
485                //if (windowWidth < 768) {
486                if (true) {
487                    let heightInstagram = 0;
488
489                    if (ios && !standalone && !safari && navigator.userAgent.match(/instagram/i)) {
490                        //uiwebview
491                        $("html").addClass("padding-top-50");
492                        heightInstagram = 113;
493                        $('.modal.popup-full-mobi.in').find(".modal-header").css("padding-top", "50px");
494                    }
495                    else {
496                        $("html").removeClass("padding-top-50");
497                        heightInstagram = 0;
498                        $('.modal.popup-full-mobi.in').find(".modal-header").removeAttr("style");
499                    }
500
501                    let maxHeightDeliveryBody = (windowHeight - $('.modal.popup-full-mobi.in').find('.header-title').innerHeight() - heightInstagram);
502
503                    if (!$('.modal.popup-full-mobi.in').find('.fix-modal-footer').hasClass('hidden')) {
504                        maxHeightDeliveryBody -= $('.modal.popup-full-mobi.in').find('.fix-modal-footer').innerHeight();
505                    }
506
507                    if (typeof window.getPwaBottomNavOffset === 'function') {
508                        maxHeightDeliveryBody -= window.getPwaBottomNavOffset();
509                    }
510
511                    if (windowWidth > 767) {
512                        maxHeightDeliveryBody -= 100;
513                    }
514
515                    if (isFacebookApp() === true && !ios) {
516                        maxHeightDeliveryBody -= 50;
517                    }
518                    $('.modal.popup-full-mobi.in').css('overflow-y', 'hidden').find(".modal-body").css('overflow-y', 'hidden');
519                    $('.modal.popup-full-mobi.in').find('.bodyservice').css({
520                        'overflow-y': 'auto',
521                        'overflow-x': 'hidden',
522                        'max-height': maxHeightDeliveryBody,
523                        'min-height': '250px',
524                    });
525                }
526            }
527        });
528    }
529});
530function setTextForBtn(btns, currentUnavailableFlag, showProductDetailId, btnCheckAvailability, btnUnavailable, classOpening) {
531    if (btns && btns.length > 0) {
532        if (currentUnavailableFlag) {
533            for (var i = 0; i < btns.length; i++) {
534                if (showProductDetailId != '') {
535                    if (!btns[i].hasClass(classOpening)) {
536                        $(btns[i]).text(btnCheckAvailability);
537                    }
538                }
539                else {
540                    $(btns[i]).text(btnCheckAvailability);
541                }
542            }
543        }
544        else {
545            for (var i = 0; i < btns.length; i++) {
546                if (showProductDetailId != '') {
547                    if (!btns[i].hasClass(classOpening)) {
548                        $(btns[i]).text(btnUnavailable);
549                    }
550                }
551                else {
552                    $(btns[i]).text(btnUnavailable);
553                }
554            }
555        }
556    }
557}
558$(document).ajaxStart(function () {
559    currentSessionTimeout = maximumSessionTimeout;
560});
561function scrollToTop() {
562    $('html, body').animate({ scrollTop: 0 }, 'slow');
563}
564
565$(document).on("click", "#scroll-top", function () {
566    $('html, body').animate({ scrollTop: 0 }, 'slow');
567});
568
569function LoadBannerSlider(shopOnline) {
570    try {
571        var displayDevice = displayTheDesktop;
572        if (window.innerWidth < 768) {
573            displayDevice = displayTheMobile;
574        }
575
576        $.ajax({
577            type: "GET",
578            url: urlLoadBannerSlider,
579            data: {
580                displayDevice: displayDevice,
581                authorization: siteId
582            },
583            success: function (result) {
584                if (result) {
585                    let hSlider = $('[data-slider="home-slider"]');
586                    hSlider.removeClass("slick-initialized slick-slider").html('');
587
588                    if (result.slideHeader && result.slideHeader.length > 0) {
589                        hSlider.html(result.slideHeader);
590                        if (hSlider.length > 0) {
591                            shopOnline.homeSlider();
592                        }
593                    }
594
595                    let fSlider = $('[data-slider="footer-slider"]');
596                    fSlider.removeClass("slick-initialized slick-slider").html('');
597
598                    if (result.slideFooter && result.slideFooter.length > 0) {
599                        fSlider.html(result.slideFooter);
600                        if (fSlider.length > 0) {
601                            shopOnline.footerSlider();
602                        }
603                    }
604                }
605            }
606        });
607    } catch (e) {
608        console.log(e);
609    }
610}
611
612function loadImageOriginal(isFirst) {
613    if (!lazyLoadingImages) {
614        var width = $(window).width();
615        var ismobile = false;
616        if (isMobile.any() && width < 1024) {
617            ismobile = true;
618        }
619        if (!ismobile) {
620            const objectWaits = document.getElementsByClassName('asyncImageWait');
621            Array.from(objectWaits).map((item) => {
622                item.classList.remove('asyncImageWait');
623                item.classList.add('asyncImage');
624            });
625        }
626
627        const objects = document.getElementsByClassName('asyncImage');
628        Array.from(objects).map((item) => {
629            if (item.src.indexOf('Default_Image/imageDefault.png') > 0 || item.src.indexOf('Default_Image/imageDefault_Small.png') > 0) {
630                //no need load
631                const img = new Image();
632                if (item.dataset.src) {
633                    item.dataset.src = "https://getz-prod.s3.ap-southeast-1.amazonaws.com/Getz/imageDefault.png";
634                    img.src = item.dataset.src;
635                    // Once image is loaded replace the src of the HTML element
636                    img.onload = () => {
637                        item.classList.remove('asyncImage');
638                        return item.nodeName === 'IMG' ?
639                            item.src = item.dataset.src :
640                            item.style.backgroundImage = `url(${item.dataset.src})`;
641                    };
642                }
643            }
644            else {
645                // Start loading image
646                const img = new Image();
647                if (item.dataset.src) {
648                    item.dataset.src = item.dataset.src.replace("Getz-live", "getz-prod");
649                }
650                img.src = item.dataset.src;
651                // Once image is loaded replace the src of the HTML element
652                img.onload = () => {
653                    item.classList.remove('asyncImage');
654
655                    return item.nodeName === 'IMG' ?
656                        item.src = item.dataset.src :
657                        item.style.backgroundImage = `url(${item.dataset.src})`;
658                };
659            }
660        });
661    }
662}
663function fnSessionTimeOut() {
664    if (currentSessionTimeout < 1) {
665        fnCancel();
666        //currentSessionTimeout = maximumSessionTimeout;
667    }
668    else {
669        currentSessionTimeout--;
670    }
671}
672
673function fnCancel() {
674    var currentUrl = window.location.href.toLowerCase();
675    if (currentUrl.indexOf('/OrderHistory/OrderStatusTracking'.toLowerCase()) > 0
676        || currentUrl.indexOf('/OrderHistory/Tracker'.toLowerCase()) > 0
677        || currentUrl.indexOf('/OrderHistory/MemberRegistration'.toLowerCase()) > 0
678        || currentUrl.indexOf('/OrderHistory/MembershipRewards'.toLowerCase()) > 0
679        || currentUrl.indexOf('/OrderHistory/PaymentReceipt'.toLowerCase()) > 0
680        || currentUrl.indexOf('/OrderHistory/Member'.toLowerCase()) > 0
681        || currentUrl.indexOf('/OrderHistory/Index'.toLowerCase()) > 0) {
682    }
683    else {
684        var url = urlIndexHome; // + 'Home/Index';
685        window.location.href = url;
686    }
687}
688
689function choosePickUp() {
690    is_switching_tab = true;
691    reset_countdown_timer_running_SessionTimeOut();
692    showSelectBranchModal(false);
693}
694function chooseDelivery() {
695    is_switching_tab = true;
696    reset_countdown_timer_running_SessionTimeOut();
697    showInputPostalCodeModal();
698}
699function reset_countdown_timer_running_SessionTimeOut() {
700    //Timer is stopped -> Start Timer
701    if (is_countdown_timer_running_SessionTimeOut == true) {
702        clearInterval(timerCountdown);
703        is_countdown_timer_running_SessionTimeOut = false;
704    }
705}
706function showSelectBranchModal(isBranch) {
707    isBranchModal = isBranch;
708    let windowWidth = $(window).width();
709    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0
709);
710    if (windowHeight < 1) {
711        windowHeight = $(window).height();
712    }
713    //if (windowWidth < 768) {
714    if (true) {
715        selectService(true);
716    }
717    else {
718        $("#brachIndexModal").modal('show');
719        $("#brachIndexModal .bodycontainer .getz-table-load-more tr").css('display', 'none');
720        $("#brachIndexModal .bodycontainer .getz-table-load-more tr").slice(0, 3).show();
721        $("#brachIndexModal #loadMore").show();
722    }
723}
724
725function showInputPostalCodeModal(isLeave) {
726    if ((!isLeave && deliveryMethodSession != "Pickup" && deliveryMethodSession != "Delivery") || !deliveryMethodSession) {
727        return $('#confirmLeaveDineIn').show();
728    }
729    if (isProcessingTab == true) {
730        return;
731    }
732    isProcessingTab = true;
733    $("#postalCodeModal").modal('show');
734}
735
736function redeemRewardByService(service) {
737    if (service == "Pickup") {
738        showSelectBranchModal(true);
739    } else if (service == "Delivery") {
740        $("#postalCodeModal").modal('show');
741    }
742}
743
744optionDayOfWeek = {
745    OPEN: 0,
746    SPLIT: 1,
747    CLOSED: 2
748}
749
750function fixLogo(logo) {
751    if (logo.width > logo.height) {
752        logo.addClass("logo-landscape");
753    }
754    else {
755        logo.addClass("logo-portrait");
756    }
757}
758
759function validateEmail(email) {
760    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
761    return re.test(email);
762}
763
764function CalculateDimensions(sourceWidth, sourceHeight, maxWidth, maxHeight) {
765    var widthPercent = maxWidth / sourceWidth;
766    var heightPercent = maxHeight / sourceHeight;
767
768    var percent = widthPercent;
769    if (heightPercent < widthPercent && heightPercent != 0) {
770        percent = heightPercent;
771    }
772
773    var destWidth = (sourceWidth * percent);
774    var destHeight = (sourceHeight * percent);
775
776    var size = new Array(2);
777    size[0] = destWidth;
778    size[1] = destHeight;
779
780    return size;
781}
782
783function AutoResizeWidthHeightImage(imageItem, elementResizeId, maxWidth, maxHeight) {
784    var sourceWidth = imageItem.width();
785    var sourceHeight = imageItem.height();
786
787    var size = CalculateDimensions(sourceWidth, sourceHeight, maxWidth, maxHeight);
788    var destWidth = size[0];
789    var destHeight = size[1];
790
791    var elementResize = $('#' + elementResizeId);
792    elementResize.removeAttr('width');
793    elementResize.removeAttr('height');
794    elementResize.attr('width', destWidth);
795    elementResize.attr('height', destHeight);
796    elementResize.css('Width', destWidth.toFixed(0).toString() + 'px');
797    elementResize.css('Height', destHeight.toFixed(0).toString() + 'px');
798}
799
800//Resize image whem page load -- BY NHAT PHAM
801function setImageSize(elementId) {
802    var deviceWidth = $(document).width();
803    var gridWidth = $('.gridItem').width() + 30;//Compensate the padding-left(15px) and padding-right(15px)
804    var width;
805    var height;
806
807    if (gridWidth < 380) {
808        width = 290;
809        height = 290 * 2 / 3;
810    } else {
811        if (deviceWidth === gridWidth) {
812            width = 290;
813            height = 290 * 2 / 3;
814        } else {
815            width = 360;
816            height = 360 * 2 / 3;
817        }
818    }
819
820    //Clear old image's size
821    var element = $(elementId);
822    element.removeAttr('width');
823    element.removeAttr('height');
824
825    //Set size for new image
826    SetAutoResizeWidthHeightImage(elementId, width, height);
827}
828
829function SetAutoResizeWidthHeightImage(elementResizeId, maxWidth, maxHeight) {
830    var imageItem = $('#' + elementResizeId);
831    var sourceWidth = imageItem.width();
832    var sourceHeight = imageItem.height();
833
834    if (sourceWidth > 0 && sourceHeight > 0) {
835        AutoResizeWidthHeightImage(imageItem, elementResizeId, maxWidth, maxHeight);
836    }
837}
838
839//Get the default allow-collecting time of branch depending on it's option (e.g. OPEN or SPLIT)
840//Just create content from datatable PickUpSetting, don't filter with other conditions (e.g. "order's prepare time" or "order's limit count in hour")
841function GetStandardAllowTimesDelivery(item, deliveryTime, prepareTime, underPrepDate, itemAvailableTime) {
842    //console.log('item', item, 'deliveryTime', deliveryTime, 'prepareTime', prepareTime);
843    //console.log('itemAvailableTime', itemAvailableTime);
844    if (parseInt(prepareTime.split(':')[0]) >= 1) prepareTime = "1:0";
845    var arrayTime = [];
846    var arrayTimeFrom = [];
847    var arrayTimeTo = [];
848
849    var arrayTimeOpeningFrom = [];
850    var arrayTimeOpeningTo = [];
851    var arrayTimeClosingFrom = [];
852    var arrayTimeClosingTo = [];
853
854    var prepareHour = 0;
855    var prepareMin = 0;
856    if (prepareTime != null && prepareTime !== "" && prepareTime.indexOf(":") > -1) {
857        prepareHour = parseInt(prepareTime.split(':')[0]);
858        prepareMin = parseInt(prepareTime.split(':')[1]);
859    }
860    if (itemAvailableTime && itemAvailableTime.itemAvailableTimes && itemAvailableTime.itemAvailableTimes.length > 0) {
861        for (var i = 0; i < itemAvailableTime.itemAvailableTimes.length; i++) {
862            var open_Closing = itemAvailableTime.itemAvailableTimes[i].open_Closing;
863
864            if (i == (itemAvailableTime.itemAvailableTimes.length - 1)) {
865                var item = itemAvailableTime.itemAvailableTimes[i];
866                var timeCloseHour = parseInt(item.open_Closing.split(':')[0]);
867                var timeCloseMin = parseInt(item.open_Closing.split(':')[1]);
868                if (timeCloseMin >= 60) {
869                    timeCloseHour++;;
870                    timeCloseMin -= 60;
871                }
872                if (timeCloseMin >= 60) {
873                    timeCloseHour++;;
874                    timeCloseMin -= 60;
875                }
876                //Round up the current time's minute
877                if (timeCloseMin > 45) {
878                    timeCloseMin = 0;
879                    timeCloseHour++;
880                } else if (timeCloseMin > 30) {
881                    timeCloseMin = 45;
882                } else if (timeCloseMin > 15) {
883                    timeCloseMin = 30;
884                } else if (timeCloseMin > 0) {
885                    timeCloseMin = 15;
886                }
887
888                open_Closing = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
889            }
890
891            arrayTimeClosingFrom = GetArrayAllowTimeDelivery(itemAvailableTime.itemAvailableTimes[i].open_Opening, open_Closing, 15, underPrepDate);
892            arrayTimeClosingTo = GetArrayAllowTimeDelivery(itemAvailableTime.itemAvailableTimes[i].open_Opening, open_Closing, 15, underPrepDate);
893
894            arrayTimeOpeningFrom = arrayTimeOpeningFrom.concat(arrayTimeClosingFrom);
895            arrayTimeOpeningTo = arrayTimeOpeningTo.concat(arrayTimeClosingTo);
896        }
897
898        //console.log(arrayTimeOpeningFrom, arrayTimeOpeningTo);
899
900        arrayTime.push(arrayTimeOpeningFrom);
901        arrayTime.push(arrayTimeOpeningTo);
902    }
903    else if (item.option === optionDayOfWeek.OPEN) {
904        var timeCloseHour = parseInt(item.open_Closing.split(':')[0]) + prepareHour;
905        var timeCloseMin = parseInt(item.open_Closing.split(':')[1]) + prepareMin;
906        if (timeCloseMin >= 60) {
907            timeCloseHour++;;
908            timeCloseMin -= 60;
909        }
910        //Round up the current time's minute
911        if (timeCloseMin > 45) {
912            timeCloseMin = 0;
913            timeCloseHour++;
914        } else if (timeCloseMin > 30) {
915            timeCloseMin = 45;
916        } else if (timeCloseMin > 15) {
917            timeCloseMin = 30;
918        } else if (timeCloseMin > 0) {
919            timeCloseMin = 15;
920        }
921
922        var open_Closing = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
923
924        arrayTimeFrom = GetArrayAllowTimeDelivery(item.open_Opening, open_Closing, 15, underPrepDate);
925        arrayTimeTo = GetArrayAllowTimeDelivery(item.open_Opening, open_Closing, 15, underPrepDate);
926
927        //console.log(arrayTimeFrom, arrayTimeTo);
928
929        arrayTimeTo.shift();
930
931        arrayTime.push(arrayTimeFrom);
932        arrayTime.push(arrayTimeTo);
933    } else if (item.option === optionDayOfWeek.SPLIT) {
934        var timeCloseHour = parseInt(item.split_ClosingEnd.split(':')[0]) + prepareHour;
935        var timeCloseMin = parseInt(item.split_ClosingEnd.split(':')[1]) + prepareMin;
936        if (timeCloseMin >= 60) {
937            timeCloseHour++;;
938            timeCloseMin -= 60;
939        }
940
941        var split_ClosingEnd = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
942
943        arrayTimeOpeningFrom = GetArrayAllowTimeDelivery(item.split_OpeningStart, item.split_OpeningEnd, 15, underPrepDate); //arrayTimeOpeningFrom.pop();
944        arrayTimeOpeningTo = GetArrayAllowTimeDelivery(item.split_OpeningStart, item.split_OpeningEnd, 15, underPrepDate);
945        arrayTimeClosingFrom = GetArrayAllowTimeDelivery(item.split_ClosingStart, split_ClosingEnd, 15, underPrepDate);
946        arrayTimeClosingTo = GetArrayAllowTimeDelivery(item.split_ClosingStart, split_ClosingEnd, 15, underPrepDate);
947
948        //console.log(arrayTimeOpeningFrom, arrayTimeOpeningFrom);
949        //console.log(arrayTimeClosingFrom, arrayTimeClosingTo);
950        arrayTime.push(arrayTimeOpeningFrom.concat(arrayTimeClosingFrom));
951        arrayTime.push(arrayTimeOpeningTo.concat(arrayTimeClosingTo));
952    } else {
953        return null;
954    }
955
956    //console.log(arrayTime);
957    return arrayTime;
958}
959
960//Get the default allow-collecting time from "timeFrom" to "timeEnd" in defined format "FromTime - ToTime"
961//Just create content from input parameters, don't filter with other conditions (e.g. "order's prepare time" or "order's limit count in hour")
962function GetArrayAllowTimeDelivery(timeFrom, timeEnd, deliveryTime, underPrepDate) {
963    if (gapTimeForMerchant && gapTimeForMerchant === siteID && currentService === 0) {
964        deliveryTime = 30;
965    }
966    var arrayAllowTime = [];
967
968    var timeOpenHour = parseInt(timeFrom.split(':')[0]);
969    var timeOpenMin = parseInt(timeFrom.split(':')[1]);
970    var timeCloseHour = parseInt(timeEnd.split(':')[0]);
971    var timeCloseMin = parseInt(timeEnd.split(':')[1]);
972
973    timeFrom = (timeOpenHour < 10 ? "0" + timeOpenHour : timeOpenHour) + ":" + (timeOpenMin < 10 ? "0" + timeOpenMin : timeOpenMin);
974
975    timeEnd = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
976
977    var timeOpen = timeOpenMin + (timeOpenHour * 60);
978    var timeClose = timeCloseMin + (timeCloseHour * 60);
979
980    var i = timeOpen;
981    while (i <= timeClose) {
982        var tempHourV = parseInt(i / 60);
983        var tempMinV = i - (tempHourV * 60);
984
985        var tempHour = tempHourV < 10 ? "0" + tempHourV.toString() : tempHourV.toString();
986        var tempMin = tempMinV < 10 ? "0" + tempMinV.toString() : tempMinV.toString();
987        var strTempTime = tempHour + ":" + tempMin;
988        if (timeFrom <= strTempTime && strTempTime <= timeEnd) {
989            arrayAllowTime.push(strTempTime);
990        }
991
992        i = i + deliveryTime;
993    }
994
995    return arrayAllowTime;
996}
997
998//Get the default allow-collecting time of branch depending on it's option (e.g. OPEN or SPLIT)
999//Just create content from datatable PickUpSetting, don't filter with other conditions (e.g. "order's prepare time" or "order's limit count in hour")
1000function GetStandardAllowTimes(item, prepareTime) {
1001    //console.log(item);
1002    //console.log(prepareTime);
1003    var arrayTime = [];
1004    var arrayTimeFrom = [];
1005    var arrayTimeTo = [];
1006
1007    var arrayTimeOpeningFrom = [];
1008    var arrayTimeOpeningTo = [];
1009    var arrayTimeClosingFrom = [];
1010    var arrayTimeClosingTo = [];
1011
1012    var prepareHour = 0;
1013    var prepareMin = 0;
1014    if (prepareTime != null && prepareTime !== "" && prepareTime.indexOf(":") > -1) {
1015        prepareHour = parseInt(prepareTime.split(':')[0]);
1016        prepareMin = parseInt(prepareTime.split(':')[1]);
1017    }
1018
1019    if (item.option === optionDayOfWeek.OPEN) {
1020        var timeCloseHour = parseInt(item.open_Closing.split(':')[0]) + prepareHour;
1021        var timeCloseMin = parseInt(item.open_Closing.split(':')[1]) + prepareMin;
1022        if (timeCloseMin >= 60) {
1023            timeCloseHour++;;
1024            timeCloseMin -= 60;
1025        }
1026
1027        var open_Closing = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
1028
1029        arrayTimeFrom = GetArrayAllowTime(item.open_Opening, open_Closing);
1030
1031        arrayTimeTo = GetArrayAllowTime(item.open_Opening, open_Closing);
1032        arrayTimeTo.shift();
1033
1034        arrayTime.push(arrayTimeFrom);
1035        arrayTime.push(arrayTimeTo);
1036    } else if (item.option === optionDayOfWeek.SPLIT) {
1037        var timeCloseHour = parseInt(item.split_ClosingEnd.split(':')[0]) + prepareHour;
1038        var timeCloseMin = parseInt(item.split_ClosingEnd.split(':')[1]) + prepareMin;
1039        if (timeCloseMin >= 60) {
1040            timeCloseHour++;;
1041            timeCloseMin -= 60;
1042        }
1043
1044        var split_ClosingEnd = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
1045
1046        arrayTimeOpeningFrom = GetArrayAllowTime(item.split_OpeningStart, item.split_OpeningEnd); //arrayTimeOpeningFrom.pop();
1047        arrayTimeOpeningTo = GetArrayAllowTime(item.split_OpeningStart, item.split_OpeningEnd);
1048        arrayTimeClosingFrom = GetArrayAllowTime(item.split_ClosingStart, split_ClosingEnd);
1049        arrayTimeClosingTo = GetArrayAllowTime(item.split_ClosingStart, split_ClosingEnd);
1050
1051        arrayTime.push(arrayTimeOpeningFrom.concat(arrayTimeClosingFrom));
1052        arrayTime.push(arrayTimeOpeningTo.concat(arrayTimeClosingTo));
1053    } else {
1054        return null;
1055    }
1056
1057    return arrayTime;
1058}
1059
1060//Get the default allow-collecting time from "timeFrom" to "timeEnd" in defined format "FromTime - ToTime"
1061//Just create content from input parameters, don't filter with other conditions (e.g. "order's prepare time" or "order's limit count in hour")
1062function GetArrayAllowTime(timeFrom, timeEnd, isOver) {
1063    var arrayAllowTime = [];
1064
1065    var timeOpenHour = parseInt(timeFrom.split(':')[0]);
1066    var timeOpenMin = parseInt(timeFrom.split(':')[1]);
1067    var timeCloseHour = parseInt(timeEnd.split(':')[0]);
1068    var timeCloseMin = parseInt(timeEnd.split(':')[1]);
1069
1070    //Round up the timeOpenMin
1071    if (timeOpenMin === 0) {
1072        timeOpenMin = 0;
1073    } else if (timeOpenMin <= 15) {
1074        timeOpenMin = 15;
1075    } else if (timeOpenMin <= 30) {
1076        timeOpenMin = 30;
1077    } else if (timeOpenMin <= 45) {
1078        timeOpenMin = 45;
1079    } else if (timeOpenMin > 45) {
1080        timeOpenMin = 0;
1081        timeOpenHour++;
1082    }
1083
1084    timeFrom = (timeOpenHour < 10 ? "0" + timeOpenHour : timeOpenHour) + ":" + (timeOpenMin < 10 ? "0" + timeOpenMin : timeOpenMin);
1085
1086    if (isOver) {
1087        if (timeCloseMin === 0) {
1088            timeCloseMin = 0;
1089        } else if (timeCloseMin <= 15) {
1090            timeCloseMin = 15;
1091        } else if (timeCloseMin <= 30) {
1092            timeCloseMin = 30;
1093        } else if (timeCloseMin <= 45) {
1094            timeCloseMin = 45;
1095        } else if (timeCloseMin > 45) {
1096            timeCloseMin = 0;
1097            timeCloseHour++;
1098        }
1099    }
1100    else {
1101        //Round down the timeCloseMin
1102        if (timeCloseMin < 15) {
1103            timeCloseMin = 0;
1104        } else if (timeCloseMin < 30) {
1105            timeCloseMin = 15;
1106        } else if (timeCloseMin < 45) {
1107            timeCloseMin = 30;
1108        } else if (timeCloseMin > 45) {
1109            timeCloseMin = 45;
1110        }
1111    }
1112
1113    timeEnd = (timeCloseHour < 10 ? "0" + timeCloseHour : timeCloseHour) + ":" + (timeCloseMin < 10 ? "0" + timeCloseMin : timeCloseMin);
1114    for (var i = timeOpenHour; i <= timeCloseHour; i++) {
1115        var tempHour = i;
1116        tempHour = tempHour < 10 ? "0" + tempHour : tempHour;
1117        for (var j = 0; j < 4; j++) {
1118            var tempMin = j * 15;
1119            tempMin = tempMin < 10 ? "0" + tempMin : tempMin;
1120
1121            var strTempTime = tempHour + ":" + tempMin;
1122            if (timeFrom <= strTempTime && strTempTime <= timeEnd) {
1123                arrayAllowTime.push(strTempTime);
1124            }
1125        }
1126    }
1127
1128    return arrayAllowTime;
1129}
1130
1131//Get the allow-collecting time that is filtered by "order's prepare time"
1132function GetCollectAllowTimes(arrayStandardAllowTime, selectingDate, prepareTime, gapTime, isOver, underPrepDate) {
1133    var arrayCollectTime = [];
1134    if (!arrayStandardAllowTime || arrayStandardAllowTime.length <= 0) {
1135        return arrayCollectTime;
1136    }
1137    var arrayTime = arrayStandardAllowTime;
1138    //Calc prepare time
1139    var prepareHour = 0;
1140    var prepareMin = 0;
1141    if (prepareTime != null && prepareTime !== "" && prepareTime.indexOf(".") > -1) {
1142        prepareHour = prepareTime.indexOf(".") > -1 ? parseInt(prepareTime.split('.')[0]) : parseInt(prepareTime);
1143        prepareMin = prepareTime.indexOf(".") > -1 ? (prepareTime.split('.')[1] * 6 < 60 ? prepareTime.split('.')[1] * 6 : prepareTime.split('.')[1] * 0.6) : 0;
1144    }
1145    if (prepareTime != null && prepareTime !== "" && prepareTime.indexOf(":") > -1) {
1146        prepareHour = parseInt(prepareTime.split(':')[0]);
1147        prepareMin = parseInt(prepareTime.split(':')[1]);
1148    }
1149
1150    //Calc current time
1151    var currentTime = new Date();
1152    var currentHour = new Date();
1153    var currentMin = new Date();
1154    if (underPrepDate) {
1155        currentTime = underPrepDate;
1156        currentHour = currentTime.getHours() - prepareHour;
1157        currentMin = currentTime.getMinutes() - prepareMin;
1158        if (deliveryMethodSession === 'PickUp') {
1159            currentMin = currentTime.getMinutes() - 15;
1160        }
1161    }
1162    else {
1163        currentHour = currentTime.getHours();
1164        currentMin = currentTime.getMinutes();
1165    }
1166
1167    var estimatedTime = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate(), currentHour + prepareHour, currentMin + prepareMin);
1168    var selectingTime = new Date(selectingDate.getFullYear(), selectingDate.getMonth(), selectingDate.getDate(),
1169        arrayTime[arrayTime.length - 1].split(":")[0], arrayTime[arrayTime.length - 1].split(":")[1]);
1170    currentHour = estimatedTime.getHours();
1171    currentMin = estimatedTime.getMinutes();
1172    //Round up the current time's minute
1173    if (currentMin > 45) {
1174        currentMin = 0;
1175        currentHour++;
1176    } else if (currentMin > 30) {
1177        currentMin = 45;
1178    } else if (currentMin > 15) {
1179        currentMin = 30;
1180    } else if (currentMin > 0) {
1181        currentMin = 15;
1182    }
1183    estimatedTime = new Date(estimatedTime.getFullYear(), estimatedTime.getMonth(), estimatedTime.getDate(), currentHour, currentMin);
1184
1185    if (selectingTime < estimatedTime) {
1186        //CASE: the selecting time is lesser than current time + prepare time -> return array Collect-AllowTimes with null value
1187        return null;
1188    } else {
1189        //CASE: the selecting time is greater than or equal to current time + prepare time -> return array Collect-AllowTimes with valid values
1190        var estimatedDate = new Date(estimatedTime.getFullYear(), estimatedTime.getMonth(), estimatedTime.getDate());
1191        var strFromTime = arrayTime[0];
1192
1193        if (selectingDate.getTime() === estimatedDate.getTime()) {
1194            //CASE: the selecting time is equal to current time + prepare time -> compare selecting hour+min and return array Collect-AllowTimes with valid values
1195
1196            //Reset strFromTime
1197            var fromHour = estimatedTime.getHours() < 10 ? "0" + estimatedTime.getHours() : estimatedTime.getHours();
1198            var fromMin = estimatedTime.getMinutes() < 10 ? "0" + estimatedTime.getMinutes() : estimatedTime.getMinutes();
1199            strFromTime = fromHour + ":" + fromMin;
1200            if (strFromTime >= arrayTime[arrayTime.length - 1]) {
1201                //CASE: the selecting date is equal to (current time + prepare time).getDate but the selecting hour+min is greater than the last value of array Collect-AllowTimes
1202                //-> return array Collect-AllowTimes with null value
1203                return null;
1204            } else {
1205                //CASE: the selecting date is equal to (current time + prepare time).getDate and the selecting hour+min is lesser than the last value of array Collect-AllowTimes
1206                //-> compare selecting hour+min and remove the invalid values of array Collect-AllowTimes
1207
1208                var indexFrom = arrayTime.indexOf(strFromTime);
1209
1210                //Remove the invalid values of array Collect-AllowTimes
1211                if (indexFrom > -1) {
1212                    arrayTime = arrayTime.splice(parseInt(indexFrom), arrayTime.length);
1213                }
1214            }
1215        }
1216
1217        //Calculate the To time -> if To time <= End time, add this From time and To time to return array
1218        var isEnd = false;
1219
1220        for (var i = 0; i < arrayTime.length; i++) {
1221            if (strFromTime <= arrayTime[i] && !isEnd) {
1222                //Calculate ToHour and ToMin
1223                var toHour = gapTime === 15 ? parseInt(arrayTime[i].split(':')[0]) : parseInt(arrayTime[i].split(':')[0]) + 1;
1224                var toMin = gapTime === 15 ? parseInt(arrayTime[i].split(':')[1]) + 15 : parseInt(arrayTime[i].split(':')[1]);
1225                if (gapTime != 15) {
1226                    toHour = parseInt(arrayTime[i].split(':')[0]);
1227                    toMin = parseInt(arrayTime[i].split(':')[1]) + gapTime;
1228                    if (toMin >= 60) {
1229                        var hour = parseInt(toMin / 60);
1230                        toHour = toHour + hour;
1231                        toMin = toMin - (hour * 60);
1232                    }
1233                }
1234                else {
1235                    //Round up the To time's minute
1236                    if (toMin > 45) {
1237                        toMin = 0;
1238                        toHour++;
1239                    } else if (toMin > 30) {
1240                        toMin = 45;
1241                    } else if (toMin > 15) {
1242                        toMin = 30;
1243                    } else if (toMin > 0) {
1244                        toMin = 15;
1245                    }
1246                }
1247                //Set the format of toTime
1248                toHour = toHour < 10 ? "0" + toHour : toHour;
1249                toMin = toMin < 10 ? "0" + toMin : toMin;
1250                //Compare ToTime with EndTime and execute 
1251                var strToTime = toHour + ":" + toMin;
1252                if (isOver) {
1253                    var text = arrayTime[i] + " - " + strToTime;
1254                    arrayCollectTime.push(text);
1255                }
1256                else {
1257                    if (strToTime <= arrayTime[arrayTime.length - 1]) {
1258                        var text = arrayTime[i] + " - " + strToTime;
1259                        arrayCollectTime.push(text);
1260                    } else {
1261                        isEnd = true;
1262                    }
1263                }
1264            }
1265        }
1266
1267        return arrayCollectTime;
1268    }
1269}
1270
1271//Nhat.Pham - TKPOS-3233: Apply limit number of order available in a period for pick up order
1272//Get the allow-collecting time when there is unlimit of "order's limit count in hour"
1273function ReloadListCollectTime(arrayTime, elementId, availableId) {
1274    var arrayAllowTime = [];
1275    var strSelectTime = "-- Select Time --";
1276
1277    //Set array collect time
1278    var collectTimeSelector = $('#' + elementId);
1279    if (arrayTime != undefined && arrayTime != null && arrayTime.length > 0) {
1280        arrayAllowTime.push(strSelectTime);
1281
1282        for (var i = 0; i < arrayTime.length; i++) {
1283            arrayAllowTime.push(arrayTime[i]);
1284        }
1285
1286        collectTimeSelector.removeAttr('disabled');
1287
1288        document.getElementById(elementId).options.length = 0;//Remove all old options of the selector to avoid redundant
1289
1290        $.each(arrayAllowTime, function (sender, text) {
1291            var option = new Option(text);
1292            collectTimeSelector.append($(option));
1293        });
1294    } else {
1295        collectTimeSelector.attr('disabled', 'disabled');
1296        collectTimeSelector.val("");
1297
1298        var availableTimeText = languageMessage["O_ThereIsCurrentlyNoValidCollectTimeInThisDay"];
1299        $("#" + availableId).html(availableTimeText);
1300    }
1301}
1302
1303function CheckAddProductToCart(id, productId, quantity, price, promotionId, step, index) {
1304    if (checkNotExistsSession()) {
1305        return false;
1306    }
1307    if (orderUserStep == 1) {
1308        selectService(false);
1309        return;
1310    }
1311    var listLimitedItemPromoAdded = [];
1312    arrayPromotionCart.forEach(function (promotion) {
1313        if (promotion.arrayProduct) {
1314            promotion.arrayProduct.forEach(function (product) {
1315                listLimitedItemPromoAdded.push(product.productID)
1316            });
1317        }
1318    });
1319
1320    if (!isChecking && !isAdding) {
1321        //urlCheckAddToCartByProductId
1322        if (listLimitedItemPromo.indexOf(productId) > -1 && listLimitedItemPromoAdded.indexOf(productId) > -1) {
1323            return;
1324        }
1325
1326        $('#confirm-id').val('');
1327        $('#confirm-productId').val('');
1328        $('#confirm-quantity').val('');
1329        $('#confirm-price').val('');
1330        $('#confirm-step').val('');
1331        $('#confirm-promotionid').val('');
1332        $('#confirm-promotionsindex').val('');
1333        isChecking = true;
1334        $.ajax({
1335            type: "POST",
1336            url: urlCheckAddToCartByProductId,
1337            //contentType: 'application/json; charset=UTF-8',
1338            data: { "id": id, "productId": productId, "qty": quantity, "price": price, "promotionId": promotionId, 'index': index, "step": step, "authorization": siteId },
1339            success: function (result) {
1340                if (result.index) {
1341                    index = result.index;
1342                }
1343                if (result.success == false && result.message) {
1344                    $('#titleconfirmNextStep').text(result.message);
1345
1346                    if (result.status == 0) {
1347                        $("#btnNextStep").html('Proceed');
1348
1349                        $('#confirm-type').val('0');
1350
1351                        $('#confirm-id').val(id);
1352                        $('#confirm-productId').val(productId);
1353                        $('#confirm-quantity').val(quantity);
1354                        $('#confirm-price').val(price);
1355                        $('#confirm-step').val(step);
1356                        $('#confirm-promotionid').val(promotionId);
1357                        $('#confirm-promotionsindex').val(index);
1358
1359                        if (result.promotionType == 5 || result.promotionType == 7) {
1360                            $("#btnNextStep").html('Close');
1361                            $('#confirm-type').val('5');
1362                            $('#btnStayHere').hide(0);
1363                        }
1364                        else {
1365                            $('#btnStayHere').show(0);
1366                        }
1367                    }
1368                    else if (result.status == 1) {
1369                        $("#btnNextStep").html('Close');
1370                        $('#confirm-type').val('5');
1371                        $('#btnStayHere').hide(0);
1372                    }
1373                    else if (result.success == false && result.status == -10) {
1374                        location.reload();
1375                    }
1376                    else if (!result.message || result.message.toLowerCase() == 'fail') {
1377                        hideShowAddToCart(productId, true);
1378                        return;
1379                    }
1380                    $('#confirmNextStepPromotion').modal('show');
1381                }
1382                else {
1383                    AddProductToCart(id, productId, quantity, price, promotionId, step, index);
1384                }
1385            },
1386            error: function () { },
1387            beforeSend: function () {
1388                $(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
1389            },
1390            complete: function () {
1391                isChecking = false;
1392                $(".addToCart-" + productId).html(languageButton["O_Add"]);
1393            }
1394        });
1395    }
1396}
1397function AddProductToCart(id, productId, quantity, price, promotionId, step, index) {
1398    if (checkNotExistsSession()) {
1399        return false;
1400    }
1401    if (orderUserStep == 1) {
1402        selectService(false);
1403        return;
1404    }
1405    var listLimitedItemPromoAdded = [];
1406    arrayPromotionCart.forEach(function (promotion) {
1407        if (promotion.arrayProduct) {
1408            promotion.arrayProduct.forEach(function (product) {
1409                listLimitedItemPromoAdded.push(product.productID)
1410            });
1411        }
1412    });
1413
1414    if (listLimitedItemPromo.indexOf(productId) > -1 && listLimitedItemPromoAdded.indexOf(productId) > -1) {
1415        return;
1416    }
1417
1418    //alert(`${isAdding}`);
1419
1420    if (!isAdding) {
1421        isAdding = true;
1422        $(".addToCart-" + productId).css("pointer-events", "none");
1423
1424        $('#confirm-id').val('');
1425        $('#confirm-productId').val('');
1426        $('#confirm-quantity').val('');
1427        $('#confirm-price').val('');
1428        $('#confirm-step').val('');
1429        $('#confirm-promotionid').val('');
1430        $('#confirm-promotionsindex').val('');
1431        isShowAnimate = false;
1432        $.ajax({
1433            type: "POST",
1434            url: urlAddToCartByProductId,
1435            //contentType: 'application/json; charset=UTF-8',
1436            data: { "id": id, "productId": productId, "qty": quantity, "price": price, "promotionId": promotionId, 'index': index, "step": step, "buffetId": $('#hdBuffetId').val(), "authorization": siteId },
1437            success: function (result) {
1438                if (result.success == false && result.status == -100) {
1439                    showProductDetailDiaLog(result.docId, result.productID);
1440                    return;
1441                }
1442                if (result.mycart == 0 && result.quantity == 0 && (!result.message || result.message.toLowerCase() == 'fail')) {
1443                    hideShowAddToCart(productId, true);
1444                    LoadContainMyCart(true);
1445                    return;
1446                }
1447                if (result && result.mycart > 0) {
1448                    $('.btn-homepage-cart-display .homepage-cart-display__quatity').text(result.mycart);
1449                }
1450                console.log(isGroupOrdering, result.meOfCartCount);
1451                if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1452                    $('.btn-homepage-cart-display .homepage-cart-display__quatity').text(result.meOfCartCount);
1453                }
1454                if (result.success == false && result.message) {
1455                    location.reload();
1456                }
1457                if (result.success == false && result.status == -10) {
1458                    location.reload();
1459                }
1460                if (promotionId && promotionId != '' && result.isPromotionOutOfPerGroup == true) {
1461                    var url = urlIndexHome; // + 'Home/Index';
1462                    window.location.href = url;
1463                }
1464                if (promotionId && promotionId != '' && result.isPromotionOutOfPerItem == true) {
1465                    disableAddToCart(productId);
1466                }
1467                isShowAnimate = true;
1468                ShowAnimate(id, productId);
1469
1470                if (result.variantId) {
1471                    $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-variantid", result.variantId);
1472                }
1473
1474                LoadContainMyCart(true);
1475
1476                UpdateNoteDes(promotionId, quantity);
1477                //mobileProgressBarDilivery();
1478                if (result.isChangedCollectDateTime == true &&
1479                    !(promotionId && promotionId != '' && index && index != '')) {
1480                    if (!isOpenDateTime) {
1481                        $('#fulfillmentChanged').modal('show');
1482                        return;
1483                    }
1484                }
1485                if (result.status == -2) {
1486                    location.reload();
1487                }
1488                if (result.status == -1 || result.status == 0) {
1489                    //location.reload();
1490                    hideShowAddToCart(productId, true);
1491                    if (result.status == 0) {
1492                        if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1493                            setCountOrderInMyCart(result.meOfCartCount);
1494                        }
1495                        else {
1496                            setCountOrderInMyCart(result.mycart);
1497                        }
1498                        if (result.index) {
1499                            index = result.index;
1500                        }
1501                    }
1502                }
1503                else {
1504                    if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1505                        setCountOrderInMyCart(result.meOfCartCount);
1506                    }
1507                    else {
1508                        setCountOrderInMyCart(result.mycart);
1509                    }
1510                    // TKPOS-11612
1511                    //ShowIsAddedToCart("#item-added-" + productId);
1512
1513                    //TKPOS - 14884 [Ads][FB Pixels]Implement Deduplication for 2 tracking methods: FP Conversion API & FB Tracking Browser
1514                    if (fbq != null && isUseEventSetupTool == "0") {
1515                        fbq('track', 'AddToCart', {}, { 'eventID': result.fbpxEventId });
1516                    }
1517
1518                    if (ga != null) {
1519                        ga('send', 'event', 'GA', 'Tracking', 'Add To Cart')
1520                    }
1521                }
1522
1523                if (result.changeAutoCollectTime == true) {
1524                    //console.log('LoadContainTimeModal 3');
1525                    LoadContainTimeModal();
1526                }
1527
1528                if (promotionId && promotionId != '' && index && index != '' && result.isnextstep) {
1529                    $('#confirm-promotionid').val(promotionId);
1530                    $('#confirm-type').val('999');
1531                    $('#confirm-promotionsindex').val(result.index);
1532
1533                    $("#img-step-promotion").attr("src", urlLikeIcon);
1534                    $(".confirm-promotion-icon").css("display", "none");
1535                    $(".confirm-promotion-icon.like-promotion-icon").css("display", "initial");
1536
1537                    $("#btnNextStep").html(localizedButton.O_YesILoveTo).css("width", "auto");
1538                    $('#titleconfirmNextStep').text(localizedMessage.O_GreatChoicePleaseProceedNextStepToSelectThePromotionItem);
1539                    $('#confirm-finishstep').val('0');
1540                    if (result.isfinishstep) {
1541                        $("#img-step-promotion").attr("src", urlLikeMedalIcon);
1542                        $(".confirm-promotion-icon").css("display", "none");
1543                        $(".confirm-promotion-icon.likemedal-promotion-icon").css("display", "initial");
1544
1545                        $("#btnNextStep").html('Yes').removeAttr("style");
1546                        $('#titleconfirmNextStep').text(localizedMessage.O_GreatChoiceAgainNowPleaseConfirmYourOrder);
1547                        $('#confirm-finishstep').val(result.isfinishstep.toString());
1548                    }
1549                    $('#btnStayHere').show(0);
1550                    continueNextStep();
1551                }
1552                else {
1553                    $("#confirmNextStepPromotion").modal('hide');
1554                }
1555                isAdding = false;
1556            },
1557            error: function () {
1558                isAdding = false;
1559            },
1560            beforeSend: function () {
1561                $('#btnCheckOut').attr('disabled', 'disabled');
1562                $(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
1563
1564                $(".addToCart-Disabled-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-check-circle\"></i>');
1565
1566                //$(`.box-add-product-${productId}`).find(".btn-quantity-product").css("pointer-events", "initial").find('i.fa').toggleClass('fa-plus fa-spinner fa-spin');
1567            },
1568            complete: function () {
1569                $(".addToCart-" + productId).css("pointer-events", "initial");
1570                //$(`.box-add-product-${productId}`).find(".btn-quantity-product").css("pointer-events", "initial").find('i.fa').toggleClass('fa-plus fa-spinner fa-spin');
1571
1572                isAdding = false;
1573                if (!isShowAnimate) {
1574                    $(".addToCart-" + productId).html(languageButton["O_Add"]);
1575                }
1576            }
1577        });
1578    }
1579}
1580
1581function AddEVoucherToCart(id, productId) {
1582    if (checkNotExistsSession()) {
1583        return false;
1584    }
1585    if (orderUserStep == 1) {
1586        selectService(false);
1587        return;
1588    }
1589
1590    if (!isAdding) {
1591        isAdding = true;
1592        $(".addToCart-" + productId).css("pointer-events", "none");
1593
1594        $('#confirm-id').val('');
1595        $('#confirm-productId').val('');
1596        $('#confirm-quantity').val('');
1597        $('#confirm-price').val('');
1598        $('#confirm-step').val('');
1599        $('#confirm-promotionid').val('');
1600        $('#confirm-promotionsindex').val('');
1601
1602        let productItem = {
1603            id: productId,
1604            quantity: 1,
1605            buffetId: $('#hdBuffetId').val()
1606        };
1607        isShowAnimate = false;
1608        $.ajax({
1609            type: "POST",
1610            url: urlAddEVoucherToCart,
1611            contentType: 'application/json; charset=UTF-8',
1612            data: JSON.stringify(Object.assign({}, productItem, { authorization: siteId })),
1613            success: function (result) {
1614                if (result.success == false && result.status == -100) {
1615                    showProductDetailDiaLog(result.docId, result.productID);
1616                    return;
1617                }
1618                if (result.mycart == 0 && result.quantity == 0 && (!result.message || result.message.toLowerCase() == 'fail')) {
1619                    hideShowAddToCart(productId, true);
1620                    LoadContainMyCart(true);
1621                    return;
1622                }
1623                if (result && result.mycart > 0) {
1624                    $('.btn-homepage-cart-display .homepage-cart-display__quatity').text(result.mycart);
1625                }
1626
1627                if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1628                    $('.btn-homepage-cart-display .homepage-cart-display__quatity').text(result.meOfCartCount);
1629                }
1630                if (result.success == false && result.message) {
1631                    location.reload();
1632                }
1633                if (result.success == false && result.status == -10) {
1634                    location.reload();
1635                }
1636
1637                isShowAnimate = true;
1638                ShowAnimate(id, productId);
1639
1640                if (result.variantId) {
1641                    $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-variantid", result.variantId);
1642                }
1643
1644                LoadContainMyCart(true);
1645
1646                if (result.status == -2) {
1647                    location.reload();
1648                }
1649
1650                if (result.status == -1 || result.status == 0) {
1651                    //location.reload();
1652                    hideShowAddToCart(productId, true);
1653                    if (result.status == 0) {
1654                        if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1655                            setCountOrderInMyCart(result.meOfCartCount);
1656                        }
1657                        else {
1658                            setCountOrderInMyCart(result.mycart);
1659                        }
1660                        if (result.index) {
1661                            index = result.index;
1662                        }
1663                    }
1664                }
1665                else {
1666                    if (isGroupOrdering && result.meOfCartCount != undefined && result.meOfCartCount != null) {
1667                        setCountOrderInMyCart(result.meOfCartCount);
1668                    }
1669                    else {
1670                        setCountOrderInMyCart(result.mycart);
1671                    }
1672                    // TKPOS-11612
1673                    //ShowIsAddedToCart("#item-added-" + productId);
1674
1675                    //TKPOS - 14884 [Ads][FB Pixels]Implement Deduplication for 2 tracking methods: FP Conversion API & FB Tracking Browser
1676                    if (fbq != null && isUseEventSetupTool == "0") {
1677                        fbq('track', 'AddToCart', {}, { 'eventID': result.fbpxEventId });
1678                    }
1679
1680                    if (ga != null) {
1681                        ga('send', 'event', 'GA', 'Tracking', 'Add To Cart')
1682                    }
1683                }
1684
1685                if (result.changeAutoCollectTime == true) {
1686                    //console.log('LoadContainTimeModal 3');
1687                    LoadContainTimeModal();
1688                }
1689
1690                isAdding = false;
1691            },
1692            error: function () {
1693                isAdding = false;
1694            },
1695            beforeSend: function () {
1696                $('#btnCheckOut').attr('disabled', 'disabled');
1697                $(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
1698
1699                $(".addToCart-Disabled-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-check-circle\"></i>');
1700
1701                //$(`.box-add-product-${productId}`).find(".btn-quantity-product").css("pointer-events", "initial").find('i.fa').toggleClass('fa-plus fa-spinner fa-spin');
1702            },
1703            complete: function () {
1704                $(".addToCart-" + productId).css("pointer-events", "initial");
1705                //$(`.box-add-product-${productId}`).find(".btn-quantity-product").css("pointer-events", "initial").find('i.fa').toggleClass('fa-plus fa-spinner fa-spin');
1706
1707                isAdding = false;
1708                if (!isShowAnimate) {
1709                    $(".addToCart-" + productId).html(languageButton["O_Add"]);
1710                }
1711            }
1712        });
1713    }
1714}
1715
1716function UpdateNoteDes(promotionId, quantity) {
1717    if (promotionId) {
1718        lessItemInCart = lessItemInCart - quantity;
1719        if (lessItemInCart > 0) {
1720            var noteDes = languageLabel["O_Please_Select_More_Items"];
1721            if (noteDes == undefined || noteDes == null || !noteDes) {
1722                noteDes = "Please select {0} more item(s)";
1723            }
1724            noteDes = noteDes.replace("{0}", lessItemInCart);
1725            $('#promotion-noteDes').text(noteDes);
1726        } else {
1727            $('#promotion-noteDes').text('');
1728        }
1729    }
1730}
1731
1732function getQuantityInCart(docId, productId, isChanged = false, isAddOnMenu = false, variantId = '') {
1733    $.ajax({
1734        type: "POST",
1735        url: urlGetQuantityInCart,
1736        data: { docId: docId, authorization: siteId },
1737        success: function (result) {
1738            if (variantId == null || variantId == '') {
1739                variantId = result.newItemVariantId;
1740            }
1741            console.log(productId);
1742            $(`.box-add-product-${productId}`).find(".btn-change-quantity").css("pointer-events", "initial").find('i.fa').removeClass('fa-spinner fa-spin');
1743            $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-only-current-item", result.isInCartOnlyCurrentItem);
1744            $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-count-item-in-cart", result.countItemInCart);
1745            $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-variantid", result.variantIdInCart).find('input.quantity-product-value').val(result.quantityInCart);
1746            if (result.quantityInCart == 0) {
1747                if (isChanged || result.existInCart > 0) {
1748                    $(`.box-add-product-${productId}`).find(".btn-add-to-cart").removeClass("hidden");
1749                }
1750                else {
1751                    $(`.box-add-product-${productId}`).find(".btn-add-to-cart").removeClass("hidden").find('i.fa').remove();
1752                }
1753
1754                $(`.box-add-product-${productId}`).find(".btn-quantity-product").addClass("hidden");
1755            }
1756            else {
1757                $(`.box-add-product-${productId}`).find(".btn-add-to-cart").addClass("hidden");
1758                $(`.box-add-product-${productId}`).find(".btn-quantity-product").removeClass("hidden");
1759            }
1760
1761            if (result.quantityPerPax == 0 && !result.isBlockItem) {
1762                const quantityPerPaxAttr = $(`.box-add-product-${productId}`)
1763                    .find(".btn-quantity-product")
1764                    .attr("data-quantity-per-pax");
1765
1766                if (quantityPerPaxAttr) {  // tự động loại bỏ undefined, null, ''
1767                    const parsed = parseInt(quantityPerPaxAttr, 10);
1768                    if (!isNaN(parsed)) { // đảm bảo convert ra số hợp lệ
1769                        result.quantityPerPax = parsed;
1770                    }
1771                }
1772            }
1773            if (result.isBlockItem || (result.quantityPerPax && result.quantityPerPax > 0)) {
1774                var btnAddToCart = $(".addToCart-" + productId);
1775                var totalOfPax = result.quantityPerPax - result.existInCart;
1776                if (totalOfPax <= 0) {
1777                    totalOfPax = 0;
1778                    if (!allowOverLimit) {
1779                        $(`.box-add-product-${productId}`).find(".btn-quantity-product").find('button[data-type-change="plus"]').attr("disabled", "disabled");
1780                        if (!btnAddToCart.hasClass('hiden')) {
1781                            btnAddToCart.attr('disabled', 'disabled');
1782                        }
1783                    }
1784                }
1785                else {
1786                    $(`.box-add-product-${productId}`).find(".btn-quantity-product").find('button[data-type-change="plus"]').removeAttr("disabled");
1787                    
1788                    if ($(`#s_span-${productId}`).hasClass("hidden") == false &&
1789                        $(`.box-add-product-${productId}`).hasClass("hidden") == true) {
1790                        hideShowAddToCart(productId, false);
1791                    }
1792                    if (!btnAddToCart.hasClass('hiden')) {
1793                        btnAddToCart.removeAttr('disabled');
1794                    }
1795                }
1796                console.log('existInCart', result.existInCart, 'totalOfPax', totalOfPax);
1797                $(`.box-product-${productId}`).find(".product__label--perpax").text(`${totalOfPax} of ${result.quantityPerPax} Remaining`);
1798            }
1799
1800            if (isAddOnMenu == true) {
1801                scrollToNewVariantId(variantId);
1802            }
1803        },
1804        error: function (error) {
1805            console.log('error: ', error);
1806        }
1807    });
1808}
1809
1810function getQuantityInCartMerchantOS(itemsInCart, isChanged = false, isAddOnMenu = false) {
1811    $.ajax({
1812        type: "POST",
1813        url: urlGetQuantityInCartMerchantOS,
1814        data: { model: itemsInCart },
1815        success: function (response) {
1816            response.data.forEach(result => {
1817                let productId = result.ProductId;
1818
1819                $(`.box-add-product-${productId}`).find(".btn-change-quantity").css("pointer-events", "initial").find('i.fa').removeClass('fa-spinner fa-spin');
1820                $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-only-current-item", result.IsInCartOnlyCurrentItem);
1821                $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-count-item-in-cart", result.CountItemInCart);
1822                $(`.box-add-product-${productId}`).find(".btn-quantity-product").attr("data-variantid", result.VariantIdInCart).find('input.quantity-product-value').val(result.QuantityInCart);
1823                if (result.QuantityInCart == 0) {
1824                    if (isChanged || result.ExistInCart > 0) {
1825                        $(`.box-add-product-${productId}`).find(".btn-add-to-cart").removeClass("hidden");
1826                    }
1827                    else {
1828                        $(`.box-add-product-${productId}`).find(".btn-add-to-cart").removeClass("hidden").find('i.fa').remove();
1829                    }
1830
1831                    $(`.box-add-product-${productId}`).find(".btn-quantity-product").addClass("hidden");
1832                }
1833                else {
1834                    $(`.box-add-product-${productId}`).find(".btn-add-to-cart").addClass("hidden");
1835                    $(`.box-add-product-${productId}`).find(".btn-quantity-product").removeClass("hidden");
1836                }
1837                
1838                if (result.isBlockItem || (result.QuantityPerPax && result.QuantityPerPax > 0)) {
1839                    var btnAddToCart = $(".addToCart-" + productId);
1840                    var totalOfPax = result.QuantityPerPax - result.ExistInCart;
1841                    if (totalOfPax <= 0) {
1842                        totalOfPax = 0;
1843                        if (!allowOverLimit) {
1844                            $(`.box-add-product-${productId}`).find(".btn-quantity-product").find('button[data-type-change="plus"]').attr("disabled", "disabled");
1845                            if (!btnAddToCart.hasClass('hiden')) {
1846                                btnAddToCart.attr('disabled', 'disabled');
1847                            }
1848                        }
1849                    }
1850                    else {
1851                        $(`.box-add-product-${productId}`).find(".btn-quantity-product").find('button[data-type-change="plus"]').removeAttr("disabled");
1852                        
1853                        if ($(`#s_span-${productId}`).hasClass("hidden") == false &&
1854                            $(`.box-add-product-${productId}`).hasClass("hidden") == true) {
1855                            hideShowAddToCart(productId, false);
1856                        }
1857                        if (!btnAddToCart.hasClass('hiden')) {
1858                            btnAddToCart.removeAttr('disabled');
1859                        }
1860                    }
1861                    console.log('existInCart', result.ExistInCart, 'totalOfPax', totalOfPax);
1862                    $(`.box-product-${productId}`).find(".product__label--perpax").text(`${totalOfPax} of ${result.QuantityPerPax} Remaining`);
1863                }
1864
1865            });
1866
1867
1868            //if (isAddOnMenu == true) {
1869            //    scrollToNewVariantId(variantId);
1870            //}
1871        },
1872        error: function (error) {
1873            console.log('error: ', error);
1874        }
1875    });
1876}
1877
1878var isShowAnimate = false;
1879function ShowAnimate(docId, productId, isChanged = false, isAddOnMenu = true, variantId = '') {
1880    $(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-check-circle\"></i>');
1881    $(".addToCart-" + productId).addClass('btn-3-added');
1882
1883    $('#my-cart-count').addClass('shaketitle');
1884    setTimeout(function () {
1885        $('#my-cart-count').removeClass('shaketitle');
1886    }, 500);
1887    setTimeout(function () {
1888        $('#my-cart-count').addClass('shaketitle');
1889        setTimeout(function () {
1890            $('#my-cart-count').removeClass('shaketitle');
1891        }, 700)
1892    }, 1300);
1893
1894    console.log('ShowAnimate');
1895    getQuantityInCart(docId, productId, isChanged, isAddOnMenu, variantId);
1896
1897    const $homepageCartButtonDisplay = $('.homepage-cart-button-display');
1898    $homepageCartButtonDisplay.addClass('show-homepage-cart-btn').removeClass('hide-homepage-cart-btn');
1899    return;
1900}
1901
1902function SelectTime(item, time, dateSelected, url, modelId, isReloadList) {
1903    $('#limitAmount_error').css('display', 'none');
1904    var m = dateSelected.getMonth() + 1, d = dateSelected.getDate(), y = dateSelected.getFullYear();
1905    $(".btn-danger.pull-right.time").attr("class", "btn btn-default pull-right");
1906    $(item).attr("class", "btn btn-danger time pull-right");
1907    if (deliveryMethodSession == "StationOrdering") {
1908        $('#dropdown-time-selecter-2').val(time);
1909    }
1910    else {
1911        $('#dropdown-time-selecter').val(time);
1912    }
1913    isSelectTime = true;
1914    let windowWidth = $(window).width();
1915    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0
1915);
1916    if (windowHeight < 1) {
1917        windowHeight = $(window).height();
1918    }
1919    //if (windowWidth < 768) {
1920    if (true) {
1921        popupLoading = new Loading({ title: 'Loading' });
1922    }
1923    $.ajax({
1924        type: "POST",
1925        url: url,
1926        data: { year: y, month: m, day: d, time: time },
1927        success: function (result) {
1928            if (deliveryMethodSession == "Delivery" && result.success) {
1929                if (result.deliveryTime > 0) {
1930                    deliveryTime = result.deliveryTime;
1931                    gapTime = result.deliveryTime;
1932                    $('#settingDeliveryTime').val(result.deliveryTime)
1933                    //console.log('set deliveryTime: ', deliveryTime);
1934                }
1935                $('#timeModal').modal('hide');
1936            }
1937            if (result.isLimitOrderByHour) {
1938                $('#order-capacity-copy-text').css('display', 'block');
1939            } else {
1940                //$("#ErrDeliveryCollectTime_Modal").removeClass("hidden");
1941            }
1942            if (result.isAutoRedirect) {
1943                if (autoRedirectType == 3) {
1944                    location.reload();
1945                }
1946                if (!result.success && result.isAutoRedirect && result.message != '') {
1947                    if (result.isLimitOrderByHour) {
1948                        $('#order-capacity-copy-text').css('display', 'block');
1949                        //if (windowWidth < 768 && isReloadList) {
1950                        if (true && isReloadList) {
1951                            resetTimePicker(dateSelected);
1952                        }
1953                    } else {
1954                        //$("#ErrDeliveryCollectTime_Modal").removeClass("hidden");
1955                    }
1956                }
1957                if (result.isChangeOutlet) {
1958                    isSelectStation = true;
1959                    $('#outletChanged').modal('show');
1960                    return;
1961                }
1962                if (!result.success && result.isAutoRedirect && result.time != '') {
1963                    $("#ErrDeliveryCollectDateTime_Modal").removeClass("hidden");
1964                    //if (windowWidth < 768 && isReloadList) {
1965                    if (true && isReloadList) {
1966                        resetTimePicker(dateSelected);
1967                    }
1968                    return;
1969                }
1970            }
1971            if (deliveryMethodSession == "StationOrdering" || result.isLimitOrderByHour) {
1972                location.reload();
1973                return;
1974            }
1975            var datetimeselected;
1976
1977            if (result.dropOffTime != null && result.dropOffTime != undefined && result.dropOffTime != '') {
1978                dropOffTime = result.dropOffTime;
1979            }
1980            if (result.dropOffTimeReselect != null && result.dropOffTimeReselect != undefined && result.dropOffTimeReselect != '') {
1981                dropOffTimeReselect = result.dropOffTimeReselect;
1982            }
1983            buildTimerSessionTimeOut();
1984            var strTime = '';
1985
1986            if (!result.success) {
1987                //$('#limitAmount_error').css('display', 'block');
1988                timeselected = time;
1989                datetimeselected = result.date + ' ' + languageMessage["O_at"] + ' ' + time;
1990                $('#collect_datetime_tw').text(datetimeselected);
1991
1992                $('#collect_datetime_dl').text(datetimeselected);
1993                $('#collect_date_dl').text(result.date);
1994                strTime = convertFormatTime(time);
1995                $('#collect_time_dl').text(strTime.replace('-', languageLabel["O_To"]).replace('(Tomorrow)', ''));
1996
1997                $('#order-pickup-date').text(result.date);
1998                $('#order-pickup-time').text(strTime);
1999                $('#order-pickup-display').text(result.displayToday);
2000
2001                $('#order-delivery-date').text(result.date);
2002                $('#order-delivery-time').text(strTime);
2003                $('.order-delivery-display').text(result.displayToday);
2004                $('#ShippingFee').text(result.shippingFeeDisplay);
2005                $('#shippingFeeOrder').text(result.shippingFeeDisplay);
2006                $('#grandTotalSpan').text(result.grandTotalDisplay);
2007
2008                $('#collect_datetime_dl').addClass('hidden');
2009                $('#collect_date_dl').removeClass('hidden');
2010                $('#collect_time_dl').removeClass('hidden');
2011                //if (windowWidth < 768 && isReloadList) {
2012                if (true && isReloadList) {
2013                    resetTimePicker(dateSelected);
2014                }
2015                return;
2016            }
2017
2018            if (result.isExistedItemHide) {
2019                $('#product-in-valid').html(result.listProductInvalid);
2020                $('#btnProductInvalidPayment').removeClass('hidden');
2021                $('#btnProductInvalidCheckout').addClass('hidden');
2022                $('#timeModal').modal('hide');
2023                $('#alertProductInvalid').modal('show');
2024                return;
2025            }
2026
2027            currentDate = dateSelected;
2028
2029            //var amountAvailable = result.amountAvailable;
2030            //var grandTotal = result.grandTotal;
2031            //if (amountAvailable !== -1 && grandTotal > amountAvailable) {
2032            //    $('#limitAmount_error').css('display', 'block');
2033            //} else {
2034            //    $('#limitAmount_error').css('display', 'none');
2035            //}
2036            timeselected = time;
2037            datetimeselected = result.date + ' at ' + time;
2038            $('#collect_datetime_tw').text(datetimeselected);
2039
2040            $('#collect_datetime_dl').text(datetimeselected);
2041            $('#collect_date_dl').text(result.date);
2042            strTime = convertFormatTime(time);
2043            $('#collect_time_dl').text(strTime.replace('-', 'to').replace('(Tomorrow)', ''));
2044
2045            $('#order-pickup-date').text(result.date);
2046            $('#order-pickup-time').text(strTime);
2047            $('#order-pickup-display').text(result.displayToday);
2048
2049            $('#order-delivery-date').text(result.date);
2050            $('#order-delivery-time').text(strTime);
2051            $('.order-delivery-display').text(result.displayToday);
2052
2053            $('#collect_datetime_dl').addClass('hidden');
2054            $('#collect_date_dl').removeClass('hidden');
2055            $('#collect_time_dl').removeClass('hidden');
2056
2057            var currentUrl = window.location.href.toLowerCase();
2058            if (currentUrl.indexOf('/checkout') > 0) {
2059                // save all data form user before reload page;
2060                saveAllFormData();
2061                //LoadPaymentMyCart();
2062                var url = urlIndexHome; // + 'Home/Index';
2063                window.location.href = url;
2064            }
2065            else {
2066                if (currentUrl.indexOf('/Promotion'.toLowerCase()) > 0) {
2067                    location.reload();
2068                }
2069                else if (result.isNotReloadPage && !result.isReloadLimitOrderByHour) {
2070                    LoadContainMyCart();
2071                }
2072            }
2073
2074            if (!result.isNotReloadPage) {
2075                return window.location.reload();
2076            }
2077
2078            if (result.isMasterMenuRedirected != null && result.isMasterMenuRedirected == true) {
2079                popupLoading = new Loading({ title: 'Loading' });
2080
2081                setTimeout(function () {
2082                    if (popupLoading && popupLoading.version) {
2083                        popupLoading.out();
2084                        popupLoading = null;
2085                    }
2086                }, 10000);
2087
2088                return window.location.reload();
2089            }
2090
2091            if (result.isReloadLimitOrderByHour) {
2092                window.location.reload();
2093            }
2094
2095            loadPromotionForHomepage();
2096        },
2097        error: function () {
2098            isSelectTime = false;
2099            if (popupLoading && popupLoading.version) {
2100                popupLoading.out();
2101                popupLoading = null;
2102            }
2103        },
2104        beforeSend: function () {
2105            $('#btnCheckOut').attr('disabled', 'disabled');
2106            if (deliveryMethodSession != "Delivery") {
2107                $('#timeModal').modal('hide');
2108            }
2109            $("#btnSubmit1").html(languageButton["O_Done"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2110            $('#btnCheckOut').attr('disabled', 'disabled');
2111            $("#ErrDeliveryCollectDateTime_Modal").addClass("hidden");
2112        },
2113        complete: function () {
2114            if (modelId && modelId != '' && !isAutoRedirect) {
2115                $("#" + modelId).modal('hide');
2116            }
2117            $("#btnSubmit1").html(languageButton["O_Done"]);
2118
2119            if (popupLoading && popupLoading.version) {
2120                popupLoading.out();
2121                popupLoading = null;
2122            }
2123        }
2124    });
2125}
2126
2127function loadPromotionForHomepage() {
2128    $.ajax({
2129        type: "POST",
2130        url: urlGetHomePagePromotion,
2131        data: { authorization: siteId },
2132        success: function (result) {
2133            $('#home-page-promotion').html(result);
2134            $('#load-more-promotions').hide();
2135        },
2136        error: function () {
2137
2138        },
2139        beforeSend: function () {
2140
2141        },
2142        complete: function () {
2143
2144        }
2145    });
2146}
2147
2148function saveAllFormData() {
2149    //console.log('saveAllFormData');
2150    // save all data in customer form fill before reload page
2151    localStorage.setItem("mFirstName", $('#member_firstName').val());
2152    localStorage.setItem("mLastName", $('#member_lastName').val());
2153    localStorage.setItem("mEmail", $('#member_email').val());
2154    localStorage.setItem("mPhoneRegion", $('#member_phoneRegion').val());
2155    localStorage.setItem("mPhone", $('#member_phone').val());
2156    localStorage.setItem("mCountry", $('#country2').val());
2157    localStorage.setItem("mZipCode", $('#member_zipCode').val());
2158    localStorage.setItem("mAddress", $('#member_address').val());
2159    localStorage.setItem("mAddress2", $('#member_address2').val());
2160    localStorage.setItem("mRemark", $('#mycart_remark').val());
2161    localStorage.setItem("mCustomRemark", $('#mycart_customRemark').val());
2162    localStorage.setItem("mStarhubHUBID", $('#member_starhubHUBID').val());
2163
2164    //window.onbeforeunload = null;
2165}
2166
2167function changeLang(code) {
2168    $.ajax({
2169        type: "POST",
2170        url: urlChangeLang,
2171        //contentType: 'application/json; charset=UTF-8',
2172        data: { id: code, authorization: siteId },
2173        success: function (data) {
2174            location.reload();
2175        },
2176        error: function (err) { console.log(err); },
2177        beforeSend: function () {
2178        },
2179        complete: function () {
2180        }
2181    });
2182
2183}
2184function ShowIsAddedToCart(domId) {
2185    var dom = $(domId);
2186    dom.text(languageMessage["O_ItemIsAddedIntoCart"]).fadeIn(300).delay(2000).fadeOut(300);
2187
2188    var s_domId = domId.replace('#', '#s_');
2189    var s_dom = $(s_domId);
2190    s_dom.text(languageMessage["O_ItemIsAddedIntoCart"]).fadeIn(300).delay(2000).fadeOut(300);
2191}
2192
2193function ChangeCheckBox(id) {
2194    $('#' + id).click();
2195}
2196
2197function showTimeModal(isGetDateTime) {
2198    let windowWidth = $(window).width();
2199    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
2200    if (windowHeight < 1) {
2201        windowHeight = $(window).height();
2202    }
2203    if (isGetDateTime) {
2204        isChoosingDateTime = true;
2205        $('#modalWelcome').modal('hide');
2206        //if (windowWidth < 768) {
2207        if (true) {
2208            $('.bodyservice .tabmoredate').addClass('hidden');
2209            $('.bodyservice .tablessdate').removeClass('hidden');
2210        }
2211        else {
2212            $('.bodyservice .tabmoredate').removeClass('hidden');
2213            $('.bodyservice .tablessdate').addClass('hidden');
2214        }
2215        $('#selectTimeModal').modal('show');
2216    } else {
2217        //if (windowWidth < 768) {
2218        if (true) {
2219            $('.bodyservice .tabmoredate').addClass('hidden');
2220            $('.bodyservice .tablessdate').removeClass('hidden');
2221        }
2222        else {
2223            $('.bodyservice .tabmoredate').removeClass('hidden');
2224            $('.bodyservice .tablessdate').addClass('hidden');
2225        }
2226
2227        $('#timeModal').modal('show');
2228    }
2229
2230}
2231
2232function showSingleDeliveryTimeModal() {
2233    $('#singleDeliveryTimeModal').modal('show');
2234}
2235
2236function checkNotExistsSession() {
2237    if ($(document).find('#textCheckOut').length === undefined || $(document).find('#textCheckOut').length === 0) {
2238        location.reload();
2239        return true;
2240    }
2241    else {
2242        return false;
2243    }
2244}
2245
2246function CheckProductPromotionAvailable(id, productId, quantity, price, promotionId, step, index) {
2247    if (checkNotExistsSession()) {
2248        return false;
2249    }
2250    if (orderUserStep == 1) {
2251        selectService(false);
2252        return;
2253    }
2254
2255    //$(".addToCart-" + productId).parents(".box-product-" + productId).css("pointer-events", "none");
2256
2257    //let htmlBtn = $(".addToCart-" + productId).html();
2258    //let spanProductId = $(".span-" + productId).html();
2259
2260    $.ajax({
2261        type: "POST",
2262        url: urlCheckAddToCartByProductId,
2263        //contentType: 'application/json; charset=UTF-8',
2264        data: { "id": id, "productId": productId, "qty": quantity, "price": price, "promotionId": promotionId, 'index': index, "step": step, "authorization": siteId },
2265        success: function (result) {
2266            if (result.index) {
2267                index = result.index;
2268            }
2269            if (result.success == false && result.message && result.status == 1) {
2270                $('#titleconfirmNextStep').text(result.message);
2271
2272                $("#btnNextStep").html('Close');
2273                $('#confirm-type').val('5');
2274                $('#btnStayHere').hide(0);
2275
2276                $('#confirmNextStepPromotion').modal('show');
2277            }
2278            else {
2279                showProductDetailDiaLog(id, productId, promotionId, step, index);
2280            }
2281        },
2282        error: function () { },
2283        beforeSend: function () {
2284            //$(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2285            //$(".span-" + productId).html(spanProductId + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2286        },
2287        complete: function () {
2288            //showProductDetailId = '';
2289            //$(".addToCart-" + productId).html(htmlBtn);
2290            //$(".span-" + productId).html(spanProductId);
2291            //$("#result-" + productId + '> div > i').remove();
2292
2293            //$(".addToCart-" + productId).parents(".box-product-" + productId).css("pointer-events", "initial");
2294        }
2295    });
2296}
2297
2298function showProductDetailDiaLog(id, productId, promotionId, step, index, variantId) {
2299    isShowOpenPricePopup = false;
2300    if (checkNotExistsSession()) {
2301        return false;
2302    }
2303    if (orderUserStep == 1) {
2304        selectService(false);
2305        return;
2306    }
2307    $(".addToCart-" + productId).parents(".box-product-" + productId).css("pointer-events", "none");
2308    if (variantId) {
2309        $(".edit-modifiers-mobile .func-edit-" + variantId).append('<i class="fa fa-spinner fa-spin" style="position: unset; font-size: 14px;"></i>');
2310        $(".func-edit-" + variantId).css("pointer-events", "none");
2311    }
2312    showProductDetailId = productId;
2313    setTimeout(function () {
2314        var htmlBtn = $(".addToCart-" + productId).html();
2315        var spanProductId = $(".span-" + productId).html();
2316        $.ajax({
2317            type: "GET",
2318            url: urlProductDetail,
2319            data: { 'id': id, 'productId': productId, 'promotionId': promotionId, 'step': step, 'index': index, 'variantId': variantId },
2320            success: function (result) {
2321                if (result.success == false && result.message) {
2322                    location.reload();
2323                }
2324                else {
2325                    if (fbq != null && isUseEventSetupTool == "0") {
2326                        fbq('track', 'ViewContent');
2327                    }
2328                    if (ga != null) {
2329                        ga('send', 'event', 'GA', 'Tracking', 'View Content')
2330                    }
2331
2332                    $('#productDetailModal_Body').html(result);
2333                    let isShowProductDetailModal = true;
2334
2335                    if (typeof isMerchantOS !== 'undefined' && isMerchantOS == true) {
2336                        var productItem = JSON.parse(JSON.stringify(data));
2337
2338                        if (productItem != null && productItem.isOpenPrice == true
2339                            && (productItem.arrayModifierGroup == null || productItem.arrayModifierGroup.length == 0)
2340                            && (productItem.variantViewModels == null || productItem.variantViewModels.length == 0)
2341                        ) {
2342                            if (GetProductItemOpenPrice(productItem)) {
2343                                isShowProductDetailModal = false;
2344
2345                                $('#productDetailModal').modal('hide');
2346                            }
2347                        }
2348                    }
2349
2350                    if (isShowProductDetailModal == true) {
2351                        $('#productDetailModal').modal('show');
2352                    }
2353                }
2354
2355                if ($(window).width() < 768) {
2356                    const scrollY = document.documentElement.style.getPropertyValue('--scroll-y');
2357                    const body = document.body;
2358                    body.style.position = 'fixed';
2359                    body.style.top = `-${scrollY}`;
2360                }
2361            },
2362            error: function () {
2363                if (variantId) {
2364                    $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2365                    $(".func-edit-" + variantId).css("pointer-events", "initial");
2366                }
2367            },
2368            beforeSend: function () {
2369                $(".addToCart-" + productId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2370                $(".span-" + productId).html(spanProductId + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2371            },
2372            complete: function () {
2373                showProductDetailId = '';
2374                $(".addToCart-" + productId).html(htmlBtn);
2375                $(".span-" + productId).html(spanProductId);
2376                $("#result-" + productId + '> div > i').remove();
2377
2378                $(".addToCart-" + productId).parents(".box-product-" + productId).css("pointer-events", "initial");
2379                if (variantId) {
2380                    $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2381                    $(".func-edit-" + variantId).css("pointer-events", "initial");
2382                }
2383            }
2384        });
2385    }, 300);
2386}
2387
2388function showEVoucherDetailDiaLog(id, eVoucherId) {
2389    isShowOpenPricePopup = false;
2390
2391    if (checkNotExistsSession()) {
2392        return false;
2393    }
2394    if (orderUserStep == 1) {
2395        selectService(false);
2396        return;
2397    }
2398    $(".addToCart-" + eVoucherId).parents(".box-product-" + eVoucherId).css("pointer-events", "none");
2399    //if (variantId) {
2400    //    $(".edit-modifiers-mobile .func-edit-" + variantId).append('<i class="fa fa-spinner fa-spin" style="position: unset; font-size: 14px;"></i>');
2401    //    $(".func-edit-" + variantId).css("pointer-events", "none");
2402    //}
2403    showProductDetailId = eVoucherId;
2404    setTimeout(function () {
2405        var htmlBtn = $(".addToCart-" + eVoucherId).html();
2406        var spanEVoucherId = $(".span-" + eVoucherId).html();
2407        $.ajax({
2408            type: "GET",
2409            url: urlEVoucherDetail,
2410            data: { 'id': id },
2411            //data: { 'id': id, 'variantId': variantId },
2412            success: function (result) {
2413                if (result.success == false && result.message) {
2414                    location.reload();
2415                }
2416                else {
2417                    if (fbq != null && isUseEventSetupTool == "0") {
2418                        fbq('track', 'ViewContent');
2419                    }
2420                    if (ga != null) {
2421                        ga('send', 'event', 'GA', 'Tracking', 'View Content')
2422                    }
2423
2424                    $(document).find('#productDetailModal_Body').html(result);
2425                    $(document).find('#productDetailModal').modal('show');
2426                }
2427
2428                if ($(window).width() < 768) {
2429                    const scrollY = document.documentElement.style.getPropertyValue('--scroll-y');
2430                    const body = document.body;
2431                    body.style.position = 'fixed';
2432                    body.style.top = `-${scrollY}`;
2433                }
2434            },
2435            error: function () {
2436                //if (variantId) {
2437                //    $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2438                //    $(".func-edit-" + variantId).css("pointer-events", "initial");
2439                //}
2440            },
2441            beforeSend: function () {
2442                $(".addToCart-" + eVoucherId).html(languageButton["O_Add"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2443                $(".span-" + eVoucherId).html(spanEVoucherId + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2444            },
2445            complete: function () {
2446                showProductDetailId = '';
2447                $(".addToCart-" + eVoucherId).html(htmlBtn);
2448                $(".span-" + eVoucherId).html(spanEVoucherId);
2449                $("#result-" + eVoucherId + '> div > i').remove();
2450
2451                $(".addToCart-" + eVoucherId).parents(".box-product-" + eVoucherId).css("pointer-events", "initial");
2452                //if (variantId) {
2453                //    $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2454                //    $(".func-edit-" + variantId).css("pointer-events", "initial");
2455                //}
2456            }
2457        });
2458    }, 300);
2459}
2460
2461function showMemberLoginDiaLog() {
2462    showPopup("#member-required-login-popup");
2463}
2464
2465function showMembershipAndRewardsPopup() {
2466    showPopup("#membership-and-rewards-popup", () => {
2467        $("#membership-and-rewards-popup").attr('data-pre-id', '#select-payment-options-popup');
2468        $('#select-payment-options-popup').addClass('pre-popup');
2469    });
2470}
2471
2472function showMarketingMaterialsConsentPopup() {
2473    showPopup("#marketing-materials-consent-popup", () => {
2474        $("#marketing-materials-consent-popup").attr('data-pre-id', '#select-payment-options-popup');
2475        $('#select-payment-options-popup').addClass('pre-popup');
2476    });
2477}
2478
2479function getEVoucherInfo(e, voucherId) {
2480    waitingForAction(e, true);
2481    $.ajax({
2482        type: "GET",
2483        cache: false,
2484        data: {
2485            voucherId: voucherId
2486        },
2487        url: urlEVoucherInfo
2488    }).done(function (response) {
2489        $(detailDiscountBody).html(response);
2490
2491        showPopup(detailDiscountPopupId);
2492
2493        $(detailDiscountPopupId).find('.popup-title').text('Detail Voucher');
2494        $(detailDiscountPopupId).find('#btn-pcv-apply').hide();
2495        $(detailDiscountPopupId).find('#btn-pcv-back').hide();
2496
2497    }).fail(function (jqXHR, textStatus) {
2498        console.log(jqXHR, textStatus);
2499    }).always(function () {
2500        waitingForAction(e, false);
2501    });
2502}
2503
2504function openVoucherTermsIframe(e, voucherId, isIssued, prePopupSelector, headerTitle, isDisabled, itemId, discountType) {
2505    waitingForAction(e, true);
2506
2507    $(detailDiscountPopupId).off('click', '#btn-pcv-back');
2508    $(detailDiscountPopupId).on('click.openVoucherTermsIframe', '#btn-pcv-back', function (ev) {
2509        if (ev && typeof ev.preventDefault === 'function') ev.preventDefault();
2510        if (ev && typeof ev.stopPropagation === 'function') ev.stopPropagation();
2511        $(detailDiscountPopupId).find('.popup-close').trigger('click');
2512    });
2513
2514    var loadingHtml = ''
2515        + '<div style="height:50vh;display:flex;align-items:center;justify-content:center;">'
2516        + '  <i class="fa fa-spinner fa-spin" style="font-size:24px;"></i>'
2517        + '</div>';
2518
2519    $(detailDiscountBody).html(loadingHtml);
2520
2521    if (prePopupSelector) {
2522        $(detailDiscountPopupId).attr('data-pre-id', prePopupSelector);
2523        $(prePopupSelector).removeClass('popup-show');
2524    }
2525
2526    showPopup(detailDiscountPopupId);
2527
2528    if (typeof UpdateDetailDiscountPopup === 'function' && typeof discountType !== 'undefined') {
2529        UpdateDetailDiscountPopup(headerTitle || 'Detail Voucher', !!isDisabled, itemId || voucherId, discountType);
2530    }
2531    else {
2532        $(detailDiscountPopupId).find('.popup-title').text(headerTitle || 'Detail Voucher');
2533        $(detailDiscountPopupId).find('#btn-pcv-apply').hide();
2534        $(detailDiscountPopupId).find('#btn-pcv-back').hide();
2535    }
2536
2537    $.ajax({
2538        type: "GET",
2539        cache: false,
2540        data: {
2541            voucherId: voucherId,
2542            isIssued: isIssued
2543        },
2544        url: discountURl.getVoucherTermsIframe
2545    }).done(function (response) {
2546        if (!response || !response.success || !response.iframeUrl) {
2547            $(detailDiscountBody).html('<div style="padding:16px;">Unable to load voucher terms. Please try again.</div>');
2548            return;
2549        }
2550
2551        var iframeHtml = '<iframe src="' + response.iframeUrl + '" style="width:100%;height:50vh;border:0;" allowfullscreen></iframe>';
2552
2553        $(detailDiscountBody).html(iframeHtml);
2554
2555    }).fail(function (jqXHR, textStatus) {
2556        console.log(jqXHR, textStatus);
2557        $(detailDiscountBody).html('<div style="padding:16px;">Unable to load voucher terms. Please try again.</div>');
2558    }).always(function () {
2559        waitingForAction(e, false);
2560    });
2561}
2562
2563function showPromotionDetail(urlPromotionDetail) {
2564    if (orderUserStep == 1) {
2565        selectService(false);
2566        return;
2567    }
2568    else {
2569        location.href = urlPromotionDetail;
2570    }
2571}
2572function showEditProductDetailDiaLog(id, productId, promotionId, step, index, variantId) {
2573    $(".edit-modifiers-desktop .func-edit-" + variantId).css("pointer-events", "none")
2574        .empty().append('<i class="fa fa-spinner fa-spin" style="position: unset;"></i>');
2575    $(".edit-modifiers-mobile .func-edit-" + variantId).append('<i class="fa fa-spinner fa-spin" style="position: unset; font-size: 14px;"></i>');
2576    $(".edit-modifiers-merchant-os .func-edit-" + variantId).append('<i class="fa fa-spinner fa-spin" style="position: unset; font-size: 14px;"></i>').find('u').hide();
2577    showProductDetailId = productId;
2578
2579    setTimeout(function () {
2580        $.ajax({
2581            type: "GET",
2582            url: urlProductDetail,
2583            data: { 'id': id, 'productId': productId, 'promotionId': promotionId, 'step': step, 'index': index, 'variantId': variantId },
2584            success: function (result) {
2585                if (result.success == false && result.message) {
2586                    location.reload();
2587                }
2588
2589                $('#productDetailModal_Body').html(result);
2590
2591                let isShowProductDetailModal = true;
2592
2593                if (typeof isMerchantOS !== 'undefined' && isMerchantOS == true) {
2594                    var productItem = JSON.parse(JSON.stringify(data));
2595
2596                    if (productItem != null && productItem.isOpenPrice == true
2597                        && (productItem.arrayModifierGroup == null || productItem.arrayModifierGroup.length == 0)
2598                        && (productItem.variantViewModels == null || productItem.variantViewModels.length == 0)
2599                    ) {
2600                        if (GetProductItemOpenPrice(productItem)) {
2601                            isShowProductDetailModal = false;
2602
2603                            $('#productDetailModal').modal('hide');
2604                        }
2605                    }
2606                }
2607
2608                if (isShowProductDetailModal == true) {
2609                    $('#productDetailModal').modal('show');
2610                }
2611
2612                if ($(window).width() < 768) {
2613                    const scrollY = document.documentElement.style.getPropertyValue('--scroll-y');
2614                    const body = document.body;
2615                    body.style.position = 'fixed';
2616                    body.style.top = `-${scrollY}`;
2617                }
2618            },
2619            error: function () {
2620                $(".edit-modifiers-desktop .func-edit-" + variantId).css("pointer-events", "initial")
2621                    .empty().append('<i class="fa fa-pencil"></i>');
2622                $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2623
2624                $(".edit-modifiers-merchant-os .func-edit-" + variantId).find('.fa-spinner').remove();
2625                $(".edit-modifiers-merchant-os .func-edit-" + variantId).find('u').show();
2626            },
2627            complete: function () {
2628                showProductDetailId = '';
2629                $(".edit-modifiers-desktop .func-edit-" + variantId).css("pointer-events", "initial")
2630                    .empty().append('<i class="fa fa-pencil"></i>');
2631                $(".edit-modifiers-mobile .func-edit-" + variantId).find('.fa-spinner').remove();
2632
2633                $(".edit-modifiers-merchant-os .func-edit-" + variantId).find('.fa-spinner').remove();
2634                $(".edit-modifiers-merchant-os .func-edit-" + variantId).find('u').show();
2635            }
2636        });
2637    }, 300);
2638}
2639
2640function hideProductDetailDiaLog() {
2641    $(document.documentElement).css('overflow', '');
2642    //$('body').css('overflow', '');
2643
2644    $('#productDetailModal').data('modal', null);
2645    $('#productDetailModal').modal('hide');
2646    $('#adjust-measurement-merchant-os').modal('hide');
2647    $('#adjust-measurement-merchant-os').find('.modal-body').html('');
2648
2649    if ($(window).width() < 768) {
2650        const body = document.body;
2651        const scrollY = body.style.top;
2652        body.style.position = '';
2653        body.style.top = '';
2654        window.scrollTo(0, parseInt(scrollY || '0') * -1);
2655    }
2656}
2657
2658function hideShowAddToCart(productId, isHide) {
2659    var buttonelementclass = `.addToCart-${productId}`;
2660    var buttonAddProduct = `.box-add-product-${productId}`;
2661    var buttonelementid = '.addToCart-Disabled-' + productId;
2662    var spanelementid = '.span-' + productId;
2663    var s_buttonelementid = '#s_addToCart-' + productId;
2664    var s_spanelementid = '#s_span-' + productId;
2665    if (isHide == true) {
2666        $(buttonelementclass).addClass("hidden");
2667        $(buttonAddProduct).addClass("hidden");
2668        $(buttonAddProduct).find(".btn-quantity-product").addClass("hidden");
2669        $(spanelementid).removeClass("hidden");
2670
2671        $(s_buttonelementid).addClass("hidden");
2672        $(s_spanelementid).removeClass("hidden");
2673    }
2674    else {
2675        if ($(buttonelementid).length == 0 || $(buttonelementid).hasClass("hidden")) {
2676            $(buttonelementid).addClass("hidden");
2677            $(buttonAddProduct).removeClass("hidden");
2678
2679            let currentQuantity = $(buttonAddProduct).find(".btn-quantity-product").find('input.quantity-product-value').val();
2680            if (currentQuantity == undefined || currentQuantity == 0) {
2681                $(buttonelementclass).removeClass("hidden");
2682                $(buttonAddProduct).find(".btn-quantity-product").addClass("hidden");
2683            }
2684            else {
2685                $(buttonelementclass).addClass("hidden");
2686                $(buttonAddProduct).find(".btn-quantity-product").removeClass("hidden");
2687            }
2688        }
2689        else {
2690            $(buttonelementid).removeClass("hidden");
2691            $(buttonelementclass).addClass("hidden");
2692        }
2693
2694        $(spanelementid).addClass("hidden");
2695
2696        $(s_buttonelementid).removeClass("hidden");
2697        $(s_spanelementid).addClass("hidden");
2698    }
2699}
2700
2701function disableAddToCart(productId) {
2702    var buttonelementclass = '.addToCart-' + productId;
2703    var buttonelementid = '.addToCart-Disabled-' + productId;
2704
2705    $(buttonelementclass).addClass("hidden");
2706    $(buttonelementid).removeClass("hidden");
2707}
2708function checkProductOutOfStock(id, productId, promotionId) {
2709    $.ajax({
2710        type: "GET",
2711        url: urlCheckProductOutOfStock,
2712        cache: false,
2713        data: { id: id, productId: productId },
2714        success: function (result) {
2715            if (result.success == true) {
2716                hideShowAddToCart(productId, result.isOutOfStock);
2717            }
2718            if (result.isInCart != true) {
2719                $(".addToCart-" + productId).html(languageButton["O_Add"]);
2720                $(".addToCart-" + productId).removeClass('btn-3-added');
2721            }
2722            else if (isShowPromotionDetail && result.isInCartOnlyPromotion != true) {
2723                $(".addToCart-" + productId).html(languageButton["O_Add"]);
2724                $(".addToCart-" + productId).removeClass('btn-3-added');
2725            }
2726        },
2727        error: function () { },
2728        beforeSend: function () { },
2729        complete: function () { }
2730    });
2731}
2732
2733function checkListProductOutOfStock(model) {
2734    $.ajax({
2735        type: "POST",
2736        url: urlCheckListProductOutOfStock,
2737        cache: false,
2738        data: {
2739            model: model
2740        },
2741        success: function (response) {
2742
2743            response.data.forEach(result => {
2744                if (result.success == true) {
2745                    hideShowAddToCart(productId, result.isOutOfStock);
2746                }
2747                if (result.isInCart != true) {
2748                    $(".addToCart-" + productId).html(languageButton["O_Add"]);
2749                    $(".addToCart-" + productId).removeClass('btn-3-added');
2750                }
2751                else if (isShowPromotionDetail && result.isInCartOnlyPromotion != true) {
2752                    $(".addToCart-" + productId).html(languageButton["O_Add"]);
2753                    $(".addToCart-" + productId).removeClass('btn-3-added');
2754                }
2755            });
2756
2757        },
2758        error: function () { },
2759        beforeSend: function () { },
2760        complete: function () { }
2761    });
2762}
2763
2764function continuePromotion(id, index, isfinishstep) {
2765    $.ajax({
2766        type: "GET",
2767        url: urlContinuePromotion,
2768        cache: false,
2769        data: { id: id, index: index, isfinishstep: isfinishstep, authorization: siteId },
2770        success: function (result) {
2771            if (result.success == true) {
2772                if (!result.isfinish) {
2773                    popupLoading = new Loading({ title: 'Loading' });
2774                    location.href = result.url;
2775                }
2776                else if (result.isfinish) {
2777                    if (isfinishstep) {
2778                        var currentUrl = window.location.href.toLowerCase();
2779                        if (result.friendly && result.friendly != '') {
2780                            if (currentUrl.indexOf(result.friendly) > 0) {
2781                                popupLoading = new Loading({ title: 'Loading' });
2782                                location.href = result.url;
2783                            }
2784                            else {
2785                                let currentUrlDecode = decodeURIComponent(currentUrl);
2786
2787                                if (currentUrlDecode.indexOf(result.friendly) > 0) {
2788                                    popupLoading = new Loading({ title: 'Loading' });
2789                                    location.href = result.url;
2790                                }
2791                            }
2792                        }
2793                        if (currentUrl.indexOf(id) > 0) {
2794                            popupLoading = new Loading({ title: 'Loading' });
2795                            location.href = result.url;
2796                        }
2797                        else {
2798                            LoadContainMyCart();
2799                        }
2800                        $("#confirmNextStepPromotion").modal('hide');
2801                    }
2802                    else {
2803                        //continuePromotion(id, index, true);
2804                        $('#confirm-url').val(result.url);
2805                        $('#confirm-promotionid').val(id);
2806                        $('#confirm-type').val('999');
2807                        $('#confirm-promotionsindex').val(index);
2808
2809                        $("#img-step-promotion").attr("src", urlLikeMedalIcon);
2810                        $(".confirm-promotion-icon").css("display", "none");
2811                        $(".confirm-promotion-icon.likemedal-promotion-icon").css("display", "initial");
2812
2813                        $("#btnNextStep").html('Yes').removeAttr("style");
2814                        $('#titleconfirmNextStep').text(localizedMessage.O_GreatChoiceAgainNowPleaseConfirmYourOrder);
2815                        $('#confirm-finishstep').val(result.isfinish.toString());
2816                        $('#btnStayHere').show(0);
2817                        $('#confirmNextStepPromotion').modal('show');
2818                    }
2819                }
2820            }
2821        },
2822        error: function (err) {
2823            $('#continue-' + id + '-' + index).html(languageButton["O_Continue"]);
2824        },
2825        beforeSend: function () {
2826            //[email protected]@promotion.promotionIndex
2827            $('#continue-' + id + '-' + index).html(languageButton["O_Continue"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
2828        },
2829        complete: function () {
2830            $('#continue-' + id + '-' + index).html(languageButton["O_Continue"]);
2831        }
2832    });
2833}
2834
2835function ResetItemHeightForLazyLoading(block) {
2836    //Re-set up the height of items
2837    var shopOnline = new ShopOnline(window, $);
2838    if (block) {
2839        shopOnline.setHeightItem(block);
2840    } else {
2841        shopOnline.fullHeightItem();
2842    }
2843}
2844
2845function CheckImagesLoadedToResetImageHeight() {
2846    var totalImages = $("body img").length;
2847    var imagesLoaded = 0;
2848
2849    $("body").find('img').each(function () {
2850        $(this).load(function () {
2851            imagesLoaded++;
2852            if (imagesLoaded >= totalImages) {
2853                // now all images are loaded.
2854                //alert("all images are loaded. Click OK to view.");
2855                ResetItemHeightForLazyLoading();
2856            }
2857        });
2858    });
2859}
2860
2861function ResetCartHeight() {
2862    //Re-set up the height of cart
2863    var shopOnline = new ShopOnline(window, $);
2864    shopOnline.initRightBar();
2865    shopOnline.setHeightRightBar();
2866
2867    if (typeof isMerchantOS !== 'undefined' && isMerchantOS == true) {
2868        $('#containmycart').find('#box-content-cart').scrollTop(scrollTopMyCart);
2869
2870        if (collapsedInforMyCart == true) {
2871            if ($('#collapseOne').hasClass('in')) {
2872                $('#btn-collapse-func').addClass('collapsed');
2873                $('#collapseOne').removeClass('in');
2874
2875                $("#box-content-cart").css("height", $("#content-cart").height() - $("#content-cart-price").height());
2876            }
2877        }
2878        else if (collapsedInforMyCart == false) {
2879            if ($('#btn-collapse-func').hasClass('collapsed')) {
2880                $('#btn-collapse-func').removeClass('collapsed');
2881                $('#collapseOne').addClass('in');
2882
2883                $("#box-content-cart").css("height", $("#content-cart").height() - 15);
2884            }
2885        }
2886    }
2887}
2888
2889function LoadContainMyCart(isAddProduct) {
2890    $.ajax({
2891        type: "GET",
2892        url: urlContainMyCart,
2893        cache: false,
2894        data: { authorization: siteId },
2895        success: function (result) {
2896            //Re-build the new content of cart
2897            $('#containmycart').html(result);
2898
2899            //Re-set up the height of cart
2900            ResetCartHeight();
2901            if (isAddProduct === true) {
2902                mobileProgressBarDilivery();
2903            }
2904
2905            // Cart HTML is replaced; re-run lazy/async image loaders so placeholders (LoaderSource GIF) resolve.
2906            if (typeof lazyLoadingImages !== 'undefined' && lazyLoadingImages && typeof echo !== 'undefined' && typeof echo.render === 'function') {
2907                echo.render();
2908            }
2909            if (typeof loadImageOriginal === 'function') {
2910                loadImageOriginal(false);
2911            }
2912        },
2913        error: function (err) { console.log(err); },
2914        beforeSend: function () {
2915            GetScrollTopMyCart();
2916        },
2917        complete: function () { }
2918    });
2919}
2920
2921function GetScrollTopMyCart() {
2922    scrollTopMyCart = $('#containmycart').find('#box-content-cart').scrollTop();
2923
2924    GetCollapsedInforMyCart();
2925}
2926
2927function GetCollapsedInforMyCart() {
2928    if ($('#btn-collapse-func').length > 0) {
2929        collapsedInforMyCart = $('#btn-collapse-func').hasClass('collapsed');
2930    }
2931}
2932
2933function LoadPaymentMyCart() {
2934    $.ajax({
2935        type: "GET",
2936        url: urlPaymentMyCart,
2937        cache: false,
2938        data: {},
2939        success: function (result) {
2940            //Re-build the new content of cart
2941            $('#paymentmycart').html(result);
2942            if (deliveryMethodSession == "Delivery") {
2943                updateDeliveryCustomerDate();
2944                updateDeliveryCustomerTime();
2945                updateDeliveryCustomerName();
2946                updateDeliveryCustomerAddess();
2947                updateDeliveryCustomerContact();
2948            }
2949            $('#ShippingFee').text($('#shippingFeeOrder').text());
2950        },
2951        error: function () { },
2952        beforeSend: function () { },
2953        complete: function () { }
2954    });
2955}
2956
2957function LoadContainTimeModal() {
2958    $.ajax({
2959        type: "GET",
2960        url: urlTimeSelectModalHome,
2961        cache: false,
2962        data: {},
2963        success: function (result) {
2964            if (!isOpenDateTime) {
2965                $('#timeModalContain').html(result);
2966            }
2967        },
2968        error: function () {
2969            //GETFIX - 406 Change copytext for PlatformM
2970            var textPickup = languageLabel["O_Pickup"];
2971            if (siteID == "af0ec0ff-a539-49ac-bdc5-6557c128a489"
2972                || siteID == "2391be96-d5f4-4edd-b5c8-9e9a8a822cd9"
2973                || siteID == "d6f9829c-91c9-48bb-8ff7-caf41124be6d"
2974                || siteID == "560bf8ac-1452-4f20-9dd4-9cec78b1536d"
2975                || siteID == "5f32c4ea-9276-4280-9496-3ee0e940e1f5") {
2976                textPickup = languageLabel["O_Takeout"];
2977            }
2978            $('#span_tab_Pick_Up').html(textPickup);
2979            $('#span_tab_Delivery').html(languageLabel["O_Delivery"]);
2980        },
2981        beforeSend: function () { },
2982        complete: function () {
2983            //GETFIX - 406 Change copytext for PlatformM
2984            var textPickup = languageLabel["O_Pickup"];
2985            if (siteID == "af0ec0ff-a539-49ac-bdc5-6557c128a489"
2986                || siteID == "2391be96-d5f4-4edd-b5c8-9e9a8a822cd9"
2987                || siteID == "d6f9829c-91c9-48bb-8ff7-caf41124be6d"
2988                || siteID == "560bf8ac-1452-4f20-9dd4-9cec78b1536d"
2989                || siteID == "5f32c4ea-9276-4280-9496-3ee0e940e1f5") {
2990                textPickup = languageLabel["O_Takeout"];
2991            }
2992            $('#span_tab_Pick_Up').html(textPickup);
2993
2994            $('#span_tab_Delivery').html(languageLabel["O_Delivery"]);
2995        }
2996    });
2997}
2998
2999function LoadContainDelivery() {
3000    $.ajax({
3001        type: "GET",
3002        url: urlDeliveryTab,
3003        cache: false,
3004        data: {},
3005        success: function (result) {
3006            $('#tab_Delivery').html(result);
3007        },
3008        error: function () {
3009            $('#span_tab_Delivery').html(languageLabel["O_Delivery"]);
3010        },
3011        beforeSend: function () { },
3012        complete: function () {
3013            $('#span_tab_Delivery').html(languageLabel["O_Delivery"]);
3014        }
3015    });
3016}
3017
3018function LoadContainPickup() {
3019    $.ajax({
3020        type: "GET",
3021        url: urlPickupTab,
3022        cache: false,
3023        data: {},
3024        success: function (result) {
3025            $('#tab_Pick_Up').html(result);
3026        },
3027        error: function () { },
3028        beforeSend: function () { },
3029        complete: function () { }
3030    });
3031}
3032
3033function LoadContainBodyMain() {
3034    if (urlBodyMain == '') {
3035        return;
3036    }
3037    //if (urlBodyMain.indexOf('Home/PartialIndex') > 0) {
3038    //    location.reload();
3039    //}
3040    //else {    
3041    $.ajax({
3042        type: "GET",
3043        url: urlBodyMain,
3044        cache: false,
3045        data: { menuId: menuId, menuType: menuType },
3046        success: function (result) {
3047            if (urlBodyMain.indexOf('Home/PartialIndex') > 0) {
3048                $('#bodyMainHome').html(result);
3049            }
3050            else {
3051                $('#bodyMain').html(result);
3052            }
3053
3054            //Re-set up the height of cart
3055            ResetCartHeight();
3056
3057            setTimeout(function () {
3058                $('.img-responsive-2').removeAttr('style');
3059                $('.img-responsive-2').attr('style', 'visibility: visible; zoom: 1; opacity: 1;');
3060            }, 400);
3061        },
3062        error: function () { },
3063        beforeSend: function () { },
3064        complete: function () { }
3065    });
3066    //}
3067}
3068
3069function LoadContainCategory(id) {
3070    var url = location.href + `&id=${id}`;
3071
3072    if (location.search == null || location.search.length == 0) {
3073        let serviceChoose = 'PickUp';
3074
3075        if (currentService == 0) {
3076            serviceChoose = 'Delivery';
3077        }
3078        else if (currentService == 2) {
3079            serviceChoose = 'Dine-in';
3080        }
3081
3082        let currentBranchChoose = '';
3083        if (settingTime != null) {
3084            currentBranchChoose = settingTime.docId;
3085        }
3086
3087        url = location.href + `?StoreID=${currentBranchChoose}&Service=${serviceChoose}&lang=${langSelect}&id=${id}`;
3088    }
3089
3090    window.location.href = url;
3091}
3092
3093function setCountOrderInMyCart(result) {
3094
3095    if (parseInt(result) > -1) {
3096        $('.q-cart-count').removeClass("hidden");
3097        $('.q-cart-count').text(result);
3098        $('.btn-homepage-cart-display .homepage-cart-display__quatity').text(result);
3099    } else {
3100        $('.q-cart-count').addClass("hidden");
3101    }
3102}
3103
3104function ajaxUpdateDeliveryAddress(address, lat, lng, callback, postal_code_find) {
3105    //console.log('ajaxUpdateDeliveryAddress', address, lat, lng, postal_code_find);
3106    $.ajax({
3107        type: "POST",
3108        data: {
3109            deliveryAddress: address,
3110            lat: lat,
3111            lng: lng,
3112            postal_code_find: postal_code_find,
3113            authorization: siteId
3114        },
3115        url: urlUpdateDeliveryAddress,
3116        success: function (result) {
3117            if (result.success) {
3118                siteID = result.siteId;
3119                gapTimeForMerchant = result.gapTimeForMerchant;
3120                if (result.isExistedItemHide) {
3121                    $('#product-in-valid').html(result.listProductInvalid);
3122                    $('#btnProductInvalidPayment').removeClass('hidden');
3123                    $('#btnProductInvalidCheckout').addClass('hidden');
3124                    $('#postalCodeModal').modal('hide');
3125                    $('#alertProductInvalid').modal('show');
3126                    return;
3127                }
3128                if (location.href.indexOf("&isRedeem=1") > -1) {
3129                    var url = location.href.replace("&isRedeem=1", "&isRedeem=0");
3130                    window.location.href = url;
3131                }
3132                else {
3133
3134                    let windowWidth = $(window).width();
3135                    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
3136                    if (windowHeight < 1) {
3137                        windowHeight = $(window).height();
3138                    }
3139                    //if (windowWidth < 768 && result.success) {
3140                    if (true && result.success) {
3141                        isClose = true;
3142                        $('#deliveryModal').modal('hide');
3143                        result.from = "UpdateDeliveryAddress";
3144                        reloadDateTimeCalendar(result);
3145                    }
3146                    else {
3147                        location.reload();
3148                    }
3149
3150                }
3151            } else {
3152                console.log(lat, lng, result)
3153                //if (result.isRetryData && lat == 0 && lng == 0) {
3154                //    doGeocodePostalCode(address, lat, lng, callback, urlGetGeoByPostalCode, postal_code_find);
3155                //}
3156                //else {
3157                ajaxTrackPostalCodeNotAvailableForDelivery(address);
3158                callback(languageMessage["O_ThePostalAddressIsNotAvailableForDeliveryYet"], address);
3159                //}
3160            }
3161
3162        },
3163        error: function (err) {
3164            console.log(err);
3165            callback(languageMessage["O_ThePostalAddressIsNotAvailableForDeliveryYet"]);
3166
3167            if (popupLoading && popupLoading.version) {
3168                popupLoading.out();
3169                popupLoading = null;
3170            }
3171        },
3172        beforeSend: function () { },
3173        complete: function () {
3174            var btn = $("#btnAddPostalCode");
3175            btn.removeAttr('disabled');
3176            var textEnter = languageButton["O_Enter"];
3177            if (!textEnter) {
3178                textEnter = "Enter";
3179            }
3180            btn.html(textEnter);
3181
3182            var btnV2 = $("#tabDelivery .btnContinue .btn");
3183            btnV2.removeAttr('disabled');
3184            textEnter = languageButton["O_Continue"];
3185            btnV2.html(textEnter);
3186
3187            if (popupLoading && popupLoading.version) {
3188                popupLoading.out();
3189                popupLoading = null;
3190            }
3191        }
3192    });
3193}
3194
3195function reloadDateTimeCalendar(result) {
3196    currentService = result.currentService;
3197    previousPopup = result.from;
3198    if (currentService == 0) {
3199        deliveryMethodSession = "Delivery";
3200    }
3201    else if (currentService == 1) {
3202        deliveryMethodSession = "Pickup";
3203    }
3204    else {
3205        deliveryMethodSession = "StationOrdering";
3206    }
3207
3208    orderType = result.currentService;
3209    stepShowCalendar = result.stepShowCalendar;
3210    currentDate = new Date(result.currentDate);
3211    timeselected = result.timeselected;
3212    deliveryTime = result.deliveryTime;
3213    settingTime = result.settingTime;
3214    listAvailableTimes = result.listAvailableTimes;
3215    preparationTime = result.preparationTime;
3216    settingBlockOut = result.settingBlockOut;
3217    autoCollectDate = new Date(result.autoCollectDate);
3218    autoCollectTime = result.autoCollectTime;
3219    isAutoRedirect = result.isAutoRedirect;
3220    autoRedirectType = result.autoRedirectType;
3221    if (isAutoRedirect && autoRedirectType == 2) {
3222        settingBlockOut = result.blockOuts;
3223        listAvailableTimes = result.outletAvailableTimes;
3224    }
3225    //if (isAutoRedirect && autoRedirectType == 3) {
3226    //    settingBlockOut = result.blockOuts;
3227    //    listAvailableTimes = result.outletAvailableTimes;
3228    //}
3229    changePostalCodeType = result.changePostalCodeType;
3230    $('#titletimepopup').text(result.serviceTitle);
3231    $('#titleselecttimepopup').text(result.serviceTitle);
3232    $('#titledatepopup').text(result.serviceTitle);
3233    $('.tabsession-postalcode').text(result.postalCode);
3234    $('.tabsession-outlettitle').text(result.outletTitle);
3235    $('.tabsession-outletaddress').text(result.outletAddress);
3236    isNeedReloadPage = true;
3237
3238    $('#settingDeliveryTime').val(settingTime.deliveryTime);
3239    $('#settingdeliveryTime3').val(settingTime.deliveryTime);
3240    var underPrepDate = new Date();
3241    $('#updateCurrentSelectedDate').val(underPrepDate.addHours(parseInt(preparationTime)));
3242    var underPrepDate3 = new Date();
3243    $('#updateCurrentSelectedDate3').val(underPrepDate3.addHours(parseInt(preparationTime3)));
3244
3245    gapTime = 60;
3246    gapTime2 = 60;
3247    gapTime3 = 60;
3248    if (currentService == 1 || currentService == 2) {
3249        gapTime = 15;
3250        gapTime2 = 15;
3251        gapTime3 = 15;
3252    }
3253    else {
3254        if ($('#settingDeliveryTime').val() != '') {
3255            gapTime = parseInt($('#settingDeliveryTime').val());
3256        }
3257        if ($('#settingdeliveryTime3').val() != '') {
3258            gapTime3 = parseInt($('#settingdeliveryTime3').val());
3259        }
3260    }
3261    if (currentService == 0 && result.postalCode) {
3262        //$('.tabsessionChangePostalCode').addClass('visible-xs');
3263        $('.tabsessionChangePostalCode').removeClass('hidden');
3264    }
3265    else {
3266        $('.tabsessionChangePostalCode').addClass('hidden');
3267        //$('.tabsessionChangePostalCode').removeClass('visible-xs');
3268    }
3269    if (result.from == 'ChooseOutlet' && autoRedirectType == 3) {
3270        $('.tabsessionChangeOutletDelivery').addClass('hidden');
3271        //$('.tabsessionChangeOutletDelivery').removeClass('visible-xs');
3272    }
3273    else if (currentService == 0 && autoRedirectType > 1 && (result.from != 'UpdateDeliveryAddress' || stepShowCalendar == 3)) {
3274        //$('.tabsessionChangeOutletDelivery').addClass('visible-xs');
3275        $('.tabsessionChangeOutletDelivery').removeClass('hidden');
3276        $('#next').removeAttr('onclick');
3277        $('#next').attr('onclick', "ShowPopupChangeOutlet('" + result.outletId + "', " + result.outletIndex + ", '" + result.outletTitle + "');");
3278    }
3279    else {
3280        $('.tabsessionChangeOutletDelivery').addClass('hidden');
3281        //$('.tabsessionChangeOutletDelivery').removeClass('visible-xs');
3282    }
3283    if (currentService == 1) {
3284        //$('.tabsessionChangeOutletPickup').addClass('visible-xs');
3285        $('.tabsessionChangeOutletPickup').removeClass('hidden');
3286    }
3287    else {
3288        $('.tabsessionChangeOutletPickup').addClass('hidden');
3289        //$('.tabsessionChangeOutletPickup').removeClass('visible-xs');
3290    }
3291    if (stepShowCalendar == 1 || stepShowCalendar == 4) {
3292        pickupInitDateSelecter(currentDate);
3293        chooseDate(0);
3294        showTimeModal(false);
3295    } else if (stepShowCalendar == 3) {
3296        dateSelected3 = new Date();
3297
3298        currentDate3 = new Date(result.currentDate);
3299        timeselected3 = result.timeselected;
3300        deliveryTime3 = result.deliveryTime;
3301        settingTime3 = result.settingTime;
3302        listAvailableTimes3 = result.listAvailableTimes;
3303        preparationTime3 = result.preparationTime;
3304        underPrepDate3 = new Date();
3305        itemsettingTime3 = {};
3306        settingBlockOut3 = result.settingBlockOut;
3307        //console.log('settingBlockOut3', settingBlockOut3);
3308        gapTime3 = 60; //Default gap time between From time and To time of Delivery is 60 mins
3309        if ($('#settingdeliveryTime3').val() != '') {
3310            gapTime3 = parseInt($('#settingdeliveryTime3').val());
3311        }
3312        autoCollectDate3 = new Date(result.autoCollectDateInitPhase2);
3313        autoCollectTime3 = result.autoCollectTimeInitPhase2;
3314        updateCurrentSelectedDate3 = new Date();
3315        pickupInitDateSelecter(currentDate3);
3316        chooseDate3(0);
3317        $('#dateModal').modal('show');
3318    } else if (changePostalCodeType == 1) {
3319        $('#outletChanged').modal('show');
3320    } else if (changePostalCodeType == 2) {
3321        //$('#dateValueSelected').text('@collect_date_display');
3322        //$('#dateValueSelected2').val('@collect_date_display');
3323        //$('#hdDateSelected').val('@collect_date_value');
3324        LoadMatchOutlet(0, '', 0, '');
3325    }
3326    else {
3327        location.reload();
3328    }
3329}
3330
3331function isValidUSZip(sZip) {
3332    //var result = /^\d{5}
3332(-\d{4})?$/.test(sZip);
3333    var result = /^\d{6}?$/.test(sZip);
3334    return result;
3335}
3336
3337function doGeocodePCFromDB(address, callback, internalUrl, postal_code_find) {
3338    $.ajax({
3339        type: "Get",
3340        url: internalUrl + '?postalCode=' + address,
3341        cache: false,
3342        success: function (res) {
3343            if (res != null) {
3344                ajaxUpdateDeliveryAddress(address, res.Latitude, res.Longitude, callback, postal_code_find);
3345            }
3346            else {
3347                callback(languageMessage["O_WrongPostalCodeOrAddress"]);
3348            }
3349        },
3350        error: function () {
3351            callback(languageMessage["O_WrongPostalCodeOrAddress"]);
3352        }
3353    });
3354}
3355
3356function doGeocodeAddress(address, lat, lng, callback, internalUrl, postal_code_find) {
3357    geocoder.geocode(
3358        {
3359            address: address,
3360            componentRestrictions: {
3361                country: 'SG'
3362            }
3363        }, function (results, status) {
3364
3365            if (status === google.maps.GeocoderStatus.OK) {
3366                ajaxUpdateDeliveryAddress(address, results[0].geometry.location.lat(), results[0].geometry.location.lng(), callback, postal_code_find);
3367            }
3368            else {
3369                $.ajax({
3370                    type: "Get",
3371                    url: internalUrl + '?postalCode=' + address,
3372                    cache: false,
3373                    success: function (res) {
3374                        if (res != null) {
3375                            ajaxUpdateDeliveryAddress(address, res.Latitude, res.Longitude, callback, postal_code_find);
3376                        }
3377                        else {
3378                            callback(languageMessage["O_WrongPostalCodeOrAddress"]);
3379                        }
3380                    },
3381                    error: function () {
3382                        callback(languageMessage["O_WrongPostalCodeOrAddress"]);
3383                    }
3384                });
3385
3386            }
3387        });
3388}
3389
3390function updateDeliveryAddress(address, lat, lng, callback, internalUrl, postal_code_find) {
3391    if (listPCUseDB.indexOf(address) >= 0) {
3392        doGeocodePCFromDB(address, callback, internalUrl, postal_code_find)
3393    } else if (!lat || !lng) {
3394        if (isValidUSZip(address)) {
3395            lat = 0;
3396            lng = 0;
3397            ajaxUpdateDeliveryAddress(address, lat, lng, callback, postal_code_find);
3398            //doGeocodePostalCodeV2(address, lat, lng, callback, internalUrl, postal_code_find);
3399        }
3400        else {
3401            doGeocodeAddress(address, lat, lng, callback, internalUrl, postal_code_find);
3402        }
3403    } else {
3404        ajaxUpdateDeliveryAddress(address, lat, lng, callback, postal_code_find);
3405    }
3406}
3407
3408var totalSessionTimeShowedPickup = 0;
3409var totalSessionTimeShowedDelivery = 0;
3410var queueStoppedPickup = [];
3411var queyeStoppedDelivery = [];
3412
3413function sessionTimeForCollect(acceptableSessionTimeInSec, id,
3414    sessionTimeRunning, sessionTimeExpired, collectDate, collectTime, collectDateTime, isDlg) {
3415    if (acceptableSessionTimeInSec == 0) {
3416        return;
3417    }
3418
3419    if (acceptableSessionTimeInSec < parseInt(Date.now() / 1000)) {
3420        reachSessionExpiredTime(sessionTimeRunning, sessionTimeExpired, collectDate,
3421            collectTime, collectDateTime, isDlg);
3422        return;
3423    }
3424
3425    var tempQueueStopped = [];
3426    var tempTotalSessionTimeShowed = 0;
3427    if (id.endsWith("Pickup")) {
3428        tempQueueStopped = queueStoppedPickup;
3429        tempTotalSessionTimeShowed = totalSessionTimeShowedPickup;
3430        ++totalSessionTimeShowedPickup;
3431    } else {
3432        tempQueueStopped = queyeStoppedDelivery;
3433        tempTotalSessionTimeShowed = totalSessionTimeShowedDelivery;
3434        ++totalSessionTimeShowedDelivery;
3435    }
3436    for (var i = 0; i < tempTotalSessionTimeShowed; ++i) {
3437        tempQueueStopped[i] = true;
3438    }
3439
3440    tempQueueStopped[tempTotalSessionTimeShowed] = false;
3441    updateSessionTimeForCollect(acceptableSessionTimeInSec - parseInt(Date.now() / 1000), id,
3442        sessionTimeRunning, sessionTimeExpired, collectDate, collectTime, collectDateTime,
3443        tempQueueStopped, tempTotalSessionTimeShowed, isDlg);
3444}
3445
3446function reachSessionExpiredTime(sessionTimeRunning, sessionTimeExpired, collectDate,
3447    collectTime, collectDateTime, isDlg) {
3448    if (isDlg !== undefined && isDlg) {
3449        $('#msgModal').modal('show');
3450        setTimeNA(collectDate, collectTime, collectDateTime);
3451        return;
3452    }
3453
3454    $("#" + sessionTimeRunning).addClass("hidden");
3455    $("#" + sessionTimeExpired).removeClass("hidden");
3456    setTimeNA(collectDate, collectTime, collectDateTime);
3457}
3458
3459function setTimeNA(collectDate, collectTime, collectDateTime) {
3460    htmlIfDefined(collectDate, "--");
3461    htmlIfDefined(collectTime, "--");
3462    htmlIfDefined(collectDateTime, "--");
3463}
3464
3465function htmlIfDefined(field, htmlContent) {
3466    if (field != undefined) {
3467        $("#" + field).html(htmlContent);
3468    }
3469}
3470
3471function updateSessionTimeForCollect(remainTime, id, sessionTimeRunning, sessionTimeExpired,
3472    collectDate, collectTime, collectDateTime, commonQueueStopped, currentSessionTimeShowed, isDlg) {
3473    var sec = remainTime % 60;
3474    var min = parseInt(remainTime / 60);
3475
3476    if (!commonQueueStopped[currentSessionTimeShowed]) {
3477        htmlIfDefined(id, padZeroIfNeeded(min) + ":" + padZeroIfNeeded(sec));
3478
3479        if (remainTime > 0) {
3480            window.setTimeout(function () {
3481                updateSessionTimeForCollect(remainTime - 1, id, sessionTimeRunning,
3482                    sessionTimeExpired, collectDate, collectTime, collectDateTime, commonQueueStopped, currentSessionTimeShowed, isDlg);
3483            }, 1000);
3484            return;
3485        }
3486
3487        reachSessionExpiredTime(sessionTimeRunning, sessionTimeExpired, collectDate,
3488            collectTime, collectDateTime, isDlg);
3489    }
3490}
3491
3492function padZeroIfNeeded(num) {
3493    var num = "0" + num;
3494    return num.substring(num.length - 2);
3495}
3496
3497function hideTooltipInSec(sec, tooltipId) {
3498    window.setTimeout(function () {
3499        hideTooltip(tooltipId);
3500    }, sec * 1000);
3501}
3502
3503function hideTooltip(tooltipId) {
3504    $("#" + tooltipId).hide();
3505}
3506
3507function searchProduct(search) {
3508    search = search.trim();
3509    if (search === undefined || search === "") {
3510        alert("Please enter text to search.");
3511
3512        return false;
3513    }
3514
3515    var url = $("#RedirectTo").val();
3516    url = url.replace("Product/", "Search/");
3517
3518    if (search.indexOf('&') > -1) {
3519        search = search.replace(new RegExp('&', 'gi'), 'ampersand_@@@');
3520    }
3521    if (search.indexOf('%') > -1) {
3522        search = search.replace(new RegExp('%', 'gi'), 'percent_@@@');
3523    }
3524    if (search.indexOf(':') > -1) {
3525        search = search.replace(new RegExp(':', 'gi'), 'colon_@@@');
3526    }
3527    if (search.indexOf('/') > -1) {
3528        search = search.replace(new RegExp('/', 'gi'), 'slash_@@@');
3529    }
3530
3531    url = url.replace("ProductGridView", search);
3532    window.location.href = url;
3533    if (search) {
3534        location.href = url;
3535    }
3536}
3537
3538function isSafariOfIOs9() {
3539    var ua = navigator.userAgent;
3540    var matches = ua.match(/^.*(iPhone|iPad).*(OS\s[0-9]).*(CriOS|Version)\/[.0-9]*\sMobile.*$/i);
3541    if (!matches) return true;
3542    else {
3543        if (matches[3] === 'CriOS') {
3544            return false;
3545        } else {
3546            if (matches[2] === 'OS 7' || matches[2] === 'OS 8') return false;
3547            else return true;
3548        }
3549    }
3550}
3551function convertFormatTime(time) {
3552    var timeValues = time.split("-");
3553    var strTime = '';
3554    if (timeValues.length == 2) {
3555        timeValues[0] = timeValues[0].trim();
3556        timeValues[1] = timeValues[1].trim();
3557        strTime = timeValues[0].toString();
3558        if (timeValues[0] >= '12:00') {
3559            var splitTimes = timeValues[0].split(":");
3560            var ampmtemp = ' PM - ';
3561            if (splitTimes.length == 2) {
3562                if (splitTimes[0] > '12') {
3563                    strTime = parseInt(splitTimes[0]) - 12;
3564                    if (strTime < 10) {
3565                        strTime = '0' + strTime;
3566                    }
3567                    if (strTime >= '12') {
3568                        strTime = parseInt(strTime) - 12;
3569                        if (strTime < 10) {
3570                            strTime = '0' + strTime;
3571                        }
3572                        ampmtemp = ' AM - ';
3573                    }
3574                    strTime = strTime + ':' + splitTimes[1];
3575                }
3576            }
3577            strTime = strTime + ampmtemp;
3578        }
3579        else {
3580            strTime = strTime + ' AM - ';
3581        }
3582
3583        var timeDisplay = strTime + timeValues[1].toString();
3584        if (timeValues[1] >= '12:00') {
3585            var splitTimes = timeValues[1].split(":");
3586            var ampmtemp = ' PM';
3587            if (splitTimes.length == 2) {
3588                if (splitTimes[0] > '12') {
3589                    var strTimeTmp = parseInt(splitTimes[0]) - 12;
3590                    if (strTimeTmp < 10) {
3591                        strTimeTmp = '0' + strTimeTmp;
3592                    }
3593                    if (splitTimes[0] >= '24') {
3594                        strTimeTmp = parseInt(strTimeTmp) - 12;
3595                        if (strTimeTmp < 10) {
3596                            strTimeTmp = '0' + strTimeTmp;
3597                        }
3598                        if (timeValues[1] != '24:00') {
3599                            ampmtemp = ' AM (Tomorrow)'
3600                        }
3601                        else if (timeValues[1] == '24:00') {
3602                            ampmtemp = ' AM';
3603                        }
3604                    }
3605                    strTimeTmp = strTimeTmp + ':' + splitTimes[1];
3606
3607                    timeDisplay = strTime + strTimeTmp;
3608                }
3609            }
3610
3611            timeDisplay = timeDisplay + ampmtemp;
3612        }
3613        else {
3614            timeDisplay = timeDisplay + ' AM';
3615        }
3616
3617        strTime = timeDisplay;
3618    }
3619    else {
3620        strTime = arrayPrepareAllowTime[i];
3621    }
3622    strTime = strTime.replace("AM", languageMessage["O_AM"]).replace("PM", languageMessage["O_PM"]);
3623    strTime = strTime.replace("AM", languageMessage["O_AM"]).replace("PM", languageMessage["O_PM"]);
3624    strTime = strTime.replace("Tomorrow", languageMessage["O_Tomorrow"]);
3625    return strTime;
3626}
3627
3628function ReloadCollectTime() {
3629    $.ajax({
3630        type: "POST",
3631        url: urlReloadCollectTime,
3632        data: {},
3633        success: function (result) {
3634            if (result.isChangeOutlet) {
3635                isSelectStation = true;
3636                $('#outletChanged').modal('show');
3637                return;
3638            }
3639            if (result.isLimitOrderByHour) {
3640                $('#fulfillmentChanged-p2').text(languageMessage["O_YourSelectedFulfillmentTimeHasBeenChanged"]);
3641                $('#fulfillmentChangedOutOfOrder').modal('show');
3642                return;
3643            }
3644            if (result.isExistedItemHide) {
3645                $('#product-in-valid').html(result.listProductInvalid);
3646                $('#btnProductInvalidPayment').removeClass('hidden');
3647                $('#btnProductInvalidCheckout').addClass('hidden');
3648                $('#alertProductInvalid').modal('show');
3649                return;
3650            }
3651
3652            location.reload();
3653        },
3654        error: function () { },
3655        beforeSend: function () {
3656        },
3657        complete: function () { }
3658    });
3659}
3660function CheckSessionTimeOut() {
3661    $.ajax({
3662        type: "POST",
3663        url: urlCheckSessionTimeOut,
3664        data: { authorization: siteId },
3665        success: function (result) {
3666            //console.log(result);
3667            if (result.success == true) {
3668                if (result.isChangeOutlet) {
3669                    isSelectStation = true;
3670                    $('#outletChanged').modal('show');
3671                }
3672                else {
3673                    if (result.dropOffTime <= 0 && result.dropOffTimeReselect <= 0) {
3674                        if (!is_switching_tab && deliveryMethodSession != 'StationOrdering') {
3675                            isSelectStation = true;
3676                            $('#fulfillmentChanged').modal('show');
3677                        }
3678                    }
3679                    else {
3680                        dropOffTime = result.dropOffTime;
3681                        if (dropOffTime <= 0) {
3682                            dropOffTimeReselect = result.dropOffTimeReselect;
3683                        }
3684                        else {
3685                            dropOffTimeReselect = dropOffTime + (5 * 60);
3686                        }
3687
3688                        buildTimerSessionTimeOut();
3689                    }
3690                }
3691            }
3692            else if (!isAmendMore) {
3693                $('#fulfillmentChanged').modal('hide');
3694                reset_countdown_timer_running_SessionTimeOut();
3695            }
3696        },
3697        error: function () { },
3698        beforeSend: function () {
3699        },
3700        complete: function () { }
3701    });
3702}
3703var dateTimeStop;
3704var timerCountdown;
3705var isSessionTimeout = true;
3706var dropOffTime = 0;
3707var dropOffTimeReselect = 1;
3708var is_countdown_timer_running_SessionTimeOut = false;
3709var is_switching_tab = false;
3710var orderType = 0;
3711function buildTimerSessionTimeOut() {
3712    //Timer is stopped -> Start Timer
3713    if (deliveryMethodSession != 'StationOrdering' && !isAmendMore) {
3714        reset_countdown_timer_running_SessionTimeOut();
3715
3716        dateTimeStop = new Date(); //don't change original date
3717        dateTimeStop.setSeconds(dateTimeStop.getSeconds() + dropOffTime);
3718        if (dropOffTime >= 1 && orderType !== 2) {
3719            startTimerSessionTimeOut();
3720        }
3721        else {
3722            if (dropOffTimeReselect <= 0) {
3723                CheckSessionTimeOut();
3724            }
3725            else {
3726                dateTimeStop = new Date(); //don't change original date
3727                if (orderType == 0) {
3728                    dateTimeStop.setSeconds(dateTimeStop.getSeconds() + dropOffTimeReselect + 60);
3729                }
3730                else if (orderType == 1) {
3731                    dateTimeStop.setSeconds(dateTimeStop.getSeconds() + dropOffTimeReselect);
3732                }
3733                else {
3734                    return;
3735                }
3736                isSessionTimeout = false;
3737                startTimerSessionTimeOut();
3738            }
3739        }
3740    }
3741}
3742function startTimerSessionTimeOut() {
3743    //console.log("Time within 5m: ", dateTimeStop);
3744    if (deliveryMethodSession != 'StationOrdering' && !isAmendMore) {
3745        is_countdown_timer_running_SessionTimeOut = true; //Timer is counting down
3746        timerCountdown = setInterval(function () {
3747            var dt = new Date();
3748            var timer = dateTimeStop - dt;
3749            timer = parseInt(timer / 1000);
3750            if (timer < 0) {
3751                is_countdown_timer_running_SessionTimeOut = false;
3752                clearInterval(timerCountdown);
3753                timer = 0;
3754                if (isSessionTimeout) {
3755                    isSelectStation = true;
3756                    if (!isOpenDateTime) {
3757                        $('#sessionTimeOut').modal('show');
3758                    }
3759                }
3760                else {
3761                    CheckSessionTimeOut();
3762                }
3763                //alert('The earliest fulfillment time will be adjusted soon. Please complete your order within 5 minutes.');
3764            }
3765            else {
3766                //console.log('countdown_timer_running', (timer - timer % 60) / 60, ':', timer % 60);
3767            }
3768        }, 1000);//1 second
3769    }
3770}
3771
3772function setTimeoutBlockoutExpired(currentUrl, blockout) {
3773
3774    if (deliveryMethodSession != 'StationOrdering') {
3775        if (blockout.enablePickup == true && blockout.earliestOrderingTimePickup > 0) {
3776            var timeout1 = (blockout.earliestOrderingTimePickup * 1000) + 60000;
3777            if (timeout1 > maxtimeout) {
3778                timeout1 = maxtimeout;
3779            }
3780            setTimeout(function () {
3781                var title = languageMessage["O_OnlineOrderingForPickupIsNowAvailable"];
3782                if (blockout.enableDelivery == true && blockout.earliestOrderingTimeDelivery == blockout.earliestOrderingTimePickup) {
3783                    title = languageMessage["O_OnlineOrderingForPickupAndDeliveryIsNowAvailable"];
3784                }
3785
3786                $('#orderingtimetitle').text(title);
3787                $('#orderingtime').modal('show');
3788                if (currentUrl.indexOf('/checkout') > 0) {
3789                    $('#ErrBlockout').addClass('hidden');
3790
3791                    if (orderType == 0) {
3792                        $('#check_payment').removeAttr('disabled');
3793                    }
3794                    else {
3795                        $('#check_paymentS').removeAttr('disabled');
3796                    }
3797                }
3798                else {
3799                    LoadContainMyCart();
3800                }
3801            }, timeout1);
3802        }
3803        if (blockout.enableDelivery == true && blockout.earliestOrderingTimeDelivery > 0 && (blockout.enablePickup != true || blockout.earliestOrderingTimeDelivery != blockout.earliestOrderingTimePickup)) {
3804            var timeout2 = (blockout.earliestOrderingTimeDelivery * 1000) + 60000;
3805            if (timeout2 > maxtimeout) {
3806                timeout2 = maxtimeout;
3807            }
3808            setTimeout(function () {
3809                var title = languageMessage["O_OnlineOrderingForDeliveryIsNowAvailable"];
3810
3811                $('#orderingtimetitle').text(title);
3812                $('#orderingtime').modal('show');
3813                if (currentUrl.indexOf('/checkout') > 0) {
3814                    $('#ErrBlockout').addClass('hidden');
3815
3816                    if (orderType == 0) {
3817                        $('#check_payment').removeAttr('disabled');
3818                    }
3819                    else {
3820                        $('#check_paymentS').removeAttr('disabled');
3821                    }
3822                }
3823                else {
3824                    LoadContainMyCart();
3825                }
3826            }, timeout2);
3827        }
3828
3829        //ordering blockout to block
3830        if (blockout.enablePickup != true && blockout.blockOrderingTimePickup > 0) {
3831            var timeout3 = (blockout.blockOrderingTimePickup * 1000) + 5000;
3832            if (timeout3 > maxtimeout) {
3833                timeout3 = maxtimeout;
3834            }
3835            setTimeout(function () {
3836                if (orderType == 1) {
3837                    if (currentUrl.indexOf('/checkout') > 0) {
3838                        $('#ErrBlockout').removeClass('hidden');
3839                        $('#check_paymentS').attr('disabled', 'disabled');
3840                    }
3841                    else {
3842                        LoadContainMyCart();
3843                    }
3844                    updateBlockout(currentUrl);
3845                }
3846            }, timeout3);
3847        }
3848        if (blockout.enableDelivery != true && blockout.blockOrderingTimeDelivery > 0) {
3849            var timeout4 = (blockout.blockOrderingTimeDelivery * 1000) + 5000;
3850            if (timeout4 > maxtimeout) {
3851                timeout4 = maxtimeout;
3852            }
3853            setTimeout(function () {
3854                if (orderType == 0) {
3855                    if (currentUrl.indexOf('/checkout') > 0) {
3856                        $('#ErrBlockout').removeClass('hidden');
3857                        $('#check_payment').attr('disabled', 'disabled');
3858                    }
3859                    else {
3860                        LoadContainMyCart();
3861                    }
3862
3863                    if (blockout.enablePickup == true || blockout.blockOrderingTimeDelivery != blockout.blockOrderingTimePickup) {
3864                        updateBlockout(currentUrl);
3865                    }
3866                }
3867            }, timeout4);
3868        }
3869
3870        if (blockout.enablePickup == true && orderType == 1 && currentUrl.indexOf('/checkout') > 0) {
3871            $('#ErrBlockout').removeClass('hidden');
3872            $('#check_paymentS').attr('disabled', 'disabled');
3873        }
3874
3875        if (blockout.enableDelivery == true && orderType == 0 && currentUrl.indexOf('/checkout') > 0) {
3876            $('#ErrBlockout').removeClass('hidden');
3877            $('#check_payment').attr('disabled', 'disabled');
3878        }
3879    }
3880}
3881function setTimeoutDeliveryPickupMethod(blockout, PickupEnable, DeliveryEnable) {
3882
3883    if (blockout && deliveryMethodSession != 'StationOrdering') {
3884        if (blockout.enablePickup == true && PickupEnable == 'True' && blockout.earliestOrderingTimePickup > 0) {
3885            var timeout1 = (blockout.earliestOrderingTimePickup * 1000) + 60000;
3886            if (timeout1 > maxtimeout) {
3887                timeout1 = maxtimeout;
3888            }
3889            setTimeout(function () {
3890                $('#btnPickup').removeAttr('disabled');
3891                deliveryMethod = 1;
3892                $('#btnDelivery').removeClass('btn-danger');
3893                $('#btnPickup').addClass('btn-danger');
3894                $('#btnPickup').removeClass('btn-default');
3895
3896                $('#btnDelivery').addClass('btn-default');
3897                $('#btnDelivery').removeClass('btn-danger');
3898                $('#btnDelivery').removeClass('btn-large');
3899
3900                if (blockout.enableDelivery == true && DeliveryEnable == 'True' && blockout.earliestOrderingTimeDelivery == blockout.earliestOrderingTimePickup) {
3901                    $('#btnDelivery').removeAttr('disabled');
3902                }
3903
3904                updateDeliveryPickupMethod(PickupEnable, DeliveryEnable);
3905            }, timeout1);
3906
3907        }
3908        if (blockout.enableDelivery == true && DeliveryEnable == 'True' && blockout.earliestOrderingTimeDelivery > 0 && (PickupEnable != 'True' || blockout.enablePickup != true || blockout.earliestOrderingTimeDelivery != blockout.earliestOrderingTimePickup)) {
3909            var timeout2 = (blockout.earliestOrderingTimeDelivery * 1000) + 60000;
3910            if (timeout2 > maxtimeout) {
3911                timeout2 = maxtimeout;
3912            }
3913            setTimeout(function () {
3914                $('#btnDelivery').removeAttr('disabled');
3915
3916                updateDeliveryPickupMethod(PickupEnable, DeliveryEnable);
3917            }, timeout2);
3918        }
3919        if (blockout.enablePickup != true && PickupEnable == 'True' && blockout.blockOrderingTimePickup > 0) {
3920            var timeout3 = (blockout.blockOrderingTimePickup * 1000) + 5000;
3921            if (timeout3 > maxtimeout) {
3922                timeout3 = maxtimeout;
3923            }
3924            setTimeout(function () {
3925                $('#btnPickup').attr('disabled', 'disabled');
3926                if (blockout.enableDelivery != true && DeliveryEnable == 'True' && blockout.blockOrderingTimePickup == blockout.blockOrderingTimeDelivery) {
3927                    $('#btnDelivery').attr('disabled', 'disabled');
3928                }
3929
3930                updateDeliveryPickupMethod(PickupEnable, DeliveryEnable);
3931            }, timeout3);
3932
3933        }
3934        if (blockout.enableDelivery != true && DeliveryEnable == 'True' && blockout.blockOrderingTimeDelivery > 0 && (PickupEnable != 'True' || blockout.enablePickup == true || blockout.blockOrderingTimePickup != blockout.blockOrderingTimeDelivery)) {
3935            var timeout4 = (blockout.blockOrderingTimeDelivery * 1000) + 5000;
3936            if (timeout4 > maxtimeout) {
3937                timeout4 = maxtimeout;
3938            }
3939            setTimeout(function () {
3940                $('#btnDelivery').attr('disabled', 'disabled');
3941
3942                updateDeliveryPickupMethod(PickupEnable, DeliveryEnable);
3943            }, timeout4);
3944        }
3945    }
3946}
3947
3948function updateBlockout(currentUrl) {
3949    $.ajax({
3950        type: "POST",
3951        url: urlBlockoutExpired,
3952        data: { authorization: siteId },
3953        cache: false,
3954        success: function (result) {
3955            blockout = result;
3956            setTimeoutBlockoutExpired(currentUrl, blockout);
3957        },
3958        error: function () { },
3959        beforeSend: function () { },
3960        complete: function () { }
3961    });
3962}
3963function updateDeliveryPickupMethod(PickupEnable, DeliveryEnable) {
3964    $.ajax({
3965        type: "POST",
3966        url: urlBlockoutExpired,
3967        data: { authorization: siteId },
3968        cache: false,
3969        success: function (result) {
3970            blockout = result;
3971            setTimeoutDeliveryPickupMethod(blockout, PickupEnable, DeliveryEnable);
3972        },
3973        error: function () { },
3974        beforeSend: function () { },
3975        complete: function () { }
3976    });
3977}
3978
3979function sendMessage(message) {
3980    $.ajax({
3981        type: "POST",
3982        url: urlSendMessage,
3983        cache: false,
3984        data: { message: message, authorization: siteId },
3985        success: function (result) {
3986        }
3987    });
3988}
3989
3990var isTrackingPostalCode = false;
3991function ajaxTrackPostalCodeNotAvailableForDelivery(postalcode) {
3992    if (!isTrackingPostalCode) {
3993        isTrackingPostalCode = true;
3994        $.ajax({
3995            type: "POST",
3996            data: {
3997                postalCode: postalcode,
3998                authorization: siteId
3999            },
4000            url: urlTrackPostalCodeNotAvailableForDelivery,
4001            success: function (result) {
4002                isTrackingPostalCode = false;
4003            },
4004            error: function () { },
4005            beforeSend: function () { },
4006            complete: function () { }
4007        });
4008    }
4009}
4010
4011var stationId = '';
4012var isSelectStation = false;
4013var enableReservation = false;
4014var isChoosingDateTime = false;
4015function goToStation(id, title, isEnableReservation, setting, outletIndex, prepareTime, status, isEstimateServingTime, isPreOrderNotification) {
4016    $('#brachIndexModalStation').modal('hide');
4017    $('#block-station-ordering').show();
4018    $('#block-reservation').show();
4019    isSelectStation = true;
4020
4021    // remove session Announcement
4022    RemoveSessionAnnouncement();
4023    var showPopupEnterOrderingInfo = CheckShowPopupEnterOrderingInfo(setting);
4024
4025    if (!prepareTime) {
4026        prepareTime = "0";
4027    }
4028    //console.log('prepareTime', prepareTime);
4029
4030    //hide station ordering section if reservation enable only
4031    if (id == "Reservation") {
4032        $('#block-station-ordering').hide();
4033    }
4034    //hide reservation section if station ordering enable only
4035    if (isEnableReservation == "0") {
4036        $('#block-reservation').hide();
4037    }
4038    if (isEnableReservation == "1") {
4039        $('#block-reservation').show();
4040        enableReservation = isEnableReservation;
4041        if (Object.prototype.toString.call(setting) == '[object String]') {
4042            setting = JSON.parse(setting);
4043        }
4044        $('#reservation-setting').val(JSON.stringify(setting));
4045        $('#reservation-outlet-index').val(outletIndex);
4046    }
4047    if (!enableReservation) {
4048        //hide reservation section
4049        $('#block-reservation').hide();
4050        $('#reservation-setting').val("");
4051        $('#reservation-outlet-index').val("");
4052    }
4053
4054    if (showPopupEnterOrderingInfo) {
4055        if (id != stationId) {
4056            //window.location = window.location.origin + "/StationOrdering/ScanQRCode/" + id;
4057            var titleWelcome = languageMessage["O_Welcometo"] + ' ' + title;
4058            $('#title-welcome-page').text(titleWelcome);
4059            $('#hdfStationId').val(id);
4060
4061            if (status == "true" && isEstimateServingTime == "true" && isPreOrderNotification == "true" && prepareTime != '0') {
4062                $('#strongPrepareTime').text(prepareTime);
4063                $('#divPrepareTime').removeClass('hidden');
4064            }
4065            else {
4066                $('#divPrepareTime').addClass('hidden');
4067            }
4068
4069            $("#modalWelcome").modal('show');
4070
4071            setTimeout(function () {
4072                if (enableReservation == "0") {
4073                    $('#totalPax').focus();
4074                }
4075            }, 1000);
4076        }
4077        else {
4078            $("#modalDineInWelcome").modal('show');
4079        }
4080    }
4081    else { //hide
4082        if (id != stationId) {
4083            //window.location = window.location.origin + "/StationOrdering/ScanQRCode/" + id;
4084            var titleWelcome = languageMessage["O_Welcometo"] + ' ' + title;
4085            $('#title-welcome-page').text(titleWelcome);
4086            $('#hdfStationId').val(id);
4087
4088            if (status == "true" && isEstimateServingTime == "true" && isPreOrderNotification == "true" && prepareTime != '0') {
4089                $('#strongPrepareTime').text(prepareTime);
4090                $('#divPrepareTime').removeClass('hidden');
4091            }
4092            else {
4093                $('#divPrepareTime').addClass('hidden');
4094            }
4095
4096            if (id == "Reservation") {
4097                var m = dateSelected2.getMonth() + 1, d = dateSelected2.getDate(), y = dateSelected2.getFullYear();
4098                var date = m + "/" + d + "/" + y;
4099
4100                isChoosingDateTime = true;
4101                SignUpDineIn('', "Reservation", 0, 'welcome', true, true, date, selectedTimeValue2, outletIndex);
4102                resetTimePicker2(new Date(autoCollectTimeReservation));
4103            }
4104            else {
4105                SignUpDineIn('', id, 0, 'welcome', true, false, null, null);
4106            }
4107        }
4108        else {
4109            if (id == "Reservation") {
4110                isChoosingDateTime = true;
4111                SignUpDineIn('', "Reservation", 0, 'welcome', true, true, date, selectedTimeValue2, outletIndex);
4112                resetTimePicker2(new Date(autoCollectTimeReservation));
4113            }
4114            else {
4115                SignUpDineIn('', id, 0, 'dinein', false);
4116            }
4117        }
4118    }
4119
4120}
4121
4122function CheckShowPopupEnterOrderingInfo(tableOrderingSetting) {
4123    if (Object.prototype.toString.call(tableOrderingSetting) == '[object String]') {
4124        tableOrderingSetting = JSON.parse(tableOrderingSetting);
4125    }
4126
4127    popupEnterOrderingInfo = tableOrderingSetting.popupEnterOrderingInfo;
4128
4129    let $modalWelcome = $("#modalWelcome, #modalDineInWelcome");
4130
4131    isSelfCollect = tableOrderingSetting.isSelfCollect;
4132    isPayLater = tableOrderingSetting.allowPayLater;
4133    isCustomServiceImage = tableOrderingSetting.isCustomServiceImage;
4134
4135    if (tableOrderingSetting.dynamicQRCodePrintSetting != null) {
4136        isGroupOrdering = tableOrderingSetting.dynamicQRCodePrintSetting.enableGroupOrdering;
4137    }
4138
4139    serviceImage = tableOrderingSetting.serviceImage;
4140    if (isSelfCollect === true) {
4141        $modalWelcome.find('.label-served').hide();
4142        $modalWelcome.find('.label-collect').show();
4143    }
4144    else {
4145        $modalWelcome.find('.label-served').show();
4146        $modalWelcome.find('.label-collect').hide();
4147    }
4148
4149    if (!popupEnterOrderingInfo.showPopupEnterOrderingInfo && !isGroupOrdering) {
4150        return false;
4151    }
4152    else {
4153
4154        if (popupEnterOrderingInfo.showEnterNumberOfPax) {
4155            $modalWelcome.find('.welcome-pax-block').show();
4156        }
4157        else {
4158            $modalWelcome.find('.welcome-pax-block').hide();
4159        }
4160
4161        if (popupEnterOrderingInfo.showEnterYourName) {
4162            $modalWelcome.find('.welcome-firstname-block').show();
4163        }
4164        else {
4165            $modalWelcome.find('.welcome-firstname-block').hide();
4166        }
4167
4168        return true;
4169    }
4170}
4171
4172function RemoveSessionAnnouncement() {
4173    $.ajax({
4174        type: "POST",
4175        url: urlRemoveSessionAnnouncement,
4176        success: function (result) {
4177        },
4178        error: function (error) { console.log(error); }
4179    });
4180}
4181
4182function goToUrl(url) {
4183    window.open(url, "_blank")
4184    //window.location.href = url;
4185}
4186
4187function goToTracker(url, id, utm_medium, lang, elementbyid, classicon) {
4188    //var url = '@Url.Action("Index", new { id= "-id-", utm_medium="-utm_medium-", lang="-lang-" })';
4189    url = url.replace("-id-", id);
4190    if (!utm_medium) {
4191        utm_medium = "";
4192    }
4193    url = url.replace("-utm_medium-", utm_medium);
4194    url = url.replace("-lang-", lang);
4195    if (elementbyid && classicon) {
4196        $('#' + elementbyid).removeClass(classicon);
4197        $('#' + elementbyid).addClass('fa-spinner');
4198        $('#' + elementbyid).addClass('fa-spin');
4199    }
4200    else if (elementbyid && elementbyid == 'iPaymentReceiptIcon') {
4201        $('#' + elementbyid).remove();
4202        var html = $('#btnPaymentReceipt').html();
4203        html = "<i class='fa fa-spinner fa-spin'></i> " + html;
4204        $('#btnPaymentReceipt').html(html);
4205    } else if (elementbyid && elementbyid == "instantDiscountBillNow") {
4206        html = "<i class='fa fa-spinner fa-spin'></i> ";
4207        $('#instantDiscount-spinner').html(html);
4208    }
4209    if (Loading) {
4210        popupLoading = new Loading({ title: 'Loading' });
4211    }
4212
4213    var authorization = (typeof siteId !== "undefined" ? siteId : "");
4214    var lowerUrl = (url || "").toLowerCase();
4215    var skipAuthForOrderPages = lowerUrl.indexOf("/orderhistory/index") >= 0 || lowerUrl.indexOf("/ordertracker/index") >= 0;
4216    if (authorization && url && url.indexOf("authorization=") < 0 && !skipAuthForOrderPages) {
4217        url += (url.indexOf("?") >= 0 ? "&" : "?") + "authorization=" + encodeURIComponent(authorization);
4218    }
4219
4220    window.location.href = url;
4221    //window.open(
4222    //    url, '_blank' // <- This is what makes it open in a new window.
4223    //);
4224}
4225
4226function loadBranchModel(isDineIn) {
4227    //goToStation
4228    if ($('.list-default-station').length == 1 && isDineIn) {
4229        var tableOrderingSetting = $('.list-enable-table-ordering-setting').first().val();
4230        if (tableOrderingSetting) {
4231            tableOrderingSetting = JSON.parse(tableOrderingSetting);
4232        }
4233
4234        goToStation($('.list-default-station').first().val(), $('.list-title-station').first().val(), $('.list-enable-reservation').first().val(), tableOrderingSetting, $('.list-outlet-index').first().val(), $('.list-outlet-preparetime').first().val(), $('.list-outlet-status').first().val(), $('.list-outlet-estimateservingtime').first().val(), $('.list-outlet-ordernotification').first().val());
4235    }
4236    else {
4237
4238        let windowWidth = $(window).width();
4239        let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
4240        if (windowHeight < 1) {
4241            windowHeight = $(window).height();
4242        }
4243        //if (windowWidth < 768) {
4244        if (true) {
4245        }
4246        else {
4247            $('#brachIndexModalStation').modal('show');
4248        }
4249    }
4250}
4251
4252window.onload = function () {
4253    let timerOnload = 500;
4254
4255    if (/iphone|ipod|ipad/.test(window.navigator.userAgent.toLowerCase())) {
4256        //timerOnload = 0;
4257    }
4258
4259
4260    var currentUrl = window.location.href.toLowerCase();
4261
4262    if (typeof history.pushState === "function") {
4263        //if (!isFirstSite) {
4264        //console.log('window.onload LoadContainMyCart');
4265        if (currentUrl.indexOf('/orderhistory') > 0
4266            || currentUrl.indexOf('/ordertracker') > 0
4267        ) { }
4268        else {
4269            setTimeout(function () {
4270                LoadContainMyCart();
4271            }, timerOnload);
4272        }
4273
4274        //}
4275        isFirstSite = false;
4276    }
4277    else {
4278        var ignoreHashChange = true;
4279        window.onhashchange = function () {
4280            //console.log('window.onhashchange LoadContainMyCart');
4281            setTimeout(function () {
4282                LoadContainMyCart();
4283            }, timerOnload);
4284        };
4285    }
4286    //console.log('window.onload', currentUrl.indexOf('/promotion/'.toLowerCase()), currentUrl.indexOf('step='.toLowerCase()));
4287    if (currentUrl.indexOf('/promotion/'.toLowerCase()) > 0 && currentUrl.indexOf('step='.toLowerCase()) > 0) {
4288        //console.log('window.onbeforeunload');
4289
4290        //console.log('window.onload', history.pushState, currentUrl);
4291        var values = currentUrl.split('?');
4292        var suburl = values[0];
4293        if (values.length > 1) {
4294            var queryurl = values[1];
4295            values = queryurl.split('&');
4296            var step = 0;
4297            for (var i = 0; i < values.length; i++) {
4298                if (values[i].indexOf('step') >= 0) {
4299                    step = parseInt(values[i].replace('step=', ''));
4300                }
4301            }
4302
4303            var id = suburl.substring(suburl.lastIndexOf('/') + 1);
4304
4305            var data = { id: id.replace('.html', ''), step: step, authorization: siteId };
4306            console.log(data);
4307            $.ajax({
4308                type: "POST",
4309                url: urlCheckPromotionDetailUrl,
4310                contentType: 'application/json; charset=UTF-8',
4311                data: JSON.stringify(data),
4312                success: function (result) {
4313                    //console.log(result);
4314                    if (result.success && result.isReload) {
4315                        location.reload();
4316                    }
4317                },
4318                error: function () { },
4319                beforeSend: function () {
4320
4321                },
4322                complete: function () {
4323                }
4324            });
4325
4326
4327        }
4328    }
4329}
4330
4331window.addEventListener("pageshow", function (event) {
4332    var historyTraversal = event.persisted || (typeof window.performance != "undefined" && window.performance.navigation.type === 2);
4333    var currentUrl = window.location.href.toLowerCase();
4334
4335    if (historyTraversal && currentUrl.indexOf('/promotion/'.toLowerCase()) > 0 && currentUrl.indexOf('step='.toLowerCase()) > 0) {
4336        // Handle page restore.
4337        window.location.reload();
4338    }
4339});
4340
4341//custom modal
4342function setModalMaxHeight(element) {
4343    this.$element = $(element);
4344    this.$content = this.$element.find('.modal-content');
4345    var borderWidth = this.$content.outerHeight() - this.$content.innerHeight();
4346    var dialogMargin = $(window).width() < 768 ? 20 : 60;
4347    var contentHeight = $(window).height() - (dialogMargin + borderWidth);
4348    var headerHeight = this.$element.find('.modal-header').outerHeight() || 0;
4349    var footerHeight = this.$element.find('.modal-footer').outerHeight() || 0;
4350    var maxHeight = contentHeight - (headerHeight + footerHeight);
4351    this.$content.css({
4352        'overflow': 'hidden'
4353    });
4354    this.$element
4355        .find('.modal-body').css({
4356            'max-height': maxHeight,
4357            //'min-height': maxHeight,
4358            'overflow-y': 'auto'
4359        });
4360}
4361var productItemTitle = '';
4362var isResetItemHeightForLazy = false;
4363$(window).resize(function () {
4364    if ($('.custom-model.in').length !== 0) {
4365        setModalMaxHeight($('.custom-model.in'));
4366    }
4367    if ($('.bodyproductdetail').length !== 0) {
4368        let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
4369        if (windowHeight < 1) {
4370            windowHeight = $(window).height();
4371        }
4372        $('.bodyproductdetail').removeAttr('style');
4373        $('#product-variant-and-modifiers').removeClass('hidden');
4374        if ($(window).width() < 768) {
4375            var pwaNavOffset = (typeof window.getPwaBottomNavOffset === 'function') ? window.getPwaBottomNavOffset() : 0;
4376            $('#productDetailModal').css('overflow-y', 'hidden').find(".modal-body").css('overflow-y', 'hidden');
4377            $('.bodyproductdetail').css({
4378                'overflow-y': 'auto',
4379                'overflow-x': 'hidden',
4380                'max-height': + (windowHeight - $('#productDetailModal').find('.header-title').innerHeight() - $('#productDetailModal').find('.product-detail-footer').innerHeight() - pwaNavOffset) + 'px'
4381            });
4382            $('#btn-NextVariantItem').attr('style', 'width: 85%');
4383            $('#btn-AddToCart').attr('style', 'width: 85%');
4384        }
4385        else {
4386            //tinh height cua title  product detail
4387            $('#productDetailModal').css('overflow-y', 'auto').find(".modal-body").css('overflow-y', 'auto');
4388            //chinh lai width cua button o product detail
4389            $('.bodyproductdetail').attr('style', 'overflow: hidden auto;max-height:' + (windowHeight - $('.header-title').height() - 190) + 'px;');
4390            if ($(window).width() < 1024) {
4391                $('#btn-NextVariantItem').attr('style', 'width: 85%');
4392                $('#btn-AddToCart').attr('style', 'width: 85%');
4393            }
4394            else {
4395                $('#btn-NextVariantItem').attr('style', 'width: 300px');
4396                $('#btn-AddToCart').attr('style', 'width: 300px');
4397            }
4398        }
4399    }
4400    //xu ly chinh lai width cua button o product detail
4401    if (!$("#btn-BackVariantItem").hasClass("hidden")) {
4402        if ($(window).width() < 1024) {
4403            $('#btn-NextVariantItem').attr('style', 'width: 85%');
4404            $('#btn-AddToCart').attr('style', 'width: 85%');
4405            $('#btn-BackVariantItem').attr('style', 'width: 120px');
4406        }
4407        else {
4408            $('#btn-NextVariantItem').attr('style', 'width: 300px');
4409            $('#btn-AddToCart').attr('style', 'width: 300px');
4410            $('#btn-BackVariantItem').attr('style', 'width: 170px');
4411        }
4412    } else {
4413        if ($(window).width() < 1024) {
4414            $('#btn-NextVariantItem').attr('style', 'width: 85%');
4415            $('#btn-AddToCart').attr('style', 'width: 85%');
4416        }
4417        else {
4418            $('#btn-NextVariantItem').attr('style', 'width: 300px');
4419            $('#btn-AddToCart').attr('style', 'width: 300px');
4420        }
4421    }
4422    var width = $(window).width();
4423    if (isResetItemHeightForLazy && width >= 768) {
4424        isResetItemHeightForLazy = false;
4425        //$('#MenuGridViewLoadMore').imagesLoaded({ background: true }, function (imgLoad) {
4426        //    //alert(imgLoad.images.length + " images loaded");
4427        //    ResetItemHeightForLazyLoading();
4428        //});
4429    }
4430    //Resize Category
4431    if ($('.item-category .row').length !== 0) {
4432        ResizeCategory(true);
4433    }
4434    if ($('.row-item-product-floating').length !== 0) {
4435        //console.log("fewffwe", $(".row-item-product-floating.loaded").length);
4436        //$(".row-item-product-floating.loaded").each(function () {
4437        //    var id = $(this).attr('id');
4438        //    $("#" + id).removeClass('loaded');
4439        //});
4440        if ($(window).width() != windowWidth) {
4441            $(".row-item-product-floating").removeClass("loaded");
4442            // Update the window width for next time
4443            windowWidth = $(window).width();
4444            // Otherwise do nothing
4445            ResizeRecommendProductFloating();
4446            // Do stuff here
4447
4448        }
4449    }
4450});
4451
4452function FocusActiveCategory(currentCategory) {
4453    let lengthScrollLeft = 0;
4454    $('#menu-tiles-mobile').find("li").each(function () {
4455        let thisLI = $(this).outerWidth() + 4;
4456        if ($(this).attr('id') === currentCategory) {
4457            lengthScrollLeft -= ($(window).outerWidth() - thisLI) / 2;
4458
4459            if (lengthScrollLeft < 0) {
4460                lengthScrollLeft = 0;
4461            }
4462
4463            $('#menu-tiles-mobile').animate({ scrollLeft: lengthScrollLeft }, 'fast');
4464            return false;
4465        }
4466        lengthScrollLeft += thisLI;
4467    });
4468}
4469
4470function GoToDiv(idCategory) {
4471    isGoing = true;
4472    var div = $('#Category_' + idCategory).offset();
4473    if (div) {
4474        var scrollTop = $('#Category_' + idCategory).position().top - $("#header .header__navbar").height();
4475        var newActive = 'li-' + idCategory;
4476        FocusActiveCategory(newActive);
4477        $('html, body').animate({ scrollTop: scrollTop }, 'slow');
4478        $('#' + categoryActive).removeClass('active');
4479        categoryActive = newActive;
4480        $('#' + newActive).addClass('active');
4481    }
4482    setTimeout(function () {
4483        isGoing = false;
4484    }, 700);
4485
4486}
4487function GoToDescriptionStar() {
4488    var div = $('#description-by-recommended').offset();
4489    if (div) {
4490        var heightTop = 150;
4491        $('html, body').animate({ scrollTop: $('#description-by-recommended').position().top - heightTop }, 'slow');
4492    }
4493}
4494var isCheckPromotion = false;
4495function checkSwichingService(orderType, isBranch, isLeave, url, ischangeservice) {
4496    if (isCheckPromotion && ischangeservice == 'True') {
4497        $.ajax({
4498            type: "POST",
4499            url: url,
4500            //contentType: 'application/json; charset=UTF-8',
4501            data: { orderType: orderType },
4502            success: function (result) {
4503                if (result.success) {
4504                    switch (orderType) {
4505                        case 0:
4506                            showInputPostalCodeModal();
4507                            break;
4508                        case 1:
4509                            checkLoadBranchModel(1, false);
4510                            break;
4511                        default:
4512                            checkLoadBranchModel(2, false, true);
4513                    }
4514                }
4515                else {
4516                    $('#confirm-type').val('3');
4517                    $('#confirm-orderType').val(orderType);
4518                    $('#confirm-isBranch').val(isBranch);
4519                    $('#confirm-isLeave').val(isLeave);
4520
4521                    $('#titleconfirmNextStep').text(result.message);
4522                    $("#btnNextStep").html('Proceed');
4523                    $('#btnStayHere').show(0);
4524                    $('#confirmNextStepPromotion').modal('show');
4525                }
4526            },
4527            error: function () { },
4528            beforeSend: function () {
4529
4530            },
4531            complete: function () {
4532            }
4533        });
4534    }
4535    else {
4536        switch (orderType) {
4537            case 0:
4538                showInputPostalCodeModal();
4539                break;
4540            case 1:
4541                checkLoadBranchModel(1, false);
4542                break;
4543            default:
4544                checkLoadBranchModel(2, false, true);
4545        }
4546    }
4547}
4548
4549function changeDateTime(orderType, isHiddeService) {
4550    hidePopup();
4551    pickupInitDatePicker();
4552    showTimeModal();
4553    return false;
4554}
4555function changeService(orderType, isHiddeService, isHostGroupOrder = false) {
4556    //console.log('changeService', orderType, isHiddeService);
4557    var deliveryMethodSessionOriginal = deliveryMethodSession;
4558    hidePopup();
4559    if (!isHiddeService) {
4560        if (orderType == 0) {
4561            deliveryMethodSession = "Delivery";
4562        }
4563        else if (orderType == 1) {
4564            deliveryMethodSession = "Pickup";
4565        }
4566        else {
4567            deliveryMethodSession = "StationOrdering";
4568        }
4569    }
4570    selectService(isHiddeService);
4571
4572    if (!isHiddeService && isHostGroupOrder == true && orderType != 0) {
4573        setTimeout(function () {
4574            $('#end-group-order-switch-modal').modal('show');
4575        }, 250);
4576    }
4577
4578    setTimeout(function () {
4579        deliveryMethodSession = deliveryMethodSessionOriginal;
4580    }, 1000);
4581}
4582function selectService(isHiddeService) {
4583    $(".session-service-item .pickupservice .fa").removeClass('fa-chevron-right');
4584    $(".session-service-item .deliveryservice .fa").removeClass('fa-pencil');
4585    $(".session-service-item .fa").addClass('fa-spinner');
4586    $(".session-service-item .fa").addClass('fa-spin');
4587    allowChangeService = !isHiddeService;
4588    console.log(allowChangeService);
4589    if (isHiddeService) {
4590        $("#tabservicepopup").addClass('hidden');
4591        $("#linemodeservicepopup").addClass('hidden');
4592        if (deliveryMethodSession == "Pickup") {
4593            $("#linkTabPickUp").trigger('click');
4594            $("#titleservicepopup").text(languageLabel["O_Pickup"]);
4595            $("#deliveryModal .modal-footer .btn").text(languageLabel['O_Confirm']);
4596            $("#tabPickup").addClass('in');
4597            $("#deliveryModal .modal-footer").removeClass('hidden');
4598        }
4599        else if (deliveryMethodSession == "Delivery") {
4600            $("#linkTabDelivery").trigger('click');
4601            $("#titleservicepopup").text(languageLabel["O_Delivery"]);
4602            //$("#deliveryModal .modal-footer .btn").text(languageLabel['O_Continue']);
4603            $("#tabDelivery").addClass('in');
4604            $("#deliveryModal .modal-footer").addClass('hidden');
4605        }
4606        else {
4607            $("#linkTabDineIn").trigger('click');
4608            $("#titleservicepopup").text(languageLabel["O_Dinein"]);
4609            $("#tabDinein").addClass('in');
4610            $("#deliveryModal .modal-footer").removeClass('hidden');
4611            $("#deliveryModal .modal-footer .btn").text(languageLabel['O_Confirm']);
4612        }
4613        outletIndexChosse = $("#hdBranchIndex").val();
4614        chooseOutletIndex(outletIndexChosse);
4615    }
4616    else {
4617        outletIndexChosse = 0;
4618        $("#tabservicepopup").removeClass('hidden');
4619        $("#linemodeservicepopup").removeClass('hidden');
4620        $("#titleservicepopup").text(languageLabel["O_SelectYourDesiredService"]);
4621        $("#deliveryModal .modal-footer").addClass('hidden');
4622        if (deliveryMethodSession == "Pickup") {
4623            $("#linkTabPickUp").trigger('click');
4624            $("#tabPickup").addClass('in');
4625        }
4626        else if (deliveryMethodSession == "Delivery") {
4627            $("#linkTabDelivery").trigger('click');
4628            $("#tabDelivery").addClass('in');
4629        }
4630        else {
4631            $("#linkTabDineIn").trigger('click');
4632            $("#tabDinein").addClass('in');
4633        }
4634    }
4635    $("#deliveryModal").modal('show');
4636}
4637
4638
4639function checkLoadBranchModel(orderType, isBranch, isLeave) {
4640    if (!isLeave && deliveryMethodSession != "Pickup" && deliveryMethodSession != "Delivery" && deliveryMethodSession != "") {
4641        $('#confirm-dinein-value-1').val(orderType);
4642        $('#confirm-dinein-value-2').val(isBranch);
4643        $('#confirmLeaveDineIn').show();
4644        return;
4645    }
4646
4647    if (isProcessingTab == true) {
4648        return;
4649    }
4650    isProcessingTab = true;
4651
4652    var order_ordertype__delivery = 0;
4653    var order_ordertype__dinein = 2;
4654    if (orderType == 2) {
4655        //$('#span_tab_Dine_In').html("<i class='fa fa-spinner fa-spin'></i>");
4656        showProcessingTab(countEnable, 3);
4657    }
4658    else if (orderType == 1) {
4659        //$('#span_tab_Pick_Up').html("<i class='fa fa-spinner fa-spin'></i>");
4660        showProcessingTab(countEnable, 1);
4661    }
4662    //if (deliveryMethodSession == "Pickup" || deliveryMethodSession == "StationOrdering") {
4663    if (deliveryMethodSession == "Pickup" && orderType == 1) {
4664        showSelectBranchModal(isBranch);
4665        return;
4666    }
4667    let windowWidth = $(window).width();
4668    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
4669    if (windowHeight < 1) {
4670        windowHeight = $(window).height();
4671    }
4672
4673    if (deliveryMethodSession == "StationOrdering" && orderType == 2) {
4674        console.log("StationOrdering");
4675        //if (windowWidth < 768) {
4676        if (true) {
4677            selectService(true);
4678        }
4679        else {
4680            loadBranchModel();
4681        }
4682        return;
4683    }
4684
4685    $.ajax({
4686        type: "POST",
4687        data: {
4688            orderType: orderType
4689        },
4690        url: urlCheckServiceAvailable,
4691        success: function (result) {
4692            if (result.success) {
4693                if (result.isAvailable) {
4694                    if (orderType == 2) {
4695                        if (result.firstName && result.firstName != '') {
4696                            SignUpDineIn(result.firstName, result.stationId, result.totalPax, true);
4697                        }
4698                        else if (result.stationId && result.stationId != '') {
4699                            goToStation(result.stationId, result.title, result.isEnableReservation, result.tableOrderingSetting, result.index);
4700                        }
4701                        else {
4702
4703                            //if ($(window).width() < 768) {
4704                            if (true) {
4705                                selectService(true);
4706                            }
4707                            else {
4708                                loadBranchModel();
4709                            }
4710                        }
4711                    }
4712                    else if (orderType !== order_ordertype__delivery) {
4713                        if (result.branchIndex && result.branchIndex > 0) {
4714                            changeBranchIndex(result.branchIndex, false);
4715                        }
4716                        else {
4717                            showSelectBranchModal(isBranch);
4718                        }
4719                    }
4720                }
4721                else {
4722                    if (orderType == 2) {
4723                        //if ($(window).width() < 768) {
4724                        if (true) {
4725                            selectService(true);
4726                        }
4727                        else {
4728                            loadBranchModel();
4729                        }
4730                    }
4731                    else if (orderType !== order_ordertype__delivery) {
4732                        showSelectBranchModal(isBranch);
4733                    }
4734                }
4735            }
4736        },
4737        error: function () { },
4738        beforeSend: function () { },
4739        complete: function () { }
4740    });
4741    //}
4742    //else {
4743    //    if (orderType == 2) {
4744    //        loadBranchModel();
4745    //    }
4746    //    else {
4747    //        showSelectBranchModal(isBranch);
4748    //    }
4749    //}
4750}
4751
4752var isClickSignUp = false;
4753function SignUpDineIn(firstname, stationId, totalPax, dinein, isCheckBeforeChange, isReservation, selectedDate, selectedTime, outletIndex, orderId, totalAdult, totalChildren) {
4754    var data = { firstname: firstname, stationId: stationId, isCheckBeforeChange: false, totalPax: totalPax, isReservation: isReservation, selectedDate: selectedDate, selectedTime: selectedTime, outletIndex: outletIndex, orderId: orderId, totalAdult: totalAdult, totalChildren: totalChildren, authorization: siteId };
4755    if (isCheckBeforeChange) {
4756        data = { firstname: firstname, stationId: stationId, isCheckBeforeChange: isCheckBeforeChange, totalPax: totalPax, isReservation: isReservation, selectedDate: selectedDate, selectedTime: selectedTime, outletIndex: outletIndex, orderId: orderId, totalAdult: totalAdult, totalChildren: totalChildren, authorization: siteId };
4757    }
4758
4759    var currentUrl = window.location.href.toLowerCase();
4760    $.ajax({
4761        type: "POST",
4762        url: urlSignUp,
4763        data: data,
4764        success: function (result) {
4765            if (result.success) {
4766                if (result.dynamicLinkUrl != null && result.dynamicLinkUrl != '') {
4767                    //console.log(result.dynamicLinkUrl);
4768                    location.href = result.dynamicLinkUrl;
4769                }
4770                else if (result.isExistedItemHide) {
4771                    //$('#product-in-valid').html(result.listProductInvalid);
4772                    //$('#btnProductInvalidPayment').removeClass('hidden');
4773                    //$('#btnProductInvalidCheckout').addClass('hidden');
4774                    //$('#modalWelcome').modal('hide');
4775                    //$('#selectTimeModal').modal('hide');
4776                    //$('#alertProductInvalid').modal('show');
4777                    location.reload();
4778                    return;
4779                }
4780                else {
4781                    isHost = true;
4782                    if (currentUrl.indexOf('/OrderHistory/Index/'.toLowerCase()) > 0 ||
4783                        currentUrl.indexOf('/OrderHistory/PaymentReceipt/'.toLowerCase()) > 0 ||
4784                        currentUrl.indexOf('/OrderHistory/MemberRegistration/'.toLowerCase()) > 0 ||
4785                        currentUrl.indexOf('/OrderHistory/MemberRegistration'.toLowerCase()) > 0) {
4786                        location.href = urlHomePage;
4787                    }
4788                    else {
4789                        //if (stationType == '2') {
4790                        //    location.reload();
4791                        //}
4792                        //else {
4793                        $('#modalWelcome').modal('hide');
4794                        location.reload();
4795                        //}
4796                    }
4797                }
4798                isScanQRCode = "False";
4799            }
4800            else if (result.url) {
4801                location.href = result.url;
4802            }
4803            else if (!result.success && result.message) {
4804                $('#confirm-type').val('6');
4805                $('#confirm-firstname').val(firstname);
4806                $('#confirm-stationId').val(stationId);
4807                $('#confirm-totalPax').val(totalPax);
4808                $('#confirm-dinein').val(dinein);
4809
4810                $('#titleconfirmNextStep').text(result.message);
4811                $("#btnNextStep").html('Proceed');
4812                $('#btnStayHere').show(0);
4813                $('#modalWelcome').modal('hide');
4814                $('#confirmNextStepPromotion').modal('show');
4815            }
4816            else {
4817                location.reload();
4818            }
4819        },
4820        error: function (error) {
4821            if (currentUrl.indexOf('/OrderHistory/Index/'.toLowerCase()) > 0) {
4822                $('#iReOrderIcon').removeClass('fa-spinner');
4823                $('#iReOrderIcon').removeClass('fa-spin');
4824                $('#iReOrderIcon').addClass('fa-qrcode');
4825            }
4826            isClickSignUp = false;
4827        },
4828        beforeSend: function () {
4829            if (currentUrl.indexOf('/OrderHistory/Index/'.toLowerCase()) > 0) {
4830                $('#iReOrderIcon').removeClass('fa-qrcode');
4831                $('#iReOrderIcon').addClass('fa-spinner');
4832                $('#iReOrderIcon').addClass('fa-spin');
4833                if (Loading) {
4834                    popupLoading = new Loading({ title: 'Redirecting' });
4835                }
4836            }
4837            else {
4838                if (isReservation) {
4839                    $('#btn-start-reserving-spinner').html("<i class='fa fa-spinner fa-spin' style='position: fixed;left: calc(50% + 70px);bottom: 12px;'></i>");
4840                } else {
4841                    if (dinein == 'dinein') {
4842                        $('#dineInSignUp').html("<input type='button' class='btn' onclick='DineInProceedSignUp();' value='" + languageLabel["O_StartOrdering"] + "' id='btnSignUp'/><i class='fa fa-spinner fa-spin white-color' style='position: fixed;left: calc(50% + 95px);bottom: 30px;'></i>");
4843                    }
4844                    else {
4845                        $('#dSignUp').html("<input type='button' class='btn' onclick='ProceedSignUp();' value='" + languageLabel["O_StartOrdering"] + "' id='btnSignUp'/><i class='fa fa-spinner fa-spin' style='position: absolute;
4845left: calc(50% + 80px);top: 13px'></i>");
4846                    }
4847                }
4848            }
4849        },
4850        complete: function () {
4851            if (currentUrl.indexOf('/OrderHistory/Index/'.toLowerCase()) > 0) {
4852                $('#iReOrderIcon').removeClass('fa-spinner');
4853                $('#iReOrderIcon').removeClass('fa-spin');
4854                $('#iReOrderIcon').addClass('fa-qrcode');
4855            }
4856            //$('#dSignUp').html("<input type='button' class='btn' onclick='ProceedSignUp();' value='Start Ordering' id='btnSignUp'/>");
4857        }
4858    });
4859}
4860
4861function SignUpDineInPayLater(firstname, stationId, totalPax, dinein, isCheckBeforeChange, isReservation, selectedDate, selectedTime, outletIndex, orderId, isReorder) {
4862    var data = { firstname: firstname, stationId: stationId, isCheckBeforeChange: false, totalPax: totalPax, isReservation: isReservation, selectedDate: selectedDate, selectedTime: selectedTime, outletIndex: outletIndex, orderId: orderId, isReorder: isReorder };
4863    if (isCheckBeforeChange) {
4864        data = { firstname: firstname, stationId: stationId, isCheckBeforeChange: isCheckBeforeChange, totalPax: totalPax, isReservation: isReservation, selectedDate: selectedDate, selectedTime: selectedTime, outletIndex: outletIndex, orderId: orderId, isReorder: isReorder };
4865    }
4866
4867    isCheckoutPayLater = false;
4868    sessionStorage.removeItem("payLaterAddMoreItems");
4869    location.reload();
4870}
4871
4872var isSelectBranch = false;
4873var isBranchModal = false;
4874function changeBranchIndex(branchIndex, isCheckBeforeChange) {
4875    isBranchModal = true;
4876    isSelectBranch = true;
4877    var btn = $("#btn-map-" + branchIndex);
4878    btn.attr('disabled', 'disabled');
4879    btn.html(languageButton["O_Select"] + ' <i class=\"fa fa-spinner fa-spin\" id=\"map-spinner-" + branchIndex + "></i>');
4880    var data = { branchIndex: branchIndex, isCheckBeforeChange: false, authorization: siteId };
4881    if (isCheckBeforeChange) {
4882        data = { branchIndex: branchIndex, isCheckBeforeChange: isCheckBeforeChange, authorization: siteId };
4883    }
4884    $.ajax({
4885        type: "POST",
4886        url: urlChangBranchIndex,
4887        data: data,
4888        success: function (result) {
4889            if (result.success) {
4890                $("#btn-map-" + branchIndex).removeAttr('disabled');
4891                $('#brachIndexModal').modal('hide');
4892            }
4893            if (!result.success && result.message) {
4894                $('#confirm-type').val('4');
4895                $('#confirm-outletIndex').val(branchIndex);
4896
4897                $('#titleconfirmNextStep').text(result.message);
4898                $("#btnNextStep").html(languageButton["O_Proceed"]);
4899                $('#btnStayHere').show(0);
4900                $('#brachIndexModal').modal('hide');
4901                $('#confirmNextStepPromotion').modal('show');
4902            }
4903            else {
4904                if (result.isExistedItemHide) {
4905                    $('#product-in-valid').html(result.listProductInvalid);
4906                    $('#btnProductInvalidPayment').removeClass('hidden');
4907                    $('#btnProductInvalidCheckout').addClass('hidden');
4908                    $('#alertProductInvalid').modal('show');
4909                    return;
4910                }
4911                //location.href = location.href.replace("&Redeem=1", "");
4912                if (location.href.indexOf("&isRedeem=1") > -1) {
4913                    var url = location.href.replace("&isRedeem=1", "&isRedeem=0");
4914                    window.location.href = url;
4915                }
4916                else {
4917
4918                    let windowWidth = $(window).width();
4919                    let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
4920                    if (windowHeight < 1) {
4921                        windowHeight = $(window).height();
4922                    }
4923                    //if (windowWidth < 768 && result.success) {
4924                    if (true && result.success) {
4925                        $('#deliveryModal').modal('hide');
4926                        result.from = "ChangeBranchIndex";
4927                        reloadDateTimeCalendar(result);
4928                    }
4929                    else {
4930                        location.reload();
4931                    }
4932
4933                }
4934            }
4935        },
4936        error: function () {
4937            if (popupLoading && popupLoading.version) {
4938                popupLoading.out();
4939                popupLoading = null;
4940            }
4941        },
4942        beforeSend: function () { },
4943        complete: function () {
4944            $(".session-service-item .fa").removeClass('fa-spinner');
4945            $(".session-service-item .fa").removeClass('fa-spin');
4946            $(".session-service-item .pickupservice .fa").addClass('fa-chevron-right');
4947            $(".session-service-item .deliveryservice .fa").addClass('fa-pencil');
4948            if (popupLoading && popupLoading.version) {
4949                popupLoading.out();
4950                popupLoading = null;
4951            }
4952        }
4953    });
4954}
4955function closeAnnouncement(id) {
4956    var data = { id: id, authorization: siteId };
4957    $.ajax({
4958        type: "POST",
4959        url: urlCloseAnnouncement,
4960        data: data,
4961        success: function (result) {
4962        },
4963        error: function () { },
4964        beforeSend: function () {
4965            if (isMainPopUpShow) {
4966                $('#sticky-announcement').remove();
4967                location.reload();
4968            }
4969        },
4970        complete: function () { }
4971    });
4972}
4973
4974
4975function closePopUpAnnouncement(id, typePopUp, typeOrder) {
4976    var data = {
4977        id: id,
4978        typePopUp: typePopUp,
4979        authorization: siteId
4980    };
4981
4982    $.ajax({
4983        type: "POST",
4984        url: urlClosePopUpAnnouncement,
4985        data: data,
4986        success: function (result) {
4987        },
4988        error: function (error) { console.log(error) },
4989        beforeSend: function () {
4990            if (typePopUp === 1) {
4991                $('#sticky-announcement').remove();
4992            }
4993        }
4994    });
4995}
4996
4997function closePopUpPromotion() {
4998    var data = {
4999        authorization: siteId
5000    };
5001
5002    $.ajax({
5003        type: "POST",
5004        url: urlClosePopUpPromotion,
5005        data: data,
5006        success: function (result) {
5007            //console.log(result);
5008            if (result.success) {
5009                $('#sticky-promotion').css('display', 'none');
5010            }
5011            else {
5012                $('#sticky-promotion').fadeIn(500);
5013                setTimeout(function () {
5014                    $('#sticky-promotion').fadeOut(500);
5015                }, 6000);
5016            }
5017        },
5018        error: function (error) { console.log(error) }
5019    });
5020}
5021function closePopUpAlertMessage() {
5022    var data = {
5023        authorization: siteId
5024    };
5025    $('#sticky-alert-message').fadeIn(500);
5026    setTimeout(function () {
5027        $('#sticky-alert-message').fadeOut(500);
5028    }, 10000);
5029    $.ajax({
5030        type: "POST",
5031        url: urlClosePopUpAlert,
5032        data: data,
5033        success: function (result) {
5034            //console.log(result);
5035            setTimeout(function () {
5036                $('#sticky-alert-message').css('display', 'none');
5037            }, 11000);
5038            if (result.success) {
5039            }
5040            else {
5041                //$('#sticky-alert-message').fadeIn(500);
5042                //setTimeout(function () {
5043                //    $('#sticky-alert-message').fadeOut(500);
5044                //}, 6000);
5045            }
5046        },
5047        error: function (error) { console.log(error) }
5048    });
5049}
5050var countEnable = 0;
5051var isProcessingTab = false;
5052function showProcessingTab(num, tab) {
5053    var styleV2 = "";
5054    var style = "";
5055    var width = $(window).width();
5056    var left = "93%";
5057    var top = "24px";
5058    var ismobile = false;
5059    if (isMobile.any() && width < 1024) {
5060        top = "11px";
5061        ismobile = true;
5062    }
5063
5064    if (num == 3) {
5065        if (tab == 1) {
5066            left = "26%";
5067            style = "position: absolute; left: 31%; top: " + top + "; z-index: 99;";
5068            if (ismobile) {
5069                style = "position: absolute; left: 25%; top: " + top + "; z-index: 99;";
5070            }
5071        }
5072        if (tab == 2) {
5073            left = "61%";
5074            style = "position: absolute; left: 61%; top: " + top + "; z-index: 99;";
5075            if (ismobile) {
5076                style = "position: absolute; left: 58%; top: " + top + "; z-index: 99;";
5077            }
5078        }
5079        if (tab == 3) {
5080            left = "93%";
5081            style = "position: absolute; left: 91%; top: " + top + "; z-index: 99;";
5082            if (ismobile) {
5083                style = "position: absolute; left: 91%; top: " + top + "; z-index: 99;";
5084            }
5085        }
5086    }
5087    else if (num == 2) {
5088        if (tab == 1) {
5089            left = "42%";
5090            style = "position: absolute; left: 44%; top: " + top + "; z-index: 99;";
5091            if (ismobile) {
5092                style = "position: absolute; left: 39%; top: " + top + "; z-index: 99;";
5093            }
5094        }
5095        if (tab == 2) {
5096            left = "93%";
5097            style = "position: absolute; left: 88%; top: " + top + "; z-index: 99;";
5098            if (ismobile) {
5099                style = "position: absolute; left: 91%; top: " + top + "; z-index: 99;";
5100            }
5101        }
5102        if (tab == 3) {
5103            style = "position: absolute; left: 75%; top: " + top + "; z-index: 99;";
5104        }
5105    }
5106    else {
5107        left = "82%";
5108        style = "position: absolute; left: 82%; top: " + top + "; z-index: 99;";
5109    }
5110    styleV2 = "position: absolute; left: " + left + "; top: 10px; z-index: 99;color: #000";
5111    //$('#iprocessingtab-V2').attr('style', styleV2);
5112    //$('#iprocessingtab').attr('style', style);
5113    $(".session-service-item .fa").addClass('fa-spinner');
5114    $(".session-service-item .fa").addClass('fa-spin');
5115    $(".session-service-item .pickupservice .fa").removeClass('fa-chevron-right');
5116    $(".session-service-item .deliveryservice .fa").removeClass('fa-pencil');
5117}
5118function hideProcessingTab() {
5119    $(".session-service-item .fa").removeClass('fa-spinner');
5120    $(".session-service-item .fa").removeClass('fa-spin');
5121    $(".session-service-item .pickupservice .fa").addClass('fa-chevron-right');
5122    $(".session-service-item .deliveryservice .fa").addClass('fa-pencil');
5123    $('#iprocessingtab-V2').attr('style', 'display:none');
5124    $('#iprocessingtab').attr('style', 'display:none');
5125}
5126
5127function autocomplete(inp, btn, arr) {
5128    var isLoadData = false;
5129    /*the autocomplete function takes two arguments,
5130    the text field element and an array of possible autocompleted values:*/
5131    var currentFocus;
5132    /*execute a function when someone writes in the text field:*/
5133    var btnClick = false;
5134    if (btn) {
5135        btn.addEventListener("click", function (e) {
5136            console.log(123123);
5137            var val = $(inp).val();
5138            if (!val) { return false; }
5139            $(inp).focus();
5140            //if (arr && arr.length > 0) {
5141            //    searchProduct(inp);
5142            //}
5143            //else
5144            if (!isLoadData) {
5145                isLoadData = true;
5146                $.ajax({
5147                    type: "POST",
5148                    url: urlSearchProductByText,
5149                    data: { authorization: siteId },
5150                    success: function (results) {
5151                        arr = results.results;
5152                        isLoadData = false;
5153                        searchProduct(inp, isLoadData);
5154                        //$( inp ).trigger( "input" );
5155                    }
5156                });
5157            }
5158            btnClick = true;
5159        });
5160    }
5161
5162    if (inp) {
5163        inp.addEventListener("input", function (e) {
5164            searchProduct(this, isLoadData);
5165        });
5166        inp.addEventListener("keyup", function (e) {
5167            if (e.which == 13) {
5168                if (arr && arr.length > 0) {
5169                    searchProduct(inp, false);
5170                }
5171                else if (!isLoadData) {
5172                    isLoadData = true;
5173                    $.ajax({
5174                        type: "POST",
5175                        url: urlSearchProductByText,
5176                        data: { authorization: siteId },
5177                        success: function (results) {
5178                            arr = results.results;
5179                            isLoadData = false;
5180                            searchProduct(inp, isLoadData);
5181                        }
5182                    });
5183                }
5184            }
5185            else if ((arr == null || arr.length == 0) && !isLoadData) {
5186                isLoadData = true;
5187                delayTimer(function () {
5188                    $.ajax({
5189                        type: "POST",
5190                        url: urlSearchProductByText,
5191                        data: { authorization: siteId },
5192                        success: function (results) {
5193                            arr = results.results;
5194                            isLoadData = false;
5195                            searchProduct(inp, isLoadData);
5196                        }
5197                    });
5198                }, 1500);
5199            }
5200        });
5201        /*execute a function presses a key on the keyboard:*/
5202        inp.addEventListener("keydown", function (e) {
5203            var x = document.getElementById(this.id + "autocomplete-list");
5204            if (x) x = x.getElementsByTagName("div");
5205            if (e.keyCode == 40) {
5206                /*If the arrow DOWN key is pressed,
5207                increase the currentFocus variable:*/
5208                currentFocus++;
5209                /*and and make the current item more visible:*/
5210                addActive(x);
5211            } else if (e.keyCode == 38) { //up
5212                /*If the arrow UP key is pressed,
5213                decrease the currentFocus variable:*/
5214                currentFocus--;
5215                /*and and make the current item more visible:*/
5216                addActive(x);
5217            } else if (e.keyCode == 13) {
5218                /*If the ENTER key is pressed, prevent the form from being submitted,*/
5219                e.preventDefault();
5220                if (currentFocus > -1) {
5221                    /*and simulate a click on the "active" item:*/
5222                    if (x) x[currentFocus].click();
5223                }
5224            }
5225        });
5226    }
5227    function addActive(x) {
5228        /*a function to classify an item as "active":*/
5229        if (!x) return false;
5230        /*start by removing the "active" class on all items:*/
5231        removeActive(x);
5232        if (currentFocus >= x.length) currentFocus = 0;
5233        if (currentFocus < 0) currentFocus = (x.length - 1);
5234        /*add class "autocomplete-active":*/
5235        x[currentFocus].classList.add("autocomplete-active");
5236    }
5237    function removeActive(x) {
5238        /*a function to remove the "active" class from all autocomplete items:*/
5239        for (var i = 0; i < x.length; i++) {
5240            x[i].classList.remove("autocomplete-active");
5241        }
5242    }
5243    function closeAllLists(elmnt) {
5244        /*close all autocomplete lists in the document,
5245        except the one passed as an argument:*/
5246        var x = document.getElementsByClassName("autocomplete-items");
5247        for (var i = 0; i < x.length; i++) {
5248            if (elmnt != x[i] && elmnt != inp) {
5249                x[i].parentNode.removeChild(x[i]);
5250            }
5251        }
5252    }
5253    function showAllLists() {
5254        /*close all autocomplete lists in the document,
5255        except the one passed as an argument:*/
5256        var x = document.getElementsByClassName("rowhidden");
5257        for (var i = 0; i < x.length; i++) {
5258            $(x[i]).removeAttr('style');
5259        }
5260    }
5261    function searchProduct(e, isLoadData = true) {
5262        var a, b, i, val = e.value;
5263        /*close any already open lists of autocompleted values*/
5264        closeAllLists();
5265        if (!val || arr.length == 0) { return false; }
5266
5267        currentFocus = -1;
5268        /*create a DIV element that will contain the items (values):*/
5269        a = document.createElement("DIV");
5270        a.setAttribute("id", e.id + "autocomplete-list");
5271        a.setAttribute("class", "autocomplete-items");
5272        /*append the DIV element as a child of the autocomplete container:*/
5273        e.parentNode.appendChild(a);
5274        /*for each item in the array...*/
5275        var searchVal = val.toUpperCase();
5276        var countResult = 0;
5277        for (i = 0; i < arr.length; i++) {
5278            /*check if the item starts with the same letters as the text field value:*/
5279            //if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
5280            var indexOfSearch = arr[i].title.toUpperCase().indexOf(searchVal);
5281            if (indexOfSearch >= 0) {
5282                //alert(indexOfSearch);
5283                countResult++;
5284                /*create a DIV element for each matching element:*/
5285                b = document.createElement("DIV");
5286                /*make the matching letters bold:*/
5287                var resultSearch = arr[i].title;
5288                var title = arr[i].title;
5289                if (indexOfSearch == 0) {
5290                    resultSearch = "<strong>" + title.substr(0, val.length) + "</strong>";
5291                    resultSearch += title.substr(val.length);
5292                }
5293                else {
5294                    resultSearch = title.substr(0, indexOfSearch);
5295                    resultSearch += "<strong>" + title.substr(indexOfSearch, val.length) + "</strong>";
5296                    resultSearch += title.substr(indexOfSearch + val.length);
5297                }
5298
5299                var str = "<DIV class='col-xs-9 text-ellipsis'>";
5300                str += resultSearch;
5301                //b.innerHTML += str;
5302                //b.innerHTML += arr[i].substr(val.length);
5303                /*insert a input field that will hold the current array item's value:*/
5304                str += "<input type='hidden' value='";
5305                str += arr[i].id;
5306                str += "'><input type='hidden' value='";
5307                str += arr[i].productId;
5308                str += "'></DIV><DIV class='col-xs-3 text-ellipsis'><span class='shym-float-right'>";
5309                //console.log(arr[i].price);
5310                if ((!isBuffet && !isBuffetDetail) || arr[i].price > 0) {
5311                    str += currency;
5312                    str += " ";
5313                    str += parseFloat(arr[i].price).toFixed(2);
5314                }
5315
5316                str += "</span></DIV>";
5317                b.innerHTML = str;
5318                if (countResult > 3) {
5319                    b.className = "autocomplete-item rowhidden";
5320                    b.style.display = "none";
5321                } else {
5322                    b.className = "autocomplete-item";
5323                }
5324                b.id = 'result-' + arr[i].id;
5325                /*execute a function when someone clicks on the item value (DIV element):*/
5326                b.addEventListener("click", function (ex) {
5327                    /*insert the value for the autocomplete text field:*/
5328                    //inp.value = this.getElementsByTagName("input")[0].value;
5329                    /*close the list of autocompleted values,
5330                    (or any other open lists of autocompleted values:*/
5331                    //closeAllLists();
5332                    var id = this.getElementsByTagName("input")[0].value;
5333                    var productId = this.getElementsByTagName("input")[1].value;
5334                    $('#result-' + id + '> div:first').prepend("<i class='fa fa-spinner fa-spin'></i>");
5335                    showProductDetailDiaLog(id, productId);
5336                    isShowProductDetail = true;
5337                });
5338                a.appendChild(b);
5339            }
5340        }
5341
5342        if (countResult > 3) {
5343            b = document.createElement("DIV");
5344            var str = "<div class='col-xs-12 text-ellipsis'><strong>" + languageLabel["O_SeeAll"] + " ";
5345            str += countResult.toString();
5346            str += " " + languageLabel["O_results"] + "</strong></div>";
5347            b.innerHTML = str;
5348            b.className = "autocomplete-item";
5349            b.addEventListener("click", function (ex) {
5350                showAllLists();
5351                //$(this).attr('style', 'display:none');
5352                $(this).remove();
5353            });
5354            a.appendChild(b);
5355        }
5356        else if (searchVal && countResult == 0 && isLoadData) {
5357            $('#myInputautocomplete-list').html('<div class="no-results-found">No results found</div>');
5358        }
5359    }
5360    /*execute a function when someone clicks in the document:*/
5361    function hideContainerOnMouseClickOut(selector, callback) {
5362        var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
5363        $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
5364            var container = $(selector);
5365            if (!container.is(e.target) // if the target of the click isn't the container...
5366                && container.has(e.target).length === 0 // ... nor a descendant of the container
5367                && $(e.target).parents('.autocomplete').length === 0) {
5368                if ($(e.target).hasClass('btn-search') || $(e.target).parents('.btn-search').length > 0) { }
5369                else {
5370                    container.hide();
5371                    $(document).off("mouseup.clickOFF touchend.clickOFF");
5372                    if (callback) callback.apply(this, args);
5373                }
5374            }
5375        });
5376    }
5377
5378    document.addEventListener("click", function (e) {
5379        hideContainerOnMouseClickOut('#myInputautocomplete-list', function (a) {
5380        });
5381    });
5382
5383    function removeParams(sParam) {
5384        var url = window.location.href.split('?')[0] + '?';
5385        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
5386            sURLVariables = sPageURL.split('&'),
5387            sParameterName,
5388            i;
5389
5390        for (i = 0; i < sURLVariables.length; i++) {
5391            sParameterName = sURLVariables[i].split('=');
5392            if (sParameterName[0] != sParam) {
5393                url = url + sParameterName[0] + '=' + sParameterName[1] + '&'
5394            }
5395        }
5396        return url.substring(0, url.length - 1);
5397    }
5398}
5399
5400function disallowItemPromo(productId) {
5401    var result;
5402    var listLimitedItemPromoAdded = [];
5403    arrayPromotionCart.forEach(function (promotion) {
5404        if (promotion.arrayProduct) {
5405            promotion.arrayProduct.forEach(function (product) {
5406                listLimitedItemPromoAdded.push(product.productID)
5407            });
5408        }
5409    });
5410
5411    if (listLimitedItemPromo.indexOf(productId) > -1) {
5412        result = 0;
5413    }
5414    if (listLimitedItemPromo.indexOf(productId) > -1 && listLimitedItemPromoAdded.indexOf(productId) > -1) {
5415        result = 1;
5416    }
5417    if (listLimitedItemPromo.indexOf(productId) === -1 && listLimitedItemPromoAdded.indexOf(productId) === -1) {
5418        result = 9;
5419    }
5420    return result;
5421}
5422
5423function checkPromoItemLimitted(productId) {
5424    if (listLimitedItemPromo.indexOf(productId) > -1) {
5425        return true;
5426    }
5427    else {
5428        return false;
5429    }
5430}
5431
5432function toggleCategoryDescription(id) {
5433    const $descCategory = $('.toggle-category-description #desc-' + id);
5434    if ($descCategory.hasClass('max-height-description-mobile')) {
5435        $descCategory.removeClass("max-height-description-mobile").css("-webkit-line-clamp", "initial");
5436    }
5437    else {
5438        $descCategory.addClass("max-height-description-mobile").removeAttr("style");
5439    }
5440}
5441
5442function toggleText(id) {
5443    $('#desc-' + id).removeAttr('style');
5444    $('#toggle-' + id).remove();
5445    $('#desc-' + id).css('cursor', 'default');
5446
5447    if ($($('#desc-' + id).parent()).parent().hasClass('lazy')) {
5448        $($($('#desc-' + id).parent()).parent()).removeAttr('style');
5449    }
5450}
5451function toggleTextMobile(id) {
5452
5453    if ($('#desc-' + id).hasClass('hidden')) {
5454        $('#desc-' + id).removeClass('hidden');
5455        $('#descfull-' + id).addClass('hidden');
5456    }
5457    else {
5458        $('#desc-' + id).addClass('hidden');
5459        $('#descfull-' + id).removeClass('hidden');
5460    }
5461}
5462var lat, lng;
5463var postal_code_find = "";
5464var selectedPostalCode = '';
5465function updatePostalCode(postalCode, postalCodeModal, isModal, showPostalCode) {
5466    if ((!selectedPostalCode || postalCode !== selectedPostalCode || postalCode == "529684")) {
5467        updateDeliveryAddress(postalCode, null, null, showPostalCode, urlGetGeoByPostalCode, postal_code_find);
5468        return false;
5469    }
5470    updateDeliveryAddress(selectedPostalCode, lat, lng, showPostalCode, urlGetGeoByPostalCode, postal_code_find);
5471    if (!isModal) {
5472        hidePostalCodeMyCartError();
5473    }
5474}
5475
5476function memberemailblur() {
5477    var email = $('#member_email').val();
5478    email = email.trim();
5479    $('#member_email').val(email);
5480}
5481
5482function memberhunIDblur() {
5483    var starhub = $('#member_starhubHUBID').val();
5484    starhub = starhub.trim();
5485    $('#member_starhubHUBID').val(starhub);
5486}
5487
5488function ResizeCategory(isLoadPage) {
5489    var itemCategory = $('.item-category .row');
5490    itemCategory.find(".row-item-category").each(function () {
5491        $(this).removeAttr('style');
5492    });
5493
5494    if ($(window).width() >= 768) {
5495        let _height = 0;
5496        itemCategory.each(function () {
5497            let that = $(this).find(".row-item-category");
5498
5499            if (isLoadPage) {
5500                _height = 0;
5501                that.each(function () {
5502                    if ($(this).height() > _height) _height = $(this).height();
5503                }).height(_height);
5504                //that.height(_height);
5505            }
5506            else {
5507                let lengthRow = that.find("img").length;
5508                let countImgLoaded = 1;
5509                that.find("img").on('load', function () {
5510                    if (lengthRow === countImgLoaded) {
5511                        that.each(function () {
5512                            $(this).removeAttr('style');
5513                        });
5514
5515                        _height = 0;
5516                        that.each(function () {
5517                            if ($(this).height() > _height) _height = $(this).height();
5518                        }).height(_height);
5519                        //that.height(_height);
5520                    }
5521                    countImgLoaded++;
5522                });
5523            }
5524        });
5525    }
5526}
5527
5528function ResizeRecommendProductFloating() {
5529    $(document).find(".row-item-product-floating").removeClass('loaded').removeAttr('style');
5530
5531    var _itemInRow = 0;
5532    if ($(window).width() > 1023) { _itemInRow = 2; }
5533    else if ($(window).width() >= 768 && $(window).width() < 1024) { _itemInRow = 1; }
5534    else if ($("#idMenuLeft").hasClass("hidden") || $('#idMenuLeft').length <= 0) { _itemInRow = 1; }
5535
5536    if (_itemInRow <= 0) {
5537        $('.row-products-floating').each(function () {
5538            $(this).find(".row-item-product-floating:not(.loaded)").each(function () {
5539                $(this).attr('style', "margin-bottom: 20px;").addClass('loaded');
5540                $(this).find(".btn-add").attr('style', "position: unset; ");
5541            });
5542        });
5543    }
5544}
5545
5546function checkAllProductOutOfStock() {
5547    $(".btn-3-added").each(function () {
5548        $(this).html(languageButton["O_Add"]).removeClass('btn-3-added');
5549    });
5550}
5551var showMeterDelivery = 0;
5552function mobileProgressBarDilivery() {
5553    if ($("#progress-dilivery").hasClass("finish-dilivery")) {
5554        showMeterDelivery++;
5555    }
5556    else {
5557        showMeterDelivery = 0;
5558    }
5559
5560    if ($(window).width() < 769 && showMeterDelivery < 2 && $("#divPostalCodeMyCart").length > 0) {
5561
5562        let showProgressBar = $("#show-progress-bar-when-add-item");
5563        let stackBottom = (typeof window.getHomepageCartStackBottom === 'function')
5564            ? window.getHomepageCartStackBottom()
5565            : ($(".homepage-cart-button-display").innerHeight() || 0);
5566        let messageGap = 8;
5567
5568        let scrollTop = $("#scroll-top");
5569        let itemDeliveryHtml = $('<div>').append($('#item_delivery').clone()).html();
5570
5571        showProgressBar.html(itemDeliveryHtml).css({
5572            "display": "block",
5573            "bottom": stackBottom + messageGap
5574        });
5575
5576        scrollTop.css("bottom", showProgressBar.outerHeight() + stackBottom + messageGap);
5577
5578        delayTimer(function () {
5579            showProgressBar.hide().html("");
5580            scrollTop.css("bottom", stackBottom + 10);
5581        }, 6500);
5582    }
5583    return;
5584}
5585
5586Date.prototype.addHours = function (h) {
5587    this.setTime(this.getTime() + (h * 60 * 60 * 1000));
5588    return this;
5589}
5590Date.prototype.addMinutes = function (minutes) {
5591    this.setMinutes(this.getMinutes() + minutes);
5592    return this;
5593};
5594
5595//Altered code to convert Date obj to string with format "MMDDYY" 
5596Date.prototype.MMDDYYYY = function () {
5597    var yyyy = this.getFullYear().toString();
5598    if (yyyy == '' || parseInt(yyyy) < 1970) {
5599        yyyy = '1970';
5600    }
5601    var mm = (this.getMonth() + 1).toString(); //getMonth() is zero-based
5602    var dd = this.getDate().toString();
5603    return (mm[1] ? mm : "0" + mm[0]) + "/" + (dd[1] ? dd : "0" + dd[0]) + "/" + yyyy; //padding
5604};
5605Date.prototype.DDMMMYY = function () {
5606    var yyyy = this.getFullYear().toString();
5607    if (yyyy == '' || parseInt(yyyy) < 1970) {
5608        yyyy = '1970';
5609    }
5610    var yy = yyyy.substring(yyyy.length - 2, yyyy.length);
5611
5612    var monthNames = ["Jan", "Feb", "Mar", "Apr",
5613        "May", "Jun", "Jul", "Aug",
5614        "Sep", "Oct", "Nov", "Dec"];
5615
5616    let monthIndex = this.getMonth();
5617    let monthName = monthNames[monthIndex];
5618
5619    var dd = this.getDate().toString();
5620
5621    return (dd[1] ? dd : "0" + dd[0]) + " " + monthName + ", " + yy; //padding
5622}
5623Date.prototype.MMMMYY = function () {
5624    var yyyy = this.getFullYear().toString();
5625    if (yyyy == '' || parseInt(yyyy) < 1970) {
5626        yyyy = '1970';
5627    }
5628    var monthNames = ["January", "February", "March", "April", "May", "June",
5629        "July", "August", "September", "October", "November", "December"
5630    ];
5631    let monthIndex = this.getMonth();
5632    let monthName = monthNames[monthIndex];
5633
5634    return monthName + " " + yyyy;
5635}
5636
5637function convertToJsDate(netDateValue) {
5638    var regex = /-?\d+/;
5639    var m = regex.exec(netDateValue);
5640    return new Date(parseInt(m[0]));
5641}
5642
5643function formatDateStringyyyyMMdd(date) {
5644    return date.getFullYear() + '/' + (("0" + (date.getMonth() + 1)).slice(-2)) + '/' + ("0" + date.getDate()).slice(-2);
5645}
5646
5647function isInDiscountRange(d, r) {
5648    var date = new Date(d);
5649    var dateString = formatDateStringyyyyMMdd(date);
5650    var found = $.inArray(dateString, r) > -1;
5651    if (found) {
5652        return true;
5653    }
5654
5655    return false;
5656}
5657
5658function GetBlockOutFromSelectedDate(blockOuts, selectedDate) {
5659    var blockOutIsChoose = [];
5660    if (blockOuts) {
5661        for (var i = 0; i < blockOuts.length; i++) {
5662            var beginDate = blockOuts[i].beginDateString.split("T")[0];
5663            var beginTime = blockOuts[i].beginDateString.split("T")[1];
5664            var endDate = blockOuts[i].endDateString.split("T")[0];
5665            var endTime = blockOuts[i].endDateString.split("T")[1];
5666
5667            var beginDay = parseInt(beginDate.split("-")[2]);
5668            var beginMonth = parseInt(beginDate.split("-")[1]) - 1;
5669            var beginYear = parseInt(beginDate.split("-")[0]);
5670
5671            var endDay = parseInt(endDate.split("-")[2]);
5672            var endMonth = parseInt(endDate.split("-")[1]) - 1;
5673            var endYear = parseInt(endDate.split("-")[0]);
5674
5675            beginDate = new Date(beginYear, beginMonth, beginDay, 0, 0, 0, 0);
5676            endDate = new Date(endYear, endMonth, endDay, 0, 0, 0, 0);
5677
5678            if (selectedDate >= beginDate && selectedDate <= endDate) {
5679                blockOuts[i].beginDate = new Date(beginYear, beginMonth, beginDay, beginTime.split(":")[0], beginTime.split(":")[1], beginTime.split(":")[2], 0);
5680                blockOuts[i].endDate = new Date(endYear, endMonth, endDay, endTime.split(":")[0], endTime.split(":")[1], endTime.split(":")[2], 0);;
5681                blockOutIsChoose.push(blockOuts[i]);
5682            }
5683        }
5684    }
5685    return blockOutIsChoose;
5686}
5687
5688function CheckSeletecdDateIsBeginOrEnd(blockOut, selectedDate) {
5689    if (selectedDate.getMonth() == blockOut.beginDate.getMonth()
5690        && selectedDate.getDate() == blockOut.beginDate.getDate()
5691        && selectedDate.getFullYear() == blockOut.beginDate.getFullYear()) {
5692        return 0;
5693    } else if (selectedDate.getMonth() == blockOut.endDate.getMonth()
5694        && selectedDate.getDate() == blockOut.endDate.getDate()
5695        && selectedDate.getFullYear() == blockOut.endDate.getFullYear()) {
5696        return 2;
5697    } else {
5698        return 1;
5699    }
5700}
5701
5702function addZero(i) {
5703    if (i < 10) {
5704        i = "0" + i;
5705    }
5706    return i;
5707}
5708function convertTimeToMinute(time) {
5709    if (time) {
5710        var arrayTime = time.split(":");
5711        return parseInt(arrayTime[0]) * 60 + parseInt(arrayTime[1]);
5712    }
5713}
5714
5715function checkSlotHasInBlockOut(beginBlockTime, endBlockTime, firstSlot, SecondSlot) {
5716    //TKPOS-14674
5717    //[MP][OS] Revamp Blockout Date / Time
5718    return (convertTimeToMinute(firstSlot) >= convertTimeToMinute(beginBlockTime) && convertTimeToMinute(firstSlot) <= convertTimeToMinute(endBlockTime));
5719    //return (convertTimeToMinute(firstSlot) >= convertTimeToMinute(beginBlockTime) && convertTimeToMinute(firstSlot) < convertTimeToMinute(endBlockTime))
5720    //    || (convertTimeToMinute(SecondSlot) >= convertTimeToMinute(beginBlockTime) && convertTimeToMinute(SecondSlot) <= convertTimeToMinute(endBlockTime))
5721
5722    //return (convertTimeToMinute(firstSlot) >= convertTimeToMinute(beginBlockTime)
5723    //    && convertTimeToMinute(firstSlot) <= convertTimeToMinute(endBlockTime)) ||
5724    //    (convertTimeToMinute(SecondSlot) >= convertTimeToMinute(beginBlockTime)
5725    //        && convertTimeToMinute(SecondSlot) <= convertTimeToMinute(endBlockTime))
5726}
5727
5728function UpdateArrayPrepareAllowTime(arrayPrepareAllowTime, blockOut, selectedDate) {
5729    var typeSelectedDate = CheckSeletecdDateIsBeginOrEnd(blockOut, selectedDate);
5730    if (typeSelectedDate == 1) {
5731        arrayPrepareAllowTime = null;
5732    }
5733    return arrayPrepareAllowTime;
5734}
5735
5736function GetBeginTimeAndEndTimeOfBlockOut(arrayPrepareAllowTime, blockOut, selectedDate) {
5737    var typeSelectedDate = CheckSeletecdDateIsBeginOrEnd(blockOut, selectedDate);
5738    //selected date == beginDate
5739    var mb = blockOut.beginDate.getMonth(), db = blockOut.beginDate.getDate(), yb = blockOut.beginDate.getFullYear();
5740    var me = blockOut.endDate.getMonth(), de = blockOut.endDate.getDate(), ye = blockOut.endDate.getFullYear();
5741    if (typeSelectedDate == 0) {
5742        //if(blockOut.beginDate.getDate()<blockOut.endDate.getDate()){
5743        //    // Get the first slot is begin time and last slot is last slot
5744        //    beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5745        //    endBlockTime = arrayPrepareAllowTime[arrayPrepareAllowTime.length-1].split("-")[1].replace(' ', '');
5746        //}else{
5747        //    // Get the first slot is begin time and last slot is end time
5748        //    beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5749        //    endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5750        //}
5751        if (mb == me && db == de && yb == ye) {
5752            // Get the first slot is begin time and last slot is end time
5753            beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5754            endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5755        } else {
5756            // Get the first slot is begin time and last slot is last slot
5757            beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5758            endBlockTime = arrayPrepareAllowTime[arrayPrepareAllowTime.length - 1].split("-")[1].replace(' ', '');
5759        }
5760
5761    }//selected date == endDate
5762    else if (typeSelectedDate == 2) {
5763        //if(blockOut.beginDate.getDate()<blockOut.endDate.getDate()){
5764        //    // Get the first slot is the first element in array and last slot is the end time
5765        //    beginBlockTime = arrayPrepareAllowTime[0].split("-")[1].replace(' ', '');
5766        //    endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5767
5768        //}else{
5769        //    // Get the first slot is begin time and last slot is end time
5770        //    beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5771        //    endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5772        //}
5773        if (mb == me && db == de && yb == ye) {
5774            // Get the first slot is begin time and last slot is end time
5775            beginBlockTime = addZero(blockOut.beginDate.getHours()) + ":" + addZero(blockOut.beginDate.getMinutes());
5776            endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5777        } else {
5778            // Get the first slot is the first element in array and last slot is the end time
5779            beginBlockTime = arrayPrepareAllowTime[0].split("-")[0].replace(' ', '');
5780            endBlockTime = addZero(blockOut.endDate.getHours()) + ":" + addZero(blockOut.endDate.getMinutes());
5781        }
5782
5783    }//selected date == middle
5784    //else{
5785    //    arrayPrepareAllowTime = null;
5786    //}
5787    //return arrayPrepareAllowTime;
5788}
5789
5790function getDateTwoYearsLater(d) {
5791    var mm = '' + (d.getMonth() + 1),
5792        dd = '' + d.getDate(),
5793        yyyy = d.getFullYear() + 2;
5794
5795    if (mm.length < 2)
5796        mm = '0' + mm;
5797    if (mm === '02' && dd === '29')
5798        dd = '28';
5799    else if (dd.length < 2)
5800        dd = '0' + dd;
5801
5802    return yyyy + '/' + mm + '/' + dd;
5803}
5804
5805var listTimeBasedDiscounts = null;
5806function displayPromotions() {
5807    if (listTimeBasedDiscounts) {
5808        for (var i = 0; i < listTimeBasedDiscounts.length; i++) {
5809            listTimeBasedDiscounts[i] = listTimeBasedDiscounts[i].substr(0, 10);
5810        }
5811        $(".xdsoft_date").val(function () {
5812            var ds = ($(this).data('month') + 1) + '/' + $(this).data('date') + '/' + $(this).data('year');
5813            if (isInDiscountRange(ds, listTimeBasedDiscounts)) {
5814                if ($(this).find('span.promotionMark')) {
5815                    $(this).find('span.promotionMark').remove();
5816                }
5817                $(this).prepend('<span class="promotionMark"></span>');
5818            }
5819        });
5820    }
5821}
5822function LoadMatchOutlet(popupType, id, outletIndex, displayName, fromtype) {
5823
5824    if (!isChooseDate) {
5825        //console.log('LoadMatchOutlet', popupType, id, outletIndex, displayName, fromtype);
5826        isChooseDate = true;
5827        var htmlSort = $("#spanSort").html();
5828        var sort = $('#dropdown-sort-selecter :selected').val();
5829        if (fromtype == 2) {
5830            sort = $('#dropdown-sort-selecter2 :selected').val();
5831        }
5832        let windowWidth = $(window).width();
5833        let windowHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0
5833);
5834        if (windowHeight < 1) {
5835            windowHeight = $(window).height();
5836        }
5837        $.ajax({
5838            type: "GET",
5839            url: urlPartialMatchOutlets,
5840            data: { dateSelected: $('#hdDateSelected').val(), sort: sort },
5841            success: function (result) {
5842                if (result) {
5843                    //if ($(window).width() < 768) {
5844                    if (true) {
5845                        $('#listMatchOutlets').html('');
5846                        $('#selecter-outlet').html(result);
5847                    }
5848                    else {
5849                        $('#selecter-outlet').html('');
5850                        $('#listMatchOutlets').html(result);
5851
5852                        $('.matchoutletrow').removeClass('selectedoutlet');
5853                        $('#currentSelectedOutlet').val('');
5854                        $('#lbCurrentSelectedOutlet').text('');
5855                    }
5856                }
5857                if (popupType == 0) {
5858                    //if ($(window).width() < 768) {
5859                    if (true) {
5860                        $('#outletsModal').modal('hide');
5861                        $('#dateModal').modal('show');
5862                    }
5863                    else {
5864                        $('#dateModal').modal('hide');
5865                        $('#outletsModal').modal('show');
5866                        if (id && displayName) {
5867                            setTimeout(function () {
5868                                SelectedMatchOutlet(id, outletIndex)
5869                            }, 500);
5870                        }
5871                    }
5872                }
5873            },
5874            error: function () {
5875                if (popupType == 0) {
5876                    //if ($(window).width() < 768) {
5877                    if (true) {
5878                        $('#outletsModal').modal('hide');
5879                        $('#dateModal').modal('show');
5880                    }
5881                    else {
5882                        $('#outletsModal').modal('hide');
5883                        $('#dateModal').modal('show');
5884                    }
5885                }
5886                isChooseDate = false;
5887            },
5888            beforeSend: function () {
5889                //if ($(window).width() < 768) {
5890                if (true) {
5891                }
5892                else {
5893                    if (popupType == 0) {
5894                        $("#btnSubmit3").html(languageButton["O_Done"] + ' <i class=\"fa fa-spinner fa-spin\"></i>');
5895                    }
5896                    if (popupType == 1) {
5897                        $("#spanSort").html('<i class=\"fa fa-spinner fa-spin\"></i>');
5898                    }
5899                }
5900            },
5901            complete: function () {
5902                //if ($(window).width() < 768) {
5903                if (true) {
5904                }
5905                else {
5906                    if (popupType == 0) {
5907                        $("#btnSubmit3").html(languageButton["O_Done"]);
5908                    }
5909                    if (popupType == 1) {
5910                        $("#spanSort").html('<i class=\"fa fa-sort-amount-desc\" aria-hidden=\"true\"></i>');
5911                    }
5912                }
5913                isChooseDate = false;
5914            }
5915        });
5916    }
5917}
5918function checkCancelPromotion(promotionId, message) {
5919    //CheckCancelPromotion
5920    $('#titleconfirmCancelPromotion').text(message);
5921    $.ajax({
5922        type: "POST",
5923        url: urlValidCancelPromotion,
5924        data: { promotionId: promotionId, authorization: siteId },
5925        success: function (result) {
5926            if (result.status) {
5927                //list and show popup
5928                generatorHtmlConfirmItem(result.arrayProduct, "#listPromotionToCart", "#confirmCancelPromotion");
5929            }
5930            else {
5931                //home page
5932                var url = urlIndexHome; // + 'Home/Index';
5933                window.location.href = url;
5934            }
5935        },
5936        error: function (error) {
5937            console.log('error: ', error);
5938        }
5939    });
5940};
5941
5942function generatorHtmlConfirmItem(arrayProduct, elementListProduct, elementPromotionPopup) {
5943
5944    if (!elementListProduct) {
5945        elementListProduct = "#listPromotionToCart";
5946    }
5947    if (!elementPromotionPopup) {
5948        elementPromotionPopup = "#confirmCancelPromotion";
5949    }
5950    var item = '';
5951    for (var i = 0; i < arrayProduct.length; i++) {
5952        item += '<div>' + '- ' + arrayProduct[i] + '</div>';
5953    }
5954    $(elementListProduct).html(item);
5955    $(elementPromotionPopup).modal('show');
5956}
5957
5958function isFacebookApp() {
5959    var ua = navigator.userAgent || navigator.vendor || window.opera;
5960    return (ua.indexOf("FBAN") > -1) || (ua.indexOf("FBAV") > -1);
5961}
5962
5963function redirectMemberUrl(currentUrl, outletIndex = 0, isPaylater = false, serviceType = "") {
5964    if (currentUrl == null || currentUrl == undefined || currentUrl.length == 0) {
5965        currentUrl = window.location.href;
5966    }
5967
5968    if (typeof ensurePwaClientCookie === 'function') {
5969        ensurePwaClientCookie();
5970    }
5971
5972    // Standalone: before sending the user through a full GetzPay login page, try to
5973    // silently resume using the locally cached JWT (still valid, or refreshable via
5974    // ValidateAndRefreshToken). The classic header only knows about the short-lived
5975    // server session, which may have expired ~30min ago even though the device's
5976    // cached token is still good. Only fall back to the full redirect if that fails.
5977    if (typeof isPwaStandaloneMode === 'function' && isPwaStandaloneMode()) {
5978        attemptStandaloneSilentLogin(outletIndex, function (success) {
5979            if (success) {
5980                location.reload();
5981                return;
5982            }
5983            performFullMemberLogin();
5984        });
5985        return;
5986    }
5987
5988    performFullMemberLogin();
5989
5990    function performFullMemberLogin() {
5991    // Some checkout/cart callers pass a relative return URL without the page query string.
5992    // Preserve PWA context from the actual browser URL in both the return URL and callback.
5993    var pageUrlParams = new URL(window.location.href).searchParams;
5994    var isStandalonePwa = typeof isPwaStandaloneMode === 'function' && isPwaStandaloneMode();
5995    if (pageUrlParams.get('fromPwa') === '1' || isStandalonePwa) {
5996        var returnUrl = new URL(currentUrl, window.location.origin);
5997        if (returnUrl.origin === window.location.origin) {
5998            returnUrl.searchParams.set('fromPwa', '1');
5999            currentUrl = returnUrl.toString();
6000        }
6001    }
6002    var isPwaLogin = new URL(currentUrl, window.location.origin)
6003        .searchParams.get('fromPwa') === '1'
6004        || isStandalonePwa;
6005
6006    var authorization = (typeof siteId !== "undefined" ? siteId : "");
6007    var lowerCurrent = (currentUrl || "").toLowerCase();
6008    var skipAuthForOrderPages = lowerCurrent.indexOf("/orderhistory/index") >= 0 || lowerCurrent.indexOf("/ordertracker/index") >= 0;
6009    if (authorization && currentUrl && currentUrl.indexOf("authorization=") < 0 && !skipAuthForOrderPages) {
6010        currentUrl += (currentUrl.indexOf("?") >= 0 ? "&" : "?") + "authorization=" + encodeURIComponent(authorization);
6011    }
6012
6013    let orderId = '';
6014    if ($('#hdOrderId') != null && $('#hdOrderId').length > 0) {
6015        orderId = $('#hdOrderId').val();
6016    }
6017
6018    if (outletIndex == 0 && $('#reservation-outlet-index') != null && $('#reservation-outlet-index').length > 0) {
6019        outletIndex = $('#reservation-outlet-index').val();
6020    }
6021
6022    $.ajax({
6023        type: "POST",
6024        url: urlLogInMember,
6025        data: {
6026            outletIndex: outletIndex,
6027            isPaylater: isPaylater,
6028            url: currentUrl,
6029            orderId: orderId
6030        },
6031        success: function (result) {
6032            if (result.status == true) {
6033                console.log(deliveryMethodSession);
6034                console.log("1111");
6035
6036                var signupType = "";
6037                if (isPwaLogin) {
6038                    serviceType = "Online Member Portal";
6039                }
6040                else if (deliveryMethodSession && (!serviceType || serviceType == null || serviceType == undefined)) {
6041
6042                    if (deliveryMethodSession == "StationOrdering") {
6043                        serviceType = "Instore QR";
6044                        signupType = "3c";
6045                    }
6046                    if (deliveryMethodSession == "Delivery") {
6047                        serviceType = "Online Delivery";
6048                        signupType = "2b";
6049                    }
6050                    if (deliveryMethodSession == "Pickup") {
6051                        serviceType = "Online Pickup";
6052                    }
6053                }
6054                sessionStorage.setItem("redirectLoginUrl", currentUrl);
6055                try {
6056                    sessionStorage.setItem('pwa_login_entry_point', 'header_login');
6057                } catch (e) { }
6058                var loginResponsePath = isPwaLogin
6059                    ? '/pwa/LoginResponse'
6060                    : '/LoginResponse';
6061                const redirectUrl = `${window.location.origin}${loginResponsePath}`;
6062                const memberPortalBaseUrl = (result.memberUrl || '').replace(/\/+$/, '');
6063                const logoutClientType = isPwaLogin ? 'PWA' : signupType;
6064                const memberPortalUrl = `${memberPortalBaseUrl}/auth?authorization=${result.authorization}&brandId=${result.brandId}&brandName=${encodeURIComponent(result.brandName)}&outletId=${result.outletId}&outletName=${encodeURIComponent(result.outletName)}&serviceType=${encodeURIComponent(serviceType)}&Type=${encodeURIComponent(logoutClientType)}&redirectUrl=${encodeURIComponent(redirectUrl)}`;
6065
6066                if (result.memberUrl) {
6067                    localStorage.setItem('USER_MEMBER_GETZPAY_URL', result.memberUrl);
6068                    sessionStorage.setItem('USER_MEMBER_GETZPAY_URL', result.memberUrl);
6069                }
6070
6071                console.log(memberPortalUrl);
6072                window.location.href = memberPortalUrl;
6073            }
6074            else {
6075                location.reload();
6076            }
6077        },
6078        error: function () { }
6079    });
6080    }
6081}
6082
6083function openAnimationMenuCategories(e) {
6084    $("#AnimationMenuCategories").hide().find('img').removeAttr('src');
6085
6086    if ($(e).parents('#dropdownMenu2').hasClass('open') && $('#dropdownMenu2 .accordion.dropdown-menu').height() > 400) {
6087        $("#AnimationMenuCategories").removeAttr('style').find('img').attr("src", urlAnimationProductDetail);
6088
6089        delayTimer(function () {
6090            $("#AnimationMenuCategories").hide().find('img').removeAttr('src');
6091        }, 1500);
6092    }
6093}
6094
6095function LogOutMember() {
6096    var isPwa = typeof isPwaMemberClientContext === 'function' && isPwaMemberClientContext();
6097    $.ajax({
6098        type: "POST",
6099        url: urlLogOutMember,
6100        data: {
6101            isPwa: isPwa
6102        },
6103        success: function (result) {
6104            //console.log(result);
6105            //$('#member-logoff-frame').attr('src', result.urlLogOffGetzMember);
6106            //LogOffGetzMember(result.urlLogOffGetzMember);
6107            if (result.status == true) {
6108                if (typeof trackPwaEvent === 'function') {
6109                    trackPwaEvent('pwa_logout', {});
6110                }
6111                sessionStorage.removeItem("aplly-voucher-text");
6112                if (typeof getOnlineShopMemberTokenKey === 'function') {
6113                    var tokenKey = getOnlineShopMemberTokenKey();
6114                    try {
6115                        localStorage.removeItem(tokenKey);
6116                        sessionStorage.removeItem(tokenKey);
6117                    } catch (e) { }
6118                }
6119
6120                location.reload();
6121            }
6122            else if (result.message != null) {
6123                if (result.message == "LoginRequired") {
6124                    $('#confirmLoginRequired').modal('show');
6125                }
6126            }
6127        },
6128        error: function () { }
6129    });
6130}
6131
6132function redirectMemberPortal() {
6133    sessionStorage.setItem("redirectLoginUrl", window.location.href);
6134
6135    var userMemberGetzpayUrl = localStorage.getItem('USER_MEMBER_GETZPAY_URL') || sessionStorage.getItem('USER_MEMBER_GETZPAY_URL');
6136    var targetBaseUrl = userMemberGetzpayUrl || (typeof memberUrl !== "undefined" && memberUrl ? memberUrl : null);
6137
6138    if (!targetBaseUrl) {
6139        return;
6140    }
6141
6142    // Standalone: GetzPay's dashboard otherwise relies on its own domain session cookie
6143    // (what the old, non-PWA flow relied on), which is unreliable inside a standalone
6144    // PWA — pass the cached JWT directly via ?accessToken= instead, refreshing it first
6145    // if needed.
6146    if (typeof isPwaStandaloneMode === 'function' && isPwaStandaloneMode()
6147        && typeof attemptStandaloneSilentLogin === 'function') {
6148        attemptStandaloneSilentLogin(0, function (success) {
6149            if (success) {
6150                var memberTokenKey = getOnlineShopMemberTokenKey();
6151                var storedToken = localStorage.getItem(memberTokenKey) || sessionStorage.getItem(memberTokenKey);
6152                var rawToken = extractTokenFromMemberTokenValue(storedToken);
6153                if (rawToken) {
6154                    window.location.href = targetBaseUrl + '/dashboard/index?accessToken=' + encodeURIComponent(rawToken);
6155                    return;
6156                }
6157            }
6158            window.location.href = targetBaseUrl + '/dashboard/index';
6159        });
6160        return;
6161    }
6162
6163    window.location.href = targetBaseUrl + '/dashboard/index';
6164}
6165
6166// ---------------------------------------------------------------------------
6167// Standalone PWA auto sign-in (JWT decode + silent refresh)
6168// Vanilla-JS equivalents of the React (pwaRuntimeUtils/memberUtils) and Angular
6169// (pwa-runtime.helper/member-jwt.helper) implementations, for classic Theme8 pages.
6170// ---------------------------------------------------------------------------
6171
6172/** True when the page runs as an installed PWA (not a normal browser tab). */
6173function isPwaStandaloneMode() {
6174    try {
6175        // Dev/test override: ?isPwaStandalone=1 (or ispwaStandalone=1)
6176        var params = new URLSearchParams(window.location.search);
6177        var override = params.get('isPwaStandalone') || params.get('ispwaStandalone');
6178        if (override === '1' || (override && override.toLowerCase() === 'true')) {
6179            return true;
6180        }
6181    } catch (e) { }
6182
6183    if (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) {
6184        return true;
6185    }
6186
6187    if (window.navigator && window.navigator.standalone === true) {
6188        return true;
6189    }
6190
6191    return !!document.referrer && document.referrer.indexOf('android-app://') > -1;
6192}
6193
6194/** Decodes a JWT payload without validating the signature (client-side expiry check only). */
6195function decodeJwtPayload(token) {
6196    try {
6197        var parts = (token || '').split('.');
6198        if (parts.length < 2) {
6199            return null;
6200        }
6201
6202        var base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
6203        var padded = base64 + '==='.slice((base64.length + 3) % 4);
6204        var jsonPayload = decodeURIComponent(
6205            atob(padded)
6206                .split('')
6207                .map(function (c) {
6208                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
6209                })
6210                .join('')
6211        );
6212
6213        return JSON.parse(jsonPayload);
6214    } catch (e) {
6215        return null;
6216    }
6217}
6218
6219function getPwaMemberDomainKey() {
6220    var origin = window.location.origin || '';
6221    if (typeof removeDomainSpecificCharacters === 'function') {
6222        return removeDomainSpecificCharacters(origin);
6223    }
6224    return origin.replace(/[^a-zA-Z0-9]/g, '');
6225}
6226
6227/** Same rule as Angular isPwaMemberClientContext / server IsPwaMemberClientContext. */
6228function isPwaMemberClientContext() {
6229    if (typeof isPwaStandaloneMode === 'function' && isPwaStandaloneMode()) {
6230        return true;
6231    }
6232    try {
6233        return new URLSearchParams(window.location.search).get('fromPwa') === '1';
6234    } catch (e) {
6235        return false;
6236    }
6237}
6238
6239/**
6240 * Lets Online Shop SSR (ViewBag.MemberLogged / _Header.cshtml) read the PWA Redis
6241 * session when the installed app opens OS routes without ?fromPwa=1 on every URL.
6242 */
6243function ensurePwaClientCookie() {
6244    if (!isPwaMemberClientContext()) {
6245        return;
6246    }
6247    try {
6248        document.cookie = 'PwaClient=1; path=/; max-age=2592000; SameSite=Lax';
6249    } catch (e) { }
6250}
6251
6252function getOnlineShopMemberTokenKey() {
6253    var domain = getPwaMemberDomainKey();
6254    return isPwaMemberClientContext()
6255        ? domain + '_pwa_member_token'
6256        : domain + '_member_token';
6257}
6258
6259function extractTokenFromMemberTokenValue(memberToken) {
6260    if (!memberToken) {
6261        return null;
6262    }
6263
6264    var underscoreIndex = memberToken.indexOf('_');
6265    if (underscoreIndex > 0 && underscoreIndex < memberToken.length - 1) {
6266        return memberToken.substring(underscoreIndex + 1);
6267    }
6268
6269    return memberToken;
6270}
6271
6272/**
6273 * Standalone-only self-heal: the classic Online Shop (Theme8 / v2 _Header) renders its
6274 * logged-in state purely from the short-lived server session (ViewBag.MemberLogged).
6275 * If the page rendered as logged-out but the device still has a locally cached GetzPay
6276 * member token (PWA key in standalone), silently validate/refresh it via the backend
6277 * and reload so the header re-renders signed in.
6278 */
6279function trySyncMemberSessionForStandalone(outletIndex) {
6280    try {
6281        if (!isPwaStandaloneMode()) {
6282            return;
6283        }
6284
6285        ensurePwaClientCookie();
6286
6287        var memberTokenKey = getOnlineShopMemberTokenKey();
6288        var storedToken = localStorage.getItem(memberTokenKey) || sessionStorage.getItem(memberTokenKey);
6289        var rawToken = extractTokenFromMemberTokenValue(storedToken);
6290
6291        if (!rawToken) {
6292            return;
6293        }
6294
6295        var payload = decodeJwtPayload(rawToken);
6296        if (!payload) {
6297            // Corrupt/unparseable token - clear it rather than sending garbage to GetzPay.
6298            localStorage.removeItem(memberTokenKey);
6299            sessionStorage.removeItem(memberTokenKey);
6300            return;
6301        }
6302
6303        $.ajax({
6304            type: "POST",
6305            url: "/Home/RefreshMemberAccessToken",
6306            data: {
6307                accessToken: rawToken,
6308                outletIndex: outletIndex || 0,
6309                isPwa: true
6310            },
6311            success: function (result) {
6312                if (result && result.status === true && result.accessToken) {
6313                    var name = result.memberName || (storedToken ? storedToken.split('_')[0] : null) || 'Member';
6314                    var newMemberToken = name + '_' + result.accessToken;
6315                    localStorage.setItem(memberTokenKey, newMemberToken);
6316                    sessionStorage.setItem(memberTokenKey, newMemberToken);
6317                    location.reload();
6318                } else {
6319                    localStorage.removeItem(memberTokenKey);
6320                    sessionStorage.removeItem(memberTokenKey);
6321                }
6322            },
6323            error: function () { }
6324        });
6325    } catch (e) { }
6326}
6327
6328/**
6329 * Standalone-only: used by the explicit "Member Login" click handler (redirectMemberUrl).
6330 * Tries to resolve the login using the locally cached GetzPay member token (still valid,
6331 * or refreshable via ValidateAndRefreshToken) instead of unconditionally sending the user
6332 * through a full GetzPay `/auth` redirect. Calls `callback(true)` when the caller should
6333 * just treat the user as signed in (reload), `callback(false)` to fall back to the normal
6334 * full-redirect login flow.
6335 */
6336function attemptStandaloneSilentLogin(outletIndex, callback) {
6337    try {
6338        ensurePwaClientCookie();
6339
6340        var memberTokenKey = getOnlineShopMemberTokenKey();
6341        var storedToken = localStorage.getItem(memberTokenKey) || sessionStorage.getItem(memberTokenKey);
6342        var rawToken = extractTokenFromMemberTokenValue(storedToken);
6343
6344        if (!rawToken) {
6345            callback(false);
6346            return;
6347        }
6348
6349        var payload = decodeJwtPayload(rawToken);
6350        if (!payload) {
6351            localStorage.removeItem(memberTokenKey);
6352            sessionStorage.removeItem(memberTokenKey);
6353            callback(false);
6354            return;
6355        }
6356
6357        $.ajax({
6358            type: "POST",
6359            url: "/Home/RefreshMemberAccessToken",
6360            data: {
6361                accessToken: rawToken,
6362                outletIndex: outletIndex || 0,
6363                isPwa: true
6364            },
6365            success: function (result) {
6366                if (result && result.status === true && result.accessToken) {
6367                    var name = result.memberName || (storedToken ? storedToken.split('_')[0] : null) || 'Member';
6368                    var newMemberToken = name + '_' + result.accessToken;
6369                    localStorage.setItem(memberTokenKey, newMemberToken);
6370                    sessionStorage.setItem(memberTokenKey, newMemberToken);
6371                    if (typeof trackPwaEvent === 'function') {
6372                        trackPwaEvent('pwa_session_restore', { result: 'success' });
6373                    }
6374                    callback(true);
6375                } else {
6376                    localStorage.removeItem(memberTokenKey);
6377                    sessionStorage.removeItem(memberTokenKey);
6378                    if (typeof trackPwaEvent === 'function') {
6379                        trackPwaEvent('pwa_session_restore', {
6380                            result: 'fail',
6381                            failure_reason: 'token_expired'
6382                        });
6383                    }
6384                    callback(false);
6385                }
6386            },
6387            error: function () {
6388                callback(false);
6389            }
6390        });
6391    } catch (e) {
6392        callback(false);
6393    }
6394}
6395
6396function LogOffGetzMember(urlLogOffGetzMember) {
6397    $.ajax({
6398        type: "GET",
6399        url: urlLogOffGetzMember,
6400        success: function () {
6401        },
6402        error: function () { }
6403    });
6404}
6405
6406function openComfirmBuffetMenuSelectionPopup(urlBuffetDetail, titleBuffet) {
6407    $('#confirm-buffet-menu-selection').find('#buffet-name-comfirmed').text(titleBuffet + '?');
6408    $('#confirm-buffet-menu-selection').find('#confirm-buffet-menu-selection__btn-confirm').attr('data-url', urlBuffetDetail);
6409    $('#confirm-buffet-menu-selection').modal('show');
6410}
6411
6412function scrollToNewVariantId(newVariantId, isRecall = false) {
6413    if (typeof isMerchantOS !== 'undefined' && isMerchantOS == true
6414        && newVariantId != null && newVariantId != '') {
6415
6416        if ($(`#item-${newVariantId}`).length > 0) {
6417            $(`#item-${newVariantId}`).addClass('item-disabled');
6418            document.getElementById(`item-${newVariantId}`).scrollIntoView({ block: 'nearest', behavior: 'smooth', inline: 'nearest' });
6419
6420            setTimeout(function () {
6421                $(`#item-${newVariantId}`).removeClass('item-disabled');
6422            }, 1000);
6423
6424            return false;
6425        }
6426        else if (isRecall == false) {
6427            console.log('scrollToNewVariantId', newVariantId);
6428            setTimeout(function () {
6429                scrollToNewVariantId(newVariantId, true);
6430            }, 1000);
6431        }
6432    }
6433}
6434
6435function showGroupOrderSwitchOutletModal() {
6436    $("#btn-cancel-group-order-switch").css('display', 'inline-block');
6437    $("#btn-group-order-switch-2").css('display', 'none');
6438    $("#btn-group-order-switch-1").css('display', 'inline-block');
6439    $("#btn-group-order-switch-3").css('display', 'none');
6440
6441    $("#group-order-switch-outlet-modal").modal('show');
6442}
6443
6444function showGroupOrderSwitchOutletModal2() {
6445    $("#btn-cancel-group-order-switch").css('display', 'inline-block');
6446    $("#btn-group-order-switch-1").css('display', 'none');
6447    $("#btn-group-order-switch-2").css('display', 'inline-block');
6448    $("#btn-group-order-switch-3").css('display', 'none');
6449
6450    $("#group-order-switch-outlet-modal").modal('show');
6451}
6452
6453function showGroupOrderSwitchOutletModal3() {
6454    $("#btn-cancel-group-order-switch").css('display', 'none');
6455    $("#btn-group-order-switch-1").css('display', 'none');
6456    $("#btn-group-order-switch-2").css('display', 'none');
6457    $("#btn-group-order-switch-3").css('display', 'inline-block');
6458
6459    $("#group-order-switch-outlet-modal").modal('show');
6460}
6461
6462$(document).on('click', '.modal .close', function () {
6463    $('#iprocessingtab').attr('style', 'display:none');
6464    $('#iprocessingtab-V2').attr('style', 'display:none');
6465    $(".session-service-item .fa").removeClass('fa-spinner');
6466    $(".session-service-item .fa").removeClass('fa-spin');
6467    $(".session-service-item .pickupservice .fa").addClass('fa-chevron-right');
6468    $(".session-service-item .deliveryservice .fa").addClass('fa-pencil');
6469});
6470
6471$(window).bind("pageshow", function (event) {
6472    if (event.originalEvent.persisted) {
6473        LoadContainMyCart();
6474    }
6475});
6476
6477$(() => {
6478
6479    $('.member-voucher-slider').on('click', '.member-reward-voucher__btn-more-info', function () {
6480        $(this).parents('.member-reward-voucher-item').addClass('open');
6481    });
6482
6483    $('.member-voucher-slider').on('click', '.member-reward-voucher__returning', function () {
6484        $(this).parents('.member-reward-voucher-item').removeClass('open');
6485    });
6486
6487    //var myCustomEvent = /iphone|ipod|ipad/.test(window.navigator.userAgent.toLowerCase()) ? 'popstate' : 'pageshow';
6488
6489    //$(window).bind(myCustomEvent, function (event) {
6490    //    if (event.originalEvent.persisted && isCheckoutPayLater == true && sessionStorage.getItem("payLaterAddMoreItems") != null
6491    //        && isOrderPayLaterAmendMore == false && /iphone|ipod|ipad/.test(window.navigator.userAgent.toLowerCase()) == false) {
6492    //        isCheckoutPayLater = false;
6493
6494    //        let payLaterAddMoreItems = sessionStorage.getItem("payLaterAddMoreItems");
6495    //        let objPayLater = JSON.parse(payLaterAddMoreItems);
6496
6497    //        if ($(".modal-mask.animated").length == 0) {
6498    //            let loading = new Loading({
6499    //                title: ''
6500    //            });
6501
6502    //            setTimeout(function () {
6503    //                loading.out();
6504    //            }, 10000);
6505    //        }
6506
6507    //        SignUpDineInPayLater(objPayLater.dineinFirstname, objPayLater.stationId,
6508    //            objPayLater.totalPax, 'dinein', false, false, '', '', 0, objPayLater.docId, true);
6509
6510    //        sessionStorage.removeItem("payLaterAddMoreItems");
6511    //    }
6512    //    else if (sessionStorage.getItem("payLaterAddMoreItems") != null) {
6513    //        sessionStorage.removeItem("payLaterAddMoreItems");
6514    //    }
6515    //});
6516
6517    $('#productDetailModal').on('click', '.btn-view-tc', (e) => {
6518        let voucherId = $(e.currentTarget).attr('data-id');
6519        openVoucherTermsIframe(e.currentTarget, voucherId, false, null);
6520    });
6521
6522    $('#select-payment-options-popup').on('click', '.btn-view-tc', (e) => {
6523        let voucherId = $(e.currentTarget).attr('data-id');
6524        let isIssuedAttr = $(e.currentTarget).attr('data-issued');
6525        let isIssued = (isIssuedAttr !== undefined && isIssuedAttr !== '') ? (isIssuedAttr === 'true') : true;
6526        openVoucherTermsIframe(e.currentTarget, voucherId, isIssued, '#select-payment-options-popup');
6527    });
6528
6529    $('#payment-option-section').on('click', '.btn-view-tc', (e) => {
6530        let voucherId = $(e.currentTarget).attr('data-id');
6531        let isIssuedAttr = $(e.currentTarget).attr('data-issued');
6532        let isIssued = (isIssuedAttr !== undefined && isIssuedAttr !== '') ? (isIssuedAttr === 'true') : true;
6533        openVoucherTermsIframe(e.currentTarget, voucherId, isIssued, null);
6534    });
6535
6536    $('#confirm-merchant-os-updated').on('click', '#confirm-merchant-os-updated__btn-confirm', (e) => {
6537        $.ajax({
6538            type: "GET",
6539            url: urlReloadMerchantOS,
6540            dataType: 'json',
6541            success: function (result) {
6542            }
6543        });
6544
6545        //fetch(urlReloadMerchantOS)
6546        //    .then(response => {
6547        //        // Check if the response is successful (status code 200)
6548        //        if (!response.ok) {
6549        //            throw new Error('Network response was not ok');
6550        //        }
6551        //        return response.json();  // Parse the JSON response
6552        //    })
6553        //    .then(data => {
6554        //        // Handle the fetched data
6555        //        console.log(data);
6556        //    })
6557        //    .catch(error => {
6558        //        // Handle any errors that occurred during the fetch
6559        //        console.error('There was a problem with the fetch operation:', error);
6560        //    });
6561
6562        $('#confirm-merchant-os-updated__btn-confirm').append('<i class=\"fa fa-spinner fa-spin\"></i>').attr('disabled', 'disabled');
6563    });
6564
6565    $('#adjust-measurement-merchant-os').on('change', '#item-measurementUnitSizeValue', function () {
6566        let measurementUnitMin = +$('#adjust-measurement-merchant-os').find('#item-measurementUnitMin').val();
6567        let measurementUnitMax = +$('#adjust-measurement-merchant-os').find('#item-measurementUnitMax').val();
6568
6569        let measurementUnitSizeValue = +$(this).val();
6570        let $adjustMeasurementUnitButtonOK = $('#adjust-measurement-merchant-os').find('#adjust-measurement-merchant-os-updated__btn-ok');
6571        let $adjustMeasurementUnitMessage = $('#adjust-measurement-merchant-os').find('.adjust-measurement-merchant-os__message');
6572        if (measurementUnitSizeValue < measurementUnitMin) {
6573            $adjustMeasurementUnitButtonOK.attr('disabled', 'disabled');
6574            $adjustMeasurementUnitMessage.text('Please input Size must be greater or equal to ' + measurementUnitMin.toFixed(2)).show();
6575        }
6576        else if (measurementUnitMax > 0 && measurementUnitSizeValue > measurementUnitMax) {
6577            $adjustMeasurementUnitButtonOK.attr('disabled', 'disabled');
6578            $adjustMeasurementUnitMessage.text('Please input Size must be lower or equal to ' + measurementUnitMax.toFixed(2)).show();
6579        }
6580        else {
6581            $adjustMeasurementUnitButtonOK.removeAttr('disabled');
6582            $adjustMeasurementUnitMessage.text('').hide();
6583        }
6584
6585        let measurementUnitPrice = $('#adjust-measurement-merchant-os').find('#item-measurementUnitPrice').val();
6586        let measurementUnitSize = $('#adjust-measurement-merchant-os').find('#item-measurementUnitSize').val();
6587        let measurementUnitPriceValue = measurementUnitSizeValue * measurementUnitPrice / measurementUnitSize;
6588
6589        if (measurementUnitPriceValue < 0) {
6590            measurementUnitPriceValue = 0;
6591        }
6592
6593        $('#adjust-measurement-merchant-os').find('#item-measurementUnitPriceValue').val(measurementUnitPriceValue.toFixed(2));
6594    })
6595
6596    $('#adjust-measurement-merchant-os').on('click', '.change-measurement-unit-size-value', function () {
6597        let $itemMeasurementUnitSizeValue = $('#adjust-measurement-merchant-os').find('#item-measurementUnitSizeValue');
6598
6599        let dataUnitSize = +$(this).attr('data-id');
6600        let currentSizeValue = +$itemMeasurementUnitSizeValue.val();
6601        let newSizeValue = currentSizeValue + dataUnitSize;
6602
6603        if (newSizeValue < 0) {
6604            newSizeValue = 0;
6605        }
6606
6607        $itemMeasurementUnitSizeValue.val(newSizeValue.toFixed(2));
6608        delayTimer(function () {
6609            $itemMeasurementUnitSizeValue.change();
6610        }, 250);
6611    })
6612
6613    $('#adjust-measurement-merchant-os').on('keyup', '#item-measurementUnitSizeValue', function () {
6614        delayTimer(function () {
6615            $('#adjust-measurement-merchant-os').find('#item-measurementUnitSizeValue').change();
6616        }, 250);
6617    })
6618
6619    $('#adjust-measurement-merchant-os').on('click', '.change-measurement-unit-size-price', function () {
6620        openKeyboardNumberMerchantOS($(this).parents('.input-group'));
6621    })
6622
6623    $('#addNoteForItemModal').on('shown.bs.modal', function () {
6624        $('#item-remark-value').focus();
6625    });
6626
6627    $('#containmycart').on('click', '.tap-to-add-note', (e) => {
6628        let variantId = $(e.currentTarget).attr('data-id');
6629        $('#item-remark-variant-id').val(variantId);
6630
6631        let itemRemark = $(e.currentTarget).find('#item-add-note-text_' + variantId).attr('data-value');
6632        $('#item-remark-value').val(itemRemark);
6633
6634        $('#addNoteForItemModal').modal('show');
6635    });
6636
6637    $('#addNoteForItemModal').on('click', '#btn-item-remark', function () {
6638        let variantId = $('#item-remark-variant-id').val();
6639
6640        if (variantId != null) {
6641            let itemRemark = $('#item-remark-value').val();
6642
6643            console.log(variantId, itemRemark);
6644            $.ajax({
6645                url: urlUpdateNoteForItem,
6646                type: 'POST',
6647                data: {
6648                    variantId: variantId,
6649                    itemRemark: itemRemark
6650                },
6651                success: function (res) {
6652                    console.log(res);
6653                    if (res.status) {
6654                        $('#item-add-note-text_' + variantId).text(res.itemRemark);
6655
6656                        if (res.isRemarkEmpty) {
6657                            $('#item-add-note-text_' + variantId).attr('data-value', '');
6658                        }
6659                        else {
6660
6661                            $('#item-add-note-text_' + variantId).attr('data-value', res.itemRemark);
6662                        }
6663                    }
6664                },
6665                error: function (xhr, status, error) {
6666                },
6667                beforeSend: function () {
6668                },
6669                complete: function () {
6670                    $('#addNoteForItemModal').modal('hide');
6671                }
6672            });
6673        }
6674    });
6675
6676});
6677
6678function ontouchstartCart() {
6679    $('body').css('overflow-y', 'hidden');
6680}
6681
6682function ontouchendCart() {
6683    $('body').removeAttr('style').css('width', '100%');
6684}
6685
6686function changeFragment(newFragment) {
6687    if (window.hj) {
6688        if (newFragment == null || newFragment.length == 0) {
6689            history.back();
6690        } else if (window.location.hash != `#${newFragment}`) {
6691            history.pushState({ fragment: newFragment }, '', `#${newFragment}`);
6692        }
6693    }
6694}

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