
// ========================
// Add Subscription To User
// ========================

$(document).ready(function () {

    var $application = $("#APPLICATION_MNEMONIC").val(), $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}");

    // -----------
    // Input Masks
    // -----------

    $(".date-mask").inputmask({alias: "datetime",
        inputFormat: "mm/dd/yyyy",
        placeholder: "MM/DD/YYYY",
        showMaskOnHover: false});

    // -------------
    // Select Picker
    // -------------

    $(".search-dropdown").selectpicker({noneSelectedText: "",
        style: "",
        styleBase: "form-select form-select-sm",
        iconBase: "bi",
        virtualScroll: true,
        size: 10,
        selectOnTab: true,
        containter: "body",
        liveSearch: true});

    // ------------
    // Date Pickers
    // ------------

    $(".subscription-end-date").each(function () {
        $(this).datepicker({
            format: "mm/dd/yyyy",
            container: $(this).closest(".subscription_end_date"),
            keyboardNavigation: false,
            showOnFocus: false,
            autoclose: true,
            orientation: "bottom left",
            todayBtn: "linked",
            todayHighlight: true
        });
    });


    // ---------------------
    // Show Calendar Buttons
    // ---------------------

    $(".btnSubscriptionEndDateCalendar").on("click", function (e) {
        e.preventDefault();
        let end_date = $(this).siblings(".subscription-end-date");

        if (!end_date.prop("disabled")) {
            end_date.focus().datepicker("show");
        }
    });

    // -----------
    // Save Button
    // -----------

    $(".btnSave").on("click", function (e) {

        e.preventDefault();

        $("#addSubscriptionToUser").submit();

    });

    // --------------
    // Cancel Button.
    // --------------

    $(".btnCancel").on("click", function () {

        $sessionStorage.action = $sessionStorage.addSubscriptionToUser || "";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    function setSubscriptionDateState(subscription_checkbox) {

        let row = subscription_checkbox.closest("tr");
        let checked = subscription_checkbox.prop("checked");

        row.find(".subscription-end-date").prop("disabled", !checked);
        row.find(".btnSubscriptionEndDateCalendar").prop("disabled", !checked);

    }

    function parseSubscriptionDate(date_value) {

        let parts = date_value.split("/");

        return new Date(parts[2], parts[0] - 1, parts[1]);

    }

    $(".subscription-checkbox").each(function () {
        setSubscriptionDateState($(this));
    });

    $(".subscription-checkbox").on("change", function () {

        let totalSubscriptions = $(".subscription-checkbox").length;
        let checkedSubscriptions = $(".subscription-checkbox:checked").length;

        $("#selectAllSubscriptions").prop("checked", totalSubscriptions === checkedSubscriptions);
        setSubscriptionDateState($(this));

    });

    $("#selectAllSubscriptions").on("change", function () {

        $(".subscription-checkbox").prop("checked", $(this).prop("checked")).each(function () {
            setSubscriptionDateState($(this));
        });

    });

    // ---------------
    // Validate Inputs
    // ---------------

    $("#addSubscriptionToUser").submit(function (e) {

        let checkedSubscriptions = $(".subscription-checkbox:checked");

        clearInputErrors();
        $("#subscriptions_errors").addClass("d-none");

        // Validate at least one subscription selected
        if (checkedSubscriptions.length === 0) {
            e.preventDefault();
            $("#subscriptions_errors").removeClass("d-none");
            return false;
        }

        for (let i = 0; i < checkedSubscriptions.length; i++) {

            let row = checkedSubscriptions.eq(i).closest("tr");
            let end_date = row.find(".subscription-end-date");

            if (isBlank(end_date)) {
                createInputError(end_date, "Date is required");
                e.preventDefault();
                return false;
            }

            if ((!isBlank(end_date)) && (!end_date.inputmask("isComplete"))) {
                createInputError(end_date, "Date is incomplete");
                e.preventDefault();
                return false;
            }

        }

        e.preventDefault();

        $.post("./", $(this).serialize())

                .done(function () {

                    $sessionStorage.action = $sessionStorage.addSubscriptionToUser || "";

                    sessionStorage.setItem($application, JSON.stringify($sessionStorage));

                    formSubmit($sessionStorage);

                });

    });

});