// FZBE
function handlePurposes($content) {
    var activePurposes = [];
    var $checkedBookingType = $("#reservation-bookingtype input:checked", $content);
    var $selectedUser = $("#reservation-user option:selected", $content);

        if($checkedBookingType.length) {
            var bookingTypePurposesStr = $checkedBookingType.data('purposes') + "";
            if (bookingTypePurposesStr) {
                var bookingTypePurposes = bookingTypePurposesStr.split(",");

                for (var i = 0; i < bookingTypePurposes.length; i++) {
                    if (!activePurposes.includes(bookingTypePurposes[i]) && bookingTypePurposes[i] != "") {
                        activePurposes.push(bookingTypePurposes[i]);
                    }
                }
            }
        }

    if($selectedUser.length) {
        var userPurposesStr = $selectedUser.data("purposes") + "" // + "" is a workaround to make even a single purpose a string

        if(userPurposesStr) {
            var userPurposes = userPurposesStr.split(",");

            for(var i = 0; i < userPurposes.length; i++) {
                if(!activePurposes.includes(userPurposes[i]) && userPurposes[i] != '') {
                    activePurposes.push(userPurposes[i]);
                }
            }
        }
    }
    var $allOptions = $("#reservation-purpose option", $content);
    $allOptions.each(function(i) {
        var $option = $($allOptions[i]);
        var uid = $option.val();

        $option.show();
        if(uid && !activePurposes.includes(uid)) {
            $option.hide();
        }
    });

    $("#reservation-purpose", $content).parents(".fancyInput").show();
    if(!activePurposes.length) {
        $("#reservation-purpose", $content).parents(".fancyInput").hide();
    }
}

handlePurposes($(document));
$(document).on("change", "#reservation-bookingtype input", function (e) {
    handlePurposes($(document));
});
$(document).on("change", "#reservation-user", function (e) {
    handlePurposes($(document));
});

function checkReservationType($content) {
    var $checkboxes = $('.ig-radio input[name="tx_igreservations_ajax[reservation][event][reservationTypes][]"], .ig-radio input[name="tx_igreservations_eventtodo[event][reservationTypes][]"]', $content);

    if ($checkboxes.is(':checked')) {
        $checkboxes.attr('required', false);
        $checkboxes.prop('required', false);
    } else {
        $checkboxes.attr('required', true);
        $checkboxes.prop('required', true);
    }
}


checkReservationType();
$(document).on("change", '.ig-radio input[name="tx_igreservations_eventtodo[reservation][event][reservationTypes][]"], .ig-radio input[name="tx_igreservations_eventtodo[event][reservationTypes][]"]', function (e) {
    checkReservationType();
});