$(function() {
    $('select[autocomplete="off"]').each(function() {
        let selectedValue = $(this).find('option[selected]').val();
        if (selectedValue) {
            $(this).val(selectedValue);
        }
    });

    function updateMaxlengths() {
        const passportType = $('#passport_type').val();

        let maxLength;
        switch (passportType) {
            case 'd':
                maxLength = 17;
                break;
            case 'k':
                maxLength = 25;
                break;
            default:
                maxLength = 17;
        }

        $('#firstname, #lastname, #location').attr('maxlength', maxLength);
    }

    updateMaxlengths();

    $('#passport_type, #district_region').on('change', function() {
        updateMaxlengths();
    });
});

function vorantragAbschicken(){

    let data = {};
    data.district_region = $('#district_region').val();
    data.passport_type = $('#passport_type').val();
    data.mail = $('#mail').val();
    data.first_name = $('#firstname').val();
    data.last_name = $('#lastname').val();
    data.location = $('#location').val();

    console.log(data);

    $.ajax({
        type: "POST",
        url: "/vorbeantragen/absenden",
        data: data,
        dataType: "json",
        success:function(r){
            if(r.messageStatus === "success"){
                $('#mail').val("");
                $('#firstname').val("");
                $('#lastname').val("");
                $('#location').val("");
                alert(r.errorMessage);
            } else {
                alert(r.errorMessage);
            }
        },
        error:function(r, a, e){
            alert(i18n.common.error_occurred + e);
        }
    });

}
