$(document).ready(function() {

    var lastOpenedBoxData; // Stores JSON-data of last opened editBox
    var notifications = []; // Stores noty-Notifications
    var reminders = []; // Stores reminder-noty-Notifications

    function noty_error_retry() {
        notifications.push(
            noty({
                layout  : 'topCenter',
                text    : 'Irgendwas ist schief gelaufen.<br>Bitte probieren Sie es später noch einmal.',
                type    : 'error',
                timeout : 3000
            }));
    }

    window.noty_reminder = noty_reminder;

    function noty_reminder(reminderID) {
        var reminderID = reminderID;
        reminders[reminderID] = noty({
            layout  : 'topCenter',
            text    : 'Erinnerung:<br>',
            type    : 'alert',
            buttons : [
                {addClass: 'btn btn-primary', text: 'OK', onClick: function(noty) {
                    data = {
                        reminderID: reminderID
                    };

                    $.getJSON("ajax.php?action=setReminderReminded", data, function(r) {
                        if(r['status'] == "OK") {
                            noty.close();
                            reminders[reminderID] = undefined;
                        } else {
                            noty_error_retry();
                        }
                    });

                }},
                {addClass: 'btn btn-danger', text: 'Snooze', onClick: function(noty) {
                    data = {
                        reminderID: reminderID
                    };

                    $.getJSON("ajax.php?action=setReminderSnooze", data, function(r) {
                        if(r['status'] == "OK") {
                            noty.close();
                            reminders[reminderID] = undefined;
                        } else {
                            noty_error_retry();
                        }
                    });
                }}
            ]
        });

        $("audio")[0].play()
    }

    function getUrlGetParameter(val) {
        var result = "Not found",
            tmp = [];
        location.search
        .substr(1)
            .split("&")
            .forEach(function (item) {
            tmp = item.split("=");
            if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
        });
        return result;
    }


    function handleEvents() {
        data = {
            userID: $("body").attr("data-user-id")
        };

        $.getJSON("ajax.php?action=getEvents", data, function(r) {
            switch (r['type']) {
                case 'reminder':
                    r['reminders'].forEach(function(item) {
                        if(reminders[item['id']] == undefined) {
                            noty_reminder(item['id']);
                        }
                    });
                    break;
                case 'ping':
                    break;
                default:
                    console.log("unknown event type:" + r['type']);

            }
        });
    }

    function addSpinner(element) {
        element.append("<div class=\"spinner\"><div class=\"bounce1\"></div><div class=\"bounce2\"></div><div class=\"bounce3\"></div></div>");
    }

    function removeSpinner(element) {
        element.children(".spinner").remove();
    }

    function loadBox(element, boxType, saveID, callback) {

        var saveButtonIDs = {
            saveMailFolder: {id: "save-mail-folder", text: "Mailkonto speichern"},
            saveDocument: {id: "save-document", text: "Dokument speichern"},
            saveLabel: {id: "save-label", text: "Label speichern"},
            saveCall: {id: "save-call", text: "Anruf speichern"}
        };

        if(boxType == "editBox") {

            $(document).on("click", element, function(e) {

                e.preventDefault();

                $.getJSON($(this).attr('href'), function(r) {

                    lastOpenedBoxData = r;

                    try {
                        var optionsContainer = document.createElement('div');

                        $.each(r['options'], function(i) {
                            switch(this.type) {
                                case 'text':
                                    $(optionsContainer).append(this.name + "<input id=\"editbox-input-" + this.name + "\" type=\"text\" value=\"" + this.value + "\" class=\"editbox-input\" /><br><br>");
                                    break;
                                case 'select':
                                    selectHtml = "<select id=\"editbox-input-" + this.name + "\" class=\"editbox-input\">";
                                    if(typeof this['values'] !== "undefined" && this['values']) {
                                        this['values'].forEach(function(item) {
                                            if(r['options'][0]['value'] == item) {
                                                selectHtml += "<option selected value=\"" + item + "\">" + item + "</option>"
                                            } else {
                                                selectHtml += "<option value=\"" + item + "\">" + item + "</option>"
                                            }
                                        });
                                    }

                                    selectHtml += "</select>";
                                    $(optionsContainer).append(this.name +  selectHtml + "<br><br>");
                                    break;
                                case 'datetime':
                                    nowDate = new Date();
                                    nowDateString = "" + nowDate.getDate() + "." + nowDate.getMonth() + "." + nowDate.getFullYear() + " " + nowDate.getHours() + ":" + nowDate.getMinutes();
                                    $(optionsContainer).append(this.name + "<input id=\"editbox-datetime-" + this.name + "\" class=\"datetimepicker editbox-input\" type=\"text\" vaue=\"" + nowDateString + "\"><br><br>");
                                    break;
                                case 'textarea':
                                    $(optionsContainer).append(this.name + "<textarea id=\"editbox-textarea-" + this.name + "\" class=\"editbox-input\">" + this.value + "</textarea><br><br><br>");
                                    break;
                                case 'checkbox':
                                    $(optionsContainer).append(this.name + "<input type=\"checkbox\" id=\"editbox-checkbox-" + this.name + "\" class=\"editbox-input\"><br><br>");
                                    break;
                                default:
                                    console.log("Missing input-type: " + this.type);
                                    break;
                            }
                        });

                        $.fancybox({
                            maxWidth	: 800,
                            maxHeight	: 600,
                            fitToView	: true,
                            width		: '70%',
                            height		: '70%',
                            autoSize	: false,
                            title       : "<h3>" + r['title'] + "</h3><hr>",
                            content     : optionsContainer.innerHTML,
                            helpers     : {
                                title: {
                                    type    : 'inside',
                                    position: 'top'
                                }
                            },
                            afterShow   : function() {
                                callback();
                                $('.fancybox-inner').append("<a href=\"#\"type=\"button\" id=\"" + saveButtonIDs[saveID]['id'] + "\" class=\"btn btn-success save-button\">" + saveButtonIDs[saveID]['text'] + "</a>");
                                $(".datetimepicker").datetimepicker({ format: 'Y-m-d H:i', startDate: new Date() });
                            }
                        });
                    } catch(e) {
                        console.log(e); // DBG
                        noty_error_retry();
                    }
                });

            });
        }
    }

    function getMailboxStatus() {
        $("#settings-mailboxes tr").each(function(item) {
            var thisTr = this;

            if(this.attributes.length > 0) {
                if($(this).children("td:first").children().length > 0) {
                    $(this).children("td:first").children().remove();
                }
                addSpinner($(this).children("td:first"));
                $.getJSON("ajax.php?action=getMailboxStatus&mailboxId=" + $(this).attr("data-mailbox-id"), function(r) {
                    if(r['connected'] == true) {
                        removeSpinner($(thisTr).children("td:first"));
                        $(thisTr).children("td:first").append("<i class=\"fa fa-check-circle\"></i>");
                    } else {
                        removeSpinner($(thisTr).children("td:first"));
                        $(thisTr).children("td:first").append("<i class=\"fa fa-exclamation-circle\"></i>");
                    }
                });
            }
        });
    }

    function settingsListener() {
        $(document).on("click", "#refresh-mailaccounts", function(e) {
            e.preventDefault();
            getMailboxStatus();

        });
    }

    function manageLabelListener() {
        $(document).on("click", "#save-mail-folder", function(e) {
            e.preventDefault();

            data = {
                mailboxFolderID: lastOpenedBoxData['mailboxFolderID'],
                account: $("#editbox-input-account").val(),
                folder: $("#editbox-input-folder").val(),
                labelID: getUrlGetParameter("labelId")
            };

            $.getJSON("ajax.php?action=saveMailFolder", data, function(r) {
                if(r['status'] == "OK") {
                    location.reload();
                } else {
                    console.log(r);
                    noty_error_retry();
                }
            });
        });
    }

    function manageLabelsListener() {
        $(document).on("click", "#save-label", function(e) {

            e.preventDefault();

            data = {
                name: $("#editbox-input-name").val(),
                path: $("#editbox-input-path").val()
            };

            $.getJSON("ajax.php?action=saveNewLabel", data, function(r) {
                if(r['status'] == "OK") {
                    location.reload();
                } else {
                    console.log(r);
                    noty_error_retry();
                }
            });
        });

        $(document).on("click", ".remove-label", function(e) {
            e.preventDefault();

            tRow = $(this).parent().parent();

            data = {
                labelId: $(this).attr("data-id")
            };

            $.getJSON("ajax.php?action=removeLabel", data, function(r) {
                if(r['status'] == "OK") {
                    tRow.fadeOut(400, function() {
                        tRow.remove();
                    });

                } else {
                    console.log(r);
                    noty_error_retry();
                }
            });
        });
    }

    function LabelListener() {
        $(document).on("change", ".fancybox-inner select", function(e) {
            reloadDraftVars();
        });

        $(document).on("click", "#save-document", function(e) {
            e.preventDefault();

            data = {
                draft: $("#editbox-input-vorlage").val(),
                filename: $("#editbox-input-filename").val(),
                labelId: getUrlGetParameter("labelId"),
                draftVars: {}
            };

            $(".editbox-draft-vars").each(function(i) {
                data['draftVars'][$(this).attr("id").replace("editbox-draft-vars-", "")] = $(this).val();
            });

            $.getJSON("ajax.php?action=saveNewDocument", data, function(r) {
                console.log(r);
            });
        });

        $(document).on("click", "#save-call", function(e) {
            e.preventDefault();

            data = {
                userID: $("body").attr("data-user-id"),
                callDate: $('#editbox-datetime-call-date').val(),
                callerTelNr: $('#editbox-input-caller-telnr').val(),
                labelID: $('#editbox-input-label-id').val(),
                callNotes: $('#editbox-textarea-call-notes').val(),
                callSetReminder: $('#editbox-checkbox-call-set-reminder').val()
            }

            $.getJSON("ajax.php?action=saveNewCall", data, function(r) {
                if(r['status'] == "OK") {
                    $.fancybox.close();
                    //$("a[href=\"#calls\"]").tab("show");
                } else {
                    noty_error_retry();
                }
            });
        });

        $(document).on("click", "#refresh-documents", function(e) {
            e.preventDefault();

            $("#refresh-documents").hide();
            addSpinner($("#document-list th:nth-child(6)"));

            $.getJSON("ajax.php?action=scanDocuments", {}, function(r) {
                if(r['status'] == "OK") {
                    if(r['new'] > 0) {
                        location.reload();
                    } else {
                        removeSpinner($("#document-list th:nth-child(6)"));
                        $("#refresh-documents").show();
                    }
                } else {
                    noty_error_retry();
                }
            });
        });

        $(document).on("click", ".reply-mail", function(e) {
            e.preventDefault();

            data = {
                mailID: $(this).attr("data-mail-id")
            };

            $.getJSON("ajax.php?action=getMailContent", data, function(r) {
                window.location.href = "mailto:" + r['to'] + "?subject=" + r['subject'] + "&body=" + r['body'];
            });
        });
    }

    function reloadDraftVars() {
        $.getJSON("ajax.php?action=getDraftVars&draft=" + $(".fancybox-inner select").val(), function(r) {

            draftVarsContainer = $("#draft-vars");

            if(draftVarsContainer.length > 0) {
                console.log(draftVarsContainer);
                draftVarsContainer.remove();
            }

            $(".fancybox-inner .save-button").before("<div id=\"draft-vars\"></div>");

            r.forEach(function(item) {
                $(".fancybox-inner #draft-vars").append(item + "<textarea id=\"editbox-draft-vars-" + item + "\" class=\"editbox-draft-vars\"></textarea><br><br><br>");

            })
        });
    }

    $.fn.editable.defaults.mode = 'inline';
    $.fn.editableform.buttons =
  '<button type="submit" class="btn btn-primary btn-sm editable-submit">'+
    '<i class="fa fa-fw fa-check"></i>'+
  '</button>'+
  '<button type="button" class="btn btn-default btn-sm editable-cancel">'+
    '<i class="fa fa-fw fa-times"></i>'+
  '</button>';

    $('.editable-element-text').editable({
        escape: false,
        success: function(response, newValue) {
            console.log(response); // Debug output from ajax.php
            if(response.status == 'error') return response.msg; //msg will be shown in editable form
        },
        error: function (xhr, status, error) {
            //var err = eval("(" + xhr.responseText + ")");
            return xhr.statusText;
        },
        params: function(params) {
            params.action = 'updateMailaccounts';
            return params;
        }
    });

    $('.editable-element-select-protocol').editable({
        defaultValue: 'imap',
        source: [
            {value: 'imap', text: 'IMAP'},
            {value: 'pop3', text: 'POP3'}
        ],
        success: function(response, newValue) {
            console.log(response); // Debug output from ajax.php
            if(response.status == 'error') return response.msg; //msg will be shown in editable form
        },
        error: function (xhr, status, error) {
            //var err = eval("(" + xhr.responseText + ")");
            return xhr.statusText;
        },
        params: function(params) {
            params.action = 'updateMailaccounts';
            return params;
        }
    });


    $('.editable-element-select-use-ssl').editable({
        defaultValue: '1',
        source: [
            {value: '1', text: 'On'},
            {value: '0', text: 'Off'}
        ],
        success: function(response, newValue) {
            console.log(response); // Debug output from ajax.php
            if(response.status == 'error') return response.msg; //msg will be shown in editable form
        },
        error: function (xhr, status, error) {
            //var err = eval("(" + xhr.responseText + ")");
            return xhr.statusText;
        },
        params: function(params) {
            params.action = 'updateMailaccounts';
            return params;
        }
    });


    $('.editable-element-select-no-valid-cert').editable({
        defaultValue: '0',
        source: [
            {value: '0', text: 'On'},
            {value: '1', text: 'Off'}
        ],
        success: function(response, newValue) {
            console.log(response); // Debug output from ajax.php
            if(response.status == 'error') return response.msg; //msg will be shown in editable form
        },
        error: function (xhr, status, error) {
            //var err = eval("(" + xhr.responseText + ")");
            return xhr.statusText;
        },
        params: function(params) {
            params.action = 'updateMailaccounts';
            return params;
        }
    });


    $('#add-mailaccount').on('click', function(e) {
        e.preventDefault();
        var uId = $(this).attr('data-uid');
        $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {'action': 'addDefaultMailaccount', 'user-id': uId},
                success: function (result) {
                    console.log(result);
                    location.reload();
                }
            });
    });

    function fancyBoxLoader() {
        $.ajax({
            url: 'ajax.php',
            data: {'action': 'getMailAccountsByUid', 'uId': $('.manage-mailboxfolder').attr('data-uid')},
            type: 'GET',
            global: false,
            async: true,
            dataType: 'json',
            success: function(data) {
                result = data;

                $('.editable-element-select-mailaccount').editable({
                    //defaultValue: '0',
                    source: result,
                    success: function(response, newValue) {
                        console.log(response); // Debug output from ajax.php
                        if(response.status == 'error') return response.msg; //msg will be shown in editable form
                    },
                    error: function (xhr, status, error) {
                        //var err = eval("(" + xhr.responseText + ")");
                        return xhr.statusText;
                    },
                    params: function(params) {
                        params.action = 'updateMailfolder';
                        return params;
                    }
                });
            }
        });

        $('.editable-element-text').editable({
            escape: false,
            success: function(response, newValue) {
                console.log(response); // Debug output from ajax.php
                if(response.status == 'error') return response.msg; //msg will be shown in editable form
            },
            error: function (xhr, status, error) {
                //var err = eval("(" + xhr.responseText + ")");
                return xhr.statusText;
            },
            params: function(params) {
                params.action = 'updateMailfolder';
                return params;
            }
        });

    }

    $('.remove-mailaccount').on('click', function(e) {
        e.preventDefault();
        var id = $(this).attr('data-id');
        $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {'action': 'removeMailaccount', 'id': id},
                success: function (result) {
                    console.log(result);
                    location.reload();
                }
            });
    });

    $('.remove-mailboxfolder').on('click', function(e) {
        e.preventDefault();
        var id = $(this).attr('data-id');
        $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {'action': 'removeMailboxFolder', 'id': id},
                success: function (result) {
                    console.log(result);
                    location.reload();
                }
            });
    });

    $('#add-mailboxfolder').on('click', function(e) {
        e.preventDefault();
        var uId = $(this).attr('data-uid');
        var lId = $(this).attr('data-lid');
        $.ajax({
                url: 'ajax.php',
                type: 'POST',
                data: {'action': 'addDefaultMailfolder', 'user-id': uId, 'label-id': lId},
                success: function (result) {
                    console.log(result);
                    location.reload();
                },
                error: function(result) {
                    console.log(result);
                }
            });
    });

    $(".datetimepicker").datetimepicker({
        format: 'Y-m-d H:i',
        startDate: new Date()
    });

    switch(getUrlGetParameter("action")) {
        case 'settings':
            getMailboxStatus();
            settingsListener();
            break;
        case 'manage-label':
            loadBox('.manage-mailboxfolder', "editBox", "saveMailFolder", function() {});
            manageLabelListener();
            break;
        case 'manage-labels':
            loadBox('#add-label', "editBox", "saveLabel", function() {});
            manageLabelsListener();
            break;
        case 'label':
            loadBox('#new-document', "editBox", "saveDocument", reloadDraftVars);
            loadBox('#new-call', 'editBox', 'saveCall', function() {});
            LabelListener();
            break;
        default:
            break;
    }

    handleEvents();
    setInterval(handleEvents, 60000);

});
