PageSourceSearch

https://www.procraftindia.com/js/checkout.js?v=705

js procraftindia.com collected 2026-10-02 00:18:47 UTC 315,449 bytes, 6,446 lines download raw bytes

1var en = {
2    SoldOut: 'SOLD OUT',
3    AddToCart: 'Add To Cart',
4    Save: 'Saved.'
5};
6
7var de = {
8    SoldOut: 'Momentan nicht verfügbar',
9    AddToCart: 'In den Warenkorb legen'
10};
11
12var Theme = Theme || {};
13Theme.Data = Theme.Data || {};
14Theme.Utils = Theme.Utils || {};
15Theme.ProductData = Theme.ProductData || {};
16Theme.Language = Theme.Language || {};
17
18Theme.Language.defaultLanguage = (typeof window.BRAND_STORE_LANGUAGE !== 'undefined') ? window.BRAND_STORE_LANGUAGE : "en"; // default language
19Theme.Language.supportedLanguages = ['en', 'fr', 'es'];
20// 2️⃣ Language dictionaries
21Theme.Language.dictionary = {
22    en: {
23        SoldOut: 'SOLD OUT',
24        AddToCart: 'Add To Cart',
25        Save: 'Saved.',
26        MadeToOrder: 'Made To Order',
27        BuyNow: 'Buy Now',
28        AddToCartListButton: '<span>Add To Cart</span> <i class="ico-cart"><svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg></i>',
29        MaxOrderQuantityTxt: 'Maximum order quantity must be ',
30        PlaceHolderMobileNoTxt: 'Enter your mobile',
31        PlaceHolderEmailTxt: 'Enter your email',
32        LabelEmail: 'Email',
33        LabelMobile: 'Mobile No.',
34        LabelWhatsappMobile: 'Whatsapp Mobile No.',
35    },
36    de: {
37        SoldOut: 'Momentan nicht verfügbar',
38        AddToCart: 'In den Warenkorb legen',
39        Save: 'Gespeichert.',
40        MadeToOrder: 'Auf Bestellung gefertigt',
41        BuyNow: 'Jetzt kaufen',
42        AddToCartListButton: '<span>In den Warenkorb legen</span> <i class="ico-cart"><svg viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg></i>',
43        MaxOrderQuantityTxt: 'Die maximale Bestellmenge muss betragen ',
44        PlaceHolderMobileNoTxt: 'Geben Sie Ihr Mobiltelefon ein',
45        PlaceHolderEmailTxt: 'Geben Sie Ihre E-Mail-Adresse ein',
46        LabelEmail: 'E-Mail',
47        LabelMobile: 'Mobil-Nr.',
48        LabelWhatsappMobile: 'WhatsApp-Mobilnummer.',        
49    }
50};
51
52// 3️⃣ Translator functions
53Theme.Language.currentLanguage = Theme.Language.defaultLanguage;
54
55// Set active language
56Theme.Language.setStr = function(lang) {
57    if (Theme.Language.supportedLanguages.includes(lang)) {
58        Theme.Language.currentLanguage = lang;
59    } else {
60        //console.warn('Unsupported language:', lang);
61        Theme.Language.currentLanguage = Theme.Language.defaultLanguage;
62    }
63};
64
65// Get translated string
66Theme.Language.getStr = function(key, fallback) {
67    const lang = Theme.Language.currentLanguage;
68    const dict = Theme.Language.dictionary;
69
70    // Try current language → fallback → default → key
71    return ((dict[lang] && dict[lang][key]) || (dict[Theme.Language.defaultLanguage] && dict[Theme.Language.defaultLanguage][key]) || fallback || key);
72};
73
74Theme.Language.ParseLanguage = function(lang) {
75    var __construct = function() {
76        if (eval('typeof ' + lang) == 'undefined') {
77            lang = "en";
78        }
79        return;
80    }();
81
82    this.getStr = function(str, defaultStr) {
83        var retStr = eval('eval(lang).' + str);
84        if (typeof retStr != 'undefined') {
85            return retStr;
86        } else {
87            if (typeof defaultStr != 'undefined') {
88                return defaultStr;
89            } else {
90                return eval('en.' + str);
91            }
92        }
93    }
94}
95
96Theme.Utils.PhoneCountryCode = function(selectors, countryISO2) {	
97		return window.intlTelInput(document.querySelector("#"+selectors), {
98                                            utilsScript: "/css/assets/plugins/intl-tel-input/js/utils.js",
99                                            initialCountry: countryISO2,
100                                            //autoInsertDialCode: true,
101                                            nationalMode: true,
102                                            //showSelectedDialCode: true,
103                                            separateDialCode: true,
104                                            formatOnDisplay: false,
105                                            strictMode: true,
106                                            // hiddenInput: function(telInputName) {
107                                            //     // Return a string or an object with 'phone' and 'country' keys
108                                            //     return "payment_phone_with_country_code"; // or { phone: "phone_full", country: "country_code" }
109                                            // }
110                                        });
111	
112}
113
114Theme.Utils.Element = {
115    init: function() {
116        /****** Condition For Date Picker ******/
117        var d = new Date();
118        d.setFullYear(d.getFullYear() - 60);
119
120        if ($('input').hasClass('datepick')) {
121            $('.datepick').datepicker({
122                format: 'dd-MM-yyyy',
123                startView: 2,
124                //minViewMode: 0,
125                todayHighlight: true,
126                //startDate: d,
127                //endDate: d,
128            });
129
130            $('.date_image_button').click(function() {
131                $(this).closest('div.input-group').find(".datepick").datepicker('show'); //support hide,show and destroy command
132            });
133        }
134
135        /****** Condition For Date Picker ******/
136        if ($('div').hasClass('clockpicker')) {
137            $('.clockpicker').clockpicker();
138        }
139
140
141        if ($('input').hasClass('timepicki')) {
142            $('.timepicki').timepicki();
143        }
144    },
145    updateURLAndReload: function(param, value) {
146        let url = new URL(window.location);
147        url.searchParams.set(param, value);
148        window.location.href = url.toString(); // Reloads the page with updated URL
149    },
150    updateQueryParamAndReload(key, value) {
151        let url = window.location.href;
152        let re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
153        let separator = url.indexOf('?') !== -1 ? "&" : "?";
154
155        if (url.match(re)) {
156            url = url.replace(re, '$1' + key + "=" + value + '$2');
157        } else {
158            url = url + separator + key + "=" + value;
159        }
160
161        window.location.href = url; // Reload the page with the updated URL
162    },
163    validateEmail(email) {
164        const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
165        return regex.test(email);
166    },
167    validateNumeric(str) {
168        return /^[0-9]+$/.test(str);
169    }
170};
171
172Theme.Utils.Home = {
173    init: function() {
174        Theme.Utils.Cookie.initCookieMessage();
175
176        var $L = 1200,
177            $cart_trigger = $('div.cd-cart-trigger'),
178            $lateral_cart = $('#cd-cart'),
179            $shadow_layer = $('#cd-shadow-layer');
180
181        //open cart
182        $cart_trigger.on('click', function(event) {
183            event.preventDefault();
184            //close lateral menu (if it's open)
185            Theme.Utils.Home.toggglePanelVisibility($lateral_cart, $shadow_layer, $('body'));
186        });
187
188        //close lateral cart or lateral menu
189        $shadow_layer.on('click', function() {
190            $shadow_layer.removeClass('is-visible');
191            if ($lateral_cart.hasClass('speed-in')) {
192                $lateral_cart.removeClass('speed-in').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
193                    $('body').removeClass('overflow-hidden panel-cart-icon');
194                });
195            } else {
196                $lateral_cart.removeClass('speed-in');
197            }
198        });
199    },
200
201    toggglePanelVisibility: function($lateral_panel, $background_layer, $body) {
202        if ($lateral_panel.hasClass('speed-in')) {
203            $lateral_panel.removeClass('speed-in').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
204                $body.removeClass('overflow-hidden panel-cart-icon');
205            });
206            $background_layer.removeClass('is-visible');
207        } else {
208            $lateral_panel.addClass('speed-in').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
209                $body.addClass('overflow-hidden panel-cart-icon');
210            });
211            $background_layer.addClass('is-visible');
212        }
213    },
214
215    initVideo: function() {}
216};
217
218Theme.Utils.Form = {
219    initFormElement: function() {
220        $('[data-toggle="tooltip"]').tooltip();
221
222        $("input, textarea").focus(function() {
223            // Cursor In...
224            $(this).closest(".field").addClass("field--active");
225        }).blur(function() {
226            // Cursor Out...
227            $(this).closest(".field").removeClass("field--active");
228        }).on('keyup paste change focus blur keydown', function() {
229            // On change...
230            ($(this).val().length != 0 && $(this).is(":visible")) ? $(this).closest(".field").addClass("field--show-floating-label"): $(this).closest(".field").removeClass("field--show-floating-label");
231        }).each(function() {
232            ($(this).val().length != 0 && $(this).is(":visible")) ? $(this).closest(".field").addClass("field--show-floating-label"): $(this).closest(".field").removeClass("field--show-floating-label");
233        });
234
235        $("select").each(function() {
236            $(this).closest(".field").addClass("field--show-floating-label");
237        }).on('keyup paste change focus blur keydown', function() {
238            // On change...
239            ($(this).is(":visible")) ? $(this).closest(".field").addClass("field--show-floating-label") : $(this).closest(".field").removeClass("field--show-floating-label");
240        });
241    }
242}
243
244Theme.Utils.Cookie = {
245    initCookieMessage: function() {
246        if ($("div.cookie-message").length > 0) {
247            var j = window.sessionStorage.cookieMessage ? JSON.parse(window.sessionStorage.cookieMessage) : undefined;
248            if (j && j.hide) {
249                $("div.cookie-message").hide();
250            } else {
251                $("div.cookie-message").show();
252                this.showCookieMessage();
253            }
254        }
255    },
256
257    showCookieMessage: function() {
258        $("div.cookie-message").find("button").on("click", function() {
259            window.sessionStorage.cookieMessage = JSON.stringify({
260                hide: true
261            });
262            $(this).css("height", $(this).css("height"));
263            $(this).children().animate({
264                opacity: 0
265            }, 100);
266            $(this).animate({
267                height: 0,
268                padding: 0
269            }, 100, "swing", function() {
270                $(this).hide()
271            })
272        });
273    },
274
275    hideCookieMessage: function() {
276        $("div.cookie-message").hide();
277    }
278}
279
280Theme.Utils.Search = {
281    init: function() {
282        var $searchlink = $('#searchtoggl i');
283        var $searchbar = $('#searchbar');
284
285        $('.scroll-search a').on('click', function(e) {
286            e.preventDefault();
287            if ($(this).attr('id') == 'searchtoggl') {
288                if (!$searchbar.is(":visible")) {
289                    // if invisible we switch the icon to appear collapsable
290                    $searchlink.removeClass('fa-search').addClass('fa-times');
291                } else {
292                    // if visible we switch the icon to appear as a toggle
293                    $searchlink.removeClass('fa-times').addClass('fa-search');
294                }
295
296                $searchbar.slideToggle(300, function() {
297                    // callback after search bar animation
298                });
299            }
300        });
301
302        $('#searchform').submit(function(e) {
303            e.preventDefault(); // stop form submission
304        });
305
306        //Auto Complete Search
307        $("input#keyword").autocomplete({
308            source: function(request, response) {
309                var keyword = request.term;
310                $.ajax({
311                    type: "POST",
312                    async: true,
313                    cache: false,
314                    url: "/store_tags/getTagsByKeyword",
315                    dataType: "json",
316                    data: {
317                        "data[StoreProduct][keyword]": keyword
318                    },
319                    beforeSend: function(XMLHttpRequest) {
320
321                    },
322                    success: function(data, textStatus) {
323                        response($.map(data, function(el) {
324                            return {
325                                label: el.tag_name,
326                                value: el.slug_url
327                            };
328                        }));
329                    },
330                    error: function(jqXHR, textStatus, errorThrown) {
331                        //console.log(jqXHR.responseText);
332
333                        if (jqXHR.status == 500) {
334                            alert("Internal error: " + jqXHR.responseText);
335                        }
336                    }
337                });
338            },
339            select: function(event, ui) {
340                //window.location.href = ui.item.value;
341                window.location.href = window.storeURL + ui.item.value;
342                ui.item.value = ui.item.label;
343
344                //Prevent value from being put in the input:
345                this.value = ui.item.label;
346                //Set the next input\'s value to the "value" of the item.
347                //$(this).next("input").value(ui.item.value);
348                event.preventDefault();
349            },
350            focus: function(event, ui) {
351                event.preventDefault();
352                $("input#keyword").val(ui.item.label);
353            }
354        });
355    }
356};
357
358Theme.Utils.BackToTop = {
359    init: function() {
360        // hide #back-top first
361        $("#back-top").hide();
362        // fade in #back-top
363
364        $(window).scroll(function() {
365            if ($(this).scrollTop() > 100) {
366                $('#back-top').fadeIn();
367            } else {
368                $('#back-top').fadeOut();
369            }
370        });
371
372        // scroll body to 0px on click
373        $('#back-top a').click(function() {
374            $('body,html').animate({
375                scrollTop: 0
376            }, 400);
377            return false;
378        });
379    }
380};
381
382Theme.Utils.PopUp = {
383    init: function(timeAfter) {
384        if (typeof(timeAfter) === 'undefined') timeAfter = 0;
385        if (sessionStorage.getItem('popHome') != "1") {
386            $(window).load(function() {
387                window.setTimeout(function() {
388                    $("#homepagePopupModal").modal('show')
389                }, parseInt(timeAfter) * 1000);
390            });
391        }
392    },
393    hidePopUp: function() {
394        $("button#btnCloseModal").on("click", function(event) {
395            $.ajax({
396                type: "POST",
397                async: true,
398                cache: false,
399                url: "/stores/hide_popup",
400                dataType: "html",
401                data: {
402                    "data[Store][hide_popup]": 1
403                },
404                beforeSend: function(XMLHttpRequest) {},
405                success: function(data, textStatus) {},
406                error: function(jqXHR, textStatus, errorThrown) {
407                    if (jqXHR.status == 500) {
408                        alert('Internal error: ' + jqXHR.responseText);
409                    }
410                }
411            });
412        });
413    }
414};
415
416Theme.Utils.CountDown = {
417    init: function(timeLeft) {
418        $('.countdown').downCount({
419            date: timeLeft,
420            offset: +5
421        });
422    }
423};
424
425Theme.Utils.Menu = {
426    init: function() {
427        // initiate layout and plugins
428        //App.init();
429        /* Sticky Menu */
430        /*
431          var fixmeTop = $('.fixme').offset().top;
432          $(window).scroll(function() {
433          var currentScroll = $(window).scrollTop();
434          if (currentScroll >= fixmeTop) {
435          $('.fixme').css({
436          position: 'fixed',
437          top: '0'
438          //left: '5px'
439          });
440          } else {
441          $('.fixme').css({
442          position: 'relative'
443          });
444          }
445          });
446
447          if ($(window).width() <= 768) {
448          $('.mobile-fixme').css({
449          position: 'fixed',
450          top: '0'
451          //left: '0'
452          });
453          } else {
454          $('.mobile-fixme').css({
455          position: 'static'
456          });
457     }*/
458
459    },
460    initNavMenu: function() {
461        var html = $('html, body'),
462            navContainer = $('.nav-container'),
463            navToggle = $('.nav-toggle'),
464            navDropdownToggle = $('.has-dropdown');
465
466        // Nav toggle
467        navToggle.on('click', function(e) {
468            var $this = $(this);
469            e.preventDefault();
470            $this.toggleClass('is-active');
471            navContainer.toggleClass('is-visible');
472            html.toggleClass('nav-open');
473        });
474
475        // Nav dropdown toggle
476        navDropdownToggle.on('click', function() {
477            var $this = $(this);
478            $this.toggleClass('is-active').children('ul').toggleClass('is-visible');
479        });
480
481        // Prevent click events from firing on children of navDropdownToggle
482        navDropdownToggle.on('click', '*', function(e) {
483            e.stopPropagation();
484        });
485
486        // Create a clone of the menu, right next to original.
487        if ($(window).width() >= 767) {
488            if ($('.menu-bar').length) {
489                $('.menu-bar').addClass('original').clone().insertAfter('.menu-bar').addClass('cloned').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '500').removeClass('original').hide();
490
491                function stickIt() {
492                    var orgElementPos = $('.original').offset();
493                    orgElementTop = orgElementPos.top;
494                    if ($(window).scrollTop() >= (orgElementTop)) {
495                        // scrolled past the original position; now only show the cloned, sticky element.
496
497                        // Cloned element should always have same left position and width as original element.     
498                        orgElement = $('.original');
499                        coordsOrgElement = orgElement.offset();
500                        leftOrgElement = coordsOrgElement.left;
501                        widthOrgElement = orgElement.css('width');
502                        $('.cloned').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
503                        $('.original').css('visibility', 'hidden');
504                    } else {
505                        // not scrolled past the menu; only show the original menu.
506                        $('.cloned').hide();
507                        $('.original').css('visibility', 'visible');
508                    }
509                }
510                scrollIntervalID = setInterval(stickIt, 10);
511            }
512        }
513
514    }
515};
516
517Theme.Utils.Category = {
518    initSort: function() {
519        $("#sort_by").on("change", function(event) {
520            event.preventDefault();
521            //var sort_by = $(this).val();
522            //var page_url = window.location.pathname;
523            //window.location.href = window.location.pathname + "?" + sort_by;
524            Theme.Utils.Category.buildQueryString();
525            return false;
526        });
527    },
528    initFilter: function() {
529        $("input.filter_groups").on("click", function(event) {
530            Theme.Utils.Category.buildQueryString();
531        });
532        $("input.filter_options").on("click", function(event) {
533            Theme.Utils.Category.buildQueryString();
534        });
535        $("input.filter_tags").on("click", function(event) {
536            Theme.Utils.Category.buildQueryString();
537        });
538    },
539    initColorFilter: function() {
540        $(".color-chk").on("click", function() {
541            Theme.Utils.Category.buildQueryString();
542        });
543    },
544    initPriceRangeFilter: function() {
545        $("input.filter_price_ranges").on("click", function() {
546            Theme.Utils.Category.buildQueryString();
547        });
548    },
549    buildQueryString: function() {
550        var page_url = window.location.pathname + "?";
551
552        //Filter Group Array
553        /*
554        var filterArray = [];
555        $('input.filter_groups:checkbox:checked').each(function () {
556                  if($(this).data('filterKey').length > 0 && $(this).data('filterValue').length > 0) {
557                       var key = $(this).data('filterKey');
558                       var value = $(this).data('filterValue');
559                       filterArray[""+ key +""] = value;
560                  }
561        });
562        */
563
564        //Filter Group Array
565        var filterArray = {};
566        var excludeFilterKeys = [];
567        $('input.filter_groups:checkbox:checked').each(function(i, e) {
568            if ($(this).data('filterKey').length > 0 && $(this).data('filterValue').length == 0) {
569                filterKey = $(this).data('filterKey');
570                excludeFilterKeys.push(filterKey);
571                $('input.filter_groups[data-filter-key=' + filterKey + ']').not(this).prop('checked', false);
572                //console.log($('input.filter_groups[data-filter-key=' + filterKey + ']'));
573            }
574
575            if ($(this).data('filterKey').length > 0 && $(this).data('filterValue').length > 0) {
576                var key = $(this).data('filterKey');
577                var value = $(this).data('filterValue');
578
579                if (excludeFilterKeys.indexOf(key) == -1) {
580                    if (key in filterArray == false) {
581                        filterArray[key] = {};
582                        filterArray[key][i] = value;
583                    } else {
584                        filterArray[key][i] = value;
585                    }
586                }
587            }
588        });
589
590        for (var key in filterArray) {
591            values = Object.keys(filterArray[key]).map(function(k) {
592                return filterArray[key][k]
593            }).join(",");
594            page_url = page_url + key + "=" + values + "&";
595        }
596
597        //Filter Option Array
598        var filterArray = [];
599        $('input.filter_options:radio:checked').each(function() {
600            if ($(this).data('optionKey').length > 0 && $(this).data('optionValue').length > 0) {
601                var key = $(this).data('optionKey');
602                var value = $(this).data('optionValue');
603                filterArray["" + key + ""] = value;
604            }
605        });
606
607        for (var key in filterArray) {
608            page_url = page_url + key + "=" + filterArray[key] + "&";
609        }
610
611        //Filter Tags
612        var filterArray = [];
613        $('input.filter_tags:radio:checked').each(function() {
614            if ($(this).data('tagKey').length > 0 && $(this).data('tagValue').length > 0) {
615                var key = $(this).data('tagKey');
616                var value = $(this).data('tagValue');
617                filterArray["" + key + ""] = value;
618            }
619        });
620
621        for (var key in filterArray) {
622            page_url = page_url + key + "=" + filterArray[key] + "&";
623        }
624
625        //Filter Price Ranges
626        var filterArray = [];
627        $('input.filter_price_ranges:radio:checked').each(function() {
628            if ($(this).data('priceRangeKey').length > 0 && $(this).data('priceRangeMaxValue') > 0) {
629                var key = $(this).data('priceRangeKey');
630                var min_value = $(this).data('priceRangeMinValue');
631                var max_value = $(this).data('priceRangeMaxValue');
632                filterArray["" + key + ""] = min_value + "-" + max_value;
633            }
634        });
635
636        for (var key in filterArray) {
637            page_url = page_url + key + "=" + filterArray[key] + "&";
638        }
639
640        //Color Array
641        var colorArray = [];
642        $('input.color-chk:checkbox:checked').each(function() {
643            colorArray.push($(this).val());
644        });
645
646        var sizeArray = [];
647        $('input.color-size:checkbox:checked').each(function() {
648            sizeArray.push($(this).val());
649        });
650
651        if (colorArray != "") {
652            page_url = page_url + "colors=" + colorArray + "&";
653        }
654
655        if (sizeArray != "") {
656            page_url = page_url + "size=" + sizeArray + "&";
657        }
658        var sort_by = $("#sort_by").val();
659        page_url = page_url + sort_by;
660
661        page_url = page_url.replace(/(^\s*&)|(&\s*$)/g, '');
662        window.location.href = page_url;
663
664    },
665    quickView: function() {
666        var appendThis = ("<div class='modal-overlay js-modal-close'></div>");
667        $(document).find(".js-modal-close, .modal-overlay").click(function() {
668            $(document).find(".quick-modal-box, .modal-overlay").fadeOut(500, function() {
669                $(document).find('#quickProduct').find(".quick-modal-body").html('');
670                $(document).find(".modal-overlay").remove();
671            });
672        });
673        /*
674        $(window).resize(function() {
675        $(document).find(".quick-modal-box").css({
676        top: ($(window).height() - $(".quick-modal-box").outerHeight()) / 2,
677        left: ($(window).width() - $(".quick-modal-box").outerWidth()) / 2
678        });
679        });
680
681        $(window).resize();
682        */
683
684        $(document).find("span.btnquick").click(function(ev) {
685            ev.preventDefault();
686            var productUrl = $(this).data('productUrl');
687            $.ajax({
688                type: "POST",
689                async: false,
690                cache: false,
691                url: "/products/quick",
692                dataType: "html",
693                data: {
694                    "data[StoreProduct][seo_url]": productUrl
695                },
696                beforeSend: function(XMLHttpRequest) {
697                    $('#quickProduct').show();
698                    $('#quickProduct').find(".quick-modal-body").html('');
699                },
700                success: function(data, textStatus) {
701                    $("body").append(appendThis);
702                    $(".modal-overlay").fadeTo(500, 0.7);
703                    $('#quickProduct').find(".quick-modal-body").html(data);
704                },
705                error: function(jqXHR, textStatus, errorThrown) {
706                    if (jqXHR.status == 500) {
707                        alert('Internal error: ' + jqXHR.responseText);
708                    }
709                    $('#quickProduct').hide();
710                }
711            });
712        });
713
714
715        /*
716        $('a[data-modal-id]').click(function(e) {
717        e.preventDefault();
718        $("body").append(appendthis);
719        $(".modal-overlay").fadeTo(500, 0.7);
720        //$(".js-modalbox").fadeIn(500);
721        var modalBox = $(this).attr('data-modal-id');
722        $('#'+modalBox).fadeIn($(this).data());
723        });
724        */
725    }
726};
727
728Theme.Utils.Product = {
729    initProduct: function() {
730
731        Theme.Utils.Element.init();
732
733        //ZOOM
734        if ($("#zoom4").length > 0) {
735            $("#zoom4").glassCase({
736                'widthDisplay': 450,
737                'heightDisplay': 600,
738                'isSlowZoom': true,
739                //'zoomPosition': 'inner',
740                'isDownloadEnabled': false,
741                'captionType': 'out',
742                'captionPosition': 'bottom',
743                'captionAlignment': 'left',
744                'colorIcons': '#000',
745                'colorActiveThumb': '#000',
746                'thumbsPosition': 'left',
747            });
748        }
749
750        function OnError(result) {
751            alert("ERROR");
752        }
753
754        $("#variant_size, #variant_color, #variant_material").on("change", function() {
755            var currValues = Theme.Utils.Product.selectedValues(); // get current values
756            var variant = Theme.Utils.Product.getVariant(currValues);
757            Theme.Utils.Product.selectCallback(variant, $(this));
758        });
759
760        $(".variant_size_span").on("click", function() {
761            var size = $(this).parent().find("input:radio[name='variant_size']").val();
762
763            //if($('input:radio[name=variant_size]:checked').val().length > 0){
764            var currValues = [];
765            currValues['size'] = size;
766            currValues.push({
767                "size": size
768            });
769
770            var variant = Theme.Utils.Product.getVariant(currValues);
771            Theme.Utils.Product.selectCallback(variant, $(this));
772            //}
773        });
774
775        $('#productTab a:first').tab('show');
776
777        $("div#diverror").hide();
778        $(document).on("click", "button#add-to-cart", function(event) {
779            event.stopPropagation();
780            if (parseInt(Theme.ProductData.product.variants.length) == 0 && parseInt(Theme.ProductData.product.minimum_order_quantity) > 0) {
781                if ($("input#quantity").val() < parseInt(Theme.ProductData.product.minimum_order_quantity)) {
782                    $("div#diverror").show();
783                    $("div#diverror").find(".label-danger").html("Minimum order quantity must be " + parseInt(Theme.ProductData.product.minimum_order_quantity));
784                    return false;
785                }
786            }
787            return true;
788        });
789
790
791        this.setDefault();
792    },
793    selectedValues: function() {
794        var currValues = [];
795        currValues['size'] = ($("#variant_size").length > 0) ? $("#variant_size").val() : null;
796        currValues['color'] = ($("#variant_color").length > 0) ? $("#variant_color").val() : null;
797        currValues['material'] = ($("#variant_material").length > 0) ? $("#variant_material").val() : null;
798        if ($("#variant_size").length > 0) {
799            currValues.push({
800                "size": $("#variant_size").val()
801            });
802        }
803        if ($("#variant_color").length > 0) {
804            currValues.push({
805                "color": $("#variant_color").val()
806            });
807        }
808        if ($("#variant_material").length > 0) {
809            currValues.push({
810                "material": $("#variant_material").val()
811            });
812        }
813        return currValues;
814    },
815    getVariant: function(selectedValues) {
816        // return the variant object if exists with given values, otherwise return null
817        var found = null;
818        if (selectedValues.length != Theme.ProductData.product.options.length) {
819            return found;
820        }
821
822        var variants = Theme.ProductData.product.variants;
823        $.each(variants, function(index, variant) {
824            var satisfied = true;
825            var j = selectedValues.length;
826
827            var size = (selectedValues.hasOwnProperty("size")) ? selectedValues.size : null;
828            var color = (selectedValues.hasOwnProperty("color")) ? selectedValues.color : null;
829            var material = (selectedValues.hasOwnProperty("material")) ? selectedValues.material : null;
830
831            if ((variant.size != size) || (variant.color != color) || (variant.material != material)) {
832                satisfied = false;
833            }
834
835            if (satisfied == true) {
836                found = variant;
837                return;
838            }
839        });
840        return found;
841    },
842    /* setDefault: function(){
843     //Auto-select first available variant on page load.
844     if(Theme.ProductData.product.variants.length > 0) {
845     var variants = Theme.ProductData.product.variants;
846     $.each(variants, function(index, variantData) {
847     if(variantData.available == true) {
848     if(variantData.hasOwnProperty("size")) {
849     $("#variant_size").val(variantData.size).trigger("change");
850     }
851     if(variantData.hasOwnProperty("color")) {
852     $("#variant_color").val(variantData.color).trigger("change");
853     }
854     if(variantData.hasOwnProperty("material")) {
855     $("#variant_material").val(variantData.material).trigger("change");
856     }
857     return false;
858     }
859     });
860     } else if (Theme.ProductData.product.available == false) {
861     $("#add-to-cart").addClass("disabled").attr("disabled", "disabled"); // set add-to-cart button to unavailable class and disable button
862     }
863}, */
864    /*
865    selectCallback: function(variant, selector) {
866    if (variant && variant.available) {
867    $("#add-to-cart").removeAttr("disabled").removeClass("disabled"); // remove unavailable class from add-to-cart button, and re-enable button
868    if(variant.product_price < variant.compare_at_price){
869    $("#price-preview").html(BrandformatMoney(variant.product_price, "{{amount}}") + " <del>" + BrandformatMoney(variant.compare_at_price, "{{amount}}") + "</del>");
870    } else {
871    $("#price-preview").html(BrandformatMoney(variant.product_price, "{{amount}}"));
872    }
873    } else {
874    $("#add-to-cart").addClass("disabled").attr("disabled", "disabled"); // set add-to-cart button to unavailable class and disable button
875    var message = variant ? "Sold Out" : "Unavailable";
876    $("#price-preview").text(message);
877    }
878
879    $("#StoreCartProductVariantId").val(variant.id);
880    }
881    */
882
883    setDefault: function() {
884        var Language = (typeof window.app.BRAND_STORE_LANGUAGE !== 'undefined') ? window.app.BRAND_STORE_LANGUAGE : "en";
885        var Translator = new Theme.Language.ParseLanguage(Language);
886
887        //Auto-select first available variant on page load.
888        if (Theme.ProductData.product.variants.length > 0) {
889            var variants = Theme.ProductData.product.variants;
890            var inStock = 0;
891            var showMain = 0;
892            var defaultVariant = {};
893            $.each(variants, function(index, variantData) {
894                if (variantData.hasOwnProperty("show_as_main") && parseInt(variantData.show_as_main) == 1 && variantData.available == true) {
895                    showMain = 1;
896                    defaultVariant = variantData;
897                }
898            });
899
900            //New Code Implemented On 13-03-2018
901            if (parseInt(showMain) === 1) {
902                inStock = 1;
903                Theme.Utils.Product.setDefaultVariant(defaultVariant);
904            } else {
905                $.each(variants, function(index, variantData) {
906                    if (variantData.available === true) {
907                        Theme.Utils.Product.setDefaultVariant(variantData);
908                        //Break Loop in case of available 
909                        inStock = 1;
910                        return false;
911                    }
912                });
913            }
914
915            if (parseInt(inStock) == 0) {
916                $("#add-to-cart").addClass("disabled btn-outstock").attr("disabled", true).text(Translator.getStr("SoldOut")); // set add-to-cart button to unavailable class and disable button
917                $("#btnnotify").css("display", "block");
918
919                //Set Variant ID In Case of Variant
920                var currValues = Theme.Utils.Product.selectedValues(); // get current values
921                if (currValues.length > 0) {
922                    var variant = Theme.Utils.Product.getVariant(currValues);
923                    $("#StoreCartProductVariantId").val(variant.id);
924                }
925            }
926        } else if (Theme.ProductData.product.available == false) {
927            $("#add-to-cart").addClass("disabled btn-outstock").attr("disabled", true).text(Translator.getStr("SoldOut")); // set add-to-cart button to unavailable class and disable button
928            $("#btnnotify").css("display", "block");
929            //var message = "Sold Out";
930            //$("#price-preview").text(message);
931            //$("#divclose").css("display", "block"); // set add-to-cart button to unavailable class and disable button
932        } else if (Theme.ProductData.product.available == true) {
933            if ($("#estimated_shipping_days").length > 0) {
934                if (Theme.ProductData.product.track_inventory && parseInt(Theme.ProductData.product.quantity) == 0 && Theme.ProductData.product.allow_purchase) {
935                    shipping_days = Theme.ProductData.product.estimated_outofstock_shipping_days;
936                    shipping_days += (parseInt(shipping_days) > 1) ? " days" : " day";
937                    $("#estimated_shipping_days").html(shipping_days);
938                }
939            }
940        }
941    },
942    setDefaultVariant: function(variantData) {
943        if (typeof variantData.size != 'undefined') {
944            if (variantData.hasOwnProperty("size")) {
945                $("#variant_size").val(variantData.size).trigger("change");
946
947                //Check Whether circle option exists
948                if ($(".variant_size_span").length) {
949                    $('.variant_size_span').each(function(i) {
950                        if ($(this).parent().find("input:radio[name='variant_size']").is(':enabled')) {
951                            $(this).trigger("click");
952                            return false;
953                        }
954                    });
955                }
956            }
957        }
958        if (typeof variantData.color != 'undefined') {
959            if (variantData.hasOwnProperty("color")) {
960                $("#variant_color").val(variantData.color).trigger("change");
961            }
962        }
963        if (typeof variantData.material != 'undefined') {
964            if (variantData.hasOwnProperty("material")) {
965                $("#variant_material").val(variantData.material).trigger("change");
966            }
967        }
968
969        if (variantData.available == true) {
970            /*if(typeof variantData.size != 'undefined'){
971               if(variantData.hasOwnProperty("size")) {
972               $("#variant_size").val(variantData.size).trigger("change");
973               }
974               }
975               if(typeof variantData.color != 'undefined'){
976               if(variantData.hasOwnProperty("color")) {
977               $("#variant_color").val(variantData.color).trigger("change");
978               }
979               }
980               if(typeof variantData.material != 'undefined'){
981               if(variantData.hasOwnProperty("material")) {
982               $("#variant_material").val(variantData.material).trigger("change");
983               }
984          }  */
985
986            //Set Estimated Shipping Days IN case track inventory true, Quantity in stock is Zero and allow_purchase is true
987            if ($("#estimated_shipping_days").length > 0) {
988                if (Theme.ProductData.product.track_inventory && parseInt(variantData.quantity) == 0 && Theme.ProductData.product.allow_purchase) {
989                    shipping_days = Theme.ProductData.product.estimated_outofstock_shipping_days;
990                } else {
991                    shipping_days = Theme.ProductData.product.estimated_shipping_days;
992                }
993                shipping_days += (parseInt(shipping_days) > 1) ? " days" : " day";
994                $("#estimated_shipping_days").html(shipping_days);
995            }
996
997            return true;
998        }
999        return false
1000    },
1001    selectCallback: function(variant, selector) {
1002        var Language = (typeof window.app.BRAND_STORE_LANGUAGE !== 'undefined') ? window.app.BRAND_STORE_LANGUAGE : "en";
1003        var Translator = new Theme.Language.ParseLanguage(Language);
1004
1005        if (variant && variant.available) {
1006            $("#add-to-cart").removeAttr("disabled").removeClass("disabled btn-outstock").html("<i class=\"flaticon-shopping-basket\"></i> " + Translator.getStr("AddToCart")).css("display", "block"); // set add-to-cart button to unavailable class and disable button
1007            $("#btnnotify").css("display", "none");
1008
1009            if (variant.product_price < variant.compare_at_price) {
1010                $("#price-preview").html("<div class=\"cut-price\"><span style=\"text-decoration: line-through;\">" + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.compare_at_price, "{{amount}}") + "</span></div> \n <div class=\"product-price text-danger\">" + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.product_price, "{{amount}}") + " </div>");
1011            } else {
1012                $("#price-preview").html("<div class=\"product-price\">" + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.product_price, "{{amount}}") + " </div>");
1013            }
1014
1015            if (Theme.ProductData.user.is_wholesaler && $("div#retail-price-preview") !== undefined) {
1016                if (variant.retail_net_price > variant.product_price) {
1017                    $("#retail-price-preview").removeClass("hidden");
1018                    $("#retail-net-price").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.retail_net_price, "{{amount}}"));
1019                } else {
1020                    $("#retail-price-preview").addClass("hidden");
1021                }
1022            } else if ($("div#retail-price-preview") !== undefined) {
1023                $("#retail-price-preview").addClass("hidden");
1024            }
1025
1026            $("#StoreCartProductVariantId").val(variant.id);
1027            $("#product-sku").html(variant.sku);
1028
1029            var totalStock = $("label#instock");
1030            if (typeof totalStock != 'undefined') {
1031                totalStock.html(variant.quantity + " in stock");
1032            }
1033
1034            var earnRewardPoints = $("span#earn_reward_points");
1035            if (typeof earnRewardPoints != 'undefined') {
1036                earnRewardPoints.html(variant.earn_reward_points);
1037            }
1038
1039            var spendRewardPoints = $("span#spend_reward_points");
1040            if (typeof spendRewardPoints != 'undefined') {
1041                spendRewardPoints.html(variant.spend_reward_points);
1042            }
1043
1044
1045            //Set Estimated Shipping Days IN case track inventory true, Quantity in stock is Zero and allow_purchase is true
1046            if ($("#estimated_shipping_days").length > 0) {
1047                if (Theme.ProductData.product.track_inventory && parseInt(variant.quantity) == 0 && Theme.ProductData.product.allow_purchase) {
1048                    shipping_days = Theme.ProductData.product.estimated_outofstock_shipping_days;
1049                } else {
1050                    shipping_days = Theme.ProductData.product.estimated_shipping_days;
1051                }
1052                shipping_days += (parseInt(shipping_days) > 1) ? " days" : " day";
1053                $("#estimated_shipping_days").html(shipping_days);
1054            }
1055
1056        } else {
1057            $("#add-to-cart").addClass("disabled btn-outstock").attr("disabled", true).text(Translator.getStr("SoldOut")); // set add-to-cart button to unavailable class and disable button
1058            $("#btnnotify").css("display", "block");
1059
1060            var message = '';
1061            if (variant && !variant.available) {
1062                if (variant.product_price < variant.compare_at_price) {
1063                    $("#price-preview").html("<div class=\"cut-price\"><span style=\"text-decoration: line-through;\">" + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.compare_at_price, "{{amount}}") + "</span></div> \n <div class=\"product-price text-danger\"> " + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.product_price, "{{amount}}") + " </div>");
1064                } else {
1065                    $("#price-preview").html("<div class=\"product-price\">" + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(variant.product_price, "{{amount}}") + " </div>");
1066                }
1067
1068                $("#StoreCartProductVariantId").val(variant.id);
1069                $("#product-sku").html(variant.sku);
1070
1071                var totalStock = $("label#instock");
1072                if (typeof totalStock != 'undefined') {
1073                    totalStock.html("0 in stock");
1074                }
1075
1076                var earnRewardPoints = $("span#earn_reward_points");
1077                if (typeof earnRewardPoints != 'undefined') {
1078                    earnRewardPoints.html(variant.earn_reward_points);
1079                }
1080
1081                var spendRewardPoints = $("span#spend_reward_points");
1082                if (typeof spendRewardPoints != 'undefined') {
1083                    spendRewardPoints.html(variant.spend_reward_points);
1084                }
1085
1086            } else {
1087                $("#price-preview").text("Unavailable");
1088                $("#StoreCartProductVariantId").val(0);
1089            }
1090        }
1091    },
1092    socialSharing: function() {
1093        $('.prettySocial').prettySocial();
1094    },
1095    setNotify: function() {
1096        $("#btnnotify").on("click", function(event) {
1097            event.preventDefault();
1098            var product_variant_id = $("form#StoreCartIndexForm").find("input#StoreCartProductVariantId").val();
1099            $("form#StoreProductNotifyIndexForm").find("input#product_variant_id").val(product_variant_id);
1100            //return false;
1101        });
1102
1103        $("button#btnnotifysubmit").on("click", function(event) {
1104            var FormID = $(this).closest("form").attr('id');
1105            $("#" + FormID + "").on('submit', function(event) {
1106
1107                var ProductId = $(this).find("input#id").val();
1108                var ProductVariantId = $(this).find("input#product_variant_id").val();
1109                var FullName = $(this).find("input#full_name").val();
1110                var Email = $(this).find("input#email").val();
1111                var MobileNo = $(this).find("input#mobile_no").val();
1112                var CustomerID = $(this).find("input#customer_id").val();
1113
1114                var FormData = "data[Product][id]=" + ProductId + "&data[Product][product_variant_id]=" + ProductVariantId + "&data[Product][full_name]=" + FullName + "&data[Product][email]=" + Email + "&data[Product][mobile_no]=" + MobileNo + "&data[Product][customer_id]=" + CustomerID + "";
1115                if (FullName.length == 0 || Email.length == 0 || MobileNo.length == 0) {
1116                    alert("Please fill all required information");
1117                    return false;
1118                }
1119                $.ajax({
1120                    type: "POST",
1121                    async: true,
1122                    cache: false,
1123                    url: "/store_products/notify",
1124                    accepts: 'application/json',
1125                    dataType: "json",
1126                    data: FormData,
1127                    beforeSend: function(XMLHttpRequest) {
1128                        //$("#payment_city_id").find("option").not(':first').remove();
1129                        $("button#btnnotifysubmit").addClass("disabled").attr("disabled", "disabled");
1130                    },
1131                    complete: function() {
1132                        $("button#btnnotifysubmit").removeClass("disabled").removeAttr("disabled");
1133                    },
1134                    success: function(data, textStatus) {
1135                        if (data.notify_status !== undefined && data.notify_status == 1) {
1136                            var strHTML = "<p class=\"text-success h5\">You asked to notify you when the product " + data.product_name + " in our store.</p> \r\n";
1137                            strHTML = strHTML + "<p>Thanks for your interest in our products.</p>";
1138                            $('#notifyModalBody').html(strHTML);
1139                            $("button#btnnotifysubmit").addClass("hidden");
1140                            setTimeout(function() {
1141                                $("#btnnotifyclose").trigger("click");
1142                            }, 2000);
1143                        } else {
1144                            var strHTML = "<p class=\"text-danger\">There was an error while processing your request. Please try again.</p>";
1145                            $('#notifyModalBody').prepend(strHTML);
1146                        }
1147                    },
1148                    error: function(jqXHR, textStatus, errorThrown) {
1149                        //console.log(jqXHR.responseText);
1150                        if (jqXHR.status == 500) {
1151                            alert('Internal error: ' + jqXHR.responseText);
1152                        }
1153                    }
1154                });
1155
1156                // stop the form from submitting the normal way and refreshing the page
1157                event.preventDefault();
1158            });
1159
1160            //event.preventDefault();
1161            //return false;  //stop the actual form post !important!
1162        });
1163    },
1164    setAttributes: function() {
1165
1166        $(document).on("click", ".swatches-title a", function(event) {
1167            event.preventDefault();
1168            var attributeId = $(this).data("attributeId");
1169            var slideID = $(this).data('slideId');
1170            $('.swatches-details').each(function() {
1171                if (parseInt($(this).data("attributeId")) == parseInt(attributeId)) {
1172                    $(this).css('display', "block");
1173                } else {
1174                    $(this).css('display', "none");
1175                }
1176            });
1177            $("#swatch_details_" + attributeId + " li#" + slideID).show().siblings("li").hide();
1178            $("#swatchesModal" + attributeId + "").modal('show');
1179            return false;
1180        });
1181
1182
1183        $(document).on("click", ".swatches a", function(event) {
1184            event.preventDefault();
1185            var attributeId = $(this).data("attributeId");
1186            $('.swatches-details').each(function() {
1187                if (parseInt($(this).data("attributeId")) == parseInt(attributeId)) {
1188                    $(this).css('display', "block");
1189                } else {
1190                    $(this).css('display', "none");
1191                }
1192            });
1193
1194            //$('html,body').animate({ scrollTop: $("#swatch_details_"+ attributeId +"").offset().top - 190}, 1000);
1195            var slideID = $(this).attr('id');
1196            //$(this).next("#swatch_details li#"+slideID).show().siblings("li").hide();
1197            $("#swatch_details_" + attributeId + " li#" + slideID).show().siblings("li").hide();
1198            $("#swatchesModal" + attributeId + "").modal('show');
1199            return false;
1200        });
1201
1202        $(".swatches-details a#next").on("click", function() {
1203            if ($(".swatches-details ul li.newboxes:visible").next().length != 0) {
1204                $(".swatches-details ul li.newboxes:visible").next().show().prev().hide();
1205            } else {
1206                $(".swatches-details ul li.newboxes:visible").hide();
1207                $(".swatches-details ul li.newboxes:first").show();
1208            }
1209            return false;
1210        });
1211
1212        $(".swatches-details a#prev").on("click", function() {
1213            if ($(".swatches-details ul li.newboxes:visible").prev().length != 0)
1214                $(".swatches-details ul li.newboxes:visible").prev().show().next().hide();
1215            else {
1216                $(".swatches-details ul li.newboxes:visible").hide();
1217                $(".swatches-details ul li.newboxes:last").show();
1218            }
1219            return false;
1220        });
1221
1222        $("a#btn_swatch_close").on('click', function(event) {
1223            event.preventDefault();
1224            $("div.swatches-details").hide();
1225        });
1226    },
1227    setReview: function() {
1228        $('#rating').rating({
1229            min: 0,
1230            max: 5,
1231            step: 1,
1232            size: 'xs',
1233            showCaption: false,
1234            showClear: false
1235        });
1236
1237        $('#rating-input').on('rating.change', function() {
1238            alert($('#rating-input').val());
1239        });
1240
1241        $("#StoreProductReviewIndexForm").validate({
1242            submitHandler: function(form) {
1243                var ProductId = $(form).find("input#id").val();
1244                var CustomerId = $(form).find("input#customer_id").val();
1245                var FullName = $(form).find("input#full_name").val();
1246                var Email = $(form).find("input#email").val();
1247                var Subject = $(form).find("input#subject").val();
1248                var Comment = $(form).find("textarea#comment").val();
1249                var Rating = $(form).find("input#rating").val();
1250                var ReviewImages = $(form).find("input#review_images").val();
1251                var FormData = "data[Product][id]=" + ProductId + "&data[Product][customer_id]=" + CustomerId + "&data[Product][full_name]=" + FullName + "&data[Product][email]=" + Email + "&data[Product][subject]=" + Subject + "&data[Product][comment]=" + Comment + "&data[Product][rating]=" + Rating + "&data[Product][review_images]=" + ReviewImages + "";
1252                //var FormData = "data[Product][id]=" + ProductId + "&data[Product][customer_id]=" + CustomerId + "&data[Product][full_name]=" + FullName + "&data[Product][email]=" + Email + "&data[Product][subject]=" + Subject + "&data[Product][comment]=" + Comment + "&data[Product][rating]=" + Rating + "";
1253
1254                $.ajax({
1255                    type: "POST",
1256                    async: true,
1257                    cache: false,
1258                    url: "/store_products/review",
1259                    accepts: 'application/json',
1260                    dataType: "json",
1261                    data: FormData,
1262                    beforeSend: function(XMLHttpRequest) {
1263                        $("button#btnreviewsubmit").addClass("disabled").attr("disabled", "disabled");
1264                    },
1265                    complete: function() {
1266                        $(form).trigger("reset");
1267                        //$('html,body').animate({ scrollTop: $("#divreview").offset().top - 60}, 1000);
1268                        $("button#btnreviewsubmit").removeClass("disabled").removeAttr("disabled");
1269                        $("#reviewform").toggle();
1270                    },
1271                    success: function(data, textStatus) {
1272                        if (data.review_status !== undefined && data.review_status == 1) {
1273                            $("#review_err").hide();
1274                            $("#review_success").show();
1275                        } else {
1276                            $("#review_err").show();
1277                            $("#review_success").hide();
1278                        }
1279                    },
1280                    error: function(jqXHR, textStatus, errorThrown) {
1281                        //console.log(jqXHR);
1282                        if (jqXHR.status == 500) {
1283                            alert('Internal error: ' + jqXHR.responseText);
1284                        }
1285                    }
1286                });
1287                return false; // blocks redirect after submission via ajax
1288            }
1289        });
1290
1291        /*
1292        $("button#btnreviewsubmit").on("click", function(event) {
1293        var FormID = $(this).closest("form").attr('id');
1294        $("#"+ FormID +"").on('submit',function(event){
1295        // stop the form from submitting the normal way and refreshing the page
1296        event.preventDefault();
1297
1298        var ProductId = $(this).find("input#id").val();
1299        var CustomerId = $(this).find("input#customer_id").val();
1300        var FullName = $(this).find("input#full_name").val();
1301        var Email = $(this).find("input#email").val();
1302        var Subject = $(this).find("input#subject").val();
1303        var Comment = $(this).find("input#comment").val();
1304        var Rating = $(this).find("input#rating").val();
1305
1306        var FormData = "data[Product][id]=" + ProductId + "&data[Product][customer_id]=" + CustomerId + "&data[Product][full_name]=" + FullName + "&data[Product][email]=" + Email + "&data[Product][subject]=" + Subject + "&data[Product][comment]=" + Comment + "&data[Product][rating]=" + Rating + "";
1307
1308        if(FullName.length == 0 || Email.length == 0 || Subject.length == 0 || Comment.length == 0 || Rating.length == 0){
1309        alert("Please fill all required information");
1310        return false;
1311        }
1312
1313
1314
1315        });
1316
1317        //event.preventDefault();
1318        //return false;  //stop the actual form post !important!
1319        });
1320        */
1321    },
1322    checkCODAvailable: function() {
1323        $("button#btncodsubmit").on("click", function(event) {
1324            event.stopImmediatePropagation();
1325            event.preventDefault();
1326
1327            var pincode = $(this).closest("form").find("input#cod_pincode").val();
1328            $('.cod_error').css({
1329                'display': 'none'
1330            });
1331            $('#cod_message').html('');
1332
1333            if (pincode === '') {
1334                $('#cod_pincode').val('').addClass('required').attr('placeholder', 'Enter valid pincode');
1335                $('.cod_error').css({
1336                    'display': 'block'
1337                });
1338                return false;
1339            }
1340            if (pincode.length < 6) {
1341                $('#cod_pincode').val('').addClass('required').attr('placeholder', 'Enter valid pincode');
1342                $('.cod_error').css({
1343                    'display': 'block'
1344                });
1345                return false;
1346            }
1347            if (pincode.length > 8) {
1348                $('#cod_pincode').val('').addClass('required').attr('placeholder', 'Enter valid pincode');
1349                $('.cod_error').css({
1350                    'display': 'block'
1351                });
1352                return false;
1353            }
1354            if (isNaN(pincode)) {
1355                $('#cod_pincode').val('').addClass('required').attr('placeholder', 'Enter valid pincode');
1356                $('.cod_error').css({
1357                    'display': 'block'
1358                });
1359                return false;
1360            }
1361
1362            var ajaxLoading = false;
1363
1364            if (!ajaxLoading) {
1365                ajaxLoading = true;
1366
1367                var CODPincode = $(this).closest("form").find("input#cod_pincode").val();
1368                var cod_enable = $(this).closest("form").find("input#cod_enable").val();
1369                var delivery_enable = $(this).closest("form").find("input#delivery_enable").val();
1370
1371                var FormData = "data[shipping_pincode]=" + CODPincode + "";
1372
1373                $.ajax({
1374                    type: "POST",
1375                    async: true,
1376                    cache: false,
1377                    url: "/store_orders/check_delivery_cod_available",
1378                    accepts: 'application/json',
1379                    dataType: "json",
1380                    data: FormData,
1381                    beforeSend: function(XMLHttpRequest) {
1382                        $("button#btncodsubmit").addClass("disabled").attr("disabled", "disabled");
1383                    },
1384                    complete: function() {
1385                        ajaxLoading = false;
1386                        $("button#btncodsubmit").removeClass("disabled").removeAttr("disabled");
1387                    },
1388                    success: function(data, textStatus) {
1389                        var strHTML = "<div class=\"row\">\r\n";
1390                        if (data.delivery_status !== undefined && data.delivery_status == 1) {
1391                            if (parseInt(delivery_enable) == 1 && parseInt(cod_enable) == 1) {
1392                                strHTML = strHTML + "<div class=\"col-md-6 col-sm-12 col-xs-12\"><strong>Delivery</strong> <br/> This item can be <span class=\"text-success\">Delivered</span> to your location</div>\r\n";
1393                            } else if (parseInt(delivery_enable) == 1) {
1394                                strHTML = strHTML + "<div class=\"col-md-12 col-sm-12 col-xs-12\"><strong>Delivery</strong> <br/> This item can be <span class=\"text-success\">Delivered</span> to your location</div>\r\n";
1395                            }
1396
1397                            if (parseInt(cod_enable) == 1) {
1398                                if (data.cod_status !== undefined && data.cod_status == 1) {
1399                                    strHTML = strHTML + "<div class=\"col-md-6 col-sm-12 col-xs-12\"><strong>COD</strong> <br/> is <span class=\"text-success\">available</span> for this item</div>\r\n";
1400                                } else {
1401                                    strHTML = strHTML + "<div class=\"col-md-6 col-sm-12 col-xs-12\"><strong>COD</strong> <br/> is <span class=\"text-danger\">not available</span> for this item</div>\r\n";
1402                                }
1403                            }
1404                        } else {
1405                            strHTML = strHTML + "<div class=\"col-md-12 col-sm-12 col-xs-12\"><strong>Delivery</strong> <br/> <span class=\"text-danger\">This item can't be delivered to your location</span></div>\r\n";
1406                        }
1407                        strHTML = strHTML + "</div>";
1408
1409                        $('#cod_message').html(strHTML);
1410                    },
1411                    error: function(jqXHR, textStatus, errorThrown) {
1412                        //console.log(jqXHR);
1413                        if (jqXHR.status == 500) {
1414                            alert('Internal error: ' + jqXHR.responseText);
1415                        }
1416                    }
1417                });
1418            }
1419
1420            //return false;  //stop the actual form post !important!
1421        });
1422    },
1423    saveWishlist: function() {
1424        $("#btn-addtowishlist").on("click", function(event) {
1425            // event.preventDefault();
1426            var ProductId = $(this).data("product-id");
1427            var LoggedIn = $(this).data("logged-in");
1428
1429            if (LoggedIn == "" || LoggedIn == 0) {
1430                alert("Please login");
1431                //window.location("/customers/login") ;
1432                //return 
1433            } else {
1434
1435                var FormData = "data[Product][id]=" + ProductId + "";
1436                $.ajax({
1437                    type: "POST",
1438                    async: true,
1439                    cache: false,
1440                    url: "/store_products/wishlist",
1441                    accepts: 'application/json',
1442                    dataType: "json",
1443                    data: FormData,
1444                    beforeSend: function(XMLHttpRequest) {
1445                        // $("button#btnreviewsubmit").addClass("disabled").attr("disabled", "disabled");
1446                    },
1447                    complete: function() {
1448                        // $('html,body').animate({ scrollTop: $("#divreview").offset().top - 60}, 1000);
1449                        // $("button#btnreviewsubmit").removeClass("disabled").removeAttr("disabled");
1450                    },
1451                    success: function(data, textStatus) {
1452                        // console.log(data);
1453                        if (data.wishlist_status !== undefined && data.wishlist_status == 1) {
1454                            $("#span-add-to-wishlist").hide();
1455                            $("#span-added-to-wishlist").show();
1456
1457                            //$("#wishlist_err").hide();
1458                            //$("#wishlist_success").show();
1459                        } else {
1460                            $("#span-add-to-wishlist").show();
1461                            $("#span-added-to-wishlist").hide();
1462
1463                            //$("#wishlist_err").show();
1464                            //$("#wishlist_success").hide();
1465                        }
1466                    },
1467                    error: function(jqXHR, textStatus, errorThrown) {
1468                        //console.log(errorThrown);
1469                        if (jqXHR.status == 500) {
1470                            alert('Internal error: ' + jqXHR.responseText);
1471                        }
1472                    }
1473                });
1474                return false; // blocks redirect after submission via ajax
1475            }
1476
1477        });
1478    },
1479    saveAjax: function() {
1480        $(document).on("click", "button#add-to-cart", function(event) {
1481            event.preventDefault();
1482
1483            if (parseInt(Theme.ProductData.product.variants.length) == 0 && parseInt(Theme.ProductData.product.minimum_order_quantity) > 0) {
1484                if ($("input#quantity").val() < parseInt(Theme.ProductData.product.minimum_order_quantity)) {
1485                    $("div#diverror").show();
1486                    $("div#diverror").find(".label-danger").html("Minimum order quantity must be " + parseInt(Theme.ProductData.product.minimum_order_quantity));
1487                    return false;
1488                } else {
1489                    $("div#diverror").hide();
1490                }
1491            } else {
1492                $("div#diverror").hide();
1493            }
1494
1495            //Check Variant Quantity
1496            var allowAdd = 1;
1497            var quickView = $(this).data("quickView");
1498            var currValues = Theme.Utils.Product.selectedValues(); // get current values
1499            var variant = Theme.Utils.Product.getVariant(currValues);
1500            var inputQuantity = $("form#StoreCartIndexForm").find("input#quantity").val();
1501
1502            if ((variant && !variant.available) || (variant && variant.available && Theme.ProductData.product.track_inventory && !Theme.ProductData.product.allow_purchase && (parseFloat(variant.quantity) < parseFloat(inputQuantity)))) {
1503                allowAdd = 0;
1504            } else if (Theme.ProductData.product.options.length == 0) {
1505                if (Theme.ProductData.product.available == false || (Theme.ProductData.product.available && Theme.ProductData.product.track_inventory && !Theme.ProductData.product.allow_purchase && (parseFloat(Theme.ProductData.product.quantity) < parseFloat(inputQuantity)))) {
1506                    allowAdd = 0;
1507                }
1508            }
1509
1510            //Now Process To Add
1511            if (parseInt(allowAdd) == 1) {
1512                //Check Form Process
1513                var FormID = $(this).closest("form").attr('id');
1514                var ProductId = $(this).closest("form").find("input#StoreCartId").val();
1515                var ProductVariantId = $(this).closest("form").find("input#StoreCartProductVariantId").val();
1516                var ProductQuantity = $(this).closest("form").find("input#quantity").val();
1517                var FormData = "data[StoreCart][id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId + "&data[StoreCart][quantity]=" + ProductQuantity;
1518
1519                //New Code Developed For Custom Fields
1520                if ($(this).closest("form").find("select#title").length > 0) {
1521                    FormData = FormData + "&data[StoreCart][title]=" + $(this).closest("form").find("select#title").val();
1522                }
1523                if ($(this).closest("form").find("input#full_name").length > 0) {
1524                    FormData = FormData + "&data[StoreCart][full_name]=" + $(this).closest("form").find("input#full_name").val();
1525                }
1526                if ($(this).closest("form").find("input#date_of_birth").length > 0) {
1527                    FormData = FormData + "&data[StoreCart][date_of_birth]=" + $(this).closest("form").find("input#date_of_birth").val();
1528                }
1529                if ($(this).closest("form").find("input#time_of_birth").length > 0) {
1530                    FormData = FormData + "&data[StoreCart][time_of_birth]=" + $(this).closest("form").find("input#time_of_birth").val();
1531                }
1532                if ($(this).closest("form").find("input#place_of_birth").length > 0) {
1533                    FormData = FormData + "&data[StoreCart][place_of_birth]=" + $(this).closest("form").find("input#place_of_birth").val();
1534                }
1535                if ($(this).closest("form").find("select#gender").length > 0) {
1536                    FormData = FormData + "&data[StoreCart][gender]=" + $(this).closest("form").find("select#gender").val();
1537                }
1538                if ($(this).closest("form").find("select#marital_status").length > 0) {
1539                    FormData = FormData + "&data[StoreCart][marital_status]=" + $(this).closest("form").find("select#marital_status").val();
1540                }
1541                if ($(this).closest("form").find("textarea#other_information").length > 0) {
1542                    FormData = FormData + "&data[StoreCart][other_information]=" + $(this).closest("form").find("textarea#other_information").val();
1543                }
1544
1545                $.ajax({
1546                    type: "POST",
1547                    async: true,
1548                    cache: false,
1549                    url: "/store_carts/ajax_add",
1550                    dataType: "html",
1551                    data: FormData,
1552                    beforeSend: function(XMLHttpRequest) {
1553
1554                    },
1555                    success: function(data, textStatus) {
1556                        var body = $("html, body");
1557                        body.animate({
1558                            scrollTop: 0
1559                        }, '1000', 'swing');
1560                        $("div#div-drop-cart").empty().append(data).find('.dropdown-menu').first().slideDown('slow').delay(5000).slideUp('fast');
1561                        $("div#div-drop-cart-xs").empty().append(data);
1562                        if (parseInt(quickView) == 1) {
1563                            $(document).find(".quick-modal-box, .modal-overlay").fadeOut(500, function() {
1564                                $(document).find('#quickProduct').find(".quick-modal-body").html('');
1565                                $(document).find(".modal-overlay").remove();
1566                            });
1567                        }
1568                    },
1569                    error: function(jqXHR, textStatus, errorThrown) {
1570                        if (jqXHR.status == 500) {
1571                            alert('Internal error: ' + jqXHR.responseText);
1572                        }
1573                    }
1574                });
1575                //Stop the form from submitting the normal way and refreshing the page
1576                return false;
1577
1578            } else {
1579                alert("SORRY, THIS VARIANT COMBINATION IS SOLD OUT, PLEASE CHOOSE ANOTHER COMBINATION");
1580                return false; //stop the actual form post !important!
1581            }
1582        });
1583    },
1584    setAddonPrice: function() {
1585        $(".product_addon_value").on("change", function() {
1586            var addonprice = 0;
1587            addonprice = $('.product_addon_value').find(':selected').data('addonprice');
1588            //$("#div-addon-price").html(window.app.BRAND_STORE_CURRENCY + ' ' + addonprice);
1589        });
1590    },
1591    saveAddonAjax: function() {
1592        $("button.btnaddoncart").on("click", function(ev) {
1593            //Check Variant Quantity
1594            var allowAdd = 0;
1595            var ProductId = 0;
1596            var ProductAddonValueId = 0;
1597            ProductId = $("#product_id").val();
1598            ProductAddonValueId = $("#product_addon_value_id").val();
1599
1600            if (ProductId && ProductAddonValueId) {
1601                allowAdd = 1;
1602            } else if (!ProductId || !ProductAddonValueId) {
1603                allowAdd = 0;
1604            }
1605
1606            //Now Process To Add
1607            if (parseInt(allowAdd) == 1) {
1608                //Check Form Process
1609                var FormID = $(this).closest("form").attr('id');
1610                var FormData = "data[StoreCart][id]=" + ProductId + "&data[StoreCart][product_addon_value_id]=" + ProductAddonValueId;
1611
1612                $.ajax({
1613                    type: "POST",
1614                    async: true,
1615                    cache: false,
1616                    url: "/store_carts/ajax_addon",
1617                    dataType: "html",
1618                    data: FormData,
1619                    beforeSend: function(XMLHttpRequest) {
1620                        //$("#StoreOrderPaymentCityId").find("option").not(':first').remove();
1621                    },
1622                    success: function(data, textStatus) {
1623                        if (data.length > 0 && data.trim() !== "failure") {
1624                            alert("Addon added successfully");
1625                        } else {
1626                            alert("Please add this product to your cart before choosing the addon.");
1627                        }
1628                    },
1629                    error: function(jqXHR, textStatus, errorThrown) {
1630                        if (jqXHR.status == 500) {
1631                            alert('Internal error: ' + jqXHR.responseText);
1632                        }
1633                    }
1634                });
1635
1636                // stop the form from submitting the normal way and refreshing the page
1637                return false;
1638
1639            } else {
1640                alert("Sorry, you need to select a addon from the given list");
1641                ev.preventDefault();
1642                return false; //stop the actual form post !important!
1643            }
1644        });
1645    },
1646    saveMultipleAjax: function() {
1647        $("button.btnattribute").on("click", function(ev) {
1648            //Now Process To Add
1649            if ($('.chkproduct:checked').size() > 0) {
1650                //Check Form Process
1651                var FormData = $("form#StoreAttributeValueIndexForm").serialize();
1652                $("form#StoreAttributeValueIndexForm").on('submit', function(event) {
1653                    $.ajax({
1654                        type: "POST",
1655                        async: true,
1656                        cache: false,
1657                        url: "/store_carts/ajax_multiple_add",
1658                        dataType: "html",
1659                        data: FormData,
1660                        beforeSend: function(XMLHttpRequest) {
1661                            //$("#StoreOrderPaymentCityId").find("option").not(':first').remove();
1662                        },
1663                        success: function(data, textStatus) {
1664                            var body = $("html, body");
1665                            body.animate({
1666                                scrollTop: 0
1667                            }, '1000', 'swing');
1668                            $("div#div-drop-cart").empty().append(data).find('.dropdown-menu').first().slideDown('slow').delay(5000).slideUp('fast');
1669                            $("div#div-drop-cart-xs").empty().append(data);
1670                        },
1671                        error: function(jqXHR, textStatus, errorThrown) {
1672                            if (jqXHR.status == 500) {
1673                                alert('Internal error: ' + jqXHR.responseText);
1674                            } else {
1675                                alert('Unexpected error.');
1676                            }
1677                        }
1678                    });
1679                    // stop the form from submitting the normal way and refreshing the page
1680                    event.preventDefault();
1681                    return false;
1682                });
1683
1684            } else {
1685                alert("PLEASE CHOOSE AT LEAST ONE FIBRE SWATCH");
1686                ev.preventDefault();
1687                return false; //stop the actual form post !important!
1688            }
1689        });
1690    },
1691    setProductQuantity: function() {
1692        // Count Input (Quantity)
1693        //------------------------------------------------------------------------------
1694        $(".incr-btn").on("click", function(e) {
1695            var $button = $(this);
1696            var inputQuantity = $button.parent().find('.quantity');
1697            var oldValue = inputQuantity.val();
1698            var minValue = inputQuantity.attr("min");
1699            $button.parent().find('.incr-btn[data-action="decrease"]').removeClass('inactive');
1700            if ($button.data('action') == "increase") {
1701                var newVal = parseFloat(oldValue) + 1;
1702            } else {
1703                // Don't allow decrementing below 1
1704                if (minValue != null) {
1705                    if (oldValue > minValue) {
1706                        var newVal = parseFloat(oldValue) - 1;
1707                    } else {
1708                        newVal = minValue;
1709                        $button.addClass('inactive');
1710                    }
1711                } else {
1712                    if (oldValue > 1) {
1713                        var newVal = parseFloat(oldValue) - 1;
1714                    } else {
1715                        newVal = 1;
1716                        $button.addClass('inactive');
1717                    }
1718                }
1719            }
1720            $button.parent().find('.quantity').val(newVal);
1721            e.preventDefault();
1722        });
1723    },
1724    preventWishlistLoginRedirection: function() {
1725        $(".wishlistLoginPopup").on("click", function(b) {
1726            b.preventDefault();
1727        })
1728    },
1729    addToWishlistFromList: function() {
1730        $(".addtowishlistfromlist").on("click", function() {
1731            var b = $(this).data("product-id"),
1732                c = $(this).data("logged-in");
1733            if ("" != c && 0 != c) {
1734                var d = "data[Product][id]=" + b;
1735                return $.ajax({
1736                    type: "POST",
1737                    async: !0,
1738                    cache: !1,
1739                    url: "/store_products/wishlist",
1740                    accepts: "application/json",
1741                    dataType: "json",
1742                    data: d,
1743                    beforeSend: function() {},
1744                    complete: function() {},
1745                    success: function(a) {
1746                        void 0 !== a.wishlist_status && 1 == a.wishlist_status ? ($("#mywishlistadd" + b).hide(), $("#mywishlistadded" + b).show()) : ($("#mywishlistadd" + b).show(), $("#mywishlistadded" + b).hide())
1747                    },
1748                    error: function(a) {
1749                        500 == a.status && alert("Internal error: " + a.responseText)
1750                    }
1751                }), !1
1752            }
1753            alert("Please login")
1754        });
1755
1756        $(document).on("click", ".addtowishlistfromlist_qc", function() {
1757            var b = $(this).data("product-id"),
1758                c = $(this).data("logged-in");
1759            if ("" != c && 0 != c) {
1760                var d = "data[Product][id]=" + b;
1761                return $.ajax({
1762                    type: "POST",
1763                    async: !0,
1764                    cache: !1,
1765                    url: "/store_products/wishlist",
1766                    accepts: "application/json",
1767                    dataType: "json",
1768                    data: d,
1769                    beforeSend: function() {},
1770                    complete: function() {},
1771                    success: function(a) {
1772                        void 0 !== a.wishlist_status && 1 == a.wishlist_status ? ($("#mywishlistadd_qc" + b).hide(), $("#mywishlistadded_qc" + b).show()) : ($("#mywishlistadd_qc" + b).show(), $("#mywishlistadded_qc" + b).hide())
1773                    },
1774                    error: function(a) {
1775                        500 == a.status && alert("Internal error: " + a.responseText)
1776                    }
1777                }), !1
1778            }
1779            alert("Please login")
1780        });
1781    },
1782    removeFromWishlist: function() {
1783        $(".removerromwishlist").on("click", function() {
1784            var b = $(this).data("product-id"),
1785                c = $(this).data("logged-in");
1786            if ("" != c && 0 != c) {
1787                var d = "data[Product][id]=" + b;
1788                return $.ajax({
1789                    type: "POST",
1790                    async: !0,
1791                    cache: !1,
1792                    url: "/store_product_wishlists/removefromwishlist",
1793                    accepts: "application/json",
1794                    dataType: "json",
1795                    data: d,
1796                    beforeSend: function() {},
1797                    complete: function() {},
1798                    success: function(a) {
1799                        void 0 !== a.wishlist_status && 1 == a.wishlist_status ? ($("#mywishlistadd" + b).show(), $("#mywishlistadded" + b).hide()) : ($("#mywishlistadd" + b).hide(), $("#mywishlistadded" + b).show())
1800                    },
1801                    error: function(a) {
1802                        500 == a.status && alert("Internal error: " + a.responseText)
1803                    }
1804                }), !1
1805            }
1806            alert("Please login")
1807        });
1808        $(document).on("click", ".removerromwishlist_qc", function() {
1809            var b = $(this).data("product-id"),
1810                c = $(this).data("logged-in");
1811            if ("" != c && 0 != c) {
1812                var d = "data[Product][id]=" + b;
1813                return $.ajax({
1814                    type: "POST",
1815                    async: !0,
1816                    cache: !1,
1817                    url: "/store_product_wishlists/removefromwishlist",
1818                    accepts: "application/json",
1819                    dataType: "json",
1820                    data: d,
1821                    beforeSend: function() {},
1822                    complete: function() {},
1823                    success: function(a) {
1824                        void 0 !== a.wishlist_status && 1 == a.wishlist_status ? ($("#mywishlistadd_qc" + b).show(), $("#mywishlistadded_qc" + b).hide()) : ($("#mywishlistadd_qc" + b).hide(), $("#mywishlistadded_qc" + b).show())
1825                    },
1826                    error: function(a) {
1827                        500 == a.status && alert("Internal error: " + a.responseText)
1828                    }
1829                }), !1
1830            }
1831            alert("Please login")
1832        })
1833    }
1834};
1835
1836Theme.Utils.CategoryProduct = {
1837    initCategoryProduct: function() {
1838        $(".product_variant").on("change", function(event) {
1839            //event.preventDefault();
1840            var product_variant_id = $(this).val();
1841            var product_price = $(this).find(':selected').data('productprice');
1842            var discount = $(this).find(':selected').data('discount');
1843            var net_price = $(this).find(':selected').data('netprice');
1844            var currency = $(this).find(':selected').data('currency');
1845            var quantity = $(this).find(':selected').data('quantity');
1846
1847            var price_row = "";
1848            if (discount > 0) {
1849                price_row = '<span class="cut-price">' + product_price + '</span>&nbsp; <span class="price text-danger" itemprop="price">' + net_price + '</span>';
1850            } else {
1851                price_row = '<span class="actual-price" itemprop="price">' + net_price + '</span>';
1852            }
1853            var product_id = $(this).closest("form").find("input#StoreCartId").val();
1854
1855            $('#price-hold-' + product_id + '').empty();
1856            $('#price-hold-' + product_id + '').html(price_row)
1857
1858        });
1859    },
1860
1861    ajaxAddCategoryProduct: function() {
1862        $(".btncart").on("click", function(event) {
1863            event.preventDefault();
1864            var product_id = $(this).closest("form").find("input#StoreCartId").val();
1865            var track_inventory = $(this).closest("form").find("input#StoreCartTrackInventory").val();
1866            var allow_purchase = $(this).closest("form").find("input#StoreCartAllowPurchase").val();
1867            var product_quantity = $(this).closest("form").find("input#StoreCartProductQuantity").val();
1868            var quantity = $(this).closest("form").find("input#quantity").val();
1869            var min_quantity = $(this).closest("form").find("input#quantity").attr('min');
1870            var variant_exist = $(this).closest("form").find("input#StoreCartVariantExist").val();
1871            var product_variant_quantity = $(this).closest("form").find(".product_variant").find(':selected').data('productvariantquantity');
1872            var showWarningModal = 0;
1873
1874            if (min_quantity != null && min_quantity > quantity) {
1875                alert('Product minimum order quantity is ' + min_quantity + '.');
1876                return false;
1877            }
1878
1879            if (track_inventory == 1 && allow_purchase == 0) {
1880                if (variant_exist > 0) {
1881                    if (quantity > product_variant_quantity && quantity > 0) {
1882                        showWarningModal = 1;
1883                    }
1884                } else {
1885                    if (quantity > product_quantity && quantity > 0) {
1886                        showWarningModal = 1;
1887                    }
1888                }
1889            }
1890
1891            if (showWarningModal == 1) {
1892                $("#inventoryModal").modal('show');
1893            } else {
1894                //Check Form Process
1895                var FormID = $(this).closest("form").attr('id');
1896                var ProductId = $(this).closest("form").find("input#StoreCartId").val();
1897                var ProductVariantId = $(this).closest("form").find("#StoreCartProductVariantId").val();
1898                var ProductQuantity = $(this).closest("form").find("input#quantity").val();
1899                var FormData = "data[StoreCart][id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId + "&data[StoreCart][quantity]=" + ProductQuantity;
1900
1901                $.ajax({
1902                    type: "POST",
1903                    async: true,
1904                    cache: false,
1905                    url: "/store_carts/ajax_add",
1906                    dataType: "html",
1907                    data: FormData,
1908                    beforeSend: function(XMLHttpRequest) {
1909
1910                    },
1911                    success: function(data, textStatus) {
1912                        var body = $("html, body");
1913                        body.animate({
1914                            scrollTop: 0
1915                        }, '1000', 'swing');
1916                        $("div#div-drop-cart").empty().append(data).find('.dropdown-menu').first().slideDown('slow').delay(5000).slideUp('fast');
1917                    },
1918                    error: function(jqXHR, textStatus, errorThrown) {
1919
1920                        if (jqXHR.status == 500) {
1921                            alert('Internal error: ' + jqXHR.responseText);
1922                        } else {
1923                            alert('Unexpected error.');
1924                        }
1925                    }
1926                });
1927            }
1928            return false;
1929
1930        });
1931    }
1932};
1933
1934	
1935Theme.Utils.Customer = {
1936    initCustomer: function() {
1937        /*
1938        if($('#CustomerCountryId').val() == 101){
1939        $("#state_name").val("");
1940        $("#state_name").hide();
1941        $("#city_name").val("");
1942        $("#city_name").hide();
1943        $("#CustomerStateId").show();
1944        $("#CustomerCityId").show();
1945        $("#CustomerStateId").attr("required", "required");
1946        $("#CustomerCityId").attr("required", "required");
1947        $("#spanstate").show();
1948        $("#spancity").show();
1949        } else{
1950        $("#CustomerStateId").val(0);
1951        $("#CustomerStateId").hide();
1952        $("#CustomerCityId").val(0);
1953        $("#CustomerCityId").hide();
1954        $("#state_name").show();
1955        $("#city_name").show();
1956        $("#CustomerStateId").removeAttr("required");
1957        $("#CustomerCityId").removeAttr("required");
1958        $("#spanstate").hide();
1959        $("#spancity").hide();
1960        }
1961        */
1962
1963        /*
1964        $("#CustomerCountryId").on("change", function (event) {
1965        if($(this).val() == 101){
1966        $("#state_name").val("");
1967        $("#state_name").hide();
1968        $("#city_name").val("");
1969        $("#city_name").hide();
1970        $("#CustomerStateId").show();
1971        $("#CustomerCityId").show();
1972        $("#CustomerStateId").attr("required", "required");
1973        $("#CustomerCityId").attr("required", "required");
1974        $("#spanstate").show();
1975        $("#spancity").show();
1976        } else {
1977        $("#CustomerStateId").val(0);
1978        $("#CustomerStateId").hide();
1979        $("#CustomerCityId").val(0);
1980        $("#CustomerCityId").hide();
1981        $("#state_name").show();
1982        $("#city_name").show();
1983        $("#CustomerStateId").removeAttr("required");
1984        $("#CustomerCityId").removeAttr("required");
1985        $("#spanstate").hide();
1986        $("#spancity").hide();
1987        }
1988        });
1989        */
1990        
1991        Theme.Utils.Element.init();
1992
1993        Theme.Utils.Customer.changeCountry();
1994        //Theme.Utils.Customer.changeState();
1995        if (parseInt(defaultValues.CountryId) > 0) {
1996            $("select#country_id").change();
1997        }
1998        /*
1999        if(parseInt(defaultValues.StateId) > 0) {
2000        $("#CustomerStateId").change();
2001        $('#CustomerCityId option[value="'+ defaultValues.CityId +'"]').prop('selected',true);
2002        }
2003        */
2004    },
2005    initEditProfile: function() {
2006        Theme.Utils.Element.init();
2007        Theme.Utils.Customer.changeCountry();
2008        //Theme.Utils.Customer.changeState();
2009
2010        if ($('#phone').length > 0) {
2011            window.phone_intlTel = Theme.Utils.PhoneCountryCode('phone', defaultValues.PhoneISO2);
2012        }
2013        if ($('#alternate_phone').length > 0) {
2014            window.alternate_phone_intlTel = Theme.Utils.PhoneCountryCode('alternate_phone', defaultValues.PhoneISO2);
2015        }        
2016        if ($('#shipping_phone').length > 0) {
2017            window.shipping_phone_intlTel = Theme.Utils.PhoneCountryCode('shipping_phone', defaultValues.ShippingPhoneISO2);
2018        }
2019        if ($('#payment_phone').length > 0) {
2020            window.payment_phone_intlTel = Theme.Utils.PhoneCountryCode('payment_phone', defaultValues.PaymentPhoneISO2);
2021        }
2022
2023        //Check Phone Number and Pincode
2024        if (parseInt(defaultValues.CountryId) > 0) {
2025            if (parseInt(defaultValues.CountryId) == 101) {
2026                //$("#phone").attr("minlength", 10).attr("maxlength", 10);
2027                $("#zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
2028                $("#phone").attr("onKeyUp", "remove_first(this);");
2029            } else {
2030                $("#phone").removeAttr("minlength").attr("maxlength", 20);
2031                $("#zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
2032            }
2033        }
2034
2035        //Display Values Accordingly
2036        if (parseInt(defaultValues.StateId) > 0) {
2037            $("#state_name").val('').hide();
2038            $("select#state_id").show().attr("required", "required");
2039            $("input#city_name").show().attr("required", "required");
2040        } else {
2041            $("select#state_id").val(0).removeAttr("required").hide();
2042            $("input#state_name").show();
2043            $("input#city_name").show().removeAttr("required");
2044        }
2045
2046        $("#CustomerEditProfileForm").validate({
2047            ignore: []
2048        });
2049    },
2050    initChangePassword: function() {
2051        $("#CustomerPasswordEditProfileForm").validate();
2052        $("#old_password").rules("add", {
2053            required: true,
2054            messages: {
2055                required: "Please enter valid old password."
2056            }
2057        });
2058        $("#new_password").rules("add", {
2059            required: true,
2060            messages: {
2061                required: "Please enter valid new password."
2062            }
2063        });
2064        $("#confirm_password").rules("add", {
2065            required: true,
2066            equalTo: "#new_password",
2067            messages: {
2068                required: "Please enter valid confirm password.",
2069                equalTo: "New Password does not match the confirm password."
2070            }
2071        });
2072    },
2073    initResetPassword: function() {
2074        $("#CustomerResetPasswordForm").validate();
2075        $("#new_password").rules("add", {
2076            required: true,
2077            messages: {
2078                required: "Please enter valid new password."
2079            }
2080        });
2081        $("#confirm_password").rules("add", {
2082            required: true,
2083            equalTo: "#new_password",
2084            messages: {
2085                required: "Please enter valid confirm password.",
2086                equalTo: "New Password does not match the confirm password."
2087            }
2088        });
2089    },
2090    getStates: function(country_id) {
2091        $.ajax({
2092            type: "POST",
2093            async: true,
2094            cache: false,
2095            url: "/customers/getStates",
2096            dataType: "html",
2097            data: {
2098                "data[Customer][country_id]": country_id
2099            },
2100            beforeSend: function(XMLHttpRequest) {
2101                // $("#CustomerCityId").find("option").remove().end().append("<option value=\"0\">Select City</option>").val(0);
2102                $("select#state_id").find("option").not(':first').remove();
2103
2104                $("#state_name").hide();
2105                $("#state_id").hide();
2106            },
2107            success: function(data, textStatus) {
2108                if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2109                    $("#state_name").val('').hide();
2110                    $("#state_id").show().attr("required", "required").append(data);
2111                    $("#city_name").attr("required", "required");
2112                } else {
2113                    $("#state_id").val(0).removeAttr("required").hide();
2114                    $("#state_name").show();
2115                    $("#city_name").removeAttr("required");
2116                }
2117
2118            },
2119            error: function(jqXHR, textStatus, errorThrown) {
2120                if (jqXHR.status == 500) {
2121                    alert('Internal error: ' + jqXHR.responseText);
2122                }
2123            }
2124        });
2125    },
2126    getCities: function(country_id, state_id) {
2127        $.ajax({
2128            type: "POST",
2129            async: true,
2130            cache: false,
2131            url: "/customers/getCities",
2132            dataType: "html",
2133            data: {
2134                "data[Customer][country_id]": country_id,
2135                "data[Customer][state_id]": state_id
2136            },
2137            beforeSend: function(XMLHttpRequest) {
2138                // $("#CustomerCityId").find("option").remove().end().append("<option value=\"0\">Select City</option>").val(0);
2139                $("#city_id").find("option").not(':first').remove();
2140            },
2141            success: function(data, textStatus) {
2142                if(parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2143                    $("#city_id").append(data);
2144                }
2145            },
2146            error: function(jqXHR, textStatus, errorThrown) {
2147                if (jqXHR.status == 500) {
2148                    alert('Internal error: ' + jqXHR.responseText);
2149                }
2150            }
2151        });
2152    },
2153    changeCountry: function() {
2154        $("select#country_id").on("change", function(event) {
2155            $("option:selected", $(this)).each(function() {
2156                var country_id = $(this).val();
2157                Theme.Utils.Customer.getStates(country_id);
2158
2159                //Check Phone Number and Pincode
2160                if (parseInt(country_id) == 101) {
2161                    //$("#phone").attr("minlength", 10).attr("maxlength", 10);
2162                    $("#phone").attr("onKeyUp", "remove_first(this);");
2163                    $("#zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
2164                } else {
2165                    $("#phone").removeAttr("minlength").attr("maxlength", 20);
2166                    $("#zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
2167                }
2168
2169                return false;
2170            });
2171        });
2172    },
2173    changeState: function() {
2174        $("#state_id").on("change", function(event) {
2175            $("option:selected", $(this)).each(function() {
2176                var country_id = $("#country_id").val();
2177                var state_id = $(this).val();
2178                Theme.Utils.Customer.getCities(country_id, state_id);
2179                return false;
2180            });
2181        });
2182    },
2183    validateCustomer: function() {
2184        $("#CustomerRegisterForm").validate({
2185            errorPlacement: function(error, element) {
2186                if (element.parent('.checkbox').length) {
2187                    error.insertAfter(element.parent());
2188                } else {
2189                    error.insertAfter(element);
2190                }
2191            }
2192        });
2193    },
2194    ajaxLogin: function() {
2195        $("#CustomerIndexForm").validate({
2196            submitHandler: function(form) {
2197                var Email = ($(form).find("input#email").length > 0) ? $(form).find("input#email").val().trim() : '';
2198                var Password = ($(form).find("input#password").length > 0) ? $(form).find("input#password").val().trim() : '';
2199                var RedirectUrl = ($(form).find("#redirect_url").length > 0) ? $(form).find("#redirect_url").val().trim() : '';
2200                
2201                if(window.googleRecaptchaSiteKey !== 'undefined') {
2202                    grecaptcha.ready(function () {
2203                        grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'customer_login'}).then(function (token) {
2204                            $(form).find('input#recaptcha_response').val(token);
2205                        });
2206                    });
2207                }
2208
2209                setTimeout(function () {
2210                    var recaptcha_response = $(form).find("input#recaptcha_response").val();
2211                    var FormData = "data[Customer][email]=" + Email + "&data[Customer][password]=" + Password + "&data[Customer][redirect_url]=" + RedirectUrl + "&data[recaptcha_response]=" + recaptcha_response;
2212
2213                    $.ajax({
2214                        type: "POST",
2215                        async: true,
2216                        cache: false,
2217                        url: "/customers/ajax_login",
2218                        accepts: 'application/json',
2219                        dataType: "json",
2220                        data: FormData,
2221                        beforeSend: function(XMLHttpRequest) {
2222                            $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled");
2223                        },
2224                        complete: function() {
2225                            $(form).trigger("reset");
2226                            //$('html,body').animate({ scrollTop: $("#divreview").offset().top - 60}, 1000);
2227                            $("button#btnloginsubmit").removeClass("disabled").removeAttr("disabled");
2228                        },
2229                        success: function(data, textStatus) {
2230                            //console.log(data);
2231                            if (data.login_status !== undefined && data.login_status == 1) {
2232                                $("#login_err").hide();
2233                                $("#login_success").fadeIn(3000);
2234                                $("#loginModal").modal('hide');
2235                                window.location.reload();
2236                            } else {
2237                                $("#login_err").show();
2238                                $("#login_success").hide();
2239                            }
2240                        },
2241                        error: function(jqXHR, textStatus, errorThrown) {
2242                            //alert(errorThrown);
2243                            //console.log(errorThrown);
2244                            if (jqXHR.status == 500) {
2245                                alert('Internal error: ' + jqXHR.responseText);
2246                            }
2247                        }
2248                    });
2249                }, 2000);
2250                return false; // blocks redirect after submission via ajax
2251            }
2252        });
2253    },
2254    validateLogin: function() {
2255        $("#CustomerLoginFormOtp").validate();
2256    },
2257    validateForgotPassword: function() {
2258        $("#CustomerForgotPasswordForm").validate();
2259    },
2260    initManageAddresses: function() {
2261        Theme.Utils.StoreOrder.changeShippingCountry();
2262        $('.edit_address').click(function() {
2263            var customerAddressId = $(this).data('id');
2264            var addressData = customAddressesObject[customerAddressId];
2265            $("input#action").val(2);
2266            if (customerAddressId != null && addressData != undefined) {
2267                //console.log(addressData);
2268                if (parseInt(addressData.shipping_state_id) > 0) {
2269                    Theme.Utils.StoreOrder.getShippingStates(addressData.shipping_country_id);
2270                }
2271
2272                if (parseInt(addressData.shipping_state_id) > 0) {
2273                    $("#shipping_state_name").val('').removeAttr("required").hide();
2274                    $(document).ajaxComplete(function(event, xhr, settings) {
2275                        if (settings.url === "/store_orders/getShippingStates") {
2276                            /////  $("select#shipping_state_id").show().attr("required", "required").val(parseInt(addressData.shipping_state_id));
2277                        }
2278                    });
2279
2280                } else {
2281                    $("select#shipping_country_id").change();
2282                    $("#shipping_state_id").val('').removeAttr("required").hide();
2283                    $("#shipping_state_name").show().removeAttr("required");
2284                }
2285
2286                $("input#customer_address_id").val(addressData.id);
2287                $("input#shipping_first_name").val(addressData.shipping_first_name);
2288                $("input#shipping_last_name").val(addressData.shipping_last_name);
2289                $("input#shipping_phone").val(addressData.shipping_phone);
2290                $("textarea#shipping_address").val(addressData.shipping_address);
2291                $("input#shipping_zip").val(addressData.shipping_postal_code);
2292                $("input#shipping_city_name").val(addressData.shipping_city);
2293                $("input#shipping_company_name").val(addressData.shipping_company_name);
2294                $("input#shipping_gstin").val(addressData.shipping_gstin);
2295                $("select#shipping_state_id").val(addressData.shipping_state_id);
2296                $("select#shipping_country_id").val(addressData.shipping_country_id);
2297                $("input#shipping_state_name").val(addressData.shipping_state);
2298                $("input#payment_address").val(addressData.payment_address);
2299                $("input#payment_first_name").val(addressData.payment_first_name);
2300                $("input#payment_last_name").val(addressData.payment_last_name);
2301                $("input#payment_zip").val(addressData.payment_postal_code);
2302                $("input#payment_email").val(addressData.payment_email);
2303                $("input#payment_city_name").val(addressData.payment_city);
2304                if (parseInt(addressData.is_default) == 1) {
2305                    $("input#is_default").prop('checked', true);
2306                    $("#defaultCheckbox").hide();
2307                } else {
2308                    $("input#is_default").prop('checked', false);
2309                    $("#defaultCheckbox").show();
2310                }
2311                $("select#payment_state_id").val(addressData.payment_state_id);
2312                $("input#payment_state_name").val(addressData.payment_state);
2313                $("select#payment_country_id").val(addressData.payment_country_id);
2314                $("select#shipping_address_type_id").val(addressData.shipping_address_type_id
2314);
2315            }
2316        });
2317
2318        $('.delete_address').click(function() {
2319            var customerAddressId = $(this).data('id');
2320            $("input#customer_address_id").val(customerAddressId);
2321        });
2322
2323        $('#add_new_address').click(function() {
2324            $("input#action").val(1);
2325            $("#shipping_state_id").val('').removeAttr("required").hide();
2326            $("input#customer_address_id").val(0);
2327            $("input#shipping_first_name").val('');
2328            $("input#shipping_last_name").val('');
2329            $("input#shipping_address").val('');
2330            $("input#shipping_phone").val('');
2331            $("input#shipping_zip").val('');
2332            $("input#shipping_city_name").val('');
2333            $("input#shipping_company_name").val('');
2334            $("input#shipping_gstin").val('');
2335            $("select#shipping_state_id").val('');
2336            $("select#shipping_country_id").val('');
2337            $("input#shipping_state_name").val('');
2338            $("input#payment_address").val('');
2339            $("input#payment_first_name").val('');
2340            $("input#payment_last_name").val('');
2341            $("input#payment_zip").val('');
2342            $("input#payment_city_name").val('');
2343            $("select#payment_state_id").val('');
2344            $("input#payment_state_name").val('');
2345            $("input#is_default").prop('checked', false);
2346            $("#defaultCheckbox").show();
2347            $("select#shipping_country_id").change();
2348            $("#shipping_state_id").val('').removeAttr("required").hide();
2349            $("#shipping_state_name").show().removeAttr("required");
2350        });
2351
2352        $("form#EditAddressForm").validate({
2353            ignore: [],
2354            debug: !0,
2355            invalidHandler: function() {
2356
2357            },
2358            errorPlacement: function(a, b) {
2359                a.insertAfter(b.parent(".checkbox").length ? b.parent() : b)
2360            },
2361            submitHandler: function(a) {
2362                a.submit()
2363            }
2364        });
2365    },
2366};
2367
2368Theme.Utils.StoreOrder = {
2369    initCheckout: function() {
2370
2371        Theme.Utils.Element.init();
2372
2373        this.changeDeliveryMode();
2374        this.changeShippingCountry();
2375        this.changeShippingState();
2376        this.changeShippingCity();
2377
2378        this.changePaymentCountry();
2379        this.changePaymentState();
2380        
2381        this.setOtherDetails();
2382        //Incase of User Logged In / Not Logged In
2383        if (defaultValues.DefaultAddressId != 0 && defaultValues.DefaultAddressId != null) {
2384            Theme.Utils.StoreOrder.editMultipleAddress(defaultValues.DefaultAddressId, false);
2385        } else {
2386            this.setCheckoutDefaults();
2387        }
2388		if ($('#shipping_phone').length > 0) {
2389            window.shipping_phone_intlTel = Theme.Utils.PhoneCountryCode('shipping_phone', defaultValues.ShippingPhoneISO2);
2390		}
2391		if ($('#payment_phone').length > 0) {
2392		    window.payment_phone_intlTel = Theme.Utils.PhoneCountryCode('payment_phone', defaultValues.PaymentPhoneISO2);
2393        }
2394        
2395        // Determine store shipping address. If donation system is enabled
2396        let customer_id = $("#customer_id").val();
2397        let is_donation_enable = $("#is_donation_enable").val();
2398        let product_shipping_address_id = $("#product_shipping_address_id").val();
2399        if (parseInt(is_donation_enable) == 1 && parseInt(product_shipping_address_id) > 0) {
2400            if (customer_id > 0) {
2401                customerShippingAddressId = $("input[name='data[StoreOrder][customer_address_selected]']:checked").val();
2402                Theme.Utils.StoreOrder.editMultipleAddress(customerShippingAddressId, true);
2403            } else {
2404                Theme.Utils.StoreOrder.editMultipleAddress(product_shipping_address_id, true);
2405            }
2406        }
2407
2408        //Either Register OR Guest Checkout
2409        $("#checkout_via1").on("click", function() {
2410            $("#divpassword").show();
2411            $("input#shipping_password").attr("required", "required");
2412
2413            // Determine store shipping address. If donation system is enabled
2414            let is_donation_enable = $("#is_donation_enable").val();
2415            let product_shipping_address_id = $("#product_shipping_address_id").val();
2416            if (parseInt(is_donation_enable) == 1 && parseInt(product_shipping_address_id) > 0) {
2417                Theme.Utils.StoreOrder.editMultipleAddress(product_shipping_address_id, true);
2418            }
2419        });
2420
2421        $("#checkout_via2").on("click", function() {
2422            $("#divpassword").hide();
2423            $("input#shipping_password").val('').removeAttr("required");
2424
2425            //Determine store shipping address. If donation system is enabled   
2426            let is_donation_enable = $("#is_donation_enable").val();
2427            let product_shipping_address_id = $("#product_shipping_address_id").val();
2428            if (parseInt(is_donation_enable) == 1 && parseInt(product_shipping_address_id) > 0) {
2429                Theme.Utils.StoreOrder.editMultipleAddress(product_shipping_address_id, true);
2430            }
2431        });
2432
2433        //Set Property of Guest Checkout
2434        if (parseInt(defaultValues.isGuestCheckoutChecked) == 1) {
2435            $('#checkout_via2').prop('checked', true);
2436        }
2437
2438        //Guest Checkout
2439        if ($('#checkout_via2').is(':checked')) {
2440            $("#divpassword").hide();
2441            $("#shipping_password").val('');
2442            $("input#shipping_password").removeAttr("required");
2443        }
2444
2445        $("a.edit-link").on("click", function(e) {
2446            e.preventDefault();
2447            $("div#divshipping").toggleClass("hidden");
2448            $("div#divbilling").toggleClass("hidden");
2449            $("div#divbillshipinfo").toggleClass("hidden");
2450
2451            if ($('#StoreOrderOtherPayment').is(':checked')) {
2452                $("#StoreOrderOtherPayment").toggle(this.checked).trigger("click");
2453            }
2454
2455            var scrollUpto = 0;
2456            if ($(this).data('scrollDiv') == "shipping") {
2457                var offsetShipping = $("div#ShippingSummary").offset();
2458                scrollUpto = offsetShipping.top - 10;
2459
2460            } else if ($(this).data('scrollDiv') == "billing") {
2461                var offsetPayment = $("div#PaymentSummary").offset();
2462                scrollUpto = offsetPayment.top - 10;
2463            }
2464
2465            $('html, body').animate({
2466                scrollTop: scrollUpto
2467            }, 1000);
2468        });
2469
2470        $("a#btnLogin").on("click", function(e) {
2471            var ele = $("div#toggleText");
2472            var text = $("a#btnLogin");
2473            ele.toggle();
2474        });
2475
2476        $('form#StoreOrderCheckoutForm input[type=text]').on('keyup', function() {
2477            Theme.Utils.StoreOrder.resetElements();
2478        });
2479
2480        if(window.googleRecaptchaSiteKey !== undefined && $('input#recaptchaResponse2').length) {
2481            grecaptcha.ready(function () {
2482                if ($("button#btnStoreOrder").is(":disabled")) {
2483                    $("button#btnStoreOrder").removeProp("disabled").html('Continue');
2484                }
2485            });
2486        }
2487
2488        if ($("button#btnStoreOrder").is(":disabled")) {
2489            $("button#btnStoreOrder").removeProp("disabled").html('Continue');
2490        } 
2491
2492
2493        //View Form Answer Details
2494        $(document).on("click", ".view-form-details", function() {
2495
2496            var order_id = $(this).data('orderId');
2497            var order_product_id = $(this).data('orderProductId');
2498            var form_answer_id = $(this).data('formAnswerId');
2499
2500            FormData = "data[StoreOrderProduct][order_id]="+ order_id +"&data[StoreOrderProduct][order_product_id]="+ order_product_id +"&data[StoreOrderProduct][form_answer_id]="+ form_answer_id ;
2501            $.ajax({
2502                type: "POST",
2503                async: true,
2504                cache: false,
2505                url: "/store_order_products/getProductFormAnswerDetails",
2506                dataType: "html",
2507                data: FormData,
2508                beforeSend: function(XMLHttpRequest) {
2509                    //$("button .verify-otp-code").addClass("disabled").attr("disabled", "disabled");
2510                },
2511                complete: function() {
2512                    //$("button .verify-otp-code").removeClass("disabled").removeAttr("disabled");
2513                },
2514                success: function(data, textStatus) {                    
2515                    //console.log(data);
2516                    $('div#div_form_details').html(data);
2517                    // Open the modal
2518                    $('div#formDetailsModal').modal('show');
2519                },
2520                error: function(jqXHR, textStatus, errorThrown) {
2521                    //console.log(jqXHR);
2522                    if (jqXHR.status == 500) {
2523                        alert('Internal error: ' + jqXHR.responseText);
2524                    }
2525                }
2526            });
2527        });       
2528    },
2529    checkRewardPoint: function() {        
2530        $(document).on("click", "#btnRewarPoint", function() {
2531            var customer_id = $('#divCreditPoint').find("#customer_id").val();
2532            var discount_percent = $('#divCreditPoint').find("#discount_percent").val();
2533            var total_spended_reward_points = $('#divCreditPoint').find("#total_spended_reward_points").val();            
2534            
2535            //Remove Coupon
2536            $.ajax({
2537                type: "POST",
2538                async: false,
2539                cache: false,
2540                url: "/store_coupons/ajax_delete_coupon",
2541                dataType: "json",                
2542                beforeSend: function(XMLHttpRequest) {
2543                    
2544                },
2545                success: function(responseData) {
2546                //Add Reward Points    
2547                    $.ajax({
2548                        type: "POST",
2549                        async: false,
2550                        cache: false,
2551                        url: "/store_reward_points/ajax_check_reward_point",
2552                        dataType: "json",
2553                        data: {
2554                            "customer_id": customer_id,
2555                            "total_spended_reward_points": total_spended_reward_points
2556                        },
2557                        beforeSend: function(XMLHttpRequest) {
2558                            
2559                        },
2560                        success: function(responseData) {
2561                            //if(responseData.success == true) {
2562                                //window.location.reload();
2563                           // }
2564                            //Add Coupon
2565                            $.ajax({
2566                                type: "POST",
2567                                async: false,
2568                                cache: false,
2569                                url: "/store_orders/ajax_set_customer_discount",
2570                                dataType: "json",
2571                                data: { "customer_discount_percent": discount_percent},
2572                                beforeSend: function(XMLHttpRequest) {
2573                                    
2574                                },
2575                                success: function(responseData) {
2576                                    //if(responseData.success == true) {
2577                                        window.location.reload();
2578                                   // }
2579                                },
2580                                error: function(jqXHR, textStatus, errorThrown) {
2581                                    if (jqXHR.status == 500) {
2582                                        alert('Internal error: ' + jqXHR.responseText);
2583                                    }
2584                                }
2585                            });
2586                        },
2587                        error: function(jqXHR, textStatus, errorThrown) {
2588                            if (jqXHR.status == 500) {
2589                                alert('Internal error: ' + jqXHR.responseText);
2590                            }
2591                        }
2592                    });
2593                },
2594                error: function(jqXHR, textStatus, errorThrown) {
2595                    if (jqXHR.status == 500) {
2596                        alert('Internal error: ' + jqXHR.responseText);
2597                    }
2598                }
2599            });
2600        });        
2601    },
2602    updateGiftInfo: function() {
2603        $('.gift-packing').change(function() {
2604            var message = $(".gift-message").val();
2605            if ($(this).is(':checked') && parseInt($(this).val()) == 1) {
2606                Theme.Utils.UpdateGiftPackingInfo.ajaxUpdateGiftInfo(1, message);
2607            } else {
2608                Theme.Utils.UpdateGiftPackingInfo.ajaxUpdateGiftInfo(0, message);
2609            }
2610        });
2611
2612        $('.gift-message').change(function() {
2613            var is_gift_packing = ($(".gift-packing").prop('checked') == true) ? 1 : 0;
2614            var message = $(this).val();
2615            Theme.Utils.UpdateGiftPackingInfo.ajaxUpdateGiftInfo(is_gift_packing, message);
2616        });
2617    },
2618    initAccordion: function() {
2619        $('.accordion-summary').click(function() {
2620            $('.summary-details').slideToggle("fast");
2621            if ($(this).hasClass('summary-open')) {
2622                $(this).addClass('summary-close').removeClass('summary-open');
2623            } else {
2624                $(this).addClass('summary-open').removeClass('summary-close');
2625            }
2626        });
2627    },
2628    setCheckoutDefaults: function() {        
2629        //Step 1: Incase Shipping Country ID Selected
2630        if (parseInt(defaultValues.ShippingCountryId) > 0) {
2631            $("select#shipping_country_id").change();
2632        }
2633
2634        //Step 2: Set States as Per Delivery Pincode
2635        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
2636            $("select#shipping_state_name").val(defaultValues.ShippingStateName).attr("selected", "selected").show();
2637            $("select#shipping_state_name").change();
2638            // if (!$("input#shipping_state_name").is(':visible')) {
2639            //     Theme.Utils.StoreOrder.getShippingServiceableStates(defaultValues.ShippingCountryId);
2640            // }
2641        } else if (parseInt(defaultValues.DeliveryPincodeCheckId) != 5) {
2642            if (parseInt(defaultValues.ShippingStateId) > 0) {
2643                $("select#shipping_state_id").val(defaultValues.ShippingStateId).attr("selected", "selected").show();
2644                $("select#shipping_state_id").change();
2645            } else {
2646                $("input#shipping_state_name").val(defaultValues.ShippingStateName);
2647            }
2648        }
2649
2650        //Step 3: Set Cities as Per Delivery Pincode
2651        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
2652            $("select#shipping_city_name").val(defaultValues.ShippingCityName).attr("selected", "selected").show();
2653            $("select#shipping_city_name").change();
2654        } else if (parseInt(defaultValues.DeliveryPincodeCheckId) != 5) {
2655            if (parseInt(defaultValues.ShippingCityId) > 0) {
2656                $("select#shipping_city_id").val(defaultValues.ShippingCityId).attr("selected", "selected").show();
2657                $("select#shipping_city_id").change();
2658            } else {
2659                $("input#shipping_city_name").val(defaultValues.ShippingCityName);
2660            }
2661        }
2662
2663        //Step 4: Set Areas as Per Delivery Pincode
2664        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
2665            $("select#shipping_serviceable_area_id").val(defaultValues.ShippingServiceableAreaId).attr("selected", "selected").show();
2666        }
2667
2668        //Step 5: Incase Payment Country ID Selected
2669        if (parseInt(defaultValues.PaymentCountryId) > 0) {
2670            $("select#payment_country_id").change();
2671        }
2672
2673        //Step 6: Incase Payment State ID Selected
2674        if (parseInt(defaultValues.PaymentStateId) > 0) {
2675            $("select#payment_state_id").val(defaultValues.PaymentStateId).attr("selected", "selected").show();
2676            $("select#payment_state_id").change();
2677        } else {
2678            $("input#payment_state_name").val(defaultValues.PaymentStateName);
2679        }
2680
2681        // if (parseInt(defaultValues.ShippingStateId) > 0) {
2682
2683        // } elseif((defaultValues.ShippingStateId)) {
2684
2685        // }
2686
2687        // if (defaultValues.IsShippingServiceableCity == 1 && parseInt(defaultValues.DeliveryPincodeCheckId) != 5 && parseInt(defaultValues.ShippingCountryId) == parseInt(defaultValues.storeCountryId)) {
2688        //     Theme.Utils.StoreOrder.getShippingSrilankaStates(defaultValues.ShippingCountryId);
2689        // }
2690        /*
2691        if (parseInt(defaultValues.ShippingStateId) > 0) {            
2692            $("input#shipping_state_name").val('').removeAttr("required").hide();
2693            $("select#shipping_state_id").attr("required", "required").val(parseInt(defaultValues.ShippingStateId)).attr("selected", "selected").show();
2694            if (parseInt(defaultValues.IsShippingServiceableCity) == 1 && parseInt(defaultValues.DeliveryPincodeCheckId) != 5) {
2695                $("input#shipping_city_name").val('').removeAttr("required").hide();
2696                $("select#shipping_city_id").attr("required", "required").val(parseInt(defaultValues.ShippingCityId)).attr("selected", "selected").show();
2697            }
2698        } else {            
2699            $("select#shipping_country_id").change();
2700            // //$("#shipping_state_id").val('').removeAttr("required").hide();
2701            // //$("#shipping_city_id").val('').removeAttr("required").hide();
2702            // //$("#shipping_state_name").show().removeAttr("required");
2703            // //$("#shipping_city_name").show().removeAttr("required");
2704        }
2705        
2706        //Set States As Per Available Cities
2707        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
2708            if (!$("input#shipping_state_name").is(':visible')) {
2709                Theme.Utils.StoreOrder.getShippingServiceableStates(defaultValues.ShippingCountryId);
2710            }
2711        }       
2712
2713        //Billing System Payment State ID
2714        if (parseInt(defaultValues.PaymentStateId) > 0) {
2715            // $("select#payment_state_id").show().attr("required", "required");
2716            // $("input#payment_state_name").val('').removeAttr("required").hide();
2717            // //$("#payment_city_id").show().attr("required", "required");
2718            // //$("#payment_city_name").val('').removeAttr("required").hide();
2719            
2720            $("input#payment_state_name").val('').removeAttr("required").hide();
2721            $("select#payment_state_id").attr("required", "required").val(parseInt(defaultValues.PaymentStateId)).attr("selected", "selected").show();
2722        }
2723        // } else {
2724        //     $("select#payment_state_id").val(0).removeAttr("required").hide();
2725        //     $("input#payment_state_name").show().removeAttr("required");
2726        //     //$("#payment_city_id").val(0).removeAttr("required").hide();
2727        //     //$("#payment_city_name").show().removeAttr("required");
2728        // }
2729        */
2730        
2731        //Incase Order Other Payment is Checked
2732        if ($('#StoreOrderOtherPayment').is(':checked')) {
2733            $("#PaymentSummary input[type=text], #PaymentSummary input[type=email]").removeAttr("required");
2734            $("#PaymentSummary textarea").removeAttr("required");
2735            $("select#payment_country_id").removeAttr("required");
2736            $("select#payment_state_id").removeAttr("required");
2737            //$("#payment_city_id").removeAttr("required");
2738            $("#PaymentSummary").hide();
2739        }
2740
2741        /*
2742        //Setting Shipping or Billing is active
2743        $("input:radio[class=delivery_mode]:first").attr('checked', true).click();
2744
2745        //Check Phone Number and Pincode
2746        if (parseInt(defaultValues.ShippingCountryId) == 101) {
2747            $("input#shipping_phone").attr("minlength", 10).attr("maxlength", 10).attr("onKeyUp", "remove_first(this);allow_numeric(this);");
2748            $("input#shipping_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
2749            $("input#shipping_zip").attr("required", "required").show();
2750        } else {
2751            $("input#shipping_phone").removeAttr("minlength").attr("maxlength", 20).attr("onKeyUp", "allow_numeric(this);");
2752            $("input#shipping_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
2753            $("input#shipping_zip").attr("required", "required").show();
2754            //$("input#shipping_city_name").attr("required", "required").show();
2755            
2756            if (parseInt(defaultValues.ShippingCountryId) == 125 || parseInt(defaultValues.ShippingCountryId.length) == 0) {
2757                $("input#shipping_zip").removeAttr("required");
2758            }
2759        }
2760
2761        //Important Do Not Remove
2762        if (parseInt(defaultValues.ShippingCountryId) == 101 && parseInt(defaultValues.DeliveryPincodeCheckId) != 5 && defaultValues.IsShippingServiceableCity == 1) {
2763            $("input#shipping_city_name").val('').removeAttr("required").hide();
2764            $("select#shipping_city_id").attr("required", "required").show();
2765        } else {
2766            $("input#shipping_city_name").attr("required", "required").show();
2767            $("select#shipping_city_id").val(0).removeAttr("required").hide();    
2768        }
2769
2770        if (parseInt(defaultValues.PaymentCountryId) == 101) {
2771            $("input#payment_phone").attr("minlength", 10).attr("maxlength", 10).attr("onKeyUp", "remove_first(this);allow_numeric(this);");
2772            $("input#payment_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
2773            $("input#payment_zip").attr("required", "required").show();
2774        } else {
2775            $("input#payment_phone").removeAttr("minlength").attr("maxlength", 20).removeAttr("onKeyUp");
2776            $("input#payment_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
2777            $("input#payment_zip").attr("required", "required").show();
2778
2779            if (!$('#StoreOrderOtherPayment').is(':checked')) {
2780                //$("input#payment_zip").attr("required", "required");
2781            }
2782            if (parseInt(defaultValues.PaymentCountryId) == 125 || parseInt(defaultValues.PaymentCountryId.length) == 0) {
2783                $("input#payment_zip").removeAttr("required");
2784            }
2785        }
2786
2787        //New Code To Handle Srilanka and Empty Country
2788        if (typeof $("select#shipping_country_id").val() !== 'undefined') {
2789            if ($("select#shipping_country_id").val().length == 0 || $("select#shipping_country_id").val() == 125) {
2790                $("input#shipping_zip").removeAttr("required");
2791            } else if ($("select#shipping_country_id").val() == 2) {
2792                $("select#shipping_state_id").change();
2793                //$("input#shipping_city_name").removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
2794                //$("label#shipping_city_name-error").hide();
2795            }
2796
2797            //Set Pincode Validation
2798            if (parseInt($("select#shipping_country_id option:selected").data("isPincodeRequired")) === 0) {
2799                $("input#shipping_zip").removeAttr("required").hide();
2800                $("label#shipping_zip-error").hide();
2801            }
2802        }
2803
2804        if (typeof $("select#payment_country_id").val() !== 'undefined') {
2805            if ($("select#payment_country_id").val().length == 0 || $("select#payment_country_id").val() == 125) {
2806                $("input#payment_zip").removeAttr("required");
2807            } else if ($("select#payment_country_id").val() == 2) {
2808                $("input#payment_city_name").removeAttr("required").hide();
2809                $("label#payment_city_name-error").hide();
2810            }
2811
2812            //Set Pincode Validation
2813            if (parseInt($("select#payment_country_id option:selected").data("isPincodeRequired")) === 0) {
2814                $("input#payment_zip").removeAttr("required").hide();
2815                $("label#payment_zip-error").hide();
2816            }
2817        }
2818        */        
2819    },
2820    setOtherDetails: function() {
2821        $("#StoreOrderOtherPayment").on("click", function() {
2822            if ($(this).is(':checked')) {
2823                $("#PaymentSummary input[type=text]").removeAttr("required");
2824                $("#PaymentSummary textarea").removeAttr("required");
2825                $("select#payment_country_id").removeAttr("required");
2826                $("select#payment_state_id").removeAttr("required");
2827                //$("#payment_city_id").removeAttr("required");
2828                $("#PaymentSummary").hide();
2829            } else {
2830                $("#PaymentSummary").show();
2831                $("#PaymentSummary input#payment_first_name").attr("required", "required");
2832                $("#PaymentSummary input#payment_last_name").attr("required", "required");
2833                $("#PaymentSummary input#payment_email").attr("required", "required");
2834                $("#PaymentSummary input#payment_phone").attr("required", "required");
2835                $("#PaymentSummary input#payment_address").attr("required", "required");
2836                if (parseInt($("select#payment_country_id").val()) == 101) {
2837                    //$("#PaymentSummary input#payment_zip").attr("required", "required");
2838                } else {
2839                    $("#PaymentSummary input#payment_zip").removeAttr("required");
2840                }
2841                if (parseInt(defaultValues.PaymentStateId) > 0) {
2842                    $("select#payment_state_id").attr("required", "required");
2843                    $("input#payment_state_name").val('').removeAttr("required").hide();
2844                }
2845            }
2846        });
2847    },
2848    getShippingStates: function(shipping_country_id) {
2849        if (parseInt(shipping_country_id) > 0) {
2850            $.ajax({
2851                type: "POST",
2852                async: false,
2853                cache: false,
2854                url: "/store_orders/getShippingStates",
2855                dataType: "html",
2856                data: {
2857                    "data[StoreOrder][shipping_country_id]": shipping_country_id
2858                },
2859                beforeSend: function(XMLHttpRequest) {
2860                    $("select#shipping_state_id").find("option").not(':first').remove();
2861                    $("select#shipping_city_id").find("option").not(':first').remove();
2862
2863                    $("input#shipping_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
2864                    $("select#shipping_state_id").hide();
2865                    $("input#shipping_city_name").attr("required", "required").show();
2866                    $("select#shipping_city_id").removeAttr("required").hide();
2867                },
2868                success: function(data, textStatus) {
2869                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2870                        $("select#shipping_state_id").attr("required", "required").append(data).val($("select#shipping_state_id option:first").val()).show().removeClass("hidden");
2871                    } else {                        
2872                        $("select#shipping_state_id").val($("select#shipping_state_id option:first").val()).removeAttr("required").hide();
2873                        $("input#shipping_state_name").val('').removeAttr("required").show().removeClass("hidden").parent("div").removeClass("field__input-wrapper--select");
2874                    }
2875                },
2876                error: function(jqXHR, textStatus, errorThrown) {
2877                    if (jqXHR.status == 500) {
2878                        alert('Internal error: ' + jqXHR.responseText);
2879                    }
2880                }
2881            });
2882        } else {
2883            $("input#shipping_state_name").val('').removeAttr("required").show().removeClass("hidden").parent("div").removeClass("field__input-wrapper--select");
2884        }
2885    },
2886    getShippingSrilankaStates: function(shipping_country_id) {
2887        if (parseInt(shipping_country_id) > 0) {
2888            $.ajax({
2889                type: "POST",
2890                async: false,
2891                cache: false,
2892                url: "/store_orders/getShippingSrilankaStates",
2893                dataType: "html",
2894                data: {
2895                    "data[StoreOrder][shipping_country_id]": shipping_country_id
2896                },
2897                beforeSend: function(XMLHttpRequest) {
2898                    $("select#shipping_state_id").find("option").not(':first').remove();
2899                    $("select#shipping_city_id").find("option").not(':first').remove();
2900                    $("input#shipping_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
2901                    $("select#shipping_state_id").val(0).hide();
2902                    $("input#shipping_city_name").val('').hide();
2903                    $("select#shipping_city_id").val(0).removeAttr("required").hide();
2904                },
2905                success: function(data, textStatus) {
2906                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2907                        $("select#shipping_state_id").attr("required", "required").append(data).show();
2908                        $("input#shipping_city_name").val('').removeAttr("required").hide();
2909                        $("select#shipping_city_id").attr("required", "required").show().closest(".field").addClass("field__input-wrapper--select");
2910                        $("select#shipping_city_id").prop('selectedIndex', 0);
2911                    } else {
2912                        $("select#shipping_state_id").val(0).removeAttr("required").hide();
2913                        $("input#shipping_state_name").val('').removeAttr("required").show().closest(".field").removeClass("field__input-wrapper--select");
2914                        $("select#shipping_city_id").removeAttr("required").hide();
2915                        $("input#shipping_city_name").val('').removeAttr("required").show().closest(".field").removeClass("field__input-wrapper--select");
2916                    }
2917
2918                    //console.log(data.length);
2919                },
2920                error: function(jqXHR, textStatus, errorThrown) {
2921                    if (jqXHR.status == 500) {
2922                        alert('Internal error: ' + jqXHR.responseText);
2923                    }
2924                }
2925            });
2926        }
2927    },
2928    getShippingCities: function(shipping_country_id, shipping_state_id) {
2929        if (parseInt(shipping_country_id) > 0 && parseInt(shipping_state_id) > 0) {
2930            $.ajax({
2931                type: "POST",
2932                async: true,
2933                cache: false,
2934                url: "/store_orders/getShippingCities",
2935                dataType: "html",
2936                data: {
2937                    "data[StoreOrder][shipping_country_id]": shipping_country_id,
2938                    "data[StoreOrder][shipping_state_id]": shipping_state_id
2939                },
2940                beforeSend: function(XMLHttpRequest) {
2941                    $("select#shipping_city_id").find("option").not(':first').remove();
2942                    $("input#shipping_state_name").val('').removeAttr("required").hide();
2943                },
2944                success: function(data, textStatus) {
2945                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2946                        $("select#shipping_city_id").append(data).show();
2947                    }
2948                },
2949                error: function(jqXHR, textStatus, errorThrown) {
2950                    if (jqXHR.status == 500) {
2951                        alert('Internal error: ' + jqXHR.responseText);
2952                    }
2953                }
2954            });
2955        }
2956    },
2957    getShippingSrilankaCities: function(shipping_country_id, shipping_state_id) {
2958        if (parseInt(shipping_country_id) > 0 && parseInt(shipping_state_id) > 0) {
2959
2960            $.ajax({
2961                type: "POST",
2962                async: false,
2963                cache: false,
2964                url: "/store_orders/getShippingSrilankaCities",
2965                dataType: "html",
2966                data: {
2967                    "data[StoreOrder][shipping_country_id]": shipping_country_id,
2968                    "data[StoreOrder][shipping_state_id]": shipping_state_id
2969                },
2970                beforeSend: function(XMLHttpRequest) {
2971                    $("input#shipping_city_name").val('').hide();
2972                    $("select#shipping_city_id").find("option").not(':first').remove();
2973                    $("select#shipping_city_id").val(0).removeAttr("required").hide();
2974                },
2975                success: function(data, textStatus) {
2976                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
2977                        $("select#shipping_city_id").attr("required", "required").append(data).show();
2978                        $("input#shipping_city_name").val('').removeAttr("required").hide();
2979                    } else {
2980                        $("select#shipping_city_id").removeAttr("required").hide();
2981                        $("input#shipping_city_name").val('').attr("required", "required").show();
2982                    }
2983                },
2984                error: function(jqXHR, textStatus, errorThrown) {
2985                    if (jqXHR.status == 500) {
2986                        alert('Internal error: ' + jqXHR.responseText);
2987                    }
2988                }
2989            });
2990        }
2991    },
2992    getShippingServiceableStates: function(shipping_country_id) {
2993        if (parseInt(shipping_country_id) > 0) {
2994            $.ajax({
2995                type: "POST",
2996                async: true,
2997                cache: false,
2998                url: "/store_orders/getShippingServiceableStates",
2999                dataType: "html",
3000                data: {
3001                    "data[StoreOrder][shipping_country_id]": shipping_country_id
3002                },
3003                beforeSend: function(XMLHttpRequest) {
3004                    $("select#shipping_state_name").find("option").not(':first').remove();
3005                    $("select#shipping_city_name").find("option").not(':first').remove();
3006                    $("select#shipping_serviceable_area_id").find("option").not(':first').remove();
3007                },
3008                complete: function(data) {
3009                    if (parseInt(defaultValues.ShippingStateName.length) > 0) {
3010                        $('select#shipping_state_name option[value=\'' + defaultValues.ShippingStateName + '\']').attr("selected", true);
3011                        $("select#shipping_state_name").trigger('change');
3012                    }
3013                },
3014                success: function(data, textStatus) {
3015                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
3016                        $("select#shipping_state_name").show().attr("required", "required").append(data);
3017                    } else {
3018                        $("select#shipping_state_name").val(0).removeAttr("required");
3019                    }
3020                },
3021                error: function(jqXHR, textStatus, errorThrown) {
3022                    if (jqXHR.status == 500) {
3023                        alert('Internal error: ' + jqXHR.responseText);
3024                    }
3025                }
3026            });
3027        }
3028    },
3029    getShippingServiceableCities: function(shipping_country_id, shipping_state_name) {
3030        if (parseInt(shipping_country_id) > 0 && parseInt(shipping_state_name.length) > 0) {
3031            $.ajax({
3032                type: "POST",
3033                async: true,
3034                cache: false,
3035                url: "/store_orders/getShippingServiceableCities",
3036                dataType: "html",
3037                data: {
3038                    "data[StoreOrder][shipping_country_id]": shipping_country_id,
3039                    "data[StoreOrder][shipping_state_name]": shipping_state_name
3040                },
3041                beforeSend: function(XMLHttpRequest) {
3042                    $("#shipping_city_name").find("option").not(':first').remove();
3043                    $("#shipping_serviceable_area_id").find("option").not(':first').remove();
3044                    if (parseInt(shipping_country_id) == 2) {
3045                        $("select#shipping_city_name").removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
3046                        $("label#shipping_city_name-error").hide();
3047                    } else {
3048                        $("select#shipping_city_name").attr("required", "required").show().closest(".field").addClass("field--show-floating-label");
3049                    }
3050                },
3051                complete: function(data) {
3052                    if (parseInt(defaultValues.ShippingCityName.length) > 0) {
3053                        $('select#shipping_city_name option[value="' + defaultValues.ShippingCityName + '"]').attr("selected", true);
3054                        $("select#shipping_city_name").trigger('change');
3055                    } 
3056
3057                    if (parseInt(shipping_country_id) == 2) {
3058                        $('select#shipping_city_name option[value="' + shipping_state_name + '"]').attr("selected", true);
3059                        $("select#shipping_city_name").trigger('change');
3060                    }
3061                },
3062                success: function(data, textStatus) {
3063                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
3064                        $("#shipping_city_name").append(data);
3065                    }
3066                },
3067                error: function(jqXHR, textStatus, errorThrown) {
3068                    if (jqXHR.status == 500) {
3069                        alert('Internal error: ' + jqXHR.responseText);
3070                    }
3071                }
3072            });
3073        }
3074    },
3075    getShippingServiceableAreas: function(shipping_country_id, shipping_state_name, shipping_city_name) {
3076        if (parseInt(shipping_country_id) > 0 && parseInt(shipping_state_name.length) > 0 && parseInt(shipping_city_name.length) > 0) {
3077            $.ajax({
3078                type: "POST",
3079                async: true,
3080                cache: false,
3081                url: "/store_orders/getShippingServiceableAreas",
3082                dataType: "html",
3083                data: {
3084                    "data[StoreOrder][shipping_country_id]": shipping_country_id,
3085                    "data[StoreOrder][shipping_state_name]": shipping_state_name,
3086                    "data[StoreOrder][shipping_city_name]": shipping_city_name
3087                },
3088                beforeSend: function(XMLHttpRequest) {
3089                    $("select#shipping_serviceable_area_id").find("option").not(':first').remove();
3090                },
3091                complete: function(data) {
3092                    if (parseInt(defaultValues.ShippingServiceableAreaId) > 0) {
3093                        $('select#shipping_serviceable_area_id option[value="' + defaultValues.ShippingServiceableAreaId + '"]').attr("selected", true);
3094                    }
3095                },
3096                success: function(data, textStatus) {
3097                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
3098                        $("select#shipping_serviceable_area_id").append(data);
3099                    }
3100                },
3101                error: function(jqXHR, textStatus, errorThrown) {
3102                    if (jqXHR.status == 500) {
3103                        alert('Internal error: ' + jqXHR.responseText);
3104                    }
3105                }
3106            });
3107        }
3108    },
3109    getPaymentStates: function(payment_country_id) {
3110        if (parseInt(payment_country_id) > 0) {
3111            $.ajax({
3112                type: "POST",
3113                async: false,
3114                cache: false,
3115                url: "/store_orders/getPaymentStates",
3116                dataType: "html",
3117                data: {
3118                    "data[StoreOrder][payment_country_id]": payment_country_id
3119                },
3120                beforeSend: function(XMLHttpRequest) {
3121                    $("select#payment_state_id").find("option").not(':first').remove();
3122                    $("input#payment_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
3123                    $("select#payment_state_id").val(0).hide();
3124                    //$("#payment_city_id").find("option").not(':first').remove();
3125                    //$("#payment_city_name").hide();
3126                    //$("#payment_city_id").hide();
3127                },
3128                success: function(data, textStatus) {
3129                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
3130                        $("select#payment_state_id").attr("required", "required").append(data).val($("select#payment_state_id option:first").val()).show();
3131                        //$("#payment_city_name").val('').removeAttr("required").hide();
3132                        //$("#payment_city_id").show().attr("required", "required");
3133                    } else {
3134                        $("select#payment_state_id").removeAttr("required").val($("select#payment_state_id option:first").val()).hide();
3135                        $("input#payment_state_name").attr("required", "required").val('').show().parent("div").removeClass("field__input-wrapper--select");
3136                        //$("#payment_city_id").val(0).removeAttr("required").hide();                        
3137                        //$("#payment_city_name").show().removeAttr("required");
3138                    }
3139                },
3140                error: function(jqXHR, textStatus, errorThrown) {
3141                    //console.log(jqXHR);
3142                    if (jqXHR.status == 500) {
3143                        alert('Internal error: ' + jqXHR.responseText);
3144                    }
3145                }
3146            });
3147        }
3148    },
3149    getPaymentCities: function(payment_country_id, payment_state_id) {
3150        if (parseInt(payment_country_id) > 0 && parseInt(payment_state_id) > 0) {
3151            $.ajax({
3152                type: "POST",
3153                async: true,
3154                cache: false,
3155                url: "/store_orders/getPaymentCities",
3156                dataType: "html",
3157                data: {
3158                    "data[StoreOrder][payment_country_id]": payment_country_id,
3159                    "data[StoreOrder][payment_state_id]": payment_state_id
3160                },
3161                beforeSend: function(XMLHttpRequest) {
3162                    $("input#payment_city_name").val('').removeAttr("required").hide();
3163                    $("select#payment_city_id").find("option").not(':first').remove();
3164                },
3165                success: function(data, textStatus) {
3166                    if (parseInt(data.length) > 10 && data.trim() != 'Record Not Found') {
3167                        $("select#payment_city_id").append(data).val('');
3168                    }
3169                },
3170                error: function(jqXHR, textStatus, errorThrown) {
3171                    if (jqXHR.status == 500) {
3172                        alert('Internal error: ' + jqXHR.responseText);
3173                    }
3174                }
3175            });
3176        }
3177    },
3178    changeShippingCountry: function() {
3179        $("select#shipping_country_id").on("change", function(event) {
3180            var eventCaller = $(event.delegateTarget);
3181            $("option:selected", $(this)).each(function() {
3182                var shipping_country_id = $(this).val();
3183                var payment_country_id = $(this).val();
3184
3185                const state_title = ($(this).data('stateTitle')) ? $(this).data('stateTitle') : '';
3186                const city_title = ($(this).data('cityTitle')) ? $(this).data('cityTitle') : '';
3187                const is_pincode_required = ($(this).data('isPincodeRequired')) ? $(this).data('isPincodeRequired') : 0;
3188                const hide_state_field = ($(this).data('hideStateField')) ? $(this).data('hideStateField') : 0;
3189                const hide_city_field = ($(this).data('hideCityField')) ? $(this).data('hideCityField') : 0;
3190
3191                $('.shipping_city').text(city_title);
3192                $("select#shipping_city_name option[value]:first").text("Select " + city_title);
3193
3194                //shipping_country_id(s) = 125 Sri Lanka, 101 India, 2 UAE, 223 USA
3195                if (parseInt(shipping_country_id) == 125) {
3196                    $('.shipping_serviceable_area').text('Town');
3197                    $("select#shipping_serviceable_area_id option[value]:first").text("Select Town");
3198                } else {
3199                    $('.shipping_serviceable_area').text('Area');
3200                    $("select#shipping_serviceable_area_id option[value]:first").text("Select Area");
3201                }
3202
3203                $("select#shipping_state_id").parent('div').find('label.field__label').html(state_title);
3204                $("select#shipping_state_id option[value]:first").text("Select " + state_title);
3205
3206                $("input#shipping_city_name").parent('div').find('label.field__label').html(city_title);
3207                $("input#shipping_city_name").attr('placeholder', city_title);
3208                
3209                if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
3210                    Theme.Utils.StoreOrder.getShippingServiceableStates(shipping_country_id);
3211                    $("select#shipping_state_name").parent('div').find('label').html(state_title);
3212                    $("select#shipping_state_name option[value]:first").text("Select " + state_title);
3213                    $("select#shipping_state_name").attr('placeholder', state_title);
3214
3215                    let shipping_state_name = ($("#shipping_state_name").val() != null) ? $("#shipping_state_name").val() : '';
3216                    if(parseInt(shipping_country_id) > 0 && parseInt(shipping_state_name.length) > 0) {
3217                        Theme.Utils.StoreOrder.getShippingServiceableCities(shipping_country_id, shipping_state_name);
3218                    }
3219                } else {
3220                    //if (defaultValues.IsShippingServiceableCity == 1 && (parseInt(shipping_country_id) == 2 || parseInt(shipping_country_id) == 101 || parseInt(shipping_country_id) == 125)) {
3221                    if (defaultValues.IsShippingServiceableCity == 1 && parseInt(shipping_country_id) == parseInt(defaultValues.storeCountryId)) {
3222                        Theme.Utils.StoreOrder.getShippingSrilankaStates(shipping_country_id);
3223                    } else {
3224                        $("#shipping_state_id").hide().closest(".field").removeClass("field__input-wrapper--select").addClass("field--show-floating-label");
3225                        $("#shipping_city_id").hide().closest(".field").removeClass("field__input-wrapper--select").addClass("field--show-floating-label");
3226
3227                        $("label#shipping_state_id-error").hide();
3228                        $("label#shipping_city_id-error").hide();
3229
3230                        Theme.Utils.StoreOrder.getShippingStates(shipping_country_id);
3231                    }
3232                }
3233
3234                //Set Billing Infomation Behalf of Shipping Information
3235                if ($("#StoreOrderOtherPayment").is(":checked")) {
3236                    if (parseInt(defaultValues.DeliveryPincodeCheckId) != 5) {
3237                        Theme.Utils.StoreOrder.getPaymentStates(payment_country_id);
3238                    }
3239                    if (parseInt(shipping_country_id) == 101) {
3240                        $("select#payment_state_id").attr("required", "required").val('').show();
3241                        $("input#payment_state_name").val('').removeAttr("required").hide();
3242                    } else {
3243                        $("select#payment_state_id").removeAttr("required").val('').hide();
3244                        $("input#payment_state_name").removeAttr("required").val('').show();
3245                        //$("input#payment_zip").attr("required", "required").show();
3246                        if (parseInt(shipping_country_id) == 125 || parseInt(shipping_country_id.length) == 0) {
3247                            $("input#payment_zip").removeAttr("required");
3248                        } else if (parseInt(shipping_country_id) == 2) {
3249                            $("input#payment_zip").removeAttr("required").hide();
3250                            $("label#payment_zip-error").hide();
3251                        }
3252                    }
3253                }
3254
3255                //Check Phone Number and Pincode
3256                if (parseInt(shipping_country_id) == 101) {
3257                    //$("input#shipping_phone").attr("minlength", 10).attr("onKeyUp", "remove_first(this);allow_numeric(this);");
3258                    $("input#shipping_phone").attr("minlength", 10).attr("onKeyUp", "remove_first(this);");
3259                    $("input#shipping_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
3260                    $("input#shipping_zip").attr("required", "required").show();
3261                    $("input#shipping_city_name").attr("required", "required").show();
3262                    $("select#shipping_city_id").removeAttr("required").hide();
3263                } else {
3264                    $("input#shipping_phone").removeAttr("minlength").attr("maxlength", 20);
3265                    $("input#shipping_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
3266                    $("input#shipping_zip").attr("required", "required").show();
3267                    $("input#shipping_city_name").attr("required", "required").show();
3268                    if (parseInt(shipping_country_id) == 125 || parseInt(shipping_country_id.length) == 0) {
3269                        $("input#shipping_zip").removeAttr("required").closest(".field").removeClass("field--show-floating-label");
3270                    } else if (parseInt(shipping_country_id) == 2) {
3271                        $("input#shipping_city_name").removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
3272                        $("label#shipping_city_name-error").hide();
3273                        $("select#shipping_city_name").removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
3274                        $("label#shipping_city_name-error").hide();
3275                    }
3276                    if (parseInt(is_pincode_required) === 0) {
3277                        $("input#shipping_zip").val('').removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
3278                        $("label#shipping_zip-error").hide();
3279                    }
3280                }
3281
3282                //Set State Visiblity As Per Country
3283                if(parseInt(hide_state_field) == 1) {
3284                    $("select#shipping_state_id").removeAttr("required");
3285                    $("input#shipping_state_name").removeAttr("required");
3286                    $("select#shipping_state_id").parent('div').hide();
3287                    $("input#shipping_state_name").parent('div').hide();
3288                } else {
3289                    $("select#shipping_state_id").parent('div').show();
3290                    $("input#shipping_state_name").parent('div').show();
3291                }
3292
3293                //Set City Visiblity As Per Country
3294                if(parseInt(hide_city_field) == 1) {
3295                    $("select#shipping_city_id").removeAttr("required");
3296                    $("input#shipping_city_name").removeAttr("required");
3297                    $("select#shipping_city_id").parent('div').hide();
3298                    $("input#shipping_city_name").parent('div').hide(); 
3299                } else {
3300                    $("select#shipping_city_id").parent('div').show();
3301                    $("input#shipping_city_name").parent('div').show(); 
3302                }
3303
3304                Theme.Utils.StoreOrder.resetElements();
3305                return false;
3306            });
3307        });
3308    },
3309    changeShippingState: function() {
3310        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
3311            /*
3312                $("#shipping_state_id").on("change", function (event) {
3313                    $("option:selected", $(this)).each(function(){
3314                        var shipping_country_id = $("#shipping_country_id").val();
3315                        var shipping_state_name = $(this).val();
3316                        Theme.Utils.StoreOrder.getShippingServiceableCities(s
3316hipping_country_id, shipping_state_name);
3317                        Theme.Utils.StoreOrder.resetElements();
3318                        return false;
3319                    });
3320                }); 
3321            */
3322            //States = We Determine From District and Towns (Serviceable States / Cities)
3323            $("select#shipping_state_name").on("change", function(event) {
3324                $("option:selected", $(this)).each(function() {
3325                    $("input#shipping_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
3326                    var shipping_country_id = $("#shipping_country_id").val();
3327                    var shipping_state_name = $(this).val();
3328                    Theme.Utils.StoreOrder.getShippingServiceableCities(shipping_country_id, shipping_state_name);
3329                    return false;
3330                });
3331            });
3332        } else {             
3333            $("select#shipping_state_id").on("change", function(event) {
3334                $("option:selected", $(this)).each(function() {
3335                    $("input#shipping_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
3336
3337                    var shipping_country_id = parseInt($("#shipping_country_id").val());
3338                    var shipping_state_id = parseInt($(this).val());
3339
3340                    //Case For UAE / INDIA / SRILANKA / US
3341                    var shipping_country_id_arr = new Array(2, 101, 125, 223);
3342                    
3343                    if (parseInt(defaultValues.IsShippingServiceableCity) == 1 && shipping_country_id_arr.indexOf(shipping_country_id) !== -1 && parseInt(shipping_country_id) == parseInt(defaultValues.storeCountryId)) {
3344                        $("input#shipping_city_name").removeAttr("required").val('').hide().parent("div").addClass("field__input-wrapper--select");
3345                        Theme.Utils.StoreOrder.getShippingSrilankaCities(shipping_country_id, shipping_state_id);
3346                        //Condition In Case of UAE (city dropdown) not required visible
3347                        if (parseInt(shipping_country_id) == 2) {
3348                            let shipping_state_name = $("select#shipping_state_id option:selected").text();
3349                            $("select#shipping_city_id option:contains(" + shipping_state_name + ")").attr('selected', true);
3350                            $("select#shipping_city_id").removeAttr("required").hide().parent("div").removeClass("field__input-wrapper--select").addClass("field--show-floating-label");
3351                            $("label#shipping_city_id-error").hide();
3352                        } else if(parseInt($('select#shipping_city_id').children('option').length) > 1) {
3353                            $("select#shipping_city_id").show().attr("required", "required");
3354                        }
3355                    }
3356
3357                    Theme.Utils.StoreOrder.resetElements();
3358                    return false;
3359                });
3360            });
3361
3362            /* 
3363            $("#shipping_state_id").on("change", function (event) {
3364                $("option:selected", $(this)).each(function(){
3365                    Theme.Utils.StoreOrder.resetElements();
3366                    return false;
3367                });
3368            });
3369            */
3370        }
3371    },
3372    changeShippingCity: function() {
3373        if (parseInt(defaultValues.DeliveryPincodeCheckId) == 5) {
3374            $("select#shipping_city_name").on("change", function(event) {
3375                $("option:selected", $(this)).each(function() {
3376                    var shipping_country_id = $("select#shipping_country_id").val();
3377                    var shipping_state_name = $("#shipping_state_name").val();
3378                    var shipping_city_name = $(this).val();
3379                    Theme.Utils.StoreOrder.getShippingServiceableAreas(shipping_country_id, shipping_state_name, shipping_city_name);
3380                    return false;
3381                });
3382            });            
3383        }
3384    },
3385    changePaymentCountry: function() {
3386        $("select#payment_country_id").on("change", function() {
3387            $("option:selected", $(this)).each(function() {
3388                var payment_country_id = $(this).val();
3389
3390                const state_title = ($(this).data('stateTitle')) ? $(this).data('stateTitle') : '';
3391                const city_title = ($(this).data('cityTitle')) ? $(this).data('cityTitle') : '';
3392                const is_pincode_required = ($(this).data('isPincodeRequired')) ? $(this).data('isPincodeRequired') : 0;
3393                const hide_state_field = ($(this).data('hideStateField')) ? $(this).data('hideStateField') : 0;
3394                const hide_city_field = ($(this).data('hideCityField')) ? $(this).data('hideCityField') : 0;
3395
3396                $("select#payment_state_id").parent('div').find('label.field__label').html(state_title);
3397                $("select#payment_state_id option[value]:first").text("Select " + state_title);
3398
3399                $("input#payment_city_name").parent('div').find('label.field__label').html(city_title);
3400                $("input#payment_city_name").attr('placeholder', city_title);
3401
3402                Theme.Utils.StoreOrder.getPaymentStates(payment_country_id);
3403
3404                //Check Phone Number and Pincode
3405                if (parseInt(payment_country_id) == 101) {
3406                    //$("input#payment_phone").attr("minlength", 10).attr("onKeyUp", "remove_first(this);allow_numeric(this);");
3407                    $("input#payment_phone").attr("minlength", 10).attr("onKeyUp", "remove_first(this);");
3408                    $("input#payment_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
3409                    $("input#payment_zip").attr("required", "required").show();
3410                    $("input#payment_city_name").attr("required", "required").show();
3411                } else {
3412                    $("input#payment_phone").removeAttr("minlength").attr("maxlength", 20);
3413                    $("input#payment_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
3414                    $("input#payment_zip").attr("required", "required").show();
3415                    $("input#payment_city_name").attr("required", "required").show();
3416
3417                    if (parseInt(payment_country_id) == 125 || parseInt(payment_country_id.length) == 0) {
3418                        $("input#payment_zip").removeAttr("required");
3419                    } else if (parseInt(payment_country_id) == 2) {
3420                        $("input#payment_city_name").removeAttr("required").hide();
3421                        $("label#payment_city_name-error").hide();
3422                    }
3423                    if (parseInt(is_pincode_required) === 0) {
3424                        $("input#payment_zip").removeAttr("required").hide();
3425                        $("label#payment_zip-error").hide();
3426                    }
3427                }
3428
3429                //Set State Visiblity As Per Country
3430                if(parseInt(hide_state_field) == 1) {
3431                    $("select#payment_state_id").removeAttr("required");
3432                    $("input#payment_state_name").removeAttr("required");
3433                    $("select#payment_state_id").parent('div').hide();
3434                    $("input#payment_state_name").parent('div').hide();
3435                    $("label#payment_state_id-error").hide();
3436                } else {
3437                    $("select#payment_state_id").parent('div').show();
3438                    $("input#payment_state_name").parent('div').show();
3439                }
3440
3441                //Set City Visiblity As Per Country
3442                if(parseInt(hide_city_field) == 1) {
3443                    $("select#payment_city_id").removeAttr("required");
3444                    $("input#payment_city_name").removeAttr("required");
3445                    $("select#payment_city_id").parent('div').hide();
3446                    $("input#payment_city_name").parent('div').hide();
3447                    $("label#payment_city_name-error").hide();
3448                } else {
3449                    $("select#payment_city_id").parent('div').show();
3450                    $("input#payment_city_name").parent('div').show(); 
3451                }
3452
3453                return false;
3454            });
3455        });
3456    },
3457    changePaymentState: function() {
3458        $("select#payment_state_id").on("change", function(event) {
3459            $("option:selected", $(this)).each(function() {
3460                $("input#payment_state_name").val('').removeAttr("required").hide().parent("div").addClass("field__input-wrapper--select");
3461
3462                // var payment_country_id = $("select#payment_country_id").val();
3463                // var payment_state_id = $(this).val();
3464                // Theme.Utils.StoreOrder.getPaymentCities(payment_country_id, payment_state_id);
3465                // return false;
3466            });
3467        });
3468    },
3469    changeDeliveryMode: function() {
3470        /* Enable According To Delivery Mode */
3471        $('.delivery_mode').on("click", function(event) {
3472            var store_address;
3473            var chkValue = $(this).filter(':checked').parent("label").text();
3474            if ($.trim(chkValue) == "Store Pickup") {
3475                $("#div_pickup_details").fadeIn(100);
3476                //store_address = $.trim($("#div_pickup_details").html());
3477                //$("#shipping_address").val(store_address);
3478
3479                /* Show or hide shipping and billing */
3480                $("div#divshipping").find("#shipping_first_name, #shipping_last_name, #shipping_email, #shipping_phone, #shipping_address, #
3480shipping_country_id, #shipping_state_id, #shipping_city_id").removeAttr("required");
3481                $("div#divshipping").hide();
3482
3483                $('#StoreOrderOtherPayment').prop('checked', false);
3484                $("div#divother").hide();
3485                $("div#PaymentSummary").show();
3486                $("div#PaymentSummary").find("#payment_first_name, #payment_last_name, #payment_email, #payment_phone, #payment_address, #payment_country_id, #payment_state_id, #payment_city_id").attr("required", true);
3487            } else {
3488                $("#div_pickup_details").fadeOut(100);
3489                /* Show or hide shipping and billing */
3490                $("div#PaymentSummary").find("#payment_first_name, #payment_last_name, #payment_email, #payment_phone, #payment_address, #payment_country_id, #payment_state_id, #payment_city_id").removeAttr("required");
3491                $("div#PaymentSummary").hide();
3492
3493                $("div#divother").show();
3494                $('#StoreOrderOtherPayment').prop('checked', true);
3495                $("div#divshipping").show();
3496                $("div#divshipping").find("#shipping_first_name, #shipping_last_name, #shipping_email, #shipping_phone, #shipping_address, #shipping_country_id, #shipping_state_id, #shipping_city_id").attr("required", true);
3497            }
3498        });
3499    },
3500    resetElements: function() {
3501        if ($('input#StoreOrderOtherPayment').is(':checked')) {
3502            $("input#payment_first_name").val($("input#shipping_first_name").val().trim());
3503            $("input#payment_last_name").val($("input#shipping_last_name").val().trim());
3504            $("input#payment_phone").val($("input#shipping_phone").val().trim());
3505            $("input#payment_address").val($("input#shipping_address").val().trim());
3506
3507            //Do not apply input tag before state_name, city_name !important
3508            if ($("#shipping_state_name").val() !== null) {
3509                $("input#payment_state_name").val($("#shipping_state_name").val().trim());
3510            }
3511            if ($("#shipping_city_name").length > 0) {
3512                $("input#payment_city_name").val($("#shipping_city_name").val().trim());
3513            }
3514
3515            $("input#payment_zip").val($("input#shipping_zip").val().trim());
3516            $("select#payment_country_id").val($("select#shipping_country_id").val().trim());
3517            if ($("select#shipping_state_id").val() != undefined) {
3518                $("select#payment_state_id").val($("select#shipping_state_id").val().trim());
3519            }
3520            if (parseInt($("select#payment_country_id").val()) == 101) {
3521                //$("input#payment_phone").attr("minlength", 10).attr("maxlength", 10);
3522                $("input#payment_phone").attr("onKeyUp", "remove_first(this);");
3523                $("input#payment_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
3524            } else {
3525                $("input#payment_phone").removeAttr("minlength").attr("maxlength", 20);
3526                $("input#payment_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
3527            }
3528        }
3529
3530        //Reset label as per Shipping Country
3531        if($("input#shipping_city_name").is(":visible") || $("select#shipping_city_id").is(":visible") || $("select#shipping_city_name").is(":visible")) {
3532            $("label.shipping_city").show();
3533        } else {
3534            $("label.shipping_city").hide();
3535        }
3536    },
3537    validateCheckout: function() {
3538        $("form#StoreOrderCheckoutForm").validate({
3539            ignore: [],
3540            debug: true,
3541            invalidHandler: function(event, validator) {
3542                $("div#divshipping").removeClass("hidden");
3543                $("div#divbilling").removeClass("hidden");
3544                $("div#divbillshipinfo").addClass("hidden");
3545            },
3546            errorPlacement: function(error, element) {
3547                //console.log(element);
3548                if ($('#store_delivery_mode_id_3').length) {
3549                    $(".tabbable-line").tabs();
3550                    $(".tabbable-line").tabs("option", "active", 2);
3551                    $($('.tabbable-line a[href="#tab_default_2"]')).tab('show');
3552                }
3553                //If any validation error than open edit area.
3554                var inputSelected = $("input[name='data[StoreOrder][customer_address_selected]']:checked").val();
3555                if (inputSelected != null) {
3556                    if (!$('#divshipping').is(':visible')) {
3557                        Theme.Utils.StoreOrder.editMultipleAddress(inputSelected, true);
3558                        //$('select#shipping_country_id').change();
3559                        //$('select#payment_country_id').change();
3560                        $('#divshipping').slideDown();
3561                        $('#divbilling').slideDown();
3562                    }
3563                    $('html, body').animate({
3564                        scrollTop: $("#divshipping").offset().top
3565                    }, 1000);
3566                }
3567                if (element.parent('.checkbox').length) {
3568                    error.insertAfter(element.parent());
3569                } else if (element.parent('.form-floating').length) {
3570                    error.insertAfter(element.parent());
3571                } else if (element.parent('.form-group').length) {
3572                    error.insertAfter(element.parent());
3573                } else {
3574                    error.insertAfter(element);
3575                }
3576            },
3577            submitHandler: function(form) {
3578                $("button#btnStoreOrder").addClass("disabled").attr("disabled", "disabled").html("Please wait <i class=\"fa fa-spinner fa-spin\" aria-hidden=\"true\"></i>");
3579                
3580                let shipping_phone_with_isd_code = window.shipping_phone_intlTel.getNumber(intlTelInputUtils.numberFormat.E164);
3581                if(shipping_phone_with_isd_code !== undefined) {
3582                    $("input[name='data[StoreOrder][shipping_phone_with_isd_code]'").val(shipping_phone_with_isd_code);
3583				}
3584				let shipping_phone_iso2_code = window.shipping_phone_intlTel.getSelectedCountryData().iso2;
3585				if(shipping_phone_iso2_code !== undefined) {
3586                    $("input[name='data[StoreOrder][shipping_phone_iso2]'").val(shipping_phone_iso2_code.toUpperCase());
3587                }
3588
3589                let payment_phone_with_isd_code = window.payment_phone_intlTel.getNumber(intlTelInputUtils.numberFormat.E164);
3590                if(payment_phone_with_isd_code !== undefined) {
3591                    $("input[name='data[StoreOrder][payment_phone_with_isd_code]'").val(payment_phone_with_isd_code);
3592                }
3593
3594			    let payment_phone_iso2_code = window.payment_phone_intlTel.getSelectedCountryData().iso2;
3595				if(payment_phone_iso2_code !== undefined) {
3596                    $("input[name='data[StoreOrder][payment_phone_iso2]'").val(payment_phone_iso2_code.toUpperCase());
3597                }
3598                
3599                if(window.googleRecaptchaSiteKey !== undefined && $('input#recaptchaResponse2').length) {
3600                    grecaptcha.ready(function () {
3601                        grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'customer_login'}).then(function (token) {
3602                            $(form).find('input#recaptchaResponse2').val(token);
3603                        });
3604                    });
3605                }
3606                
3607                setTimeout(function () {
3608                    form.submit();
3609                }, 1000);
3610
3611                //if(Theme.Utils.StoreOrder.checkDeliveryAvailable()){
3612                //     form.submit();
3613                //} else {
3614                //     //console.log(Theme.Utils.StoreOrder.checkDeliveryAvailable());
3615                //}
3616
3617            }
3618        });
3619    },
3620    validateCustomerCheckout: function() {
3621        $("form#CustomerCheckoutForm").validate({
3622            // ignore: [],
3623            // debug: true,
3624            invalidHandler: function(event, validator) {
3625            },
3626            errorPlacement: function(error, element) {
3627            },
3628            submitHandler: function(form) {
3629                if(window.googleRecaptchaSiteKey !== undefined) {
3630                    grecaptcha.ready(function () {
3631                        grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'customer_login'}).then(function (token) {
3632                            $(form).find('input#recaptchaResponse').val(token);
3633                        });
3634                    });
3635                }
3636                
3637                setTimeout(function () {
3638                    form.submit();
3639                }, 1000);
3640            }
3641        });
3642    },
3643    validateCoupon: function() {
3644        $("form#StoreCouponCartForm").validate();
3645
3646        //Auto Apply Session Storage Coupon
3647        if (sessionStorage.getItem("coupon_code") != null) {
3648            // Check if coupon was already applied in this session
3649            if (parseInt(sessionStorage.getItem('coupon_code_applied')) === 1) {
3650                console.log("Coupon has already been applied in this session");
3651                return;
3652            } else {
3653                $("input#coupon_code").val(sessionStorage.getItem("coupon_code"));
3654                if($("input#coupon_code").length > 0 && $("input#coupon_code").val().length > 0) {
3655                    // Set flag in sessionStorage before applying
3656                    sessionStorage.setItem('coupon_code_applied', 1);
3657                    //$("form#StoreCouponCheckCouponForm").find("#submit").prop("disabled", false)
3658                    $("form#StoreCouponCheckCouponForm").trigger('submit');
3659                }
3660            }
3661        }
3662
3663        //Remove Coupon Programming
3664        $('.remove_coupon').on("click", function(event) {
3665            if (sessionStorage.getItem('coupon_code') !== null) {
3666                sessionStorage.removeItem('coupon_code');
3667            }
3668            if (sessionStorage.getItem('discount_amount') !== null) {
3669                sessionStorage.removeItem('discount_amount');
3670            }
3671            if (sessionStorage.getItem('coupon_code_applied') !== null) {
3672                sessionStorage.removeItem('coupon_code_applied');
3673            }
3674
3675            return true;
3676        });
3677    },
3678    checkDeliveryAvailable: function() {
3679        var pincode = $("#StoreOrderCheckoutForm").find("input#shipping_zip").val();
3680
3681        if (pincode === '' || pincode.length < 4 || pincode.length > 10) {
3682            $('#shipping_zip').val('').addClass('required').attr('placeholder', 'Enter valid pincode');
3683            alert("Enter valid pincode");
3684            return false;
3685        }
3686
3687        var delivery_status = false;
3688        var ajaxLoading = false;
3689
3690        if (!ajaxLoading) {
3691            ajaxLoading = true;
3692
3693            var ShippingPincode = $("#StoreOrderCheckoutForm").find("input#shipping_zip").val();
3694            var FormData = "data[shipping_pincode]=" + ShippingPincode + "";
3695
3696            $("button#btnStoreOrder").addClass("disabled").attr("disabled", "disabled").html("Please wait <i class=\"fa fa-spinner fa-spin\" aria-hidden=\"true\"></i>");
3697            $.ajax({
3698                type: "POST",
3699                async: false,
3700                cache: false,
3701                url: "/store_orders/check_delivery_cod_available",
3702                accepts: 'application/json',
3703                dataType: "json",
3704                data: FormData,
3705                beforeSend: function(XMLHttpRequest) {
3706                    //$("button#btnStoreOrder").addClass("disabled").attr("disabled", "disabled");
3707                },
3708                complete: function() {
3709                    ajaxLoading = false;
3710                    $("button#btnStoreOrder").removeClass("disabled").removeAttr("disabled").html("Continue");
3711                },
3712                success: function(data, textStatus) {
3713                    //console.log(data);
3714                    if (data.delivery_status !== undefined && data.delivery_status == 1) {
3715                        delivery_status = true;
3716                    } else {
3717                        alert("Delivery not available at this pincode");
3718                    }
3719                },
3720                error: function(jqXHR, textStatus, errorThrown) {
3721                    //console.log(jqXHR.responseText);
3722                    if (jqXHR.status == 500) {
3723                        alert('Internal error: ' + jqXHR.responseText);
3724                    }
3725                }
3726            });
3727
3728        }
3729        return delivery_status; //stop the actual form post !important!
3730    },
3731    changePaymentOption: function() {
3732        var payment_mode_val = $('.payment_mode:checked').data('paymentModeId');
3733        if(payment_mode_val != null) {
3734            if (parseInt(payment_mode_val) == 25) {
3735                $('.ccinfo-hold').removeClass('d-none').slideDown();
3736                $.validator.addMethod('card-field', function(value) {
3737                    return value != '';
3738                }, 'Please fill required feilds.');
3739            } else if (parseInt(payment_mode_val) == 51) {
3740                $('div#div_paypal_smart').removeClass('d-none').slideDown();
3741            } else if (parseInt(payment_mode_val) == 68) {
3742                Theme.Utils.Element.updateURLAndReload('is_partial_cod', 1);
3743            }
3744        }
3745
3746        //Payment Mode Change
3747        $(document).on("change", "input.payment_mode", function() {
3748            var payment_mode_val = $(this).data('paymentModeId');
3749            $('.span_cod_charges_extra').addClass('hidden').slideUp();
3750            //Payment Mode Id = 4
3751            if ($(this).is(':checked') && parseInt($(this).data('paymentModeId')) == 4) {
3752                // var m_price = $(this).data('m-price');
3753                // $("#span_shipping").text(parseFloat(m_price));
3754                // console.log(parseFloat(m_price));
3755				
3756			   $('.span_cod_charges_extra').removeClass('hidden').slideDown();
3757            }
3758
3759            //Payment Mode Id = 25
3760            if ($(this).is(':checked') && parseInt($(this).data('paymentModeId')) == 25) {
3761                $('.ccinfo-hold').removeClass('d-none').slideDown();
3762                $.validator.addMethod('card-field', function(value) {
3763                    return value != '';
3764                }, 'Please fill required fields.');
3765            } else {
3766                $('.ccinfo-hold').slideUp();
3767            }            
3768
3769            //Payment Mode Id = 51
3770            if ($(this).is(':checked') && parseInt($(this).data('paymentModeId')) == 51) {
3771                $('div#div_paypal_smart').removeClass('d-none').slideDown();
3772            } else {
3773                $('div#div_paypal_smart').slideUp();
3774            }
3775
3776            //Payment Mode Id = 68
3777            if ($(this).is(':checked') && parseInt($(this).data('paymentModeId')) == 68) {
3778                //let $this = $(this);
3779                //if (confirm("Are you sure you want to enable Partial COD?")) {
3780                    Theme.Utils.Element.updateURLAndReload('is_partial_cod', 1);
3781                //} else {
3782                //    $this.prop("checked", false); // Uncheck if canceled
3783                //    return false;
3784                //}
3785            }
3786
3787            //Payment Mode Id = 73
3788            if ($(this).is(':checked') && parseInt($(this).data('paymentModeId')) == 73) {
3789                Theme.Utils.Element.updateURLAndReload('is_wallet_used', 1);                
3790            }
3791
3792            Theme.Utils.StoreOrder.calculatePrepaidDiscount(payment_mode_val);
3793        });
3794    },
3795    changeCustomPaymentOption: function() {
3796        $(document).on('click', 'ul.resp-tabs-list li', function() {
3797            let custom_payment_mode_id = $(this).data('customPaymentModeId');
3798            $('input:radio[name=\'data[StoreOrder][store_custom_payment_option_id]\']').prop('checked', false);
3799            $("div#div_custom_payment_mode_"+ custom_payment_mode_id +"").find("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:first").prop('checked', true);
3800
3801            if($("div#div_custom_payment_mode_"+ custom_payment_mode_id +" input
3801:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked")) {
3802                $("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked").trigger('click');
3803                //let custom_payment_option_id = $("div#div_custom_payment_mode_"+ custom_payment_mode_id +" input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked").val();
3804                //$("div#div_custom_payment_option_"+ custom_payment_option_id +" input:radio[name='data[StoreOrder][store_custom_payment_option_value_id]']:first").attr('checked', true);
3805            }
3806        });
3807
3808        $(document).on('click', 'div.resp-tabs-container h2.resp-accordion', function() {
3809            let custom_payment_mode_id = $(this).data('customPaymentModeId');
3810            $('input:radio[name=\'data[StoreOrder][store_custom_payment_option_id]\']').prop('checked', false);
3811            $("div#div_custom_payment_mode_"+ custom_payment_mode_id +"").find("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:first").prop('checked', true);
3812            if($("div#div_custom_payment_mode_"+ custom_payment_mode_id +" input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked")) {
3813                $("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked").trigger('click');
3814            }
3815        });        
3816
3817        //Incase of Click
3818        $(document).on('click', 'input:radio[name=\'data[StoreOrder][store_custom_payment_option_id]\']', function(){
3819            let custom_payment_mode_id = $(this).data('customPaymentModeId');
3820            let custom_payment_option_id = $(this).data('customPaymentOptionId');
3821            let store_custom_payment_mode_id = $(this).data('storeCustomPaymentModeId');
3822            let store_custom_payment_option_id = $(this).data('storeCustomPaymentOptionId');
3823                       
3824            Theme.Utils.StoreOrder.getCustomPaymentOptionFields(store_custom_payment_mode_id, store_custom_payment_option_id, custom_payment_option_id);
3825            Theme.Utils.StoreOrder.getCustomPaymentOptionValues(store_custom_payment_mode_id, store_custom_payment_option_id, custom_payment_option_id);
3826        });
3827
3828        if($("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked")) {
3829            $("input:radio[name='data[StoreOrder][store_custom_payment_option_id]']:checked").trigger('click');
3830        }
3831        
3832        //Incase of Click
3833        $(document).on('click', 'input:radio[name=\'data[StoreOrder][store_custom_payment_option_value_id]\']', function(){
3834            let store_custom_payment_option_id = 0;
3835            let store_custom_payment_option_value_id = $(this).val();
3836            Theme.Utils.StoreOrder.calculateConvensFee(store_custom_payment_option_id, store_custom_payment_option_value_id);
3837        });     
3838    },
3839    calculatePrepaidDiscount: function(payment_mode_val) {
3840        var total_order_amount = parseFloat($("input#total_order_amount").val());
3841        var total_bundle_discount = parseFloat($("input#total_bundle_discount").val());
3842        var total_shipping = parseFloat($("input#total_shipping").val());
3843        var total_tax = parseFloat($("input#total_tax").val());
3844        var total_discount = parseFloat($("input#total_discount").val());
3845        var total_reward_discount = ($("input#total_reward_discount").length > 0) ? parseFloat($("input#total_reward_discount").val()) : 0;
3846        var total_gift_discount = parseFloat($("input#total_gift_discount").val());
3847        var total_shipping_extra_charges = parseFloat($("input#total_shipping_extra_charges").val());
3848        var total_payment_mode_extra_charges = parseFloat($("input#total_payment_mode_extra_charges").val());
3849        var total_prepaid_discount = parseFloat($("input#total_prepaid_discount").val());
3850        var prepaid_discount_percent = parseInt($('#prepaid_discount_percent').val());
3851        var total_save = parseFloat($('#total_save').val());
3852
3853        if (prepaid_discount_percent > 0) {
3854            if (payment_mode_val !== 3 && payment_mode_val !== 4) {
3855                var totalOrderAmount = parseFloat(total_order_amount) - parseFloat(total_bundle_discount) - parseFloat(total_discount) - parseFloat(total_reward_discount) - parseFloat(total_gift_discount);
3856                total_prepaid_discount = ((totalOrderAmount * prepaid_discount_percent) / 100).toFixed(2);
3857                //console.log(totalOrderAmount+"=="+total_prepaid_discount+"="+payment_mode_val);
3858                $("#total_prepaid_discount").val(total_prepaid_discount);
3859                $("#prepaid_discount").html('<td style="border:none; padding:4px">Prepaid Discount</td><td style="border:none; padding:4px" class="text-end">' + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_prepaid_discount * 100, "{{amount}}") + '</td>');
3860                $("#prepaid_discount_m").html('<span class="text-dark">Prepaid Discount</span><span class="text-dark" style="min-width:80px; display:inline-block; padding-left:6px;"><strong>' + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_prepaid_discount * 100, "{{amount}}") + '</strong></span>');
3861            } else {
3862                total_prepaid_discount = 0;
3863                $("#total_prepaid_discount").val(total_prepaid_discount);
3864                $("#prepaid_discount").html('');
3865                $("#prepaid_discount_m").html('');
3866            }
3867        }
3868
3869        var total_payable_amount = parseFloat(total_order_amount) - parseFloat(total_bundle_discount) + parseFloat(total_shipping) + parseFloat(total_tax) - parseFloat(total_discount) - parseFloat(total_reward_discount) - parseFloat(total_gift_discount) - parseFloat(total_prepaid_discount) + parseFloat(total_shipping_extra_charges) + parseFloat(total_payment_mode_extra_charges);
3870
3871        $("span.span_total_payable").each(function() {
3872            if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
3873                $(this).html(Brand.formatMoney(total_payable_amount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY);
3874            } else {
3875                $(this).html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_payable_amount * 100, "{{amount}}"));
3876            }
3877        });
3878
3879        var total_discount_save = parseFloat(total_save) + parseFloat(total_prepaid_discount);
3880        if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
3881            $("span.total-save").html(Brand.formatMoney(total_discount_save * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY);
3882        } else {
3883            $("span.total-save").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_discount_save * 100, "{{amount}}"));
3884        }
3885    },
3886    validatePaymentOption: function() {
3887        $.validator.addMethod('payment_mode', function(value) {
3888            return $('.payment_mode:checked').length > 0;
3889        }, 'Please select atleast one payment option');
3890
3891        $("form#StoreOrderCartForm, form#StoreOrderPaymentForm").validate({
3892            errorPlacement: function(error, element) {
3893                if (element.hasClass("payment_mode") || element.hasClass("emi_option_mode")) {
3894                    error.prependTo(element.parent("div").parent("div"));
3895                } else if(element.hasClass("custom_duty")) {
3896                    error.appendTo(element.parent("div").parent("div")).addClass('text-danger');
3897                } else {
3898                    error.insertAfter(element);
3899                }
3900            }
3901        });
3902
3903        $(document).on("click", "input.shipping_option", function() {
3904            Theme.Utils.StoreOrder.processCalculation();
3905        });
3906
3907        $(document).on("click", "input.shipping_mode_rate", function() {
3908            Theme.Utils.StoreOrder.processCalculation();
3909        });
3910
3911        $(document).on("click", "input.payment_mode", function() {
3912            Theme.Utils.StoreOrder.processCalculation();
3913        });
3914
3915        $(document).on("click", "input.import_duty_option", function() {
3916            Theme.Utils.StoreOrder.processCalculation();
3917        });
3918
3919        Theme.Utils.StoreOrder.processCalculation();
3920    },
3921    processCalculation: function() {
3922        Theme.Utils.StoreOrder.calculateShipping();
3923        var payment_mode_val = $('.payment_mode:checked').data('paymentModeId');
3924        Theme.Utils.StoreOrder.calculatePrepaidDiscount(payment_mode_val);
3925        
3926        var store_custom_payment_option_id = $('.payment_option:checked').data('storeCustomPaymentOptionId');
3927        var store_custom_payment_option_value_id = $("input[name='data[StoreOrder][store_custom_payment_option_value_id]']:checked").val();
3928        if(store_custom_payment_option_value_id == 'undefined'){ store_custom_payment_option_value_id = 0;}
3929        Theme.Utils.StoreOrder.calculateConvensFee(store_custom_payment_option_id, store_custom_payment_option_value_id);
3930    },
3931    changeDocumentUploadOption: function() {
3932        if ($('.document_upload_option').length > 0) {
3933            var document_upload_option = $('.document_upload_option:checked').val();
3934            if (parseInt(document_upload_option) == 1) {
3935                $('input#additional_document').addClass('required').attr("required", "required");
3936            } else {
3937                $('input#additional_document').removeClass('required').removeAttr("required");
3938            }
3939
3940            $('.document_upload_option').change(function() {
3941                if ($(this).is(':checked') && parseInt($(this).val()) == 1) {
3942                    $('input#additional_document').addClass('required').attr("required", "required");
3943                } else {
3944                    $('input#additional_document').removeClass('required').removeAttr("required");
3945                }
3946            });
3947        }
3948    },
3949    validateReview: function() {
3950        $("form#StoreOrderReviewForm").validate();
3951        $("form#StoreOrderConfirmForm").validate({
3952            submitHandler: function(form) { // <- pass 'form' argument in
3953                $("#btnStoreOrder").attr("disabled", true);
3954                form.submit(); // <- use 'form' argument here.
3955            }
3956        });
3957    },
3958    calculateShipping: function() {
3959        if ($("input[type='radio'].shipping_option").is(':checked')) {
3960            if ($("input[type='radio'].shipping_option:checked").data("shippingOptionId") !== undefined && parseInt($("input[type='radio'].shipping_option:checked").data("shippingOptionId")) == 2) {
3961                $("input#total_shipping_extra_charges").val(parseFloat($("input[type='radio'].shipping_option:checked").data('shippingExtraCharges')));
3962            } else {
3963                $("input#total_shipping_extra_charges").val(0);
3964            }
3965        }
3966
3967        if ($("input[type='radio'].shipping_mode_rate").is(':checked')) {
3968            if ($("input[type='radio'].shipping_mode_rate:checked").data("shippingServiceName") !== undefined) {
3969                $("input#store_shipping_service_name").val($("input[type='radio'].shipping_mode_rate:checked").data("shippingServiceName"));
3970                $("input#total_shipping").val($("input[type='radio'].shipping_mode_rate:checked").data("shippingServiceAmount"));
3971            } else {
3972                $("input#store_shipping_service_name").val('');
3973            }
3974        }
3975
3976        if ($("input[type='radio'].payment_mode").is(':checked')) {
3977            if ($("input[type='radio'].payment_mode:checked").data("paymentModeId") !== undefined && parseInt($("input[type='radio'].payment_mode:checked").data("paymentModeId")) == 4) {
3978                //cod_charges = parseFloat($("input#extra_charges").val());
3979                $("input#total_payment_mode_extra_charges").val(parseFloat($("input[type='radio'].payment_mode:checked").data('paymentModeExtraCharges')));
3980            } else {
3981                $("input#total_payment_mode_extra_charges").val(0);
3982            }
3983        }
3984
3985        //Import Duty Purpose
3986        if($(".import_duty").length > 0) {
3987            $(".import_duty").change(function() {
3988                if($(this).is(":checked")) {
3989                    $("div#div_payment_options").show();
3990                    $("input#is_import_duty_charged").val(2); //Value 2 For Paid By Customer Later
3991                    $("input#total_import_duty").val(0);
3992                } else {
3993                    $("div#div_payment_options").hide();
3994                    $("input#is_import_duty_charged").val(0);
3995                    $("input#total_import_duty").val(0);
3996                }
3997
3998                if($('input[class="payment_mode"]:checked').data('payment-mode-id') == 51) { 
3999                    $(".continue-btn").hide();
4000                } else {
4001                    $(".continue-btn").show();
4002                }
4003            });
4004
4005            if($(".import_duty").is(":checked") === false) {
4006                $("div#div_payment_options").hide();
4007                $(".continue-btn").hide();   
4008            }
4009        }
4010
4011        if ($("input[type='radio'].import_duty_option").length > 0 && $("input[type='radio'].import_duty_option").is(':checked')) {
4012            if (parseInt($("input[type='radio'].import_duty_option:checked").data("importDutyOptionId")) == 3 && parseInt($("input[type='radio'].import_duty_option:checked").val()) == 1) {
4013                $("input#total_import_duty").val(parseFloat($("input[type='radio'].import_duty_option:checked").data('importDutyCharges')));
4014                $("input#is_import_duty_charged").val(1); //Value 1 For Pay Right Now
4015            } else {
4016                $("input#is_import_duty_charged").val(2); //Value 2 For Paid By Customer Later
4017                $("input#total_import_duty").val(0);
4018            }
4019            $("div#div_payment_options").show();
4020            if($('input[class="payment_mode"]:checked').data('payment-mode-id') == 51){ 
4021                $(".continue-btn").hide();
4022            } else {
4023                $(".continue-btn").show();
4024            }
4025        } else if ($("input[type='radio'].import_duty_option").length > 0 && $("input[type='radio'].import_duty_option").is(':checked') === false) {
4026            $("input#total_import_duty").val(0);
4027            $("div#div_payment_options").hide();
4028            $(".continue-btn").hide();
4029        } else if ($("input#is_import_duty_charged").length > 0 && parseInt($("input#is_import_duty_charged").val()) == 0) {
4030            $("input#total_import_duty").val(0);
4031        }
4032
4033        var total_order_amount = parseFloat($("input#total_order_amount").val());
4034        var total_bundle_discount = parseFloat($("input#total_bundle_discount").val());
4035        var total_shipping = parseFloat($("input#total_shipping").val());
4036        var total_tax = parseFloat($("input#total_tax").val());
4037        var total_discount = parseFloat($("input#total_discount").val());
4038        var total_reward_discount = ($("input#total_reward_discount").length > 0) ? parseFloat($("input#total_reward_discount").val()) : 0;
4039        var total_gift_discount = parseFloat($("input#total_gift_discount").val());
4040        var total_shipping_extra_charges = parseFloat($("input#total_shipping_extra_charges").val());
4041        var total_payment_mode_extra_charges = parseFloat($("input#total_payment_mode_extra_charges").val());
4042        var total_import_duty = parseFloat($("input#total_import_duty").val());
4043
4044
4045        var total_payable_amount = parseFloat(total_order_amount) - parseFloat(total_bundle_discount) + parseFloat(total_shipping) + parseFloat(total_tax) - parseFloat(total_discount) - parseFloat(total_reward_discount) - parseFloat(total_gift_discount) + parseFloat(total_shipping_extra_charges) + parseFloat(total_payment_mode_extra_charges) + parseFloat(total_import_duty);
4046
4047        total_shipping = parseFloat(total_shipping) + parseFloat(total_shipping_extra_charges);
4048        total_payable_amount = parseFloat(total_payable_amount);
4049
4050        if (parseInt(total_shipping) > 0) {
4051            $("span.span_shipping").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_shipping * 100, "{{amount}}"));
4052        } else {
4053            let freeText = (defaultValues.shippingChargeZeroText.length > 0) ? defaultValues.shippingChargeZeroText : 'FREE';
4054            $("span.span_shipping").html(freeText);
4055        }
4056
4057        if (parseInt(total_payment_mode_extra_charges) > 0) {
4058            $("span.span_total_cod").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_payment_mode_extra_charges * 100, "{{amount}}"));
4059            $(".span_cod_charges_extra").removeClass("d-none");
4060        } else {
4061            $(".span_cod_charges_extra").addClass("d-none");
4062        }
4063
4064        if (parseInt(total_import_duty) > 0) {
4065            $("span.span_import_duty").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_import_duty * 100, "{{amount}}"));
4066            $(".span_import_duty_extra").removeClass("d-none");
4067        } else {
4068            $(".span_import_duty_extra").addClass("d-none");
4069        }
4070
4071        if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
4072            $("span.span_total_payable").html(Brand.formatMoney(total_payable_amount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY);
4073        } else {
4074            $("span.span_total_payable").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_payable_amount * 100, "{{amount}}"));
4075        }
4076    },
4077    showCouponDetail: function() {
4078        $(document).on("click", "a.coupon_detail", function(event) {
4079            event.stopPropagation();
4080            if ($(this).data('couponCode').length > 0) {
4081                var couponCode = $(this).data('couponCode');
4082
4083                $.ajax({
4084                    type: "POST",
4085                    async: false,
4086                    cache: false,
4087                    url: "/store_coupons/term_condition",
4088                    dataType: "html",
4089                    data: {
4090                        "data[StoreCoupon][coupon_code]": couponCode
4091                    },
4092                    beforeSend: function(XMLHttpRequest) {
4093                        $('#myCouponModal').show();
4094                        $('#myCouponModal').find(".modal-body").html('');
4095                    },
4096                    success: function(data, textStatus) {
4097                        $('#myCouponModal').find(".modal-body").html(data);
4098                    },
4099                    error: function(jqXHR, textStatus, errorThrown) {
4100                        if (jqXHR.status == 500) {
4101                            alert('Internal error: ' + jqXHR.responseText);
4102                        }
4103                        $('#myCouponModal').hide();
4104                    }
4105                });
4106            }
4107        });
4108
4109        $(document).on("click", ".apply_code", function(event) {
4110            event.preventDefault();
4111            let couponCodeText = ($(this).parent().find('h5#coupon_code_text').length > 0) ? $(this).parent().find('h5#coupon_code_text').text() : ($(this).parent().find('span#coupon_code_text').length > 0) ? $(this).parent().find('span#coupon_code_text').text() : '';
4112            $('input#coupon_code').val(couponCodeText);
4113            $("#submit").prop("disabled", false);
4114
4115            const $offcanvas = $('#couponOffcanvas');    
4116            if ($offcanvas.length) {
4117                try {
4118                    const offcanvasElement = $offcanvas[0];
4119                    const offcanvas = bootstrap.Offcanvas.getOrCreateInstance(offcanvasElement);
4120                    offcanvas.hide();
4121                    console.log('Offcanvas closed successfully');
4122                } catch (error) {
4123                    console.error('Error closing offcanvas:', error);
4124                }                
4125            } else {
4126                //console.log('Offcanvas element not found');
4127            }
4128        });
4129
4130        $(document).on("click", ".apply_code_mobile", function(event) {
4131            var couponCodeText = $(this).parent().find('h5#coupon_code_text_mobile').text();
4132            $('input#coupon_code').val(couponCodeText);
4133        });
4134
4135        /* 
4136        $(document).on("click","form#StoreCouponCartForm button", function(event){
4137            $(this).attr('disabled','disabled');
4138        });
4139        */
4140    },
4141    getStorePickupMap: function() {
4142        $('.nav-tabs li').click(function(event) {
4143            event.preventDefault();
4144            $(".nav-tabs").find("li").removeClass("active");
4145            $(this).addClass("active");
4146
4147            $("div.tab-content").find("div.tab-pane").removeClass("show active");
4148            $("div#"+$(this).data('tabId')+"").addClass("show active");
4149
4150            FormData = "data[Customer][pickup_postal_code]=0";
4151            $.ajax({
4152                type: "POST",
4153                async: true,
4154                cache: false,
4155                url: "/store_orders/ajax_getStoreByPincode",
4156                dataType: "json",
4157                data: FormData,
4158                beforeSend: function(XMLHttpRequest) {
4159                    //$("button .verify-otp-code").addClass("disabled").attr("disabled", "disabled");
4160                },
4161                complete: function() {
4162                    //$("button .verify-otp-code").removeClass("disabled").removeAttr("disabled");
4163                },
4164                success: function(data, textStatus) {
4165                    if (data != undefined) {
4166                        pupAddress = data;
4167                        Theme.Utils.StoreOrder.initializeGoogleMap();
4168                    }
4169                    //console.log(data);
4170                },
4171                error: function(jqXHR, textStatus, errorThrown) {
4172                    //console.log(jqXHR);
4173                    if (jqXHR.status == 500) {
4174                        alert('Internal error: ' + jqXHR.responseText);
4175                    }
4176                }
4177            });
4178        });
4179
4180        $('#pickup_postal_code').keyup(function() {
4181            Theme.Utils.StoreOrder.getClickedMapResult($(this).val());
4182        });
4183    },
4184    initializeGoogleMap: function() {
4185        if(typeof google !== 'undefined') {
4186            var myOptions = {
4187                // scrollwheel: false,
4188                zoom: 16,
4189                draggable: true,
4190                mapTypeId: google.maps.MapTypeId.ROADMAP
4191            };
4192            //Creates a map object.
4193            mapCanvas = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
4194
4195            //Creates a infowindow object.
4196            infoWnd = new google.maps.InfoWindow({
4197                maxWidth: 350
4198            });
4199
4200            //Mapping markers on the map
4201            var bounds = new google.maps.LatLngBounds();
4202            var pup, i, latlng;
4203            var firstMarker;
4204            for (i in pupAddress) {
4205                //Creates a marker
4206                pup = pupAddress[i];
4207                latlng = new google.maps.LatLng(pup.latlng[0], pup.latlng[1]);
4208                bounds.extend(latlng);
4209                var marker = Theme.Utils.StoreOrder.createMapMarker(mapCanvas, latlng, pup.name);
4210
4211                if (defaultPUPAddressId == pup.addressId) {
4212                    firstMarker = marker;
4213                    defaultFound = true;
4214                }
4215
4216                if (defaultFound == false && rdoCounter == 0) {
4217                    firstMarker = marker;
4218                }
4219
4220                Theme.Utils.StoreOrder.createMapMarkerButton(marker, i, pup.addressId, pup.address_seperated, defaultPUPAddressId);
4221                google.maps.event.trigger(firstMarker, 'click');
4222            }
4223
4224            //Fits the map bounds
4225            mapCanvas.fitBounds(bounds);
4226            zoomChangeBoundsListener = google.maps.event.addListenerOnce(mapCanvas, 'bounds_changed', function(event) {
4227                if (this.getZoom()) {
4228                    this.setZoom(16);
4229                }
4230            });
4231            setTimeout(function() {
4232                google.maps.event.removeListener(zoomChangeBoundsListener);
4233            }, 2000);
4234        }
4235    },
4236    createMapMarker: function(map, latlng, title) {
4237        //Creates a marker
4238        var marker = new google.maps.Marker({
4239            position: latlng,
4240            map: map,
4241            id: title,
4242            animation: google.maps.Animation.DROP,
4243            // icon: 'https://img.dmart.in/images/rwd/dmart-symbol-logo.svg',// Marker icon
4244            scaledSize: new google.maps.Size(10, 10) // scaled size
4245        });
4246        //The infoWindow is opened when the address is clicked
4247        google.maps.event.addListener(marker, 'click', function() {
4248            infoWnd.setContent($(this).attr('id'));
4249            map.setZoom(16);
4250            map.panTo(marker.getPosition());
4251            infoWnd.open(map, marker);
4252            // infoWnd.close();
4253            marker.addListener('click', toggleBounce);
4254        });
4255        return marker;
4256
4257        function toggleBounce() {
4258            if (marker.getAnimation() !== null) {
4259                marker.setAnimation(null);
4260            } else {
4261                marker.setAnimation(google.maps.Animation.BOUNCE);
4262            }
4263        }
4264    },
4265    createMapMarkerButton: function(marker, i, addressId, addressSep, defaultPUPAddressId) {
4266        //Creates a address buttons
4267        var ul = document.getElementById('marker_list');
4268        var li = ul.querySelector('#sotreAddressLi_' + addressId);
4269        google.maps.event.addDomListener(li, 'click', function() {
4270            google.maps.event.trigger(marker, 'click');
4271        });
4272    },
4273    getClickedMapResult: function(pincode) {
4274        var inputString = pincode;
4275        $.each($("#marker_list").children(), function(index, physicalStore) {
4276            var htmlData = $(physicalStore).html();
4277            if (htmlData.toLowerCase().indexOf(inputString.toLowerCase()) == -1) {
4278                $(physicalStore).hide()
4279            } else {
4280                $("#pupDiv").css("display", "block");
4281                $(physicalStore).show()
4282            }
4283        });
4284        if (!$("#marker_list li").is(":visible")) {
4285            $("#divPincodeErrorBlock").css("display", "block");
4286            $("#divSearchPostalCodes").css("display", "none");
4287        } else {
4288            $("#divPincodeErrorBlock").css("display", "none");
4289            $("#divSearchPostalCodes").css("display", "block");
4290        }
4291    },
4292    getMultipleAddresses: function() {
4293        $("input[name='data[StoreOrder][customer_address_selected]']").change(function() {
4294            $('#divbilling').slideUp();
4295            $('#divshipping').slideUp();
4296
4297            $('.radio-block').removeClass('active');
4298            $(this).parent().parent().addClass('active');
4299            var customerAddressId = $(this).val();
4300            Theme.Utils.StoreOrder.editMultipleAddress(customerAddressId, false);
4301            /* 
4302            var addressData = customAddressesObject[customerAddressId];
4303            if(customerAddressId != null && addressData != undefined){
4304                 $("input#customer_address_id").val(addressData.id);
4305                 $("input#shipping_first_name").val(addressData.shipping_first_name);
4306                 $("input#shipping_last_name").val(addressData.shipping_last_name);
4307                 $("input#shipping_address").val(addressData.shipping_address);
4308                 $("input#shipping_zip").val(addressData.shipping_postal_code);
4309                 $("select#shipping_city_id").val(addressData.shipping_city_id);
4310                 $("input#shipping_city_name").val(addressData.shipping_city);
4311                 $("input#shipping_company_name").val(addressData.shipping_company_name);
4312                 $("input#shipping_gstin").val(addressData.shipping_gstin);
4313                 $("select#shipping_state_id").val(addressData.shipping_state_id);
4314                 $("select#shipping_country_id").val(addressData.shipping_country_id);
4315                 $("input#shipping_state_name").val(addressData.shipping_state);
4316                 $("input#payment_address").val(addressData.payment_address);
4317                 $("input#payment_first_name").val(addressData.payment_first_name);
4318                 $("input#payment_last_name").val(addressData.payment_last_name);
4319                 $("input#payment_zip").val(addressData.payment_postal_code);
4320                 $("input#payment_city_name").val(addressData.payment_city);
4321                 $("select#payment_state_id").val(addressData.payment_state_id);
4322                 $("select#payment_country_id").val(addressData.payment_country_id);
4323                 $("input#payment_state_name").val(addressData.payment_state);
4324                 $("select#shipping_address_type_id").val(addressData.shipping_address_type_id);
4325                 if(parseInt(addressData.is_default) == 1){
4326                      $("input#default_address_id").prop('checked',true);
4327                 } else {
4328                      $("input#default_address_id").prop('checked',false);
4329                 }
4330                 
4331                 if(defaultValues.IsShippingServiceableCity == 1 && parseInt(addressData.shipping_country_id) == 101 && addressData.shipping_city_id == 0){
4332                      Theme.Utils.StoreOrder.getShippingSrilankaCities(addressData.shipping_country_id, addressData.shipping_state_id);     
4333                 }
4334            } else {
4335                 alert('Invalid Request');
4336            } 
4337            */
4338        });
4339
4340        $('#add_new_address').click(function() {
4341            $('.exitingalladdress').prop('checked', false);
4342            $('label.error').fadeOut();
4343            if ($('#divshipping').is(':visible')) {
4344                $('#divshipping').fadeOut();
4345                $('#divbilling').fadeOut();
4346                $('#divshipping').fadeIn();
4347                $('#divbilling').fadeIn();
4348            } else {
4349                $('#divshipping').slideDown();
4350                $('#divbilling').slideDown();
4351            }
4352
4353            $('html, body').animate({
4354                scrollTop: $("#divshipping").offset().top
4355            }, 1000);
4356
4357            if (!$('#StoreOrderOtherPayment').is(':checked')) {
4358                $("#StoreOrderOtherPayment").toggle(this.checked).trigger("click").show();
4359            }
4360
4361            setTimeout(function() {
4362                $("input#customer_address_id").val(0);
4363                $("input#cost_center").val('');
4364                $("input#shipping_first_name").val('');
4365                $("input#shipping_last_name").val('');
4366                $("input#shipping_address").val('');
4367                $("input#shipping_zip").val('');
4368                $("input#shipping_phone").val('');
4369                $("input#shipping_company_name").val('');
4370                $("input#shipping_gstin").val('');
4371                $("select#shipping_country_id").val('').attr('selected', true);
4372                $("select#shipping_state_id").val(0);
4373                $("select#shipping_state_id").find("option").not(':first').remove();
4374                $("select#shipping_state_name").find("option").not(':first').remove();
4375                $("input#shipping_state_name").val('');
4376                $("input#shipping_city_name").val('');
4377                //$("select#shipping_city_id").val(0);
4378                $("select#shipping_city_id").find("option").not(':first').remove();
4379                $("select#shipping_city_name").find("option").not(':first').remove();
4380                $("select#shipping_serviceable_area_id").find("option").not(':first').remove();
4381
4382                setTimeout(function() {
4383                    $("select#shipping_country_id").trigger("change");
4384                }, 1000);
4385
4386                $("input#payment_first_name").val('');
4387                $("input#payment_last_name").val('');
4388                $("input#payment_address").val('');
4389                $("input#payment_zip").val('');
4390                $("input#payment_city_name").val('');
4391                //$("select#payment_state_id").val('');
4392                $("select#payment_state_id").find("option").not(':first').remove();
4393                $("input#payment_state_name").val('');
4394                $("input#payment_phone").val('');
4395
4396                // setTimeout(function() {
4397                //     $("select#payment_country_id").trigger("change");
4398                // }, 1000);
4399
4400                $("input#default_address_id").prop('checked', false);
4401            }, 400);
4402        });
4403
4404        $('.edit_address').click(function() {
4405            var customerAddressId = $(this).data('id');
4406            Theme.Utils.StoreOrder.editMultipleAddress(customerAddressId, true);
4407        });
4408
4409        $('.delivery-option-ul').click(function() {
4410            var inputVar = $(this).find('input');
4411            inputVar.prop('checked', true);
4412        });
4413    },
4414    editMultipleAddress: function(customerAddressId, isOpenView) {
4415        var addressData = customAddressesObject[customerAddressId];
4416
4417        if (customerAddressId != null && addressData != undefined) {
4418            if (isOpenView) {
4419                if ($('#divshipping').is(':visible')) {
4420                    $('#divshipping').fadeOut();
4421                    $('#divbilling').fadeOut();
4422                    $('#divshipping').fadeIn();
4423                    $('#divbilling').fadeIn();
4424                } else {
4425                    $('#divshipping').slideDown();
4426                    $('#divbilling').slideDown();
4427                }
4428                $('html, body').animate({
4429                    scrollTop: $("#divshipping").offset().top
4430                }, 1000);
4431            }
4432
4433            /*
4434            //Case For UAE / INDIA / SRILANKA / USA
4435            var shipping_country_id_arr = new Array(2, 101, 125, 223);
4436
4437            if (parseInt(deliveryPincodeCheckId) != 5) {
4438                if (defaultValues.IsShippingServiceableCity == 1 && shipping_country_id_arr.includes(addressData.shipping_country_id) != -1 && parseInt(addressData.shipping_country_id) == parseInt(defaultValues.storeCountryId)) {
4439                    //if (defaultValues.IsShippingServiceableCity == 1 && (parseInt(addressData.shipping_country_id) == 2 || parseInt(addressData.shipping_country_id) == 101 || parseInt(addressData.shipping_country_id) == 125)) {
4440                    if ($('select#shipping_state_id').has('option').length < 2) {
4441                        Theme.Utils.StoreOrder.getShippingSrilankaStates(addressData.shipping_country_id);
4442                    }
4443                    Theme.Utils.StoreOrder.getShippingSrilankaCities(addressData.shipping_country_id, addressData.shipping_state_id);
4444                } else if (addressData.shipping_state_id != 0 && ($('select#shipping_state_id option').length < 2)) {
4445                    Theme.Utils.StoreOrder.getShippingStates(addressData.shipping_country_id);
4446                    Theme.Utils.StoreOrder.getShippingCities(addressData.shipping_country_id, addressData.shipping_state_id);
4447                }
4448            }            
4449
4450            //Set Default condition.
4451            if (parseInt(addressData.shipping_state_id) > 0) {
4452                $("input#shipping_state_name").val('').removeAttr("required").hide();
4453                $("select#shipping_state_id").show().removeClass('hidden').attr("required", "required").val(parseInt(addressData.shipping_state_id));
4454            } else {
4455                //$("select#shipping_country_id").change();
4456                $("select#shipping_state_id").val(0).removeAttr("required").hide();
4457                $("input#shipping_state_name").val('').removeAttr("required").show().removeClass('hidden');
4458            }
4459
4460            //Incase Delivery Pincode Check = 5 And Get States By Serviceable States
4461            if (parseInt(deliveryPincodeCheckId) == 5) {
4462                if (!$("input#shipping_state_name").is(':visible')) {
4463                    Theme.Utils.StoreOrder.getShippingServiceableStates(addressData.shipping_country_id);
4464                }
4465            }
4466
4467            //Case For UAE / INDIA / SRILANKA / USA
4468            if (parseInt(defaultValues.IsShippingServiceableCity) == 0 && shipping_country_id_arr.includes(addressData.shipping_country_id) == -1) {
4469                //if ((parseInt(addressData.shipping_country_id) != 2 && parseInt(addressData.shipping_country_id) != 101 && parseInt(addressData.shipping_country_id) != 125) || defaultValues.IsShippingServiceableCity == 0) {
4470                $("select#shipping_city_id").val(0).removeAttr("required").hide();
4471                $("input#shipping_city_name").show().removeAttr("required");
4472            } else {
4473                //Incase Delivery Pincode Check != 5 And Get States By States
4474                if (parseInt(deliveryPincodeCheckId) != 5) {
4475                    $("select#shipping_city_id").show().attr("required", "required");
4476                    $("input#shipping_city_name").val('').removeAttr("required").hide();
4477                }
4478            }
4479
4480            //Billing System
4481            if (parseInt(addressData.payment_state_id) > 0) {
4482                if ($('select#payment_state_id option').length < 2) {
4483                    Theme.Utils.StoreOrder.getPaymentStates(addressData.payment_country_id);
4484                }
4485                $("select#payment_state_id").show().attr("required", "required");
4486                $("input#payment_state_name").val('').removeAttr("required").hide();
4487            } else {
4488                $("select#payment_state_id").removeAttr("required").val('').hide();
4489                $("input#payment_state_name").removeAttr("required").val('').show();
4490            }
4491
4492            //Check Phone Number and Pincode
4493            if (parseInt(addressData.shipping_country_id) == 101) {
4494                $("input#shipping_phone").attr("minlength", 10).attr("maxlength", 10);
4495                $("input#shipping_phone").attr("onKeyUp", "remove_first(this);allow_numeric(this);");
4496                $("input#shipping_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
4497                $("input#shipping_zip").attr("required", "required").show();
4498            } else {
4499                $("input#shipping_phone").removeAttr("minlength").attr("maxlength", 20).attr("onKeyUp", "allow_numeric(this);");
4500                $("input#shipping_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
4501                $("input#shipping_city_name").attr("required", "required").show();
4502
4503                if (parseInt(addressData.shipping_country_id) == 125 || parseInt(addressData.shipping_country_id.length) == 0) {
4504                    $("input#shipping_zip").removeAttr("required");
4505                    if (parseInt(addressData.shipping_country_id) == 125 && parseInt(addressData.shipping_state_id) > 0 && parseInt(addressData.shipping_city_id) > 0) {
4506                        $("input#shipping_city_name").val('').removeAttr("required").hide();
4507                    }
4508                } else if (parseInt(addressData.shipping_country_id) == 2) {
4509                    $("input#shipping_city_name").removeAttr("required").hide();
4510                }
4511
4512                if (parseInt($("select#shipping_country_id option:selected").data("isPincodeRequired")) === 0) {
4513                    $("input#shipping_zip").removeAttr("required").hide().closest(".field").removeClass("field--show-floating-label");
4514                    $("label#shipping_zip-error").hide();
4515                }
4516            }
4517            */
4518            
4519            //Store Other Payment Check / Uncheck
4520            if ($('#StoreOrderOtherPayment').is(':checked')) {
4521                $("#StoreOrderOtherPayment").toggle(this.checked).trigger("click").show();
4522            }
4523
4524            /*
4525            //Check Phone Number and Pincode
4526            if (parseInt(addressData.payment_country_id) == 101) {
4527                $("#payment_phone").attr("minlength", 10).attr("maxlength", 10).attr("onKeyUp", "remove_first(this);allow_numeric(this);");
4528                $("input#payment_zip").attr("minlength", 6).attr("maxlength", 6).attr("onKeyUp", "allow_numeric(this);");
4529                $("input#payment_zip").attr("required", "required").show();
4530                $("input#payment_city_name").attr("required", "required").show();
4531            } else {
4532                $("input#payment_phone").removeAttr("minlength").attr("maxlength", 20).attr("onKeyUp", "allow_numeric(this);");
4533                $("input#payment_zip").attr("minlength", 1).attr("maxlength", 10).removeAttr("onKeyUp");
4534                $("input#payment_zip").attr("required", "required").show();
4535                $("input#payment_city_name").attr("required", "required").show();
4536
4537                if (parseInt(addressData.payment_country_id) == 125 || parseInt(addressData.payment_country_id.length) == 0) {
4538                    $("input#payment_zip").removeAttr("required");
4539                } else if (parseInt(addressData.payment_country_id) == 2) {
4540                    $("input#payment_city_name").removeAttr("required").hide();
4541                    $("label#payment_city_name-error").hide();
4542                }
4543
4544                if (parseInt($("select#payment_country_id option:selected").data("isPincodeRequired")) === 0) {
4545                    $("input#payment_zip").removeAttr("required").hide();
4546                    $("label#payment_zip-error").hide();
4547                }
4548            }
4549            */
4550            setTimeout(function() {
4551                $("input#customer_address_id").val(addressData.id);
4552
4553                $("input#cost_center").val(addressData.cost_center);
4554                $("input#shipping_first_name").val(addressData.shipping_first_name);
4555                $("input#shipping_last_name").val(addressData.shipping_last_name);
4556                $("input#shipping_phone").val(addressData.shipping_phone);
4557                $("input#shipping_address").val(addressData.shipping_address);
4558                $("input#shipping_zip").val(addressData.shipping_postal_code);
4559                
4560                if(parseInt(addressData.shipping_country_id) > 0) {
4561                    $("select#shipping_country_id").val(addressData.shipping_country_id);
4562                    $("select#shipping_country_id").trigger("change");
4563                }
4564                
4565                if(parseInt(addressData.shipping_state_id) > 0) {
4566                    $("select#shipping_state_id").val(addressData.shipping_state_id);
4567                    $("select#shipping_state_id").trigger("change");
4568                } else if(addressData.shipping_state.length > 0) {
4569                    $("input#shipping_state_name").val(addressData.shipping_state);
4570                }
4571                                
4572                if(parseInt(addressData.shipping_city_id) > 0) {
4573                    $("select#shipping_city_id").val(addressData.shipping_city_id);
4574                    $("select#shipping_city_id").trigger("change");
4575                } else if(addressData.shipping_city.length > 0) {
4576                    $("input#shipping_city_name").val(addressData.shipping_city);
4577                }
4578                
4579                $("input#shipping_company_name").val(addressData.shipping_company_name);
4580                $("input#shipping_gstin").val(addressData.shipping_gstin);
4581
4582                $("input#payment_first_name").val(addressData.payment_first_name);
4583                $("input#payment_last_name").val(addressData.payment_last_name);
4584                $("input#payment_address").val(addressData.payment_address);
4585                $("input#payment_zip").val(addressData.payment_postal_code);
4586                $("select#payment_country_id").val(addressData.payment_country_id);
4587                $("select#payment_state_id").val(addressData.payment_state_id);
4588                $("input#payment_state_name").val(addressData.payment_state);
4589
4590                if(parseInt(addressData.payment_country_id) > 0) {
4591                    $("select#payment_country_id").val(addressData.payment_country_id);
4592                    $("select#payment_country_id").trigger("change");
4593                }
4594
4595                if(parseInt(addressData.payment_state_id) > 0) {
4596                    $("select#payment_state_id").val(addressData.payment_state_id);
4597                    setTimeout(function() {
4598                        $("select#payment_state_id").trigger("change");
4599                    }, 1000);
4600                } else if(parseInt(addressData.payment_state.length) > 0) {
4601                    $("input#payment_state_name").val(addressData.payment_state);
4602                }
4603                $("input#payment_city_name").val(addressData.payment_city);
4604                
4605                $("select#shipping_address_type_id").val(addressData.shipping_address_type_id
4605);
4606                if (parseInt(addressData.is_default) == 1) {
4607                    $("input#default_address_id").prop('checked', true);
4608                } else {
4609                    $("input#default_address_id").prop('checked', false);
4610                }
4611                
4612                
4613                // $("input[name='data[StoreOrder][shipping_address_type_id]']").prop('checked',false);
4614                // if(addressData.shipping_address_type_id == 1) {
4615                //      $("input#shipping_address_type_id_home").prop('checked',true);
4616                //      } else if(addressData.shipping_address_type_id == 2){
4617                //      $("input#shipping_address_type_id_office").prop('checked',true);
4618                //      } else if(addressData.shipping_address_type_id == 3){
4619                //      $("input#shipping_address_type_id_other").prop('checked',true);
4620                //      } else {
4621                //      $("input#shipping_address_type_id_home").prop('checked',true);
4622                // }
4623
4624                /*
4625                //Set Shipping States
4626                if (parseInt(addressData.shipping_state_id) != 0 && ($('select#shipping_state_id option').length > 2) && ($("select#shipping_state_id").val() == null || $("select#shipping_state_id").val() == '')) {
4627                    Theme.Utils.StoreOrder.getShippingStates(addressData.shipping_country_id);
4628                    $("select#shipping_state_id").val(addressData.shipping_state_id);
4629                }
4630
4631                //Set Payment States
4632                if (parseInt(addressData.payment_state_id) != 0 && ($('select#payment_state_id option').length > 2) && ($("select#payment_state_id").val() == null || $("select#payment_state_id").val() == '')) {
4633                    Theme.Utils.StoreOrder.getPaymentStates(addressData.payment_country_id);
4634                    $("select#payment_state_id").val(addressData.payment_state_id);
4635                }
4636
4637                //Set Shipping State Heading
4638                let shipping_state_title = ($('select#shipping_country_id').find(':selected').data('stateTitle')) ? $('select#shipping_country_id').find(':selected').data('stateTitle') : '';
4639                let shipping_city_title = ($('select#shipping_country_id').find(':selected').data('cityTitle')) ? $('select#shipping_country_id').find(':selected').data('cityTitle') : '';
4640                $("select#shipping_state_id").parent('div').find('label.field__label').html(shipping_state_title);
4641                $("select#shipping_city_id").parent('div').find('label.field__label').html(shipping_city_title);
4642                $("input#shipping_city_name").parent('div').find('label.field__label').html(shipping_city_title);
4643
4644                //Set Payment State Heading
4645                let billing_state_title = ($('select#payment_country_id').find(':selected').data('stateTitle')) ? $('select#payment_country_id').find(':selected').data('stateTitle') : '';
4646                let billing_city_title = ($('select#payment_country_id').find(':selected').data('cityTitle')) ? $('select#payment_country_id').find(':selected').data('cityTitle') : '';
4647                $("select#payment_state_id").parent('div').find('label.field__label').html(billing_state_title);
4648                $("input#payment_city_name").parent('div').find('label.field__label').html(billing_city_title);
4649                $("input#payment_city_name").attr('placeholder', billing_city_title);
4650                */
4651
4652                if (parseInt(addressData.is_disabled) == 1) {
4653                    $("input#shipping_email").prop("disabled", true);
4654                    $("input#shipping_first_name").prop("disabled", true);
4655                    $("input#shipping_last_name").prop("disabled", true);
4656                    $("input#shipping_phone").prop("disabled", true);
4657                    $("input#shipping_address").prop("disabled", true);
4658                    $("input#shipping_zip").prop("disabled", true);
4659                    $("select#shipping_country_id").prop("disabled", true);
4660                    $("select#shipping_state_id").prop("disabled", true);
4661                    $("input#shipping_state_name").prop("disabled", true);
4662                    $("select#shipping_city_id").prop("disabled", true);
4663                    $("input#shipping_city_name").prop("disabled", true);
4664                    $("input#shipping_company_name").prop("disabled", true);
4665                    $("input#shipping_gstin").prop("disabled", true);
4666                    $(".billing-address").hide();
4667                }
4668            }, 500);
4669        } else {
4670            alert('Invalid Request');
4671        }
4672
4673        //Check If Address is Blank
4674        // setTimeout(function() {
4675        //     if ($("input#shipping_address").val().length == 0) {
4676        //         $("select#shipping_country_id").trigger("change");
4677
4678        //         //Trigger Shipping State Event If Visible
4679        //         if ($('select#shipping_state_id').is(':visible')) {
4680        //             $("select#shipping_state_id").prop('selectedIndex', 0);
4681        //             setTimeout(function() {
4682        //                 $("select#shipping_state_id").trigger("change");
4683        //             }, 2000);
4684        //         }
4685
4686        //         $("select#payment_country_id").trigger("change");
4687
4688        //         //Trigger Payment State Event If Visible
4689        //         if ($('select#payment_state_id').is(':visible')) {
4690        //             setTimeout(function() {
4691        //                 $("select#payment_state_id").prop('selectedIndex', 0);
4692        //             }, 2000);
4693
4694        //             setTimeout(function() {
4695        //                 $("select#payment_state_id").trigger("change");
4696        //             }, 2000);
4697        //         }
4698        //     }
4699        // }, 1000);
4700    },
4701    initOTPMobileCheckout: function() {
4702        var resendTimer;
4703
4704        $('#phone_email').keyup(function() {
4705            Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', '');
4706            
4707            // inputDetail = $(this);
4708            // parentDiv = inputDetail.parent('div');
4709            // boxClass = parentDiv.find('span .fa');
4710            // labelTag = parentDiv.find('label');
4711            // if (inputDetail.val().length >= 4) {
4712            //     if (!$.isNumeric(inputDetail.val())) {
4713            //         boxClass.removeClass('fa-mobile', {
4714            //             duration: 150
4715            //         }).addClass('fa-envelope-o', {
4716            //             duration: 200
4717            //         });
4718            //         labelTag.html('Enter Email Address <span class="text-danger">*</span>');
4719            //         inputDetail.data('isMobile', 2);
4720            //     } else {
4721            //         boxClass.removeClass('fa-envelope-o', {
4722            //             duration: 150
4723            //         }).addClass('fa-mobile', {
4724            //             duration: 200
4725            //         });
4726            //         labelTag.html('Enter Mobile No <span class="text-danger">*</span>');
4727            //         $('.password-div').slideUp();
4728            //         inputDetail.data('isMobile', 1);
4729            //     }
4730            // }
4731        });
4732
4733        $(".mobile-otp .otp__input").keyup(function() {
4734            if (this.value.length == this.maxLength) {
4735                var $next = $(this).next('.otp__input');
4736                if ($next.length) {
4737                    $(this).next('.otp__input').focus();
4738                } else {
4739                    $(this).blur();
4740                    $(this).next('button').prop('disabled', false);
4741                }
4742            }
4743        });
4744
4745        // $("#CustomerLoginWithOtpForm").validate({
4746        //     submitHandler: function(form) {
4747        //         //$('#otp_code').trigger("reset");
4748        //         //var otpCode = '';
4749        //         //$('.otp__input').each(function(){
4750        //         //     otpCode = otpCode+$(this).val();
4751        //         //});
4752        //         //$('#otp_code').val(otpCode);
4753
4754        //         Theme.Utils.StoreOrder.verifyLoginOtp();
4755        //     }
4756        // });
4757        
4758        $("#CustomerLoginWithOtpForm").validate({
4759            submitHandler: function(form) {
4760                //$('#otp_code').trigger("reset");
4761                //var otpCode = '';
4762                //$('.otp__input').each(function(){
4763                //  otpCode = otpCode+$(this).val();
4764                //});
4765                //$('#otp_code').val(otpCode);
4766                $("button.verify-otp-code").addClass("disabled").attr("disabled", "disabled").find("span.spinner").removeClass("d-none");
4767                setTimeout(function() {
4768                    Theme.Utils.StoreOrder.verifyLoginOtp();
4769                }, 2000);
4770            }
4771        });
4772
4773        // $('#btnloginsubmit').click(function() {
4774        //     var loginInputData = $('.login-input').val();
4775        //     // if ($('#phone_email').data('isMobile') == 1) {
4776        //  //  if ($('#phone_email').val() != '') {
4777        //  //      $('#login_mobile_p').html($('#phone_email').val());
4778        //  //      Theme.Utils.StoreOrder.sendLoginOtp(0);
4779        //  //  }
4780        //  //  return false;
4781        //     // } else if ($('#phone_email').data('isMobile') == 2) {
4782        //     //     Theme.Utils.StoreOrder.checkAjaxEmailExists();
4783        //     // } else if ($('#phone_email').data('isMobile') == 3) {
4784        //     //     $("#CustomerLoginFormOtp").submit();
4785        //     // }
4786
4787        //     Theme.Utils.StoreOrder.sendLoginOtp(0);
4788        // });
4789
4790        // $('#btnloginsubmitotp').click(function() {
4791        //     var loginInputData = $('.login-input').val();
4792
4793        //     if ($('#phone_email').data('isMobile') == 1) {
4794        //         $('#login_mobile_p').html($('#phone_email').val());
4795        //         Theme.Utils.StoreOrder.sendLoginOtp(0);
4796        //     } else if ($('#phone_email').data('isMobile') == 2) {
4797        //         Theme.Utils.StoreOrder.checkAjaxEmailExists();
4798        //     } else if ($('#phone_email').data('isMobile') == 3) {
4799        //         $("#CustomerLoginFormOtp").submit();
4800        //     }
4801        // });
4802        
4803        $('.btnloginsubmitotp').on('click', function(event) {
4804            event.preventDefault(); // Prevent the default form submission
4805            var clickedForm = $(this).closest('form');
4806
4807            var loginInputData = clickedForm.find('.login-input').val();
4808            let loginOtpOptions = clickedForm.find('input[name=loginOtpOptions]:checked').val();
4809            
4810            if (loginInputData) {
4811                if(loginOtpOptions.toLowerCase() == 'email') {
4812                    if(loginInputData.length > 0 && Theme.Utils.Element.validateEmail(loginInputData) === true) {
4813                        Theme.Utils.StoreOrder.sendLoginOtp(clickedForm, 0);
4814                    } else {
4815                        Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Please enter valid email.');
4816                        return;
4817                    }
4818                } else if(loginOtpOptions.toLowerCase() == 'sms' || loginOtpOptions.toLowerCase() == 'whatsapp') {
4819                    if (loginInputData.length >= 10 && Theme.Utils.Element.validateNumeric(loginInputData) === true) {
4820                        Theme.Utils.StoreOrder.sendLoginOtp(clickedForm, 0);    
4821                    } else {
4822                        Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Please enter valid mobile no.')
4823                        return;
4824                    }                    
4825                }
4826                // if (clickedForm.find('#phone_email').data('isMobile') == 1) {
4827                //     clickedForm.find('#login_mobile_p').html();
4828                //     console.log(1);
4829                //     Theme.Utils.StoreOrder.sendLoginOtp(clickedForm, 0);
4830                // } else if (clickedForm.find('#phone_email').data('isMobile') == 2) {
4831                //     console.log(2);
4832                //     Theme.Utils.StoreOrder.checkAjaxEmailExists();
4833                // } else if (clickedForm.find('#phone_email').data('isMobile') == 3) {
4834                //     //$("form#CustomerLoginFormOtp").submit();
4835                //     console.log(3);
4836                //     clickedForm.submit();
4837                // }
4838            } else {
4839                if(loginOtpOptions.toLowerCase() == 'email') {
4840                    if(loginInputData.length <= 0 || Theme.Utils.Element.validateEmail(loginInputData) === false) {
4841                        Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Please enter valid email.');
4842                        return;
4843                    }
4844                } else if(loginOtpOptions.toLowerCase() == 'sms' || loginOtpOptions.toLowerCase() == 'whatsapp') {
4845                    if (loginInputData.length < 10 || Theme.Utils.Element.validateNumeric(loginInputData) === false) {
4846                        Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Please enter valid mobile no.')
4847                        return;
4848                    }                    
4849                }
4850            }
4851        });
4852
4853        // $('.otp-resend-code').click(function() {
4854        //     Theme.Utils.StoreOrder.sendLoginOtp(1);
4855        //     Theme.Utils.StoreOrder.reverseCountdownTimer();
4856        //     $('.otp-resend-code').hide();
4857        //     $('.otp-count-down').show();
4858        // });
4859
4860        $('.otp-resend-code').click(function() {
4861            let clickedForm = $("form#CustomerLoginFormOtp"); 
4862            Theme.Utils.StoreOrder.sendLoginOtp(clickedForm, 1);
4863            Theme.Utils.StoreOrder.reverseCountdownTimer();
4864            $('.otp-resend-code').hide();
4865            $('.otp-count-down').show();
4866        });
4867
4868        $('input[name=loginOtpOptions]').on('click', function(event) {
4869            let loginOtpOptions = $(this).val();    
4870            if(loginOtpOptions.toLowerCase() == 'email') {
4871                $(this).closest('form').find('.login_via').text(Theme.Language.getStr('LabelEmail'));
4872                $(this).closest('form').find('input#phone_email').attr('placeholder', Theme.Language.getStr('PlaceHolderEmailTxt'));
4873            } else if(loginOtpOptions.toLowerCase() == 'sms') {
4874                $(this).closest('form').find('.login_via').text(Theme.Language.getStr('LabelMobile'));
4875                $(this).closest('form').find('input#phone_email').attr('placeholder', Theme.Language.getStr('PlaceHolderMobileNoTxt'));
4876            } else if(loginOtpOptions.toLowerCase() == 'whatsapp') {
4877                $(this).closest('form').find('.login_via').text(Theme.Language.getStr('LabelWhatsappMobile'));
4878                $(this).closest('form').find('input#phone_email').attr('placeholder', Theme.Language.getStr('PlaceHolderMobileNoTxt'));
4879            }            
4880        });
4881
4882        $('#edit_login_mobile_number').click(function() {
4883            $('#otpCountainer').fadeOut();
4884            $('#credentialCountainer').slideDown();
4885        });
4886
4887        Theme.Utils.StoreOrder.ajaxLogin();
4888        Theme.Utils.StoreOrder.validateOTPMobileCheckout();
4889    },
4890    validateOTPMobileCheckout: function() {
4891        $("form#CustomerRegistrationForm").validate({
4892            // ignore: [],
4893            // debug: true,
4894            invalidHandler: function(event, validator) {
4895            },
4896            errorPlacement: function(error, element) {
4897            },
4898            submitHandler: function(form) {
4899                if(window.googleRecaptchaSiteKey !== undefined) {
4900                    grecaptcha.ready(function () {
4901                        grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'customer_login'}).then(function (token) {
4902                            $(form).find('input#recaptchaResponse').val(token);
4903                        });
4904                    });
4905                }
4906                
4907                setTimeout(function () {
4908                    form.submit();
4909                }, 1000);
4910            }
4911        });    
4912    },
4913    ajaxLogin: function() {
4914        $("#CustomerLoginFormOtp").validate({
4915            submitHandler: function(form) {
4916                $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled").html('Please Wait');
4917                
4918                var email = ($(form).find("input#phone_email").length > 0) ? $(form).find("input#phone_email").val().trim() : '';
4919                var password = ($(form).find("input#password").length > 0) ? $(form).find("input#password").val().trim() : '';
4920                var redirect_url = ($(form).find("#redirect_url").length > 0) ? $(form).find("#redirect_url").val().trim() : '';
4921
4922                if(window.googleRecaptchaSiteKey !== 'undefined') {
4923                    grecaptcha.ready(function () {
4924                        grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'customer_login'}).then(function (token) {
4925                            $(form).find('input#recaptchaResponse').val(token);
4926                        });
4927                    });
4928                }
4929
4930                setTimeout(function () {
4931                    var recaptcha_response = ($(form).find("input#recaptchaResponse").length > 0) ? $(form).find("input#recaptchaResponse").val() : '';
4932                    var FormData = "data[Customer][email]=" + email + "&data[Customer][password]=" + password + "&data[Customer][redirect_url]=" + redirect_url + "&data[recaptcha_response]=" + recaptcha_response;
4933
4934                    $.ajax({
4935                        type: "POST",
4936                        async: true,
4937                        cache: false,
4938                        url: "/customers/ajax_login",
4939                        accepts: 'application/json',
4940                        dataType: "json",
4941                        data: FormData,
4942                        beforeSend: function(XMLHttpRequest) {
4943                            $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled").html('Please Wait');
4944                        },
4945                        complete: function() {
4946                            $("button#btnloginsubmit").removeClass("disabled").removeAttr("disabled").html('Continue');
4947                        },
4948                        success: function(data, textStatus) {
4949                            if (data.login_status !== undefined && data.login_status == 1) {
4950                                window.location.reload();
4951                            } else {
4952                                Theme.Utils.StoreOrder.ajaxValidation('data[Customer][password]', data.message);
4953                            }
4954                        },
4955                        error: function(jqXHR, textStatus, errorThrown) {
4956                            if (jqXHR.status == 500) {
4957                                alert('Internal error: ' + jqXHR.responseText);
4958                            }
4959                        }
4960                    });
4961                }, 2000);
4962                
4963                return false; // blocks redirect after submission via ajax
4964            }
4965        });
4966    },
4967    reverseCountdownTimer: function() {
4968        var timeleft = 60;
4969        var resendTimer;
4970        // Stop previous timer if already running
4971        if (resendTimer !== null) {
4972            clearInterval(resendTimer);
4973        }
4974
4975        $("#count_down_timer").text(timeleft);
4976        $('.otp-resend-code').hide();
4977        $('.otp-count-down').show();
4978        
4979        resendTimer = setInterval(function () {
4980            timeleft--;
4981            $("#count_down_timer").text(timeleft);
4982
4983            if (timeleft <= 0) {
4984                clearInterval(resendTimer);
4985                resendTimer = null;
4986
4987                $('.otp-count-down').hide();
4988                $('.otp-resend-code').show();
4989            }
4990        }, 1000);
4991        // var timeleft = 30;
4992        // clearInterval(resendTimer);
4993        // $("#count_down_timer").text(timeleft);
4994        // var resendTimer = setInterval(function() {
4995        //     $("#count_down_timer").text(timeleft--);
4996        //     if (timeleft <= 0) {
4997        //         clearInterval(resendTimer);
4998        //         $('.otp-count-down').hide();
4999        //         $('.otp-resend-code').show();
5000        //     }
5001        // }, 1000);
5002    },
5003    checkAjaxEmailExists: function() {
5004        var inputDetail = $("input#phone_email");
5005        var Email = inputDetail.val();
5006        $.ajax({
5007            type: "POST",
5008            async: true,
5009            cache: false,
5010            url: "/customers/ajax_email_exist",
5011            accepts: 'application/json',
5012            dataType: "json",
5013            data: "data[Customer][email]=" + Email,
5014            beforeSend: function(XMLHttpRequest) {
5015                $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled");
5016            },
5017            complete: function() {
5018                //$('html,body').animate({ scrollTop: $("#divreview").offset().top - 60}, 1000);
5019                $("button#btnloginsubmit").removeClass("disabled").removeAttr("disabled");
5020            },
5021            success: function(data, textStatus) {
5022                //console.log(data);
5023                if (data.email_exists !== undefined && data.email_exists == 1) {
5024                    //console.log(data);
5025
5026                    $('.password-div').slideDown();
5027                    inputDetail.data('isMobile', 3);
5028                } else {
5029                    $('#loginSignUpDiv').slideUp();
5030                    $('#createAccountDiv').slideDown();
5031                    $('#register_email').val(Email);
5032                    $('#register_otp_div').hide();
5033                }
5034            },
5035            error: function(jqXHR, textStatus, errorThrown) {
5036                //alert(errorThrown);
5037                //console.log(errorThrown);
5038                if (jqXHR.status == 500) {
5039                    alert('Internal error: ' + jqXHR.responseText);
5040                }
5041            }
5042        });
5043    },
5044    ajaxValidation: function(elementName, message) {
5045        let msg = '<label class="text-danger error-message" for="' + elementName + '" id="' + elementName + '-error">' + message + '</label>';
5046        let $input = $('input[name="' + elementName + '"], select[name="' + elementName + '"]');
5047        
5048        // Check if parent has .float-label
5049        if ($input.parents('div.float-label').length > 0) {
5050            // place error inside float box (after input)
5051            $input.parents('div.float-label').next('.error-message').remove();
5052            $input.parents('div.float-label').after(msg);
5053        } else if ($input.parents('div.form-floating').length > 0) {
5054            // place error inside float box (after input)
5055            $input.parents('div.form-floating').next('.error-message').remove();
5056            $input.parents('div.form-floating').after(msg);
5057        } else {
5058            // normal error placement after input
5059            $input.next('.error-message').remove();
5060            $input.after(msg);
5061        }        
5062    },
5063    // sendLoginOtp: function(resend) {
5064    //     var phone = $("input#phone_email").val();
5065    //     var isResend = resend;
5066    //     var FormData = "data[Customer][phone]=" + phone + "&data[Customer][is_resend]=" + isResend;
5067
5068    //     $.ajax({
5069    //         type: "POST",
5070    //         async: true,
5071    //         cache: false,
5072    //         url: "/customers/send_login_otp",
5073    //         accepts: 'application/json',
5074    //         dataType: "json",
5075    //         data: FormData,
5076    //         beforeSend: function(XMLHttpRequest) {
5077    //             $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled");
5078    //         },
5079    //         complete: function() {
5080    //             $("button#btnloginsubmit").removeClass("disabled").removeAttr("disabled");
5081    //         },
5082    //         success: function(data, textStatus) {
5083    //             //console.log(data);
5084    //             if (data.otp_status !== undefined && data.otp_status == 1) {
5085	// 				//if (data.register_status !== undefined && data.register_status == 1 && data.is_resend == 0) {
5086    //                 if (data.register_status !== undefined && data.is_resend == 0) {
5087    //                     $('#credentialCountainer').slideUp();
5088    //                     $('#otpCountainer').fadeIn();
5089    //                     Theme.Utils.StoreOrder.reverseCountdownTimer();
5090    //                 } else if (data.register_status !== undefined && data.is_resend == 0) {
5091    //                     $('#loginSignUpDiv').slideUp();
5092    //                     $('#createAccountDiv').slideDown();
5093    //                     $('#register_phone').val(phone);
5094    //                 }
5095    //             } else {
5096    //                 Theme.Utils.StoreOrder.ajaxValidation('otp_code', data.message);
5097    //             }
5098    //         },
5099    //         error: function(jqXHR, textStatus, errorThrown) {
5100    //             //console.log(jqXHR);
5101    //             if (jqXHR.status == 500) {
5102    //                 alert('Internal error: ' + jqXHR.responseText);
5103    //             }
5104    //         }
5105    //     });
5106    //     return false;
5107    // },
5108    sendLoginOtp: function(clickedForm, resend) {
5109        var phone = clickedForm.find("input#phone_email").val();
5110        var loginOtpOptions = clickedForm.find('input[name="loginOtpOptions"]:checked').val();
5111        
5112        if(loginOtpOptions == undefined) {
5113            loginOtpOptions = 'SMS';
5114        }
5115
5116        if (!$.isNumeric(phone)) {
5117            var pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
5118
5119            if(!pattern.test(phone)) {
5120              Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Please enter valid email address.')
5121              return; 
5122            }            
5123        } else {
5124            if (parseInt(window.Store.StoreConfig.store_country_id) == 101 && (phone.length < 10 || phone.length > 10)) {
5125                Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', 'Mobile number must be 10 digit numeric value.')
5126                return;
5127            }
5128        }
5129        
5130        var isResend = resend;
5131        clickedForm.find("button#btnloginsubmitotp").addClass("disabled").attr("disabled", "disabled").find("span.spinner").removeClass("d-none");
5132        if(typeof window.googleRecaptchaSiteKey != 'undefined') {
5133            grecaptcha.ready(function () {
5134                grecaptcha.execute(window.googleRecaptchaSiteKey, {action: 'login'}).then(function (token) {
5135                    clickedForm.find('input#recaptcha_response_mobile_login').val(token);
5136                });
5137            });
5138        }
5139
5140        setTimeout(function() {
5141            var recaptcha_response = clickedForm.find("input#recaptcha_response_mobile_login").val();
5142            var FormData = "data[Customer][phone]=" + phone + "&data[Customer][loginOtpOptions]=" + loginOtpOptions + "&data[Customer][is_resend]=" + isResend + "&recaptcha_response=" + recaptcha_response;
5143
5144            $.ajax({
5145                type: "POST",
5146                async: true,
5147                cache: false,
5148                url: "/customers/send_login_otp",
5149                accepts: 'application/json',
5150                dataType: "json",
5151                data: FormData,
5152                beforeSend: function(XMLHttpRequest) {
5153                    $("button#btnloginsubmit").addClass("disabled").attr("disabled", "disabled");
5154                    $("button#btnloginsubmitotp").addClass("disabled").attr("disabled", "disabled").find("span.spinner").removeClass("d-none");
5155                },
5156                complete: function() {
5157                    $("button#btnloginsubmit").removeClass("disabled").removeAttr("disabled");
5158                    $("button#btnloginsubmitotp").removeClass("disabled").removeAttr("disabled").find("span.spinner").addClass("d-none");
5159                },
5160                success: function(data, textStatus) {
5161                    console.log(data);
5162                    if (data.otp_status !== undefined && data.otp_status == 1) {
5163                        $('#credentialCountainer').slideUp();
5164                        $('#otpCountainer').fadeIn();
5165                        Theme.Utils.StoreOrder.reverseCountdownTimer();
5166                        
5167                        //if (data.register_status !== undefined && data.register_status == 1 && data.is_resend == 0) {
5168                        // if (data.is_resend == 0) {
5169                        //     if (data.register_status !== undefined && data.is_resend == 0) {
5170                                
5171                        //     }
5172                        //     // // $('#credentialCountainer').slideUp();
5173                        //     // // $('#otpCountainer').fadeIn();
5174                        //     // // $('#otpCountainer').css('display', 'inline');
5175                        //     // var login_user_id = phone.substring(3);
5176                        //     // $('.login-user-id').html("***"+login_user_id);
5177                        //     // $("div#loginwithemail").fadeOut('slow').addClass("d-none");
5178                        //     // $("div#otpCountainer").fadeIn('slow').removeClass("d-none"); 
5179
5180                        //     // Theme.Utils.StoreOrder.reverseCountdownTimer();
5181                        //     // // } else if (data.register_status !== undefined && data.is_resend == 0) {
5182                        //     // //     alert("s");
5183                        //     // //     $('#loginSignUpDiv').slideUp();
5184                        //     // //     $('#createAccountDiv').slideDown();
5185                        //     // //     $('#register_phone').val(phone);
5186                        //     // //     $(".msignup").css('display', 'none');
5187                        // }
5188                    } else {
5189                        Theme.Utils.StoreOrder.ajaxValidation('data[Customer][phone_email]', data.message);
5190                        return;
5191                    }
5192                },
5193                error: function(jqXHR, textStatus, errorThrown) {
5194                    console.log(jqXHR);
5195                    if (jqXHR.status == 500) {
5196                        alert('Internal error: ' + jqXHR.responseText);
5197                    }
5198                }
5199            });
5200        }, 2000);
5201
5202        return false;
5203    },
5204    verifyLoginOtp: function() {
5205        var phone = $("input#phone_email").val();
5206        var otpCode = $("input#otp_code").val();
5207        var FormData = "data[Customer][phone]=" + phone + "&data[Customer][otp_code]=" + otpCode;
5208
5209        $.ajax({
5210            type: "POST",
5211            async: true,
5212            cache: false,
5213            url: "/customers/verify_login_otp",
5214            accepts: 'application/json',
5215            dataType: "json",
5216            data: FormData,
5217            beforeSend: function(XMLHttpRequest) {
5218                $("button.verify-otp-code").addClass("disabled").attr("disabled", "disabled");
5219            },
5220            complete: function() {
5221                $("button.verify-otp-code").removeClass("disabled").removeAttr("disabled");
5222            },
5223            success: function(data, textStatus) {
5224                if (data.login_status !== undefined && data.login_status == 1) {
5225                    window.location.reload();
5226                } else if(data.login_status == 0 && data.register_status == 1) {
5227                    window.location.reload();      
5228                } else if(data.login_status == 0 && data.register_status == 0){
5229				        $('#loginSignUpDiv').slideUp();
5230                        $('#createAccountDiv').slideDown();
5231                        $('#register_phone').val(phone);	
5232				} else {
5233                    Theme.Utils.StoreOrder.ajaxValidation('otp_code', data.message);
5234                }
5235            },
5236            error: function(jqXHR, textStatus, errorThrown) {
5237                //console.log(jqXHR);
5238                if (jqXHR.status == 500) {
5239                    alert('Internal error: ' + jqXHR.responseText);
5240                }
5241            }
5242        });
5243        return false;
5244    },
5245    setDeliverySlot: function() {
5246        if ($('input.datepick') !== 'undefined') {
5247            //console.log(window.deliverySlotDates);
5248
5249            function enableAllTheseDays(date) {
5250                var sdate = $.datepicker.formatDate('yy-mm-dd', date)
5251                //console.log(sdate)
5252                if ($.inArray(sdate, window.deliverySlotDates) != -1) {
5253                    return {
5254                        enabled: true,
5255                        //classes: ($("input#tentative_delivery_date").val() == sdate) ? "active" : ''
5256                    };
5257                }
5258                return {
5259                    enabled: false
5260                };
5261            }
5262
5263            $('#delivery_date_picker').datepicker({
5264                minViewMode: 0,
5265                language: "en",
5266                format: 'dd-mm-yyyy',
5267                todayHighlight: false,
5268                //setDate: $.datepicker.formatDate('dd-mm-yy'), 
5269                beforeShowDay: enableAllTheseDays,
5270                //startDate: new Date(window.deliverySlotDates[0])
5271            }).on('changeDate', function(ev) {
5272                selectedDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
5273                $('input#tentative_delivery_date').val(selectedDate);
5274
5275                $alreadyChecked = 0;
5276                $("input.delivery_time_slot").each(function() {
5277                    var deliveryDate = $(this).data("deliveryDate");
5278                    if (deliveryDate == selectedDate) {
5279                        $(this).parent("li").removeClass('d-none');
5280                        if ($alreadyChecked == 0) {
5281                            $(this).attr('checked', 'checked');
5282                            $alreadyChecked = 1;
5283                        }
5284                    } else {
5285                        $(this).parent("li").addClass('d-none');
5286                        $(this).removeAttr('checked');
5287                    }
5288                });
5289
5290            });
5291
5292            var setDate = new Date(window.deliverySlotDates[0]);
5293            $("#delivery_date_picker").datepicker("setDate", setDate);
5294        }
5295    },
5296    getCustomPaymentOptionFields: function(store_custom_payment_mode_id = 0, store_custom_payment_option_id = 0, custom_payment_option_id = 0) {
5297        if (parseInt(store_custom_payment_mode_id) > 0 && parseInt(store_custom_payment_option_id) > 0) {
5298            $.ajax({
5299                type: "POST",
5300                async: true,
5301                cache: false,
5302                url: "/store_orders/getCustomPaymentOptionFields",
5303                dataType: "html",
5304                data: {
5305                    "data[StoreOrder][store_custom_payment_mode_id]": store_custom_payment_mode_id,
5306                    "data[StoreOrder][store_custom_payment_option_id]": store_custom_payment_option_id
5307                },
5308                beforeSend: function(XMLHttpRequest) {
5309                    $('div.custom_payment_option').html('');
5310                    $("div#div_custom_payment_option_" + custom_payment_option_id).html('');
5311                },
5312                complete: function(data) {
5313                    
5314                },
5315                success: function(dataResponse, textStatus) {
5316                    $("div#div_custom_payment_option_" + custom_payment_option_id).append(dataResponse);
5317                },
5318                error: function(jqXHR, textStatus, errorThrown) {
5319                    if (jqXHR.status == 500) {
5320                        alert('Internal error: ' + jqXHR.responseText);
5321                    }
5322                }
5323            });
5324        }
5325    },
5326    getCustomPaymentOptionValues: function(store_custom_payment_mode_id = 0, store_custom_payment_option_id = 0, custom_payment_option_id = 0) {
5327        if (parseInt(store_custom_payment_mode_id) > 0 && parseInt(store_custom_payment_option_id) > 0) {
5328            $.ajax({
5329                type: "POST",
5330                async: true,
5331                cache: false,
5332                url: "/store_orders/getCustomPaymentOptionValues",
5333                dataType: "html",
5334                data: {
5335                    "data[StoreOrder][store_custom_payment_mode_id]": store_custom_payment_mode_id,
5336                    "data[StoreOrder][store_custom_payment_option_id]": store_custom_payment_option_id
5337                },
5338                beforeSend: function(XMLHttpRequest) {
5339                    $('div.custom_payment_option_value').html('');
5340                    $("div#div_custom_payment_option_value_" + custom_payment_option_id).html('');
5341                },
5342                complete: function(data) {
5343                    var store_custom_payment_option_value_id = $("input[name='data[StoreOrder][store_custom_payment_option_value_id]']:checked").val();
5344                    if(store_custom_payment_option_value_id == 'undefined'){ store_custom_payment_option_value_id = 0;}
5345                    Theme.Utils.StoreOrder.calculateConvensFee(store_custom_payment_option_id, store_custom_payment_option_value_id);
5346                },
5347                success: function(dataResponse, textStatus) {
5348                    $("div#div_custom_payment_option_value_" + custom_payment_option_id).append(dataResponse);
5349                },
5350                error: function(jqXHR, textStatus, errorThrown) {
5351                    if (jqXHR.status == 500) {
5352                        alert('Internal error: ' + jqXHR.responseText);
5353                    }
5354                }
5355            });
5356        }
5357    },
5358    calculateConvensFee: function(store_custom_payment_option_id = 0, store_custom_payment_option_value_id = 0 ) {
5359        if(store_custom_payment_option_value_id == 0){
5360            var convenience_fee_percent = parseFloat($("#store_custom_payment_option_id_"+store_custom_payment_option_id).data('storeCustomPaymentOptionConvenienceFee'));
5361        } else {
5362            var convenience_fee_percent = parseFloat($("#store_custom_payment_option_value_id_"+store_custom_payment_option_value_id).data('storeCustomPaymentOptionValueConvenienceFee'));
5363        }
5364        
5365        var total_order_amount = parseFloat($("input#total_order_amount").val());
5366        var total_bundle_discount = parseFloat($("input#total_bundle_discount").val());
5367        var total_shipping = parseFloat($("input#total_shipping").val());
5368        var total_tax = parseFloat($("input#total_tax").val());
5369        var total_discount = parseFloat($("input#total_discount").val());
5370        var total_reward_discount = ($("input#total_reward_discount").length > 0) ? parseFloat($("input#total_reward_discount").val()) : 0;
5371        var total_gift_discount = parseFloat($("input#total_gift_discount").val());
5372        var total_shipping_extra_charges = parseFloat($("input#total_shipping_extra_charges").val());
5373        var total_payment_mode_extra_charges = parseFloat($("input#total_payment_mode_extra_charges").val());
5374        var total_prepaid_discount = parseFloat($("input#total_prepaid_discount").val());
5375        var total_import_duty = parseFloat($("input#total_import_duty").val());
5376
5377        //var prepaid_discount_percent = parseInt($('#prepaid_discount_percent').val());
5378        var total_save = parseFloat($('#total_save').val());
5379        let total_convenience_fee = 0;
5380        let totalOrderAmount = 0;
5381
5382        if (parseFloat(convenience_fee_percent) > 0) {           
5383            totalOrderAmount = parseFloat(total_order_amount);
5384            total_convenience_fee = Math.round((totalOrderAmount * convenience_fee_percent) / 100);
5385            //console.log(totalOrderAmount+"=="+total_prepaid_discount+"="+payment_mode_val);
5386            $("#convens_fee_percent").val(convenience_fee_percent);
5387            $("#total_convens_fee").val(total_convenience_fee);
5388            $("#convens_fee").html('<td style="border:none; padding:4px">Convenience fee</td><td style="border:none; padding:4px" class="text-end">' + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_convenience_fee * 100, "{{amount}}") + '</td>');
5389            $("#convens_fee_m").html('<span class="text-dark">Convenience fee</span><span class="text-dark" style="min-width:80px; display:inline-block; padding-left:6px;"><strong>' + window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_convenience_fee * 100, "{{amount}}") + '</strong></span>');
5390        } else {
5391            $("#convens_fee_percent").val(0);
5392            $("#total_convens_fee").val(0);
5393            $("#convens_fee").html('');
5394            $("#convens_fee_m").html('');
5395        }
5396
5397        var total_payable_amount = parseFloat(total_order_amount) - parseFloat(total_bundle_discount) - parseFloat(total_prepaid_discount) + parseFloat(total_shipping) + parseFloat(total_tax) - parseFloat(total_discount) - parseFloat(total_reward_discount) - parseFloat(total_gift_discount) + parseFloat(total_shipping_extra_charges) + parseFloat(total_payment_mode_extra_charges) + parseFloat(total_convenience_fee) + parseFloat(total_import_duty);
5398
5399        $("span.span_total_payable").each(function() {
5400            if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
5401                $(this).html(Brand.formatMoney(total_payable_amount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY);
5402            } else {
5403                $(this).html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_payable_amount * 100, "{{amount}}"));
5404            }            
5405        });
5406
5407        var total_discount_save = parseFloat(total_save);
5408        if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
5409            $("span.total-save").html(Brand.formatMoney(total_discount_save * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY);
5410        } else {
5411            $("span.total-save").html(window.app.BRAND_STORE_CURRENCY + " " + Brand.formatMoney(total_discount_save * 100, "{{amount}}"));
5412        }
5413    },
5414    validateCard: function() {
5415        $(document).on("keyup","#card_number",function(){
5416            var card = $(this).val();
5417            var len = card.length;
5418            if(len == 6 || len == 9) {                
5419                $.ajax({
5420                    type: "POST",
5421                    async: true,
5422                    cache: false,
5423                    url: "/store_orders/validate_card",
5424                    dataType: "json",
5425                    data: { "data[StoreOrder][card_number]": card },
5426                    beforeSend: function(XMLHttpRequest) {                    
5427                    },
5428                    complete: function(data) {                    
5429                    },
5430                    success: function(dataResponse, textStatus) {
5431                        //$("div#div_custom_payment_option_value_" + custom_payment_option_id).append(dataResponse);
5432                    },
5433                    error: function(jqXHR, textStatus, errorThrown) {
5434                        if (jqXHR.status == 500) {
5435                            alert('Internal error: ' + jqXHR.responseText);
5436                        }
5437                    }
5438                });
5439            }
5440        });
5441    },
5442	changeShippingOption: function() {      
5443        var shipping_option = $('input[class="shipping_option"]:checked').data("shipping-option-id");
5444        Theme.Utils.StoreOrder.hidePaymentOption(shipping_option);
5445        $(document).on('change','.shipping_option', function() {
5446            var shipping_option =  $(this).data("shipping-option-id");
5447            Theme.Utils.StoreOrder.hidePaymentOption(shipping_option);
5448            $(this).trigger('click');      
5449        });
5450    },
5451    hidePaymentOption: function(value) {        
5452        if (value == 2) {
5453            $("#store_payment_mode_id_4").prop("disabled", true); 
5454            
5455            $("input:radio[class^=payment_mode]").not(':checked').each(function(i) {
5456                var paymentMode =  $(this).data("payment-mode-id");
5457                if(typeof paymentMode !== 'undefined' && parseInt(paymentMode) != 4) {
5458                    // console.log(paymentMode);
5459                    $("#store_payment_mode_id_4").prop('checked', false);
5460                    $("#store_payment_mode_id_"+paymentMode).prop('checked', true).trigger('change');
5461                    return false;
5462                }
5463            });
5464        } else {
5465            $("#store_payment_mode_id_4").prop("disabled", false);                    
5466        }
5467    },
5468    setOnlyForStoreOrderCartAndReview: function() {
5469        $(".cart-remove").on("click", function(event) {
5470            event.preventDefault();
5471            let ProductId = ($(this).closest("form").find("input#StoreCartProductId").length > 0) ? $(this).closest("form").find("input#StoreCartProductId").val() : 0;
5472            let ProductVariantId = ($(this).closest("form").find("input#StoreCartProductVariantId").length > 0) ? $(this).closest("form").find("input#StoreCartProductVariantId").val() : 0;
5473
5474            let FormData = "data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId;
5475
5476            $.ajax({
5477                type: "POST",
5478                async: true,
5479                cache: false,
5480                url: "/store_carts/ajax_cart_remove",
5481                dataType: "json",
5482                data: FormData,
5483                beforeSend: function(XMLHttpRequest) {
5484
5485                },
5486                success: function(data, textStatus) {
5487                    if (data.success == true) {
5488                        $("div#success_msg_div").show();
5489                        $("span#success_msg").html(data.message);
5490                        //if(parseInt(ProductVariantId) > 0) {
5491                            $("div.cart-div_" + ProductId + "_" + ProductVariantId + "").remove();
5492                        //} else {
5493                        //    $(".cart-div_" + ProductId).remove();
5494                        //}
5495
5496                        let CouponCode = sessionStorage.getItem("coupon_code");
5497                        if(CouponCode != null) {
5498                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5499                        } else {
5500                            Theme.Utils.StoreCart.ajaxCart();
5501                        }
5502                    }
5503                },
5504                error: function(jqXHR, textStatus, errorThrown) {
5505                    if (jqXHR.status == 500) {
5506                        alert('Internal error: ' + jqXHR.responseText);
5507                    } else {
5508                        alert('Unexpected error.');
5509                    }
5510                }
5511            }).done(function(result) {
5512                setTimeout(function() {
5513                    window.location.reload();
5514                }, 1000);
5515            });
5516        });
5517
5518        $(".cart-to-wishlist").on("click", function(event) {
5519            event.preventDefault();
5520            var ProductId = $(this).closest("form").find("input#StoreCartProductId").val();
5521            var ProductVariantId = $(this).closest("form").find("input#StoreCartProductVariantId").val();
5522
5523            ProductId = parseInt(ProductId) || 0;
5524            ProductVariantId = parseInt(ProductVariantId) || 0;
5525
5526            var FormData = "data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId;
5527
5528            $.ajax({
5529                type: "POST",
5530                async: true,
5531                cache: false,
5532                url: "/store_carts/ajax_wishlist",
5533                dataType: "json",
5534                data: FormData,
5535                beforeSend: function(XMLHttpRequest) {
5536
5537                },
5538                success: function(data, textStatus) {
5539                    if (data.success == true) {
5540                        $("#success_msg_div").show();
5541                        $("#success_msg").html(data.message);
5542                        $(".cart-div_" + ProductId + "_" + ProductVariantId).remove();
5543
5544                        let CouponCode = sessionStorage.getItem("coupon_code");
5545                        if(CouponCode != null) {
5546                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5547                        } else {
5548                            Theme.Utils.StoreCart.ajaxCart();
5549                        }
5550                    }
5551                },
5552                error: function(jqXHR, textStatus, errorThrown) {
5553                    if (jqXHR.status == 500) {
5554                        alert('Internal error: ' + jqXHR.responseText);
5555                    } else {
5556                        alert('Unexpected error.');
5557                    }
5558                }
5559            }).done(function(result) {
5560                setTimeout(function() {
5561                    window.location.reload();
5562                }, 1000);
5563            });
5564        });
5565    }	
5566};
5567
5568Theme.Utils.OrderHistory = {
5569    initOrderHistory: function() {
5570        $('[data-toggle="tooltip"]').tooltip();
5571    },
5572};
5573
5574Theme.Utils.OrderTracking = {
5575    validateOrderTracking: function() {
5576        $("#TrackOrderForm").validate();
5577    }
5578};
5579
5580Theme.Utils.IPGPayment = {
5581    initIPG: function() {
5582        $("#StorePaymentModeIpgForm").submit();
5583    }
5584};
5585
5586Theme.Utils.Page = {
5587    initContact: function() {
5588        $("#StorePageContactForm").validate();
5589    },
5590    initCustomRequirement: function() {
5591        $("#StorePageCustomRequirementForm").validate();
5592    }
5593};
5594
5595Theme.Utils.NewsletterSubscribe = {
5596    validateSubscribe: function() {
5597        $("#StoreNewsletterSubscriber").validate({
5598            errorPlacement: function(error, element) {
5599                if (element.parent('.checkbox').length) {
5600                    error.insertAfter(element.parent());
5601                } else {
5602                    error.insertAfter(element);
5603                }
5604            },
5605            submitHandler: function(form) {
5606                var data_serialize = $(form).serialize();
5607
5608                $.ajax({
5609                    type: "POST",
5610                    async: true,
5611                    cache: false,
5612                    url: "/store_newsletter_subscribers/subscribe",
5613                    dataType: "html",
5614                    data: data_serialize,
5615                    beforeSend: function(XMLHttpRequest) {
5616                        $("#btnpopsubmit").attr('disabled', 'disabled').text("Please wait...");
5617                    },
5618                    success: function(data, textStatus) {
5619                        $("#div_pop_response").append(data);
5620                        $(form).remove();
5621                        //Set Popup not to display again
5622                        sessionStorage.setItem('popHome', "1");
5623                        setTimeout(function() {
5624                            $("#homepagePopupModal").modal('hide');
5625                        }, 2000);
5626                    },
5627                    error: function(jqXHR, textStatus, errorThrown) {
5628                        if (jqXHR.status == 500) {
5629                            alert('Internal error: ' + jqXHR.responseText);
5630                        }
5631                    }
5632                });
5633            }
5634        });
5635    }
5636};
5637
5638Theme.Utils.Wishlist = {
5639    deleteWishlist: function() {
5640        $.validator.addMethod('chkwishlist', function(value) {
5641            return $('.chkwishlist:checked').size() > 0;
5642        }, 'Please select atleast one checkbox');
5643
5644        $("#StoreProductWishlistPreviewForm").validate({
5645            submitHandler: function(form) {
5646                var answer = confirm("You cannot recover deleted products, do you wish to continue?");
5647                if (answer) {
5648                    form.submit();
5649                    return true;
5650                } else {
5651                    return false;
5652                }
5653            },
5654            errorPlacement: function(error, element) {
5655                if (element.parent('.checkbox').length) {
5656                    error.insertAfter(element.parent());
5657                } else {
5658                    error.insertAfter(element);
5659                }
5660            }
5661        });
5662    }
5663};
5664
5665Theme.Utils.Testimonial = {
5666    validateTestimonial: function() {
5667        $.validator.addMethod("country", function(value, element) {
5668            return $("#country_id").val() > 0;
5669        }, "Please select a country");
5670
5671        $("#StoreTestimonialIndexForm").validate();
5672    }
5673};
5674
5675Theme.Utils.PhotoGallery = {
5676    initPhotoGallery: function() {
5677        initPhotoSwipeFromDOM(".photo-gallery");
5678    }
5679};
5680
5681Theme.Utils.PressCoverage = {
5682    initPressCoverage: function() {
5683        $("img.thumbnail").on("click", function(e) {
5684            e.preventDefault
5685            $('div#pressModal .modal-body').empty();
5686            var title = $(this).closest('a').attr("title");
5687            $('div#pressModal .modal-title').html(title);
5688            var image_path = $(this).closest('a').data("image");
5689            var img = '<img src="' + image_path + '" alt="" id="imgLarge" name="imgLarge" class="img-responsive margin0auto" />';
5690            $(img).appendTo('div#pressModal .modal-body');
5691            $('#pressModal').modal({
5692                show: true
5693            });
5694        });
5695    }
5696};
5697
5698Theme.Utils.Currency = {
5699    initCurrency: function() {
5700        Theme.Utils.Currency.changeCurrency();
5701    },
5702    changeCurrency: function() {
5703        $(".currency-dropdown").on("change", function(event) {
5704            $(this).closest('form').submit();
5705        });
5706    }
5707};
5708
5709Theme.Utils.Language = {
5710    initLanguage: function() {
5711        Theme.Utils.Language.changeLanguage();
5712    },
5713    changeLanguage: function() {
5714        $(".language-dropdown").on("change", function(event) {
5715            $(this).closest('form').submit();
5716        });
5717    }
5718};
5719
5720Theme.Utils.ClientLogo = {
5721    initClientLogo: function() {
5722        $(".clients-logo img").on("click", function(e) {
5723            e.preventDefault
5724            $('div#clientModal .modal-body').empty();
5725            var title = $(this).parent('a').attr("title");
5726            $('div#clientModal .modal-title').html(title);
5727            var image_path = $(this).parent('a').data("image");
5728            var img = '<img src="' + image_path + '" alt="" id="imgLarge" name="imgLarge" class="img-responsive" />';
5729            $(img).appendTo('div#clientModal .modal-body');
5730            $('#clientModal').modal({
5731                show: true
5732            });
5733        });
5734    }
5735};
5736
5737Theme.Utils.Tag = {
5738    initSort: function() {
5739        $("#sort_by").on("change", function(event) {
5740            event.preventDefault();
5741            Theme.Utils.Tag.buildQueryString();
5742            return false;
5743        });
5744    },
5745    initColorFilter: function() {
5746        $(".color-chk").on("click", function() {
5747            var colorArray = [];
5748            $('input.color-chk:checkbox:checked').each(function() {
5749                colorArray.push($(this).val());
5750            });
5751            Theme.Utils.Category.buildQueryString();
5752        });
5753    },
5754    buildQueryString: function() {
5755        var sort_by = $("#sort_by").val();
5756
5757        var colorArray = [];
5758        $('input.color-chk:checkbox:checked').each(function() {
5759            colorArray.push($(this).val());
5760        });
5761        var page_url = window.location.pathname + "?" + sort_by;
5762
5763        if (colorArray != "") {
5764            page_url = page_url + "&colors=" + colorArray;
5765        }
5766        page_url = page_url.replace(/(^\s*&)|(&\s*$)/g, '');
5767
5768        window.location.href = page_url;
5769    }
5770};
5771
5772Theme.Utils.CustomForm = {
5773    initCustomEnquiryForm: function() {
5774        /*
5775        $('.datepick').datetimepicker({
5776        language:  'en',
5777        weekStart: 1,
5778        todayBtn:  1,
5779        autoclose: 1,
5780        todayHighlight: 1,
5781        startView: 2,
5782        forceParse: 0,
5783        showMeridian: 1,
5784        startDate : new Date(),
5785        pickTime: false
5786        });
5787
5788        $('#date_image_button').on('click', function(){
5789        $('.datepick').datetimepicker('show'); //support hide, show and destroy command
5790        });
5791        */
5792        Theme.Utils.Element.init();
5793        $("form#StoreCustomEnquiryForm").validate();
5794    }
5795};
5796
5797Theme.Utils.Blog = {
5798    socialSharing: function() {
5799        $('.prettySocial').prettySocial();
5800    }
5801};
5802
5803Theme.Utils.Career = {
5804    validateCareer: function() {
5805        $.validator.addMethod("country", function(value, element) {
5806            return $("#country_id").val() > 0;
5807        }, "Please select a country");
5808
5809        $("#StoreCareerIndexForm").validate();
5810    }
5811};
5812
5813Theme.Utils.StoreCart = {
5814    initCart: function() {      
5815        $(".select-qty").on("change", function(event) {
5816            event.preventDefault();
5817            var CartId = $(this).closest("form").find("input#StoreCartId").val();
5818            var ProductId = $(this).closest("form").find("input#StoreCartProductId").val();
5819            var ProductVariantId = $(this).closest("form").find("input#StoreCartProductVariantId").val();
5820            var ProductQuantity = $(this).closest("form").find("select#quantity_" + ProductId + "_" + ProductVariantId + "").val();
5821
5822            var FormData = "data[StoreCart][id]=" + CartId + "&data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId + "&data[StoreCart][quantity]=" + ProductQuantity;
5823
5824            $.ajax({
5825                type: "POST",
5826                async: true,
5827                cache: false,
5828                url: "/store_carts/ajax_update",
5829                dataType: "json",
5830                data: FormData,
5831                beforeSend: function(XMLHttpRequest) {
5832
5833                },
5834                success: function(data, textStatus) {
5835                    if (data.success == true) {
5836                        $("div#success_msg_div").show();
5837                        $("span#success_msg").html(data.message);
5838                        let CouponCode = sessionStorage.getItem("coupon_code");
5839                        if(CouponCode != null) {
5840                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5841                        } else {
5842                            Theme.Utils.StoreCart.ajaxCart();
5843                        }
5844                    }
5845                },
5846                error: function(jqXHR, textStatus, errorThrown) {
5847                    if (jqXHR.status == 500) {
5848                        alert('Internal error: ' + jqXHR.responseText);
5849                    } else {
5850                        alert('Unexpected error.');
5851                    }
5852                }
5853            });
5854        });
5855
5856        $(".btnremove").on("click", function(event) {
5857            let ProductId = $(this).data("productId");
5858            let ProductVariantId = $(this).data("productVariantId"); 
5859            let FormData = "data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId;
5860            
5861            $.ajax({
5862                type: "POST",
5863                async: true,
5864                cache: false,
5865                url: "/store_carts/ajax_cart_remove",
5866                dataType: "json",
5867                data: FormData,
5868                beforeSend: function(XMLHttpRequest) {
5869
5870                },
5871                success: function(data, textStatus) {                   
5872                    if (data.success == true) {
5873                        $("div#success_msg_div").show();
5874                        $("span#success_msg").html(data.message);
5875                        //if(parseInt(ProductVariantId) > 0) {
5876                            $("div.cart-div_" + ProductId + "_" + ProductVariantId + "").remove();
5877                        //} else {
5878                        //    $(".cart-div_" + ProductId).remove();
5879                        //}
5880
5881                        let CouponCode = sessionStorage.getItem("coupon_code");
5882                        if(CouponCode != null) {
5883                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5884                        } else {
5885                            Theme.Utils.StoreCart.ajaxCart();
5886                        } 
5887                    }
5888                },
5889                error: function(jqXHR, textStatus, errorThrown) {
5890                    if (jqXHR.status == 500) {
5891                        alert('Internal error: ' + jqXHR.responseText);
5892                    } else {
5893                        alert('Unexpected error.');
5894                    }
5895                }
5896            }).done(function(result) {
5897                setTimeout(function() {
5898                    window.location.reload();
5899                }, 1000);
5900            });      
5901        });  
5902
5903        $(".cart-remove").on("click", function(event) {
5904            event.preventDefault();
5905            let ProductId = ($(this).closest("form").find("input#StoreCartProductId").length > 0) ? $(this).closest("form").find("input#StoreCartProductId").val() : 0;
5906            let ProductVariantId = ($(this).closest("form").find("input#StoreCartProductVariantId").length > 0) ? $(this).closest("form").find("input#StoreCartProductVariantId").val() : 0;
5907            
5908            let FormData = "data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId;
5909
5910            $.ajax({
5911                type: "POST",
5912                async: true,
5913                cache: false,
5914                url: "/store_carts/ajax_cart_remove",
5915                dataType: "json",
5916                data: FormData,
5917                beforeSend: function(XMLHttpRequest) {
5918
5919                },
5920                success: function(data, textStatus) {                   
5921                    if (data.success == true) {
5922                        $("div#success_msg_div").show();
5923                        $("span#success_msg").html(data.message);
5924                        //if(parseInt(ProductVariantId) > 0) {
5925                            $("div.cart-div_" + ProductId + "_" + ProductVariantId + "").remove();
5926                        //} else {
5927                        //    $(".cart-div_" + ProductId).remove();
5928                        //}
5929
5930                        let CouponCode = sessionStorage.getItem("coupon_code");
5931                        if(CouponCode != null) {
5932                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5933                        } else {
5934                            Theme.Utils.StoreCart.ajaxCart();
5935                        } 
5936                    }
5937                },
5938                error: function(jqXHR, textStatus, errorThrown) {
5939                    if (jqXHR.status == 500) {
5940                        alert('Internal error: ' + jqXHR.responseText);
5941                    } else {
5942                        alert('Unexpected error.');
5943                    }
5944                }
5945            }).done(function(result) {
5946                setTimeout(function() {
5947                    window.location.reload();
5948                }, 1000);
5949            });
5950        });
5951
5952        $(".cart-to-wishlist").on("click", function(event) {
5953            event.preventDefault();
5954            var ProductId = $(this).closest("form").find("input#StoreCartProductId").val();
5955            var ProductVariantId = $(this).closest("form").find("input#StoreCartProductVariantId").val();
5956
5957            ProductId = parseInt(ProductId) || 0;
5958            ProductVariantId = parseInt(ProductVariantId) || 0;
5959
5960            var FormData = "data[StoreCart][product_id]=" + ProductId + "&data[StoreCart][product_variant_id]=" + ProductVariantId;
5961
5962            $.ajax({
5963                type: "POST",
5964                async: true,
5965                cache: false,
5966                url: "/store_carts/ajax_wishlist",
5967                dataType: "json",
5968                data: FormData,
5969                beforeSend: function(XMLHttpRequest) {
5970
5971                },
5972                success: function(data, textStatus) {
5973                    if (data.success == true) {
5974                        $("#success_msg_div").show();
5975                        $("#success_msg").html(data.message);
5976                        $(".cart-div_" + ProductId + "_" + ProductVariantId).remove();
5977
5978                        let CouponCode = sessionStorage.getItem("coupon_code");
5979                        if(CouponCode != null) {
5980                            Theme.Utils.StoreCart.ajaxCoupon(CouponCode);
5981                        } else {
5982                            Theme.Utils.StoreCart.ajaxCart();
5983                        }                           
5984                    }
5985                },
5986                error: function(jqXHR, textStatus, errorThrown) {
5987
5988                    if (jqXHR.status == 500) {
5989                        alert('Internal error: ' + jqXHR.responseText);
5990                    } else {
5991                        alert('Unexpected error.' + jqXHR.responseText);
5992                    }
5993                }
5994            }).done(function(result) {
5995                setTimeout(function() {
5996                    window.location.reload();
5997                }, 1000);
5998            });
5999        });
6000
6001        $(document).on("click", ".apply_code", function(event) {
6002            //Copy the text inside the text field           
6003            var $temp = $("<input>");
6004            $("body").append($temp);
6005            $temp.val($('#coupon_code_text').text()).select();
6006            document.execCommand("copy");
6007            $temp.remove();
6008        });
6009
6010        //Apply Coupon Click
6011        $("button#couponSubmitButton").click(function(event) {
6012            event.preventDefault();
6013            let form = $("form#StoreCouponApplyForm");
6014            //var OrderId = $(this).closest("form").find("input#StoreCouponOrderId").val();
6015            //var CustomerId = $(this).closest("form").find("input#StoreCouponCustomerId").val();
6016            let couponCode = $(this).closest("form").find("input#coupon_code").val();
6017            if(couponCode.length > 0) {
6018                Theme.Utils.StoreCart.ajaxCoupon(couponCode);
6019            }
6020        });
6021
6022        let couponCode = sessionStorage.getItem("coupon_code");
6023        if(couponCode != null) {
6024            Theme.Utils.StoreCart.ajaxCoupon(couponCode);
6025        }
6026        
6027        if (sessionStorage.getItem("coupon_code") != null) {
6028            $("input#coupon_code").val(sessionStorage.getItem("coupon_code"));
6029            $("div#applyCouponDiv").hide();
6030            $("div.use-coupon-code").hide();
6031            //$("div#removeCouponDiv").show();
6032            Theme.Utils.StoreCart.ajaxCart();
6033        }
6034
6035        $("button#remove_coupon").on("click", function(event) {
6036            //sessionStorage.clear();
6037            event.preventDefault();
6038            if (sessionStorage.getItem('coupon_code') !== null) {
6039                sessionStorage.removeItem('coupon_code');
6040            }
6041            if (sessionStorage.getItem('discount_amount') !== null) {
6042                sessionStorage.removeItem('discount_amount');
6043            }            
6044
6045            $("input#coupon_code").val('');
6046            $("div#applyCouponDiv").show();
6047            $("div.use-coupon-code").show();
6048            //$("div#removeCouponDiv").hide();
6049            $("#coupon_success_msg").show();
6050            $(".coupon_msg").html("Coupon is remove successfully");
6051            Theme.Utils.StoreCart.ajaxCart();
6052        });
6053    },
6054    ajaxCart: function() {
6055        $.ajax({
6056            type: "POST",
6057            async: true,
6058            cache: false,
6059            url: "/store_carts/ajax_cart",
6060            dataType: "json",
6061            data: FormData,
6062            beforeSend: function(XMLHttpRequest) {
6063
6064            },
6065            success: function(data, textStatus) {
6066                let subtotal = 0;
6067                let totalsubtotal = 0;
6068                let discount = 0;
6069                let currency_symbol = data.currency_symbol;
6070                
6071                $.each(data['product_info'], function(index, productdata) {
6072                    subtotal = subtotal + parseFloat(productdata['StoreCart']['sub_total']);
6073                });
6074                
6075                totalsubtotal = parseFloat(subtotal);
6076
6077                if (sessionStorage.getItem("discount_amount") != null) {
6078                    $("#discount_div").removeClass("d-none");
6079                    $("#discount_mobile_div").removeClass("d-none");
6080                    discount = sessionStorage.getItem("discount_amount");
6081                    totalsubtotal = parseFloat(totalsubtotal) - parseFloat(discount);
6082                } else {
6083                    $("#discount_div").addClass("d-none");
6084                    $("#discount_mobile_div").addClass("d-none");
6085                }
6086                
6087                if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
6088                    $("#sub_total_amount").html("" + Brand.formatMoney(subtotal * 100, "{{amount}}") +" "+ window.app.BRAND_STORE_CURRENCY + " ");
6089                    $("#total_discount").html("" + Brand.formatMoney(discount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY +  " ");
6090                    $("#total_discount_mobile").html("" + Brand.formatMoney(discount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY + " ");
6091                    $("#total_amount").html("" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY + " ");
6092                    $("#total_amount_mobile").html("" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY +" ");
6093                } else {                  
6094                    $("#sub_total_amount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(subtotal * 100, "{{amount}}") + " ");
6095                    $("#total_discount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(discount * 100, "{{amount}}") + " ");
6096                    $("#total_discount_mobile").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(discount * 100, "{{amount}}") + " ");
6097                    $("#total_amount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " ");
6098                    $("#total_amount_mobile").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " ");
6099                }
6100            },
6101            error: function(jqXHR, textStatus, errorThrown) {
6102                if (jqXHR.status == 500) {
6103                    alert('Internal error: ' + jqXHR.responseText);
6104                } else {
6105                    alert('Unexpected error.' + jqXHR.responseText);
6106                }
6107            }
6108        });
6109    },
6110    ajaxCoupon: function(couponCode = '') {
6111        if (couponCode == '') {
6112            Theme.Utils.StoreCart.ajaxCart();
6113            return false;
6114        }
6115
6116        let FormData = "coupon_code=" + couponCode;    
6117        $.ajax({
6118            type: "POST",
6119            async: true,
6120            cache: false,
6121            url: "/store_coupons/rest_check_cart_coupon",
6122            dataType: "json",
6123            data: FormData,
6124            beforeSend: function(XMLHttpRequest) {
6125
6126            },
6127            success: function(data, textStatus) {
6128                if (data['response'].success == true) {
6129                    $("#coupon_fail_msg").hide();
6130                    $("#coupon_success_msg").show();
6131                    $(".coupon_fail_msg_box").hide();
6132                    $(".coupon_success_msg_box").show();
6133                    $(".coupon_msg").html(data['response'].message);
6134                    
6135                    sessionStorage.setItem("coupon_code", data['response']['data'].coupon_code);
6136                    sessionStorage.setItem("discount_amount", data['response']['data'].discount_amount);
6137                    sessionStorage.setItem("coupon_code_applied", 0); // Used for Checkout Page
6138                    
6139                    $("#applyCouponDiv").hide();
6140                    $(".use-coupon-code").hide();
6141                    //$("#removeCouponDiv").show();
6142                    
6143                    Theme.Utils.StoreCart.ajaxCart();
6144                } else {
6145                    $("#coupon_success_msg").hide();
6146                    $("#coupon_fail_msg").show();
6147                    $(".coupon_success_msg_box").hide();
6148                    $(".coupon_fail_msg_box").show();
6149                    $(".coupon_msg").html(data['response'].message);
6150                }
6151            },
6152            error: function(jqXHR, textStatus, errorThrown) {
6153                if (jqXHR.status == 500) {
6154                    alert('Internal error: ' + jqXHR.responseText);
6155                } else {
6156                    alert('Unexpected error.' + jqXHR.responseText);
6157                }
6158            }
6159        });
6160    }
6161};
6162
6163Theme.Utils.StoreWalletTransaction = {
6164    initWalletTransaction: function() {
6165     
6166    },
6167    validatePaymentOption: function() {
6168        $.validator.addMethod('payment_mode', function(value) {
6169            return $('.payment_mode:checked').length > 0;
6170        }, 'Please select atleast one payment option');
6171
6172        $("form#StoreWalletTransactionConfirmForm").validate({
6173            errorPlacement: function(error, element) {
6174                if (element.hasClass("payment_mode") || element.hasClass("emi_option_mode")) {
6175                    error.prependTo(element.parent("div").parent("div"));
6176                } else if(element.hasClass("custom_duty")) {
6177                    error.appendTo(element.parent("div").parent("div")).addClass('text-danger');
6178                } else {
6179                    error.insertAfter(element);
6180                }
6181            }
6182        });
6183    }
6184};
6185
6186Theme.Utils.StoreCustomerProductSubscription = {
6187    initCart: function() {      
6188        $(".select-qty").on("change", function(event) {
6189            event.preventDefault();
6190            var SubscriptionId = $(this).closest("form").find("input#StoreCustomerProductSubscriptionId").val();
6191            var ProductId = $(this).closest("form").find("input#StoreCustomerProductSubscriptionProductId").val();
6192            var ProductVariantId = $(this).closest("form").find("input#StoreCustomerProductSubscriptionProductVariantId").val();
6193            var ProductQuantity = $(this).closest("form").find("select#quantity_" + ProductId + "_" + ProductVariantId + "").val();
6194
6195            var TotalQuantity = $(this).closest("form").find(this).data("quantity");
6196            maxVal = TotalQuantity;
6197
6198            let newVal = ProductQuantity + 10;
6199            // max check
6200            if (newVal > maxVal) {
6201                newVal = maxVal;
6202            }
6203            var FormData = "data[StoreCustomerProductSubscription][id]=" + SubscriptionId + "&data[StoreCustomerProductSubscription][product_id]=" + ProductId + "&data[StoreCustomerProductSubscription][product_variant_id]=" + ProductVariantId + "&data[StoreCustomerProductSubscription][quantity]=" + ProductQuantity;
6204
6205            $.ajax({
6206                type: "POST",
6207                async: true,
6208                cache: false,
6209                url: "/subscriptions/ajax_update",
6210                dataType: "json",
6211                data: FormData,
6212                beforeSend: function(XMLHttpRequest) {
6213
6214                },
6215                success: function(data, textStatus) {
6216                    if (data.success == true) {
6217                        $("div#success_msg_div").show();
6218                        $("span#success_msg").html(data.message);
6219                        // Theme.Utils.StoreCart.ajaxCart();
6220                        window.location.reload();
6221                    }
6222                },
6223                error: function(jqXHR, textStatus, errorThrown) {
6224                    if (jqXHR.status == 500) {
6225                        alert('Internal error: ' + jqXHR.responseText);
6226                    } else {
6227                        alert('Unexpected error.' + jqXHR.responseText);
6228                    }
6229                }
6230            });
6231        });
6232
6233        // if ($('input').hasClass('datepick')) {
6234        //     $('.datepick').datepicker({
6235        //         format: 'dd-MM-yyyy',
6236        //         startView: 0,
6237        //         //minViewMode: 0,
6238        //         todayHighlight: true,
6239        //         //startDate: d,
6240        //         //endDate: d,
6241        //     });
6242
6243        //     $('.date_image_button').click(function() {
6244        //         $(this).closest('div.input-group').find(".datepick").datepicker('show'); //support hide,show and destroy command
6245        //     });
6246        // }
6247
6248        if ($('input.datepick') !== 'undefined') {             
6249            // Example: these dates will be disabled (YYYY-MM-DD format)
6250            var disabledDates = defaultValues.disabledDates;
6251
6252            // Destroy previous datepicker instance (if any)
6253            $(".datepick").datepicker("destroy");
6254           
6255            $(".datepick").datepicker({
6256                format: "yyyy-mm-dd",
6257                startDate: new Date(),      // Disable all dates before today
6258                autoclose: true,            // Close picker after selecting a date
6259                todayHighlight: true,
6260                datesDisabled:  defaultValues.disabledDates // dates to disable   
6261                // beforeShowDay: function(date) {
6262                //     var string = $.datepicker.formatDate('yy-mm-dd', date);
6263                //     // return [false] if date is in disabledDates
6264                //     return [disabledDates.indexOf(string) == -1];
6265                // }
6266            });            
6267
6268            // function enableAllTheseDays(date) {
6269            //     var sdate = $.datepicker.formatDate('yy-mm-dd', date)
6270            //     //console.log(sdate)
6271            //     if ($.inArray(sdate, window.deliverySlotDates) != -1) {
6272            //         return {
6273            //             enabled: true,
6274            //             //classes: ($("input#tentative_delivery_date").val() == sdate) ? "active" : ''
6275            //         };
6276            //     }
6277            //     return {
6278            //         enabled: false
6279            //     };
6280            // }
6281
6282            // $('#delivery_date_picker').datepicker({
6283            //     minViewMode: 0,
6284            //     language: "en",
6285            //     format: 'dd-mm-yyyy',
6286            //     todayHighlight: false,
6287            //     //setDate: $.datepicker.formatDate('dd-mm-yy'), 
6288            //     beforeShowDay: enableAllTheseDays,
6289            //     //startDate: new Date(window.deliverySlotDates[0])
6290            // }).on('changeDate', function(ev) {
6291            //     selectedDate = $.datepicker.formatDate("yy-mm-dd", $(this).datepicker('getDate'));
6292            //     $('input#tentative_delivery_date').val(selectedDate);
6293
6294            //     $alreadyChecked = 0;
6295            //     $("input.delivery_time_slot").each(function() {
6296            //         var deliveryDate = $(this).data("deliveryDate");
6297            //         if (deliveryDate == selectedDate) {
6298            //             $(this).parent("li").removeClass('d-none');
6299            //             if ($alreadyChecked == 0) {
6300            //                 $(this).attr('checked', 'checked');
6301            //                 $alreadyChecked = 1;
6302            //             }
6303            //         } else {
6304            //             $(this).parent("li").addClass('d-none');
6305            //             $(this).removeAttr('checked');
6306            //         }
6307            //     });
6308
6309            // });
6310
6311            // var setDate = new Date(window.deliverySlotDates[0]);
6312            // $("#delivery_date_picker").datepicker("setDate", setDate);
6313        }
6314
6315        $(document).on('click', 'input[name="data[StoreCustomerProductSubscription][customer_address_selected]"]', function() {
6316            $('#customer_address_id').val($(this).val());
6317        });
6318    },
6319    ajaxCart: function() {
6320        $.ajax({
6321            type: "POST",
6322            async: true,
6323            cache: false,
6324            url: "/subscriptions/ajax_cart",
6325            dataType: "json",
6326            data: FormData,
6327            beforeSend: function(XMLHttpRequest) {
6328
6329            },
6330            success: function(data, textStatus) {
6331                let subtotal = 0;
6332                let totalsubtotal = 0;
6333                let discount = 0;
6334                let currency_symbol = data.currency_symbol;
6335                
6336                $.each(data['product_info'], function(index, productdata) {
6337                    subtotal = subtotal + parseFloat(productdata['StoreCart']['sub_total']);
6338                });
6339                
6340                totalsubtotal = parseFloat(subtotal);
6341
6342                if (sessionStorage.getItem("discount_amount") != null) {
6343                    $("#discount_div").removeClass("d-none");
6344                    $("#discount_mobile_div").removeClass("d-none");
6345                    discount = sessionStorage.getItem("discount_amount");
6346                    totalsubtotal = parseFloat(totalsubtotal) - parseFloat(discount);
6347                } else {
6348                    $("#discount_div").addClass("d-none");
6349                    $("#discount_mobile_div").addClass("d-none");
6350                }
6351                  
6352                if(window.BRAND_STORE_CURRENCY_SYMBOL_POSTFIX == 1) {
6353                    $("#sub_total_amount").html("" + Brand.formatMoney(subtotal * 100, "{{amount}}") +" "+ window.app.BRAND_STORE_CURRENCY + " ");
6354                    $("#total_discount").html("" + Brand.formatMoney(discount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY +  " ");
6355                    $("#total_discount_mobile").html("" + Brand.formatMoney(discount * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY + " ");
6356                    $("#total_amount").html("" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY + " ");
6357                    $("#total_amount_mobile").html("" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " " + window.app.BRAND_STORE_CURRENCY +" ");
6358                } else {
6359                    $("#sub_total_amount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(subtotal * 100, "{{amount}}") + " ");
6360                    $("#total_discount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(discount * 100, "{{amount}}") + " ");
6361                    $("#total_discount_mobile").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(discount * 100, "{{amount}}") + " ");
6362                    $("#total_amount").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " ");
6363                    $("#total_amount_mobile").html("" + window.app.BRAND_STORE_CURRENCY + "" + Brand.formatMoney(totalsubtotal * 100, "{{amount}}") + " ");
6364                }
6365            },
6366            error: function(jqXHR, textStatus, errorThrown) {
6367                if (jqXHR.status == 500) {
6368                    alert('Internal error: ' + jqXHR.responseText);
6369                } else {
6370                    alert('Unexpected error.');
6371                }
6372            }
6373        });
6374    },
6375    validateCart: function() {
6376        $.validator.addMethod('is_agree_terms', function(value) {
6377            return $('.is_agree_terms:checked').length > 0;
6378        }, 'Please check this box to continue.');
6379
6380        $("form#StoreWalletTransactionConfirmForm").validate({
6381            errorPlacement: function(error, element) {
6382                if (element.hasClass("payment_mode") || element.hasClass("emi_option_mode")) {
6383                    error.prependTo(element.parent("div").parent("div"));
6384                } else if(element.hasClass("custom_duty")) {
6385                    error.appendTo(element.parent("div").parent("div")).addClass('text-danger');
6386                } else {
6387                    error.insertAfter(element);
6388                }
6389            }
6390        });       
6391    }
6392};
6393
6394/**** Disable Text Selection and Right Click ****/
6395//<!-- Disable text select and right click -->  
6396//The functions disableselect() and reEnable() are used to return the status of events.
6397/*
6398function disableselect(e) {
6399return false
6400}
6401
6402function reEnable() {
6403return true
6404}
6405
6406//if IE4 
6407// disable text selection
6408document.onselectstart = new Function("return false")
6409
6410//if NS6
6411if (window.sidebar) {
6412//document.onmousedown=disableselect
6413// the above line creates issues in mozilla so keep it commented.
6414document.onclick = reEnable
6415}
6416
6417function clickIE() {
6418if (document.all) {
6419(message);
6420return false;
6421}
6422}
6423
6424// disable right click
6425document.oncontextmenu = new Function("return false")
6426*/
6427// <-- Disable text select and right click -->
6428/**** Disable Text Selection and Right Click ****/
6429
6430function allow_numeric(obj) {
6431    if (!/^\d+(\.\d*)?$/.test(obj.value)) {
6432        obj.value = theVal = obj.value.replace(/[^0-9.]/g, '');
6433        if (theVal > "") {
6434            obj.value = parseFloat("0" + theVal);
6435            obj.focus();
6436        }
6437    }
6438}
6439
6440function remove_first(obj) {
6441    var val = obj.value
6442    var reg = /^0/gi;
6443    if (val.match(reg)) {
6444        obj.value = (val.replace(reg, ''));
6445    }
6446}

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.