function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        var expires = "; expires=" + date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function cookieUpdate(id, quantity) {
    var cookieName = sbuy_obj.cookie_name;
    var cookie = [];
    var obj = {};
    if (readCookie(cookieName)) {
        cookie = JSON.parse(readCookie(cookieName));
        cookie.forEach((product, i) => {
            if (id === product.id) {
                if (quantity < 1) {
                    cookie.splice(i, 1);
                } else {
                    obj["id"] = id;
                    obj["quantity"] = parseInt(quantity);
                    cookie.splice(i, 1);
                }
            } else {
                obj["id"] = id;
                obj["quantity"] = product.quantity;
            }
        });
    } else {
        obj["id"] = id;
        obj["quantity"] = quantity;
    }
    cookie.push(obj);
    createCookie(cookieName, JSON.stringify(cookie), 1);
}

function validateEmail(email) {
    return email.match(
        /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    );
}

function validatePostalCode(postalCode) {
    const s = String(postalCode ?? '').trim();

    return /^[A-Za-z0-9][A-Za-z0-9 -]{1,8}[A-Za-z0-9]$/.test(s);
}

function validatePhone(phone) {
    return phone.match(/^[\d +-]+$/);
}

function textToNumber(text) {
    var price = text.replace(/\s/g, "");
    var reversePrice = price.split("").reverse().join("");
    var decimalSeperator = "";
    // if only dot exists, set decimal_seperator to dot
    if (price.indexOf(".") > 0 && price.indexOf(",") == -1) {
        decimalSeperator = ".";
    }

    // if only comma exists, set decimal_seperator to comma
    if (price.indexOf(",") > 0 && price.indexOf(".") == -1) {
        decimalSeperator = ",";
    }

    // if comma and dot exists, calculte positions of comma and dot for determine decimal seperator
    if (price.indexOf(",") > 0 && price.indexOf(".") > 0) {
        var commaPosition = reversePrice.indexOf(",")
            ? reversePrice.indexOf(",")
            : 0;
        var dotPosition = reversePrice.indexOf(".") ? reversePrice.indexOf(".") : 0;
        decimalSeperator = commaPosition < dotPosition ? "," : ".";
    }

    if (price.indexOf(",") == -1 && price.indexOf(".") == -1) {
        decimalSeperator = ".";
    }

    var splittedPrice = price.split(decimalSeperator),
        thousands = splittedPrice[0] ? splittedPrice[0] : 0,
        decimals = splittedPrice[1] ? splittedPrice[1] : 0;

    thousands = thousands ? thousands.replace(/[,.]/g, "") : 0;
    var newPrice = thousands + "." + decimals;

    return parseFloat(newPrice).toFixed(2);
}

function numberToText(number) {
    var text = new Intl.NumberFormat("en-DE", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(number);
    return text;
}

function subTotalUpdate(id, quantity) {
    var price = parseFloat(
        textToNumber(jQuery(`tr[data-product-id="${id}"] .price .amount`).text())
    );
    var newSubTotal = price * quantity;
    jQuery(`#details-subtotal-${id} .amount`).text(numberToText(newSubTotal));
}

function totalUpdate() {
    var total = 0;
    jQuery("#details-table tbody tr").each(function (i, item) {
        var subtotal = parseFloat(
            textToNumber(
                jQuery(this).find("td[id^='details-subtotal'] .amount").text()
            )
        );
        total = total + subtotal;
    });
    jQuery("#details-total .amount").text(numberToText(total));
}

function surchargeUpdate() {
    var total = 0;
    jQuery("#summary-table tbody tr").each(function () {
        var price = parseFloat(textToNumber(jQuery(this).find(".amount").text()));
        total += price;
    });
    var minimumPickup = sbuy_obj.minimum_pickup
        ? parseFloat(sbuy_obj.minimum_pickup).toFixed(2)
        : 0;

    if (total < minimumPickup) {
        var surchargeAmount = minimumPickup - total;
        if (jQuery("#min-order-surcharge-area").length) {
            jQuery("#min-order-surcharge-area .amount").text(
                numberToText(surchargeAmount)
            );
        } else {
            var html = `<tr id="min-order-surcharge-area">
					<td class="label">${sbuy_obj.surchage_text}</td>
					<td class="price"><span class="amount">${numberToText(
                surchargeAmount
            )}</span> <span class="currency">${
                sbuy_obj.currency_symbol
            }</span></td>
				</tr>`;

            jQuery("#elevator-walkway-sucharge-area").before(html);
            summaryTotalUpdate();
        }
    } else {
        jQuery("#min-order-surcharge-area").remove();
    }
}

function summaryTotalUpdate() {
    var total = parseFloat(textToNumber(jQuery("#details-total .amount").text()));
    var minimumPickup = sbuy_obj.minimum_pickup
        ? parseFloat(sbuy_obj.minimum_pickup).toFixed(2)
        : 0;
    if (total > minimumPickup) {
        jQuery("#summary-total .amount").text(numberToText(total));
    } else {
        jQuery("#summary-total .amount").text(numberToText(minimumPickup));
    }
    if (jQuery("#elevator-walkway-suchar"))
        var elevatorSurcharge = parseFloat(
            textToNumber(jQuery("#elevator-walkway-sucharge-area .amount").text())
        );
    if (elevatorSurcharge) {
        var newTotal = parseFloat(
            textToNumber(jQuery("#summary-total .amount").text())
        );
        total = newTotal + elevatorSurcharge;
        jQuery("#summary-total .amount").text(numberToText(total));
    }
}

function summarySubtotalUpdate(productId) {
    var subTotal = jQuery(`#details-subtotal-${productId} .amount`).text();
    jQuery(`#summary-subtotal-${productId} .amount`).text(subTotal);
}

function summaryQuantityUpdate(productId) {
    var quantity = jQuery(
        `input[type="number"][data-quantity="${productId}"]`
    ).val();
    jQuery(`#summary-quantity-${productId}`).text(quantity);
}

function summaryTableUpdate(productId) {
    jQuery(`#product-${productId}`).remove();
}

function surchargeDistanceUpdate() {
    var elevator = jQuery("#elevator").find("option:selected").val();
    var floorNumber = 0;
    if (elevator === "no") {
        floorNumber = parseInt(jQuery("#floor").find("option:selected").val()) ?? 0;
    }

    var walkway = parseInt(jQuery("#walkway").find("option:selected").val());

    var previousTotal = 0;
    jQuery("#summary-table tbody tr").each(function () {
        var price = parseFloat(textToNumber(jQuery(this).find(".amount").text()));
        previousTotal += price;
    });
    if (jQuery("#min-order-surcharge-area").length) {
        previousTotal += parseFloat(
            textToNumber(jQuery("#min-order-surcharge-area .amount").text())
        );
    }
    var surchargeFloor = sbuy_obj.surcharge_floor
        ? parseFloat(sbuy_obj.surcharge_floor)
        : 0;
    var surchargeWalkway = 0;
    if (walkway == 1 && sbuy_obj.surcharge_15_50_meter) {
        surchargeWalkway = parseFloat(sbuy_obj.surcharge_15_50_meter) ?? 0;
    }
    if (walkway == 2 && sbuy_obj.surcharge_50_plus_meter) {
        surchargeWalkway = parseFloat(sbuy_obj.surcharge_50_plus_meter) ?? 0;
    }
    if (floorNumber >= 4 || surchargeWalkway) {
        var surchargeDistance = 0;

        if (floorNumber >= 4 && walkway >= 1) {
            surchargeDistance = Math.max(surchargeFloor, surchargeWalkway);
        } else if (floorNumber >= 4 && !walkway) {
            surchargeDistance = surchargeFloor;
        } else if (walkway >= 1 && !floorNumber) {
            surchargeDistance = surchargeWalkway;
        }

        var surchargeAmount = (previousTotal * surchargeDistance) / 100;
        if (surchargeAmount) {
            var newTotal = previousTotal + surchargeAmount;
            jQuery("#elevator-walkway-sucharge-area").show();
            jQuery("#elevator-walkway-sucharge-area .price .amount").text(
                numberToText(surchargeAmount)
            );
            jQuery("#summary-total .amount").text(numberToText(newTotal));
        } else {
            jQuery("#elevator-walkway-sucharge-area .price .amount").text("0");
            jQuery("#elevator-walkway-sucharge-area").hide();
            jQuery("#summary-total .amount").text(numberToText(previousTotal));
        }
    } else {
        jQuery("#elevator-walkway-sucharge-area .price .amount").text("0");
        jQuery("#elevator-walkway-sucharge-area").hide();
        jQuery("#summary-total .amount").text(numberToText(previousTotal));
    }
}

function dateSelected(date) {
    jQuery.ajax({
        method: "POST",
        url: sbuy_obj.ajaxurl,
        data: {
            action: "sbuy_date_selected",
            nonce: sbuy_obj.nonce,
            date: date,
        },
        success: function (response) {
            // Rebuild the dropdown cleanly each time. Previously we just
            // .append()-ed the new option, which visually displayed it but
            // left the initial disabled "select-date-first" as the actually
            // selected option — so $("#slot option:selected").val() still
            // returned a placeholder and the submit validator rejected the
            // booking ("please choose a time slot") even though the user saw
            // a valid time in the dropdown.
            var $slot = jQuery("select#slot").empty().removeClass("error");
            if (response.success) {
                var time    = response.data.time;
                var message = response.data.message;
                $slot.append(
                    `<option value="${time}" selected>${message}</option>`
                )
                    .val(time)
                    .trigger("change");
            } else {
                $slot.append(
                    `<option value="no-available-time" disabled selected>${response.data.message}</option>`
                );
            }
        },
    });
}

jQuery(document)
    .on("click", "#details-table .plus", function () {
        var productId = jQuery(this).closest("tr").data("product-id"),
            oldProductQuantity = parseInt(
                jQuery(`input[type="number"][data-quantity="${productId}"]`).val()
            );
        jQuery(`input[type="number"][data-quantity="${productId}"]`).val(
            oldProductQuantity + 1
        );
        var newProductQuantity = jQuery(
            `input[type="number"][data-quantity="${productId}"]`
        ).val();
        cookieUpdate(productId, newProductQuantity);

        subTotalUpdate(productId, newProductQuantity);
        totalUpdate();
        summaryQuantityUpdate(productId);
        summarySubtotalUpdate(productId);
        summaryTotalUpdate();
        surchargeDistanceUpdate();
        surchargeUpdate();
    })
    .on("click", "#details-table .minus", function () {
        var productId = jQuery(this).closest("tr").data("product-id"),
            oldProductQuantity = parseInt(
                jQuery(`input[type="number"][data-quantity="${productId}"]`).val()
            );
        jQuery(`input[type="number"][data-quantity="${productId}"]`).val(
            oldProductQuantity - 1
        );
        var newProductQuantity = parseInt(
            jQuery(`input[type="number"][data-quantity="${productId}"]`).val()
        );
        if (newProductQuantity <= 0) {
            jQuery(`tr[data-product-id="${productId}"] .remove-product`).trigger(
                "click"
            );
        } else {
            cookieUpdate(productId, newProductQuantity);
        }

        subTotalUpdate(productId, newProductQuantity);
        totalUpdate();
        summaryQuantityUpdate(productId);
        summarySubtotalUpdate(productId);
        summaryTotalUpdate();
        surchargeDistanceUpdate();
        surchargeUpdate();
    })
    .on("click", ".remove-product", function () {
        var cookieName = sbuy_obj.cookie_name,
            productCookie = JSON.parse(readCookie(cookieName)),
            productId = jQuery(this).closest("tr").data("product-id"),
            total = parseInt(jQuery("#details-total .amount").text());

        productCookie.forEach((product, i) => {
            if (product.id === productId) {
                var subTotal = jQuery(this).closest("tr").find(".subtotal").text();
                total = total - subTotal;
                productCookie.splice(i, 1);
            }
        });

        if (productCookie === "undefined" || productCookie.length == 0) {
            eraseCookie(cookieName);
            window.location.replace(sbuy_obj.cart_page_link);
        } else {
            createCookie(cookieName, JSON.stringify(productCookie), 30);
        }

        jQuery(this).closest("tr").remove();
        totalUpdate();
        surchargeUpdate();
        summaryTableUpdate(productId);
        summaryTotalUpdate();
        surchargeDistanceUpdate();
        surchargeUpdate();
    })
    .on("click", "#submit", function (e) {
        e.preventDefault();
        jQuery(".error-info").remove();
        jQuery(".formfield input, .formfield select").removeClass("error");
        jQuery("label").removeClass("error-label");
        jQuery(".sb-submit-error").removeClass('sb-submit-error--show');

        var formError = false,
            terms = jQuery("#terms").is(":checked");

        if (jQuery("#terms").length && !terms) {
            jQuery('label[for="terms"]').after(
                `<p class="error-info">${sbuy_obj.terms_error}</p>`
            );
            formError = true;
        }

        var company = jQuery("#company-name").val(),
            firstName = jQuery("#first-name").val(),
            lastName = jQuery("#last-name").val(),
            streetNo =
                (jQuery("#street").val() ? jQuery("#street").val() : "") +
                " " +
                (jQuery("#street2").val() ? jQuery("#street2").val() : ""),
            postalCode = jQuery("#postal-code").val(),
            city = jQuery("#city").val(),
            phone = jQuery("#phone").val(),
            email = jQuery("#email").val(),
            doorbell = jQuery("#doorbell").val(),
            date = jQuery("#date").val(),
            time = jQuery("#slot option:selected").text(),
            shift = jQuery("#slot option:selected").val(),
            notes = jQuery("#note").val();

        var requiredField = [
            "first-name",
            "last-name",
            "street",
            "postal-code",
            "city",
            "phone",
            "email",
            "doorbell",
            "date",
        ];

        for (let i = 0; i < requiredField.length; i++) {
            if (!jQuery(`#${requiredField[i]}`).val()) {
                jQuery(`label[for="${requiredField[i]}"]`).addClass("error-label");
                jQuery(`input#${requiredField[i]}`).addClass("error");
                formError = true;
            }
        }

        // Time slot is required — the #slot select has placeholder values
        // like "select-date-first" / "no-available-time" that must not count.
        if (!shift || shift === "select-date-first" || shift === "no-available-time") {
            jQuery('label[for="slot"]').addClass("error-label");
            jQuery("#slot").addClass("error");
            formError = true;
        }

        // Walkway: keep the numeric value (0/1/2) for server-side price calc,
        // AND the human-readable label for email display. Previously we
        // overwrote `walkway` with the label, which broke server-side
        // surcharge calculation (is_numeric("mehr als 50 Meter") === false).
        var walkway = jQuery("#walkway option:selected").attr("value");
        var walkwayText = "";
        if (!walkway && walkway !== "0") {
            jQuery('label[for="walkway"]').addClass("error-label");
            jQuery("#walkway").addClass("error");
            formError = true;
        } else {
            walkwayText = jQuery("#walkway option:selected").text();
        }

        var elevator = jQuery("#elevator option:selected").attr("value");
        var elevatorText = jQuery("#elevator option:selected").text();
        if (!elevator) {
            jQuery('label[for="elevator"]').addClass("error-label");
            jQuery("#elevator").addClass("error");
            formError = true;
        }
        // Floor: same value/label split as walkway above.
        var floor = "";
        var floorText = "";
        if (elevator === "no") {
            floor = jQuery("#floor option:selected").attr("value");
            if (!floor && floor !== "0") {
                jQuery("#floor").addClass("error");
                formError = true;
            } else {
                floorText = jQuery("#floor option:selected").text();
            }
        }

        var billingAddress = jQuery("#billing-address").is(":checked");

        var billingCompany = jQuery("#billing-company-name").val(),
            billingFirstName = jQuery("#billing-first-name").val(),
            billingLastName = jQuery("#billing-last-name").val(),
            billingStreet = jQuery("#billing-street").val(),
            billingPostalCode = jQuery("#billing-postal-code").val(),
            billingCity = jQuery("#billing-city").val();

        var plantingTree = jQuery("#planting").is(":checked");

        var emailValidation = validateEmail(email);
        if (email && !emailValidation) {
            jQuery("#email-area").addClass("error");
            jQuery("#email-area label").addClass("error-label");
            jQuery("input#email").after(
                `<p class="error-info">${sbuy_obj.email_error}</p>`
            );
            formError = true;
        }

        var postalCodeValid = validatePostalCode(postalCode);
        if (postalCode && !postalCodeValid) {
            jQuery("#postal-code-area").addClass("error");
            jQuery("#postal-code-area label").addClass("error-label");
            jQuery("input#postal-code").after(
                `<p class="error-info">${sbuy_obj.postalcode_error}</p>`
            );
            formError = true;
        }

        var phoneNumberValidate = validatePhone(phone);
        if (phone && !phoneNumberValidate) {
            jQuery("#phone-area").addClass("error");
            jQuery("#phone-area label").addClass("error-label");
            jQuery("input#phone").after(
                `<p class="error-info">${sbuy_obj.phone_error}</p>`
            );
            formError = true;
        }

        var productList = [];
        jQuery("#summary-table tbody tr").each(function (index, element) {
            var name = jQuery(this).find(".name").text();
            var quantity = jQuery(this).find(".quantity").text();
            var productId = jQuery(this).data("productid");
            var perProductPrice = jQuery(
                `#details-table tbody tr[data-product-id=${productId}] .price .amount`
            ).text();
            var subTotal = jQuery(`#details-subtotal-${productId} .amount`).text();
            productList.push({id: productId, name, quantity, perProductPrice, subTotal});
        });

        var minOrderSurcharge = 0;
        if (jQuery("#min-order-surcharge-area").length) {
            minOrderSurcharge = jQuery(
                "#min-order-surcharge-area .price .amount"
            ).text();
        }

        var elevatorWalkwaySurcharge = jQuery(
            "#elevator-walkway-sucharge-area .price .amount"
        ).text();
        var totlalPrice = jQuery("#summary-total .amount").text();

        var products = {
            productList,
            minOrderSurcharge,
            elevatorWalkwaySurcharge,
            totlalPrice,
        };

        if (formError) {
            var $errorFields = jQuery(".formfield input.error, .formfield select.error");
            var missingCount = $errorFields.length;
            console.log("[sbuy] formError=true, missing fields:", missingCount, $errorFields.toArray().map(function (el) { return el.id; }));
            var tmpl = (sbuy_obj && sbuy_obj.fields_missing_template) || "Please fill in all required fields. (%d field(s) missing)";
            jQuery(".sb-submit-error")
                .text(tmpl.replace("%d", missingCount))
                .addClass("sb-submit-error--show");

            var firstError = $errorFields.get(0);
            if (firstError) {
                console.log("[sbuy] scrolling to first error:", firstError.id);
                firstError.scrollIntoView({behavior: "smooth", block: "center"});
                try { firstError.focus({preventScroll: true}); } catch (_) { firstError.focus(); }
            }
            return;
        }

        // Only clean slot options *after* we know the form is valid and
        // we're about to re-fetch the shift from the server below. Doing
        // this before the formError return would wipe out the user's
        // already-selected "morning" / "afternoon" option whenever any
        // other required field was missing, leaving the Zeit dropdown
        // empty on the next submit attempt.
        jQuery('select#slot option[value="select-date-first"]').remove();
        jQuery('select#slot option[value="morning"]').remove();
        jQuery('select#slot option[value="afternoon"]').remove();
        jQuery('select#slot option[value="no-available-time"]').remove();

        jQuery.ajax({
            method: "POST",
            url: sbuy_obj.ajaxurl,
            data: {
                action: "sbuy_date_selected",
                nonce: sbuy_obj.nonce,
                date: date,
            },
            success: function (response) {
                if (response.success) {
                    var time = response.data.time,
                        message = response.data.message;
                    jQuery("select#slot").append(
                        `<option value="${time}">${message}</option>`
                    );

                    var time = jQuery("#slot option:selected").attr("value");
                    if (time === "select-date-first" || time === "no-available-time") {
                        jQuery("#slot").addClass("error");
                        formError = true;
                    } else {
                        jQuery("#slot").removeClass("error");
                        var time = jQuery("#slot option:selected").text();
                    }

                    if (!formError) {
                        var cookieName = sbuy_obj.cookie_name;

                        var information = {
                            company,
                            firstName,
                            lastName,
                            streetNo,
                            postalCode,
                            city,
                            phone,
                            email,
                            doorbell,
                            date,
                            time,
                            shift,
                            elevator,
                            elevatorText,
                            floor,
                            floorText,
                            walkway,
                            walkwayText,
                            notes,
                            plantingTree,
                            billingAddress,
                            billingCompany,
                            billingFirstName,
                            billingLastName,
                            billingStreet,
                            billingPostalCode,
                            billingCity,
                        };

                        jQuery.ajax({
                            type: "post",
                            url: sbuy_obj.ajaxurl,
                            data: {
                                action: "sbuy_submit_checkout_book",
                                nonce: sbuy_obj.nonce,
                                information: information,
                                products: products,
                            },
                            beforeSend: function () {
                                jQuery("#sb-checkout-page").append(
                                    '<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"></div></div>'
                                );
                            },
                            success: function (response) {
                                if (response.success) {
                                    jQuery("#sb-checkout-page .progress").remove();
                                    eraseCookie(cookieName);
                                    window.location.href = sbuy_obj.thankyou_page_link;
                                } else {
                                    jQuery("#sb-checkout-page .progress").remove();
                                    alert(response.data.message);
                                    eraseCookie(cookieName);
                                    window.location.href = sbuy_obj.thankyou_page_link;
                                }
                            },
                        });
                    } else {
                        jQuery(".sb-submit-error").addClass('sb-submit-error--show')
                    }
                } else {
                    jQuery("select#slot").append(
                        `<option value="no-available-time">${sbuy_obj.no_available_time}</option>`
                    );
                    jQuery("#slot").addClass("error");
                    jQuery("#date").addClass("error");
                    jQuery(".sb-submit-error").addClass('sb-submit-error--show')
                }
            },
        });
    })

    .on("change", "#elevator", function (e) {
        var elevatorAvailibility = jQuery("#elevator option:selected").val();
        if (elevatorAvailibility == "yes") {
            jQuery("#floor-area").hide();
        } else {
            jQuery("#floor-area").show();
        }
    })
    .on("input", '.quantity-area input[type="number"]', function (e) {
        if (jQuery(this).val() < 1) {
            jQuery(this).val(1);
        } else {
            jQuery(this).val();
        }
        var quantity = jQuery(this).val(),
            productId = parseInt(jQuery(this).data("quantity"));
        if (quantity) {
            cookieUpdate(productId, quantity);
        }
        subTotalUpdate(productId, quantity);
        totalUpdate();
        summaryQuantityUpdate(productId);
        summarySubtotalUpdate(productId);
        summaryTotalUpdate();
        surchargeDistanceUpdate();
        surchargeUpdate();
    })
    .on("click", "#billing-address", function () {
        var checked = jQuery("#billing-address").is(":checked");
        if (checked) {
            jQuery("#billing-address-information").show();
        } else {
            jQuery("#billing-address-information").hide();
        }
    })
    .on("change", "#floor, #walkway, #elevator", function () {
        surchargeDistanceUpdate();
        summaryTotalUpdate();
    });

var disabledDates = sbuy_obj.disabled_dates,
    dateFormat = sbuy_obj.date_format,
    months = sbuy_obj.months,
    days = sbuy_obj.days,
    clearDate = sbuy_obj.clear_datepicker,
    currentTime = parseInt(sbuy_obj.current_time),
    dateOffset = sbuy_obj.min_booking_days;

jQuery("#date").Zebra_DatePicker({
    direction: dateOffset,
    disabled_dates: disabledDates,
    format: dateFormat,
    days: days,
    months: months,
    lang_clear_date: clearDate,
    onSelect: function (e) {
        jQuery('select#slot option[value="select-date-first"]').remove();
        jQuery('select#slot option[value="morning"]').remove();
        jQuery('select#slot option[value="afternoon"]').remove();
        jQuery('select#slot option[value="no-available-time"]').remove();

        var date = jQuery(this)[0].value;
        if (date) {
            dateSelected(date);
        }
    },
    onClear: function () {
        jQuery('select#slot option[value="select-date-first"]').remove();
        jQuery('select#slot option[value="morning"]').remove();
        jQuery('select#slot option[value="afternoon"]').remove();
        jQuery('select#slot option[value="no-available-time"]').remove();
        jQuery("select#slot").append(
            `<option value="select-date-first" disabled selected>${sbuy_obj.initial_text_for_time}</option>`
        );
    },
});
