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

function addBlog(){

    let b = {};
    b.title = $('#blogTitle_new').val();
    b.body = $('#blogBody_new').val();
    b.published = $('#blogPublished_new').is(":checked") ? "1" : "0";
    b.language = $('#blogLanguage_new').val();

    console.log(b);

    if(window.confirm(i18n.blog.confirm_save)){
        $.ajax({
            type: "POST",
            url: "/intern/nachrichten/add",
            data: b,
            dataType: "json",
            success:function(r){
                if(r.messageStatus === "success"){
                    $('#blogTitle_new').val("");
                    $('#blogBody_new').val("");
                    $('#blogLanguage_new').val("de");
                    location.reload();
                } else {
                    alert(r.errorMessage);
                }
            },
            error:function(r, a, e){
                alert(i18n.common.error_occurred + e);
            }
        });
    }
}

function editBlog(blogId){
    let b = {};
    b.id = blogId;
    b.title = $('#blogTitle_'+blogId).val();
    b.body = $('#blogBody_'+blogId).val();
    b.published = $('#blogPublished_'+blogId).is(":checked") ? "1" : "0";
    b.language = $('#blogLanguage_'+blogId).val();

    if(window.confirm(i18n.blog.confirm_save)){
        $.ajax({
            type: "PUT",
            url: "/intern/nachrichten/edit",
            data: b,
            dataType: "json",
            success:function(r){
                if(r.messageStatus === "success"){
                    location.reload();
                } else {
                    alert(r.errorMessage);
                }
            },
            error:function(r, a, e){
                alert(i18n.common.error_occurred + e);
            }
        });
    }
}

function deleteBlog(blogId){
    let b = {};
    b.id = blogId;

    if(window.confirm(i18n.blog.confirm_delete)){
        $.ajax({
            type:"DELETE",
            url:"/intern/nachrichten/delete",
            data:b,
            dataType:"json",
            success:function(r){
                if(r.messageStatus === "success"){
                    $('#blogDelete_' + blogId).closest('.blogEdit').fadeOut(300, function() {
                        $(this).remove();
                    });
                } else {
                    alert(r.errorMessage);
                }
            },
            error:function(r, a, e){
                alert(i18n.common.error_occurred + e);
            }
        })
    }
}
