$(document).ready(function () {
    RepeatCall();
    $("#Messages").click(function () {
            console.log("Toggle");

        if (!$("#MessageBox").is(":visible")) {
            $.ajax({
                type: "POST",
                url: "index.php?module=messages&event=listMessages" + "&" + $('#MessageForm').serialize(),
                data: $('#MessageForm').serialize(),
                //contentType: 'Content-type: multipart/form-data; charset=iso-8859-1',
//                beforeSend: function (jqXHR) {
//                    jqXHR.overrideMimeType('multipart/form-data;charset=iso-8859-1');
//                }
            }).done(function (data) {
                //console.log(data);
                $("#MessageBox").html(data);

                $("#MessageFilter").select2({theme: 'bootstrap-5'});

            });
        }
        $("#MessageBox").toggle();
    })

    $(function () {
        var intervalID;
        var freqSecs = 60;
        intervalID = setInterval(RepeatCall, freqSecs * 1000);
    });

    function RepeatCall() {
        $.ajax({
            type: "POST",
            data: $('#MessageForm').serialize(),
            url: "index.php?module=messages&event=checkMessages"
        }).done(function (json) {
            console.log(json);
            if (json.cntAllMessages > 0) {
                $('#MessageCount').show();
                //$('#MessageSymbol').css('opacity', '1');
                //$('#MessageCount').html(json.cntAllMessages);    
                $('#Messages').attr('title', json.cntAllMessages + ' ' + strMessagesExists);
                $("#Messages").attr("disabled", false);
            } else {
                $('#MessageCount').hide();
                //$('#MessageSymbol').css('opacity', '0.3');
                $('#Messages').attr('title', strNoMessageExist);
                $("#Messages").attr("disabled", true);
            }


            //$('#NewMessages').html(json.cntNewMessages ? json.cntNewMessages : '');
            if (0 < json.cntNewMessages) {
                $('#Messages').fadeOut().fadeIn();

                if (json.cntNewMessages >= 3) {
                    var n = noty({
                        text: "",
                        closeWith: ['click'], // ['click', 'button', 'hover']
                        layout: 'topRight',
                        type: 'information',
                        //  theme: 'bootstrapTheme',
                        template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
                        timeout: 2000, // delay for closing event. Set false for sticky notifications
                        force: false, // adds notification to the beginning of queue when set to true
                        modal: false,
                        maxVisible: 5, // you can set max visible notification for dismissQueue true option,
                        killer: false, // for close all notifications before show                        
                        buttons: [
                            {addClass: 'btn btn-outline-primary', text: 'Alle schlie&szlig;en', onClick: function () {
                                    $.noty.closeAll();
                                }
                            },
                            {addClass: 'btn btn-outline-primary', text: 'Alle l&ouml;schen', onClick: function ($noty) {
                                    $.each(json.Messages, function (i, item) {
                                        deleteMessage(item.id);
                                    });
                                    $.noty.closeAll();
                                }
                            }
                        ]
                    });
                }

                if (json.Messages.lenght > 4) {
//console.log("mind 4 neue Nachrichten...");                       
                    if (typeof (Notification) != 'undefined' && Notification.permission === "granted") {
                        // If it's okay let's create a notification
                        var notification = new Notification(
                                "Heinzelmann:",
                                {
                                    body: ts_NewMessagesString,

                                });
                        notification.onclick = function () {
                            notification.close();
                            window.location.href = "index.php";
                        };
                    }

//Nachrichten als Angezeigt markieren:
                    $.each(json.Messages, function (i, item) {
                        $.ajax({
                            type: "POST",
                            url: "index.php?module=messages&event=messageShowed&id=" + item.id
                        })
                    });
//Eine Nachricht anzeigen:
                        var n = noty({
                            text: ts_NewMessagesString,
                            layout: 'topRight',
                           // theme: 'bootstrapTheme',
                            type: 'information',
                            template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
                            timeout: 2000, // delay for closing event. Set false for sticky notifications
                            force: false, // adds notification to the beginning of queue when set to true
                            modal: false,
                            maxVisible: 5, // you can set max visible notification for dismissQueue true option,
                            killer: false, // for close all notifications before show
                            closeWith: ['click'] // ['click', 'button', 'hover']                        
                        });
                } else {

                    $.each(json.Messages, function (i, item) {
//console.log("Neue Nachricht:--- " + item.plaintext);                    
                        if (true) {

                            if (typeof (Notification) != 'undefined' && Notification.permission === "granted") {
//console.log("sollte angezeigt werden " + item.plaintext);                               
                                // If it's okay let's create a notification
                                var notification = new Notification(
                                        "Heinzelmann:",
                                        {
                                            body: item.plaintext,
                                            onshow: function () {
//console.log("...wurde angezeigt " + item.plaintext);                                               
                                                $.ajax({
                                                    type: "POST",
                                                    url: "index.php?module=messages&event=messageShowed&id=" + item.id
                                                })
                                            }
                                        });
                                notification.onclick = function () {
                                    notification.close();
                                    window.location.href = item.url;
                                }
                            }
                        }

                        var n = noty({
                            text: item.message,
                            layout: 'topRight',
                          //  theme: 'bootstrapTheme',
                            type: 'information',
                            template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
                            timeout: 2000, // delay for closing event. Set false for sticky notifications
                            force: false, // adds notification to the beginning of queue when set to true
                            modal: false,
                            maxVisible: 5, // you can set max visible notification for dismissQueue true option,
                            killer: false, // for close all notifications before show
                            closeWith: ['click'], // ['click', 'button', 'hover']                        
                            callback: {
                                afterShow: function () {
                                    $.ajax({
                                        type: "POST",
                                        url: "index.php?module=messages&event=messageShowed&id=" + item.id
                                    })
                                }
                            }
                        });

                    });

                }


            }
        });
    }





});


function deleteMessage(ID) {
    $.ajax({
        type: "POST",
        url: "index.php?module=messages&event=deleteMessage&id=" + ID,
    }).done(function (data) {
        if (data == 1) {
            $("#Message_" + ID).hide();
            var cnt = $('#MessageCount').html();
            if ($(".noty_message").length < 2) {
                $('#MessageCount').hide();
                $("#Messages").attr("disabled", true);
            }
        }

    });
}
$(document).click(function (event) {
    if (!$(event.target).closest('#MessageBox, #Messages, .ui-widget, .select2-dropdown').length) {
        if ($('#MessageBox').is(":visible")) {
                console.log("Test line207");
            $('#MessageBox').hide();
        }
    }
})
$(document).ready(function () {
     $('#MessageBox').hide();
   
})

function deleteAllMessages() {
    $.ajax({
        type: "POST",
        url: "index.php?module=messages&event=deleteAllMessages",
    }).done(function (data) {
        if (data == 1) {
//            $('#MessageCount').html(0);
            $('#MessageCount').hide();
            $("#Messages").attr("disabled", true);
            $("#Messages").click();
        }
    });
}


function filterMessages() {
    //$("#MessageBox").hide();
    console.log("Test");
    //$('#Messages').dropdown('toggle');

//    $("#Messages").click();
}

if (window.Notification && Notification.permission !== "granted") {
    Notification.requestPermission(function (status) {
        if (Notification.permission !== status) {
            Notification.permission = status;
        }
    });
}

