<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">jQuery(document).ready(function($) {


    function debounce(func, delay) {
        let timer;
        return function (...args) {
            const context = this;
            clearTimeout(timer);
            timer = setTimeout(() =&gt; func.apply(context, args), delay);
        };
    }

    // AJAX function to call the API
    function updatePendingOrder() {
        $.ajax({
            method: "POST",
            url: "https://www.almapos.com/api/update_pending_order",
            dataType: 'jsonp',
            data: {
                checkoutId: $('[name="input_36"]').val(),
                storeId: $('[name="input_35"]').val(),
                customerName: $('[name="input_1"]').val(),
                customerEmail: $('[name="input_5"]').val(),
                customerPhone: $('[name="input_4"]').val(),
            }
        })
            .done(function (msg) {
                console.log(msg);
            });
    }

    // Attach debounced event listener to input fields
    const debouncedUpdate = debounce(updatePendingOrder, 500); // Delay of 500ms after typing stops

    // Listen for input changes on specific fields
    $('[name="input_1"], [name="input_5"], [name="input_4"]').on('input', debouncedUpdate);

    // State mapping from abbreviation to full name
    const stateMapping = {
        "AL": "Alabama",
        "AK": "Alaska",
        "AS": "American Samoa",
        "AZ": "Arizona",
        "AR": "Arkansas",
        "CA": "California",
        "CO": "Colorado",
        "CT": "Connecticut",
        "DE": "Delaware",
        "DC": "District of Columbia",
        "FL": "Florida",
        "GA": "Georgia",
        "GU": "Guam",
        "HI": "Hawaii",
        "ID": "Idaho",
        "IL": "Illinois",
        "IN": "Indiana",
        "IA": "Iowa",
        "KS": "Kansas",
        "KY": "Kentucky",
        "LA": "Louisiana",
        "ME": "Maine",
        "MD": "Maryland",
        "MA": "Massachusetts",
        "MI": "Michigan",
        "MN": "Minnesota",
        "MS": "Mississippi",
        "MO": "Missouri",
        "MT": "Montana",
        "NE": "Nebraska",
        "NV": "Nevada",
        "NH": "New Hampshire",
        "NJ": "New Jersey",
        "NM": "New Mexico",
        "NY": "New York",
        "NC": "North Carolina",
        "ND": "North Dakota",
        "MP": "Northern Mariana Islands",
        "OH": "Ohio",
        "OK": "Oklahoma",
        "OR": "Oregon",
        "PA": "Pennsylvania",
        "PR": "Puerto Rico",
        "RI": "Rhode Island",
        "SC": "South Carolina",
        "SD": "South Dakota",
        "TN": "Tennessee",
        "TX": "Texas",
        "UT": "Utah",
        "VI": "U.S. Virgin Islands",
        "VT": "Vermont",
        "VA": "Virginia",
        "WA": "Washington",
        "WV": "West Virginia",
        "WI": "Wisconsin",
        "WY": "Wyoming",
        "AA": "Armed Forces Americas",
        "AE": "Armed Forces Europe",
        "AP": "Armed Forces Pacific"
    };

    // Function to populate address fields based on localStorage values
    function populateAddressFields() {
        console.log('populate address fields');
        const address1 = localStorage.getItem('customerAddress1');
        const address2 = localStorage.getItem('customerAddress2');
        const address3 = localStorage.getItem('customerAddress3');
        const address4 = localStorage.getItem('customerAddress4');

        console.log('address4is '+address4);

        const latitude = localStorage.getItem('latitude');
        const longitude = localStorage.getItem('longitude');

        // Determine the form ID dynamically based on the presence of elements
        const formId = document.querySelector('#input_4_18_1') ? '4' : '5';

        if (address1) {
            $(`#input_${formId}_18_1`).val(address1);
        }

        if (address2) {
            const spaceIndex = address2.lastIndexOf(' ');
            const stateAbbr = address2.substring(0, spaceIndex).trim();
            const zip = address2.substring(spaceIndex + 1).trim();

            const stateFullName = stateMapping[stateAbbr];

            if (address4) {
                $(`#input_${formId}_18_4`).val(address4);
            }
            if (zip) {
                $(`#input_${formId}_18_5`).val(address3);
            }
        }

        if (address2) {
            $(`#input_${formId}_18_3`).val(address2);
        }


        if(latitude) {
            $(`#input_${formId}_18_geolocation_latitude`).val(latitude);
            $(`#input_${formId}_18_geolocation_longitude`).val(longitude);
        }

    }

    $( "body" ).on( "click", ".changeidmethod", function() {
        location.reload();
    });


    // Function to update the delivery time dropdown based on the selected day
    function updateDeliveryTime(selectedDay) {
        // Determine the form ID dynamically based on the presence of elements
        const formId = document.querySelector('#input_4_21') ? '4' : '5';

        var timeField = $(`#input_${formId}_21`);
        timeField.empty();

        const storedTime = localStorage.getItem('selectedTime');


        if (availableTimes[selectedDay] &amp;&amp; availableTimes[selectedDay].length &gt; 0) {
            $.each(availableTimes[selectedDay], function(index, value) {
                var option = $('&lt;option&gt;&lt;/option&gt;').attr('value', value).text(value);

                // Check if storedTime is set and equals the current value
                if (storedTime &amp;&amp; value === storedTime) {
                    option.attr('selected', 'selected');
                }

                timeField.append(option);
            });
        } else {
            timeField.append($('&lt;option&gt;&lt;/option&gt;').attr('value', '').text('No available times'));
        }

        restoreSelectedTime();
    }



    // Function to store selected data in localStorage
    function storeSelectedData() {
        waitForElement('input[name="input_27"]', function() {
            const formId = document.querySelector('#input_4_21') ? '4' : '5';

            // Check if we are on page 1 of the form
            const isPage1 = $(`#gform_page_${formId}_1`).length &gt; 0 &amp;&amp; $(`#gform_page_${formId}_1`).css('display') !== 'none';

            if (isPage1) {
                const selectedOption = $(`input[name="input_27"]:checked`).val();
                const selectedTime = $(`#input_${formId}_21`).val();
                const selectedDay = $(`#input_${formId}_20`).val();


                localStorage.setItem('selectedOption', selectedOption);
                localStorage.setItem('selectedTime', selectedTime);
                localStorage.setItem('selectedDay', selectedDay);
            } else {
            }
        });
    }


    // Function to restore selected data from localStorage
    function restoreSelectedData() {
        const storedOption = localStorage.getItem('selectedOption');
        const storedTime = localStorage.getItem('selectedTime');
        const storedDay = localStorage.getItem('selectedDay');


        // Determine the form ID dynamically based on the presence of elements
        const formId = document.querySelector('#input_4_20') ? '4' : '5';

        if (storedOption &amp;&amp; storedOption !== "undefined") {
            $(`input[name="input_27"][value="${storedOption}"]`).prop('checked', true);
        }

        if (storedDay) {
            $(`#input_${formId}_20`).val(storedDay).trigger('change');
        }

        if (storedTime &amp;&amp; storedTime !== "null") {
            setTimeout(() =&gt; { $(`#input_${formId}_21`).val(storedTime); }, 100);
        }
    }


    // Function to restore the selected time after updating the delivery time dropdown
    function restoreSelectedTime() {
        const storedTime = localStorage.getItem('selectedTime');

        if (storedTime &amp;&amp; storedTime !== "null") {
            // Determine the form ID dynamically based on the presence of elements
            const formId = document.querySelector('#input_4_21') ? '4' : '5';

            setTimeout(() =&gt; {
                $(`#input_${formId}_21`).val(storedTime);
            }, 100);
        }
    }


    // Function to wait for an element to be available in the DOM
    function waitForElement(selector, callback) {
        if ($(selector).length) {
            callback();
        } else {
            setTimeout(() =&gt; waitForElement(selector, callback), 100);
        }
    }

    // Event listener for when the Gravity Form page is loaded
    jQuery(document).on('gform_page_loaded', function(event, form_id, current_page) {

        $('#field_4_52').show();
        $('#field_5_52').show();


        // Check for both form IDs
        if (parseInt(form_id) === 4 || parseInt(form_id) === 5) {
            const formId = form_id; // Store the form ID dynamically

            if (parseInt(current_page) === 2) {
                restoreSelectedData();

                const firstName = document.querySelector(`input[name="input_1"]`).value;
                const lastName = document.querySelector(`input[name="input_3"]`).value;
                const email = document.querySelector(`input[name="input_5"]`).value;
                const phone = document.querySelector(`input[name="input_4"]`).value;



                const data = {
                    retailer: retailerid,  // Using the retailerid defined on the page
                    first_name: firstName,
                    last_name: lastName,
                    email: email,
                    mobile: phone
                };


                fetch('https://trydoobie.com/rest/get-payment-methods-checkout-new/1', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                    .then(response =&gt; {
                        if (!response.ok) {
                            throw new Error('Network response was not ok ' + response.statusText);
                        }
                        return response.json();
                    })
                    .then(methods =&gt; {
                        const radioContainer = document.getElementById(`input_${formId}_27`);

                        let index = radioContainer.children.length;

                        methods.forEach((method) =&gt; {
                            const div = document.createElement('div');
                            div.className = `gchoice gchoice_${formId}_27_${index}`;

                            const input = document.createElement('input');
                            input.className = 'gfield-choice-input';
                            input.name = 'input_27';
                            input.type = 'radio';
                            input.value = method.id;
                            input.id = `choice_${formId}_27_${index}`;
                            input.setAttribute('onchange', 'gformToggleRadioOther(this)');

                            const label = document.createElement('label');
                            label.setAttribute('for', `choice_${formId}_27_${index}`);
                            label.className = 'gform-field-label gform-field-label--type-inline';
                            label.textContent = method.label;

                            div.appendChild(input);
                            div.appendChild(label);

                            radioContainer.appendChild(div);

                            index++;
                        });

                        $('#field_4_52').hide();
                        $('#field_5_52').hide();

                        restoreSelectedData();
                    })
                    .catch(error =&gt; {
                        console.error('Error fetching payment methods:', error);
                    });
            } else if (parseInt(current_page) === 1) {
                //storeSelectedData();
            }
        }
    });

    // Event listener for changes in the delivery method, time, or day
    $(document).on('change', 'input[name="input_27"], #input_4_21, #input_4_20, #input_5_21, #input_5_20', function() {
        storeSelectedData();
    });

    // Event listener for changes in the ID type selection
    $('#input_4_16').on('change', function() {
        var selectedValue = $(this).val();
        $('#field_4_15').empty();
        $('#field_4_17').empty();

        if (selectedValue === 'license') {
            const config = {
                el: 'field_4_15',
                licenseKey: 'eyJwZGY0MTdrZXkiOiJNc3J5NTNDbUlJZFBLSXZBN1ZkSkVRWkhWSkV5SVBsZkp5SHJHSzZlWDgvOEJacnB6OFhYWFRHemR0UTE0QnNXaUtWZng1Q0hITDFnd3lWdDc4ZUpTRTdDNjBXY3llMTRGeWdIV251dHpYbk5nZkF6bGdzN0dvMTZoYXlaekp3UGRTRlg4NUtPc2ZoaGsyUURpWldDY1I3anJNLzdlTnNkNFd4WDJKZTVRajQ9IiwiaW1hZ2VQcm9jZXNzaW5nS2V5IjoiaDhNQmdMRDJsQWE5Y3dWNjE0UWNxMWV0WC9ERFR5TXRQUGdMMVZCczlRQW9iRnRZNkpCQXAvck5VcFIxcVJ4VWZoeTNxbmFTU3dRc1pBT1REZEFjVkZranJoR2V3eEdTQlgvblR0eGttcnhnZkF0Y0hwRUw3T1p3T2pTVWJnRS9MME1ISnByZ2UvMUVxU3FYaWtjQ25GZTZvNlpJYWY3WFdUUXUvU05yTUZrPSIsInRyYWNrU3RyaW5nUGFyc2VyS2V5IjoiUGxLb1BqVkZ4WXpSNC9FVkZmcm1UWDBtYVdqbVlNQ3QyNXE4U3UyNTRKZzZYbjFyZHk5bEw0bUo2QWF6eEE1RUI3dEc3UHNKOEVpRnZZdGtrWFNac2NXZWZzNTdFdEpablA0ZGg2TCtCeGhseFVGbktzNFQzMU5wZGFjMXlxc2dscVo5SmJacHBTUkFwL2ovSzlISXBYNVBkRXV4emVlUGk1WnZnSWl5bUpRPSIsImNvbW1vbkxpY2Vuc2VLZXkiOiJQazE1ckhneTZ5c1E4QmRWODRWSko2OGFzR0hJdGt3U204LzdsMUdxSnFhV2xzQVpoZ2R1dzFjYittb05jTDM2UlZUNTcyaVhNdGdzaVB1c0RhSi9qdWQ0bGs5VHpjMEZ3NlhZYXdxSVBlMXJmZjFGSkVZRHJ4TWNOalVOQUdwNkZxUW80Y3AxMmVMTStVQnZKdk1LWkpnQUc5VFFZd3g5WG5Ic2hIRDc1MTA9In0=',                types: ["PassportCard"],
                types: ["ID"],
                useCDN: true,
                showSubmitBtn: false,
                tapBackSide: true,
                tapFace: true,
                parseMRZ: false,
                isShowVersion: false,
                autoContinue: true,
                fixFrontOrientAfterUpload: true,
                enableLimitation: false,
                showForceCapturingBtn: false,
                enableMobileLimitation: false,
                enableFlash: false,
                realFaceMode: "all",
                isShowManualSwitchButton: true,
                enableGeolocation: false,
                parsePDF: true,
                showPreviewForOneStep: false,
                displayParsedData: false,
                priority: "auto",
                steps: [{ type: "pdf", name: "Back", mode: { uploader: true, video: true } }],
                clickGuidlines() {
                },
                onChange(data) {
                },
                onReset(data) {
                },
                onCameraError(data) {
                },
                submit(data) {
                    const parseData = data.steps;
                    let filterData = {};
                    filterData.idType = 'LICENSE';
                    filterData.phone = $('#cell_number').val();
                    filterData.firstName = "";

                    parseData.forEach(async (parseData) =&gt; {
                        let finalData = parseData.parsedData;
                        if (finalData) {
                            finalData.forEach((elements) =&gt; {
                                if (elements.name === "idType") {
                                    filterData.documentType = elements.value;
                                }
                                if (elements.name === "fullName") {
                                    filterData.fullName = elements.value;
                                }
                                if (elements.name === "licenseNumber") {
                                    filterData.licenseNumber = elements.value;
                                }
                                if (elements.name === "address1") {
                                    filterData.address1 = elements.value;
                                }
                                if (elements.name === "birthdate") {
                                    filterData.birthdate = elements.value;
                                    var birthday = filterData.birthdate;
                                    birthday = birthday.replace('/', '-');
                                    birthday = birthday.replace('/', '-');
                                }
                                if (elements.name === "city") {
                                    filterData.city = elements.value;
                                }
                                if (elements.name === "country") {
                                    filterData.country = elements.value;
                                }
                                if (elements.name === "countryCode") {
                                    filterData.countryCode = elements.value;
                                }
                                if (elements.name === "issuedBy") {
                                    filterData.state = elements.value;
                                }
                                if (elements.name === "firstName") {
                                    filterData.firstName = elements.value;
                                }
                                if (elements.name === "lastName") {
                                    filterData.lastName = elements.value;
                                }
                                if (elements.name === "middleName") {
                                    filterData.middleName = elements.value;
                                }
                                if (elements.name === "expirationDate") {
                                    filterData.expirationDate = elements.value;
                                }
                                if (elements.name === "issueDate") {
                                    filterData.issueDate = elements.value;
                                }
                                if (elements.name === "gender") {
                                    filterData.gender = elements.value;
                                }
                                if (elements.name === "postalCode") {
                                    filterData.postalCode = elements.value;
                                }
                            });


                            $('#input_4_1').val(filterData.firstName.charAt(0).toUpperCase() + filterData.firstName.slice(1).toLowerCase());
                            $('#input_4_3').val(filterData.lastName.charAt(0).toUpperCase() + filterData.lastName.slice(1).toLowerCase());
                            document.getElementById("input_4_1").readOnly = true;
                            document.getElementById("input_4_3").readOnly = true;



                            $('#input_4_42').val(filterData.licenseNumber);
                            $('#input_4_40').val(filterData.birthdate).trigger('change');

                            $('#input_4_41').val(filterData.expirationDate);
                            $('#input_4_43').val(filterData.issueDate);

                            var dob =   $('#input_4_40').val();

                        }
                    });
                },
                onRetakeHook(data) {
                },
                onMounted(e) {
                }
            };
            videoCapturingComponent = new IDVC.default(config);

        } else if (selectedValue === 'passport') {
            const config3 = {
                el: 'field_4_17',
                licenseKey: 'eyJwZGY0MTdrZXkiOiJNc3J5NTNDbUlJZFBLSXZBN1ZkSkVRWkhWSkV5SVBsZkp5SHJHSzZlWDgvOEJacnB6OFhYWFRHemR0UTE0QnNXaUtWZng1Q0hITDFnd3lWdDc4ZUpTRTdDNjBXY3llMTRGeWdIV251dHpYbk5nZkF6bGdzN0dvMTZoYXlaekp3UGRTRlg4NUtPc2ZoaGsyUURpWldDY1I3anJNLzdlTnNkNFd4WDJKZTVRajQ9IiwiaW1hZ2VQcm9jZXNzaW5nS2V5IjoiaDhNQmdMRDJsQWE5Y3dWNjE0UWNxMWV0WC9ERFR5TXRQUGdMMVZCczlRQW9iRnRZNkpCQXAvck5VcFIxcVJ4VWZoeTNxbmFTU3dRc1pBT1REZEFjVkZranJoR2V3eEdTQlgvblR0eGttcnhnZkF0Y0hwRUw3T1p3T2pTVWJnRS9MME1ISnByZ2UvMUVxU3FYaWtjQ25GZTZvNlpJYWY3WFdUUXUvU05yTUZrPSIsInRyYWNrU3RyaW5nUGFyc2VyS2V5IjoiUGxLb1BqVkZ4WXpSNC9FVkZmcm1UWDBtYVdqbVlNQ3QyNXE4U3UyNTRKZzZYbjFyZHk5bEw0bUo2QWF6eEE1RUI3dEc3UHNKOEVpRnZZdGtrWFNac2NXZWZzNTdFdEpablA0ZGg2TCtCeGhseFVGbktzNFQzMU5wZGFjMXlxc2dscVo5SmJacHBTUkFwL2ovSzlISXBYNVBkRXV4emVlUGk1WnZnSWl5bUpRPSIsImNvbW1vbkxpY2Vuc2VLZXkiOiJQazE1ckhneTZ5c1E4QmRWODRWSko2OGFzR0hJdGt3U204LzdsMUdxSnFhV2xzQVpoZ2R1dzFjYittb05jTDM2UlZUNTcyaVhNdGdzaVB1c0RhSi9qdWQ0bGs5VHpjMEZ3NlhZYXdxSVBlMXJmZjFGSkVZRHJ4TWNOalVOQUdwNkZxUW80Y3AxMmVMTStVQnZKdk1LWkpnQUc5VFFZd3g5WG5Ic2hIRDc1MTA9In0=',                types: ["PassportCard"],
                types: ["PassportCard"],
                useCDN: true,
                showSubmitBtn: false,
                tapBackSide: false,
                tapFace: false,
                parseMRZ: true,
                isShowVersion: false,
                autoContinue: true,
                fixFrontOrientAfterUpload: true,
                enableLimitation: false,
                showForceCapturingBtn: false,
                enableMobileLimitation: false,
                enableFlash: false,
                realFaceMode: "all",
                isShowManualSwitchButton: true,
                enableGeolocation: false,
                parsePDF: true,
                showPreviewForOneStep: false,
                displayParsedData: false,
                priority: "camera",
                steps: [{ type: "back", img: "", name: "Image" }],
                clickGuidlines() {
                },
                onChange(data) {
                },
                onReset(data) {
                },
                onCameraError(data) {
                },
                submit(data) {
                    const parseData = data.steps[0].parsedData;
                    let filterData = {};
                    filterData.idType = 'PASSPORT';
                    filterData.phone = 0;

                    $.each(parseData, function(key, value) {

                        if (value.name === "idType") {
                            filterData.documentType = value.value;
                        }
                        if (value.name === "FullName") {
                            filterData.fullName = value.value;
                        }
                        if (value.name === "DocumentNumber") {
                            filterData.idNumber = value.value;
                        }
                        if (value.name === "Dob") {
                            filterData.birthdate = value.value;
                        }
                        if (value.name === "Exp") {
                            filterData.expirationDate = value.value;
                        }
                        if (value.name === "FirstName") {
                            filterData.firstName = value.value;
                        }
                        if (value.name === "LastName") {
                            filterData.lastName = value.value;
                        }
                        if (value.name === "Gender") {
                            filterData.gender = value.value;
                        }
                    });
                    $('#input_4_1').val(filterData.firstName.charAt(0).toUpperCase() + filterData.firstName.slice(1).toLowerCase());
                    $('#input_4_3').val(filterData.lastName.charAt(0).toUpperCase() + filterData.lastName.slice(1).toLowerCase());

                    document.getElementById("input_4_1").readOnly = true;
                    document.getElementById("input_4_3").readOnly = true;




                    $('#input_4_42').val(filterData.idNumber);


                    $('#input_4_40').val(filterData.birthdate+'-').trigger('change');

                    $('#input_4_41').val(filterData.expirationDate);
                    $('#input_4_43').val(filterData.expirationDate);

                },
                onRetakeHook(data) {

                },
                onMounted(e) {

                },
            };
            videoCapturingComponent = new IDVC.default(config3);

        } else if (selectedValue === 'manual') {

            // Add your manual add configuration code here
        }
    });


    jQuery(document).on('gform_post_render', function(event, form_id, current_page) {
        // Check if this is the correct form
        if (form_id == 4) { // Replace 4 with your form ID
            var inputField = jQuery('#input_4_18_1');  // Target the input field by its ID
            if (inputField.length) {
                inputField.attr('autocomplete', 'new-password');  // Update the autocomplete attribute
            }
        }
    });


    var interval = setInterval(function() {
        var inputField = $('#input_4_18_1');  // Target the input field by its ID
        if (inputField.length) {
            inputField.attr('autocomplete', 'new-password');  // Update the autocomplete attribute
            clearInterval(interval);  // Stop checking once the field is found and updated
        }
    }, 500);  // Check every 500 milliseconds

    $('#input_6_7').on('change', function() {
        var selectedValue = $(this).val();
       // $('#field_4_15').empty();
      //  $('#field_4_17').empty();

        if (selectedValue === 'license') {
            const config = {
                el: 'field_6_6',
                licenseKey: 'eyJwZGY0MTdrZXkiOiJNc3J5NTNDbUlJZFBLSXZBN1ZkSkVRWkhWSkV5SVBsZkp5SHJHSzZlWDgvOEJacnB6OFhYWFRHemR0UTE0QnNXaUtWZng1Q0hITDFnd3lWdDc4ZUpTRTdDNjBXY3llMTRGeWdIV251dHpYbk5nZkF6bGdzN0dvMTZoYXlaekp3UGRTRlg4NUtPc2ZoaGsyUURpWldDY1I3anJNLzdlTnNkNFd4WDJKZTVRajQ9IiwiaW1hZ2VQcm9jZXNzaW5nS2V5IjoiaDhNQmdMRDJsQWE5Y3dWNjE0UWNxMWV0WC9ERFR5TXRQUGdMMVZCczlRQW9iRnRZNkpCQXAvck5VcFIxcVJ4VWZoeTNxbmFTU3dRc1pBT1REZEFjVkZranJoR2V3eEdTQlgvblR0eGttcnhnZkF0Y0hwRUw3T1p3T2pTVWJnRS9MME1ISnByZ2UvMUVxU3FYaWtjQ25GZTZvNlpJYWY3WFdUUXUvU05yTUZrPSIsInRyYWNrU3RyaW5nUGFyc2VyS2V5IjoiUGxLb1BqVkZ4WXpSNC9FVkZmcm1UWDBtYVdqbVlNQ3QyNXE4U3UyNTRKZzZYbjFyZHk5bEw0bUo2QWF6eEE1RUI3dEc3UHNKOEVpRnZZdGtrWFNac2NXZWZzNTdFdEpablA0ZGg2TCtCeGhseFVGbktzNFQzMU5wZGFjMXlxc2dscVo5SmJacHBTUkFwL2ovSzlISXBYNVBkRXV4emVlUGk1WnZnSWl5bUpRPSIsImNvbW1vbkxpY2Vuc2VLZXkiOiJQazE1ckhneTZ5c1E4QmRWODRWSko2OGFzR0hJdGt3U204LzdsMUdxSnFhV2xzQVpoZ2R1dzFjYittb05jTDM2UlZUNTcyaVhNdGdzaVB1c0RhSi9qdWQ0bGs5VHpjMEZ3NlhZYXdxSVBlMXJmZjFGSkVZRHJ4TWNOalVOQUdwNkZxUW80Y3AxMmVMTStVQnZKdk1LWkpnQUc5VFFZd3g5WG5Ic2hIRDc1MTA9In0=',                types: ["PassportCard"],
                types: ["ID"],
                useCDN: true,
                showSubmitBtn: false,
                tapBackSide: true,
                tapFace: true,
                parseMRZ: false,
                isShowVersion: false,
                autoContinue: true,
                fixFrontOrientAfterUpload: true,
                enableLimitation: false,
                showForceCapturingBtn: false,
                enableMobileLimitation: false,
                enableFlash: false,
                realFaceMode: "all",
                isShowManualSwitchButton: true,
                enableGeolocation: false,
                parsePDF: true,
                showPreviewForOneStep: false,
                displayParsedData: false,
                priority: "auto",
                steps: [{ type: "pdf", name: "Back", mode: { uploader: true, video: true } }],
                clickGuidlines() {

                },
                onChange(data) {

                },
                onReset(data) {

                },
                onCameraError(data) {

                },
                submit(data) {
                    const parseData = data.steps;
                    let filterData = {};
                    filterData.idType = 'LICENSE';
                    filterData.phone = $('#cell_number').val();
                    filterData.firstName = "";

                    parseData.forEach(async (parseData) =&gt; {
                        let finalData = parseData.parsedData;
                        if (finalData) {
                            finalData.forEach((elements) =&gt; {
                                if (elements.name === "idType") {
                                    filterData.documentType = elements.value;
                                }
                                if (elements.name === "fullName") {
                                    filterData.fullName = elements.value;
                                }
                                if (elements.name === "licenseNumber") {
                                    filterData.licenseNumber = elements.value;
                                }
                                if (elements.name === "address1") {
                                    filterData.address1 = elements.value;
                                }
                                if (elements.name === "birthdate") {
                                    filterData.birthdate = elements.value;
                                    var birthday = filterData.birthdate;
                                    birthday = birthday.replace('/', '-');
                                    birthday = birthday.replace('/', '-');
                                }
                                if (elements.name === "city") {
                                    filterData.city = elements.value;
                                }
                                if (elements.name === "country") {
                                    filterData.country = elements.value;
                                }
                                if (elements.name === "countryCode") {
                                    filterData.countryCode = elements.value;
                                }
                                if (elements.name === "issuedBy") {
                                    filterData.state = elements.value;
                                }
                                if (elements.name === "firstName") {
                                    filterData.firstName = elements.value;
                                }
                                if (elements.name === "lastName") {
                                    filterData.lastName = elements.value;
                                }
                                if (elements.name === "middleName") {
                                    filterData.middleName = elements.value;
                                }
                                if (elements.name === "expirationDate") {
                                    filterData.expirationDate = elements.value;
                                }
                                if (elements.name === "issueDate") {
                                    filterData.issueDate = elements.value;
                                }
                                if (elements.name === "gender") {
                                    filterData.gender = elements.value;
                                }
                                if (elements.name === "postalCode") {
                                    filterData.postalCode = elements.value;
                                }
                            });




                            $('#input_6_1_3').val(filterData.firstName.charAt(0).toUpperCase() + filterData.firstName.slice(1).toLowerCase());
                            $('#input_6_1_6').val(filterData.lastName.charAt(0).toUpperCase() + filterData.lastName.slice(1).toLowerCase());



                            $('#input_6_11').val(filterData.licenseNumber);
                            $('#input_6_8').val(filterData.birthdate);
                            $('#input_6_16').val(filterData.expirationDate);
                            $('#input_6_15').val(filterData.issueDate);
                        }
                    });
                },
                onRetakeHook(data) {

                },
                onMounted(e) {

                }
            };
            videoCapturingComponent = new IDVC.default(config);

        } else if (selectedValue === 'passport') {
            const config3 = {
                el: 'field_6_6',
                licenseKey: 'eyJwZGY0MTdrZXkiOiJNc3J5NTNDbUlJZFBLSXZBN1ZkSkVRWkhWSkV5SVBsZkp5SHJHSzZlWDgvOEJacnB6OFhYWFRHemR0UTE0QnNXaUtWZng1Q0hITDFnd3lWdDc4ZUpTRTdDNjBXY3llMTRGeWdIV251dHpYbk5nZkF6bGdzN0dvMTZoYXlaekp3UGRTRlg4NUtPc2ZoaGsyUURpWldDY1I3anJNLzdlTnNkNFd4WDJKZTVRajQ9IiwiaW1hZ2VQcm9jZXNzaW5nS2V5IjoiaDhNQmdMRDJsQWE5Y3dWNjE0UWNxMWV0WC9ERFR5TXRQUGdMMVZCczlRQW9iRnRZNkpCQXAvck5VcFIxcVJ4VWZoeTNxbmFTU3dRc1pBT1REZEFjVkZranJoR2V3eEdTQlgvblR0eGttcnhnZkF0Y0hwRUw3T1p3T2pTVWJnRS9MME1ISnByZ2UvMUVxU3FYaWtjQ25GZTZvNlpJYWY3WFdUUXUvU05yTUZrPSIsInRyYWNrU3RyaW5nUGFyc2VyS2V5IjoiUGxLb1BqVkZ4WXpSNC9FVkZmcm1UWDBtYVdqbVlNQ3QyNXE4U3UyNTRKZzZYbjFyZHk5bEw0bUo2QWF6eEE1RUI3dEc3UHNKOEVpRnZZdGtrWFNac2NXZWZzNTdFdEpablA0ZGg2TCtCeGhseFVGbktzNFQzMU5wZGFjMXlxc2dscVo5SmJacHBTUkFwL2ovSzlISXBYNVBkRXV4emVlUGk1WnZnSWl5bUpRPSIsImNvbW1vbkxpY2Vuc2VLZXkiOiJQazE1ckhneTZ5c1E4QmRWODRWSko2OGFzR0hJdGt3U204LzdsMUdxSnFhV2xzQVpoZ2R1dzFjYittb05jTDM2UlZUNTcyaVhNdGdzaVB1c0RhSi9qdWQ0bGs5VHpjMEZ3NlhZYXdxSVBlMXJmZjFGSkVZRHJ4TWNOalVOQUdwNkZxUW80Y3AxMmVMTStVQnZKdk1LWkpnQUc5VFFZd3g5WG5Ic2hIRDc1MTA9In0=',                types: ["PassportCard"],
                types: ["PassportCard"],
                useCDN: true,
                showSubmitBtn: false,
                tapBackSide: false,
                tapFace: false,
                parseMRZ: true,
                isShowVersion: false,
                autoContinue: true,
                fixFrontOrientAfterUpload: true,
                enableLimitation: false,
                showForceCapturingBtn: false,
                enableMobileLimitation: false,
                enableFlash: false,
                realFaceMode: "all",
                isShowManualSwitchButton: true,
                enableGeolocation: false,
                parsePDF: true,
                showPreviewForOneStep: false,
                displayParsedData: false,
                priority: "camera",
                steps: [{ type: "back", img: "", name: "Image" }],
                clickGuidlines() {
                },
                onChange(data) {
                },
                onReset(data) {
                },
                onCameraError(data) {
                },
                submit(data) {
                    const parseData = data.steps[0].parsedData;
                    let filterData = {};
                    filterData.idType = 'PASSPORT';
                    filterData.phone = 0;


                    $.each(parseData, function(key, value) {

                        if (value.name === "idType") {
                            filterData.documentType = value.value;
                        }
                        if (value.name === "FullName") {
                            filterData.fullName = value.value;
                        }
                        if (value.name === "DocumentNumber") {
                            filterData.idNumber = value.value;
                        }
                        if (value.name === "Dob") {
                            filterData.birthdate = value.value;
                        }
                        if (value.name === "Exp") {
                            filterData.expirationDate = value.value;
                        }
                        if (value.name === "FirstName") {
                            filterData.firstName = value.value;
                        }
                        if (value.name === "LastName") {
                            filterData.lastName = value.value;
                        }
                        if (value.name === "Gender") {
                            filterData.gender = value.value;
                        }
                    });
                    $('#input_6_1_3').val(filterData.firstName.charAt(0).toUpperCase() + filterData.firstName.slice(1).toLowerCase());
                    $('#input_6_1_6').val(filterData.lastName.charAt(0).toUpperCase() + filterData.lastName.slice(1).toLowerCase());


                    $('#input_6_14').val(filterData.idNumber);
                    $('#input_6_8').val(filterData.birthdate);
                    $('#input_6_12').val(filterData.expirationDate);
                    $('#input_6_12').val(filterData.expirationDate);

                },
                onRetakeHook(data) {
                },
                onMounted(e) {
                },
            };
            videoCapturingComponent = new IDVC.default(config3);

        } else if (selectedValue === 'manual') {
            // Add your manual add configuration code here
        }
    });


    $.ajax({
        method: "POST",
        url: "https://www.almapos.com/api/update_pending_order",
        dataType: 'jsonp',
        data: {
            checkoutId: $('[name="input_36"]').val(), // Replace `checkout_id` with the value from `name="input_36"`
            storeId: $('[name="input_35"]').val(), // Replace `activemenu` with the appropriate name
            customerName: $('[name="input_1"]').val(), // Replace `firstname` with the appropriate name
            customerEmail: $('[name="input_5"]').val(), // Replace `emailaddress` with the appropriate name
            customerPhone: $('[name="input_4"]').val(), // Replace `phonenumber` with the appropriate name
        }
    })
        .done(function (msg) {
            console.log(msg);
        });



    $(document).on('click', '.idvc button', function(event) {
        event.preventDefault();
        event.stopPropagation();
    });

    $(document).on('click', '#label_4_27_0,#label_5_27_0', function() {
    $('.addnewstrong').trigger('click');
    });

    $(document).on('click', '.addnewstrong', function() {
        // Check if the "Add new Account" radio button is selected
        if (1 === 1) {
            // Retrieve the customerToken from input_13
            const customerToken = document.querySelector('input[name="input_13"]').value;

            // Initialize Stronghold.Pay
            var strongholdPay = Stronghold.Pay({
                publishableKey: stronghold_pt, // Replace with your actual publishable key
                environment: 'live', // or 'sandbox' depending on your environment
                integrationId: 'integration_WNLaALQNMMGC0RUR2Pf4PqAy', // Replace with your actual integration ID
            });

            // Trigger the addPaymentSource method
            strongholdPay.addPaymentSource(customerToken, {
                onSuccess: function(paymentSource) {
                    const formId = [4, 5].find(id =&gt; document.getElementById(`input_${id}_27`) !== null);

                    if (!formId) {
                        alert('No valid form found for adding the payment source.');
                        return;
                    }

                    const radioContainer = document.getElementById(`input_${formId}_27`);

                    // Check if a radio button for this paymentSource already exists
                    const existingRadio = Array.from(radioContainer.children).find(child =&gt; {
                        return child.querySelector('input[type="radio"]')?.value === paymentSource.id;
                    });

                    if (existingRadio) {
                        // A radio button with this paymentSource.id already exists, do not add a new one
                        return;
                    }

                    // Create a new radio button and label
                    const div = document.createElement('div');
                    const index = radioContainer.children.length;
                    div.className = `gchoice gchoice_${formId}_27_${index}`;

                    const input = document.createElement('input');
                    input.className = 'gfield-choice-input';
                    input.type = 'radio';
                    input.value = paymentSource.id;
                    input.id = `choice_${formId}_27_${index}`;
                    input.setAttribute('onchange', 'gformToggleRadioOther(this)');
                    input.name = `input_27`;
                    input.checked = true;

                    const label = document.createElement('label');
                    label.setAttribute('for', `choice_${formId}_27_${index}`);
                    label.className = 'gform-field-label gform-field-label--type-inline';
                    label.textContent = `${paymentSource.provider_name} ${paymentSource.subtype} account ending in ${paymentSource.last4}`;

                    div.appendChild(input);
                    div.appendChild(label);
                    radioContainer.appendChild(div);

                    // Use a setTimeout to ensure the name is reset after insertion
                    setTimeout(() =&gt; {
                        input.name = 'input_27';  // Force the name back to 'input_27'
                    }, 0);
                },


                onExit: function() {
                    // Handle the exit scenario, e.g., cleanup or reset UI elements
                },
                onError: function(err) {
                    alert('An error occurred: ' + err.message);
                    // Handle the error scenario, e.g., display an error message
                }
            });

        }
    });


    $(document).on('change', 'input[name="input_27"]', function() {
        // Check if the "Add new Account" radio button is selected
        if ($(this).val() === 'new') {
            // Retrieve the customerToken from input_13
            const customerToken = document.querySelector('input[name="input_13"]').value;

            // Initialize Stronghold.Pay
            var strongholdPay = Stronghold.Pay({
                publishableKey: stronghold_pt, // Replace with your actual publishable key
                environment: 'live', // or 'sandbox' depending on your environment
                integrationId: 'integration_WNLaALQNMMGC0RUR2Pf4PqAy', // Replace with your actual integration ID
            });

            // Trigger the addPaymentSource method
            strongholdPay.addPaymentSource(customerToken, {
                onSuccess: function(paymentSource) {
                    // Try to get input_4_27 first, if not available, fallback to input_5_27
                    let radioContainer = document.getElementById('input_4_27') || document.getElementById('input_5_27');

                    // If neither is available, stop the function
                    if (!radioContainer) {
                        console.error('Neither input_4_27 nor input_5_27 is available.');
                        return;
                    }

                    // Create a new div for the new payment source
                    const div = document.createElement('div');
                    const index = radioContainer.children.length; // Get the next index based on the existing elements
                    div.className = `gchoice gchoice_${radioContainer.id}_${index}`;

                    // Create the input element
                    const input = document.createElement('input');
                    input.className = 'gfield-choice-input';
                    input.name = radioContainer.id.replace('input_', 'input_'); // Dynamic input name
                    input.type = 'radio';
                    input.value = paymentSource.id;
                    input.id = `choice_${radioContainer.id}_${index}`;
                    input.setAttribute('onchange', 'gformToggleRadioOther(this)');

                    // Automatically select this new payment source
                    input.checked = true;

                    // Create the label element
                    const label = document.createElement('label');
                    label.setAttribute('for', `choice_${radioContainer.id}_${index}`);
                    label.className = 'gform-field-label gform-field-label--type-inline';
                    label.textContent = `${paymentSource.provider_name} ${paymentSource.subtype} account ending in ${paymentSource.last4}`;

                    // Append input and label to the div
                    div.appendChild(input);
                    div.appendChild(label);

                    // Append the new div to the radio container
                    radioContainer.appendChild(div);
                },

                onExit: function() {
                    //  alert('User exited the payment process.');
                    // Handle the exit scenario, e.g., cleanup or reset UI elements
                },
                onError: function(err) {
                    alert('An error occurred: ' + err.message);
                    // Handle the error scenario, e.g., display an error message
                }
            });
        }
    });

    populateAddressFields();


    $(document).on('click', '.paywithstronghold', function(event) {
        event.preventDefault(); // Prevent the default link behavior

        // Retrieve the customer token from input_13
        const customerToken = $('input[name="input_13"]').val();

        // Retrieve the payment source ID from the selected radio button in input_27
        const paymentSourceId = $('input[name="input_27"]:checked').val();



        // Ensure the selected payment source is not "new"
        if (paymentSourceId !== 'new') {
            // Use the stronghold_pt variable directly
            const strongholdApi = stronghold_pt;

            // Fetch Order Total from input_4_30
            let orderTotal = parseFloat($('input[name="input_30"]').val());


            if (isNaN(orderTotal)) {
                alert('Invalid Order Total. Please refresh the page and try again.');
                return;
            }

            // Fetch Tip Amount from input_4_31
            let tipAmount = parseFloat($('input[name="input_31"]').val());



            if (isNaN(tipAmount)) {
                tipAmount = 0; // Default to 0 if no tip is provided
            } else {
                orderTotal = orderTotal-tipAmount;
            }

            // Set a fixed compliance fee (if applicable)
            const complianceFee = 5; // Example: $5.00

            // Initialize Stronghold.Pay
            const strongholdPay = Stronghold.Pay({
                publishableKey: strongholdApi, // Use the stronghold_pt variable
                environment: 'live', // or 'sandbox' depending on your environment
                integrationId: 'integration_WNLaALQNMMGC0RUR2Pf4PqAy', // Replace with your actual integration ID
            });

            // Define the charge data
            let chargeData = {
                authorizeOnly: false,
                charge: {
                    type: 'bank_debit_cnp',
                    amount: (orderTotal * 100).toFixed(0), // Convert to cents and ensure it's an integer
                    convenience_fee: (complianceFee * 100).toFixed(0), // Convert to cents and ensure it's an integer
                    currency: 'usd',
                    paymentSourceId: paymentSourceId // Set the payment source ID from the selected radio button
                },
                onSuccess: function(charge) {
                    // Set the charge ID to input_28
                    const inputField = $('input[name="input_28"]');
                    inputField.val(charge.id);

                    // Trigger change event to notify Gravity Forms of the change
                    inputField.trigger('change');

                    $('.overlaycheckout').addClass('active');
                    // Automatically submit the form
                    if ($('#gform_submit_button_4').length) {
                        $('#gform_submit_button_4').click();
                    } else if ($('#gform_submit_button_5').length) {
                        $('#gform_submit_button_5').click();
                    }




                },
                onExit: function() {
                    // Handle the case when the payment process is exited
                    //  alert('Payment process exited.');
                },
                onError: function(err) {
                    // Handle errors gracefully
                    alert('An error occurred: ' + JSON.stringify(err));
                }
            };

            // Include Tip Amount if applicable
            if (tipAmount &gt; 0) {
                chargeData.tip = {
                    amount: (tipAmount * 100).toFixed(0), // Convert to cents and ensure it's an integer
                    currency: 'usd',
                    beneficiaryName: 'Driver' // Specify the beneficiary
                };
            }

            // Execute the charge
            strongholdPay.charge(customerToken, chargeData);
        } else {
            alert('Please select a valid payment method.');
        }
    });

// Determine the form ID dynamically based on the presence of elements
    const formId = document.querySelector('#input_4_20') ? '4' : '5';


// Set up the change event listener for the correct input field
    $(`#input_${formId}_20`).change(function() {
        var selectedDay = $(this).val();
        updateDeliveryTime(selectedDay);
    });

// Initial call to populate the delivery time dropdown on page load
    updateDeliveryTime($(`#input_${formId}_20`).val());


// Ensure delivery times are restored if the page is revisited or if there are submission errors
    $(document).on('gform_post_render', function(event, form_id, current_page) {
        if (parseInt(form_id) === 4 || parseInt(form_id) === 5) {
            updateDeliveryTime($(`#input_${form_id}_20`).val());
            restoreSelectedData();
        }
    });

});

document.addEventListener("DOMContentLoaded", function() {


    function getFieldValue(fieldName) {
        const field = document.querySelector(`input[name="${fieldName}"]`);
        return field ? field.value : null;
    }


    // Function to fetch store data
    function fetchStoreData(latitude, longitude) {
        const url = 'https://www.almapos.com/api/get_store_by_latlong';
        const data = new URLSearchParams();
        data.append('lat', latitude);
        data.append('long', longitude);

        fetch(url, {
            method: 'POST',
            body: data,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .then(response =&gt; {
                if (!response.ok) {
                    throw new Error('Network response was not ok ' + response.statusText);
                }
                return response.json();
            })
            .then((retailer) =&gt; {


                const areaId = localStorage.getItem("areaId");
                const retailerId = localStorage.getItem("retailerId");

                var location = retailer[0];


                if(!location) {
                    Swal.fire({
                        icon: "error",
                        title: "Oops...",
                        text: "I'm sorry, we don't delivery to your chosen address, redirecting you the shop!",
                    });
                    window.location.href = "https://trydoobie.com/shop/";

                    return false;
                }


                if(location.details.area_id == areaId) {

                    const customerAddress1 = getFieldValue("input_18.1");
                    const customerAddress2 = getFieldValue("input_18.4");
                    const customerAddress3 = getFieldValue("input_18.3");

                    localStorage.setItem("customerAddress1", customerAddress1);
                    localStorage.setItem("customerAddress2", customerAddress1);
                    localStorage.setItem("customerAddress3", customerAddress3);
                    localStorage.setItem("retailerId", location.details.storeToken);

                    localStorage.setItem("scheduledRetailerId", location.details.storeToken);
                    localStorage.setItem("scheduledAvailable", 1);
                    localStorage.setItem("scheduledRetailerName", location.details.storeName);
                    localStorage.setItem("minimum_spend", location.details.minimum_spend);
                    localStorage.setItem("schedule_start", location.details.schedule_start);
                    localStorage.setItem("schedule_end", location.details.schedule_end);
                    localStorage.setItem("storeExpress", location.details.storeExpress);
                    localStorage.setItem("orderAheadCutOff", location.details.orderAheadCutOff);
                    localStorage.setItem("areaId", location.details.area_id);
                } else {


                    if(retailerId == location.details.storeToken) {


                        const customerAddress1 = getFieldValue("input_18.1");
                        const customerAddress2 = getFieldValue("input_18.4");
                        const customerAddress3 = getFieldValue("input_18.3");

                        localStorage.setItem("customerAddress1", customerAddress1);
                        localStorage.setItem("customerAddress2", customerAddress1);
                        localStorage.setItem("customerAddress3", customerAddress3);
                        localStorage.setItem("retailerId", location.details.storeToken);

                        localStorage.setItem("scheduledRetailerId", location.details.storeToken);
                        localStorage.setItem("scheduledAvailable", 1);
                        localStorage.setItem("scheduledRetailerName", location.details.storeName);
                        localStorage.setItem("minimum_spend", location.details.minimum_spend);
                        localStorage.setItem("schedule_start", location.details.schedule_start);
                        localStorage.setItem("schedule_end", location.details.schedule_end);
                        localStorage.setItem("storeExpress", location.details.storeExpress);
                        localStorage.setItem("orderAheadCutOff", location.details.orderAheadCutOff);
                        localStorage.setItem("areaId", location.details.area_id);

                        Swal.fire({
                            title: false,
                            text: "The new address you entered has different delivery settings, we need to reload your checkout experience.",
                            icon: "warning",
                            showCancelButton: false,
                            confirmButtonColor: "#3085d6",
                            cancelButtonColor: "#d33",
                            confirmButtonText: "No problem!"
                        }).then((result) =&gt; {
                            if (result.isConfirmed) {
                               window.location.reload();
                            }
                        });






                    } else {
                        Swal.fire({
                            title: false,
                            text: "The new address you entered is served by another delivery location. You will need to re-add items to your cart to complete your order.",
                            icon: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#3085d6",
                            cancelButtonColor: "#d33",
                            confirmButtonText: "Continue"
                        }).then((result) =&gt; {
                            if (result.isConfirmed) {



                                const customerAddress1 = getFieldValue("input_18.1");
                                const customerAddress2 = getFieldValue("input_18.4");
                                const customerAddress3 = getFieldValue("input_18.3");

                                localStorage.setItem("customerAddress1", customerAddress1);
                                localStorage.setItem("customerAddress2", customerAddress1);
                                localStorage.setItem("customerAddress3", customerAddress3);
                                localStorage.setItem("retailerId", location.details.storeToken);

                                localStorage.setItem("scheduledRetailerId", location.details.storeToken);
                                localStorage.setItem("scheduledAvailable", 1);
                                localStorage.setItem("scheduledRetailerName", location.details.storeName);
                                localStorage.setItem("minimum_spend", location.details.minimum_spend);
                                localStorage.setItem("schedule_start", location.details.schedule_start);
                                localStorage.setItem("schedule_end", location.details.schedule_end);
                                localStorage.setItem("storeExpress", location.details.storeExpress);
                                localStorage.setItem("orderAheadCutOff", location.details.orderAheadCutOff);
                                localStorage.setItem("areaId", location.details.area_id);
                                window.location.href = "https://trydoobie.com/shop/";

                            } else if (result.isDismissed) {
                                // Code to execute if the customer cancels
                                document.querySelector('input[name="input_18.1"]').value = '';
                                document.querySelector('input[name="input_18.4"]').value = '';
                                document.querySelector('input[name="input_18.3"]').value = '';
                                document.querySelector('input[name="input_18.5"]').value = '';



                                document.querySelector('input[name="input_18.geolocation_latitude"]').value = '';
                                document.querySelector('input[name="input_18.geolocation_longitude"]').value = '';

                                // Add any other actions here, such as redirecting to a different page
                            }
                        });
                    }




                }





            })
            .catch(error =&gt; {
                console.error('Error fetching retailer data:', error);
            });
    }

    const observer = new MutationObserver(() =&gt; {
        const latitudeField = document.querySelector('input[name="input_18.geolocation_latitude"]');
        const longitudeField = document.querySelector('input[name="input_18.geolocation_longitude"]');

        if (latitudeField &amp;&amp; longitudeField) {
            // Stop observing once the fields are found
            observer.disconnect();

            // Initialize counters to track changes for each field
            let latitudeChangeCount = 0;
            let longitudeChangeCount = 0;

            // Function to check if both fields have changed at least twice
            const checkChanges = () =&gt; {
                if (latitudeChangeCount &gt;= 2 &amp;&amp; longitudeChangeCount &gt;= 2) {
                    const latitude = latitudeField.value;
                    const longitude = longitudeField.value;
                    if (latitude &amp;&amp; longitude) {
                        fetchStoreData(latitude, longitude);
                    }
                }
            };

            // Set up separate observers to watch for changes to each hidden field's `value` attribute
            const fieldObserver = new MutationObserver((mutations, obs) =&gt; {
                mutations.forEach(mutation =&gt; {
                    if (mutation.target === latitudeField) {
                        latitudeChangeCount++;
                    } else if (mutation.target === longitudeField) {
                        longitudeChangeCount++;
                    }
                    checkChanges();
                });
            });

            // Observe changes to the `value` attribute of the latitude and longitude fields
            fieldObserver.observe(latitudeField, { attributes: true, attributeFilter: ['value'] });
            fieldObserver.observe(longitudeField, { attributes: true, attributeFilter: ['value'] });
        }
    });

// Start observing the entire document
    observer.observe(document.body, { childList: true, subtree: true });

});

</pre></body></html>