$(document).ready(function () {
    $dataTable = $('#documentsGrid');
    $dataTable.DataTable({
        responsive: false,
        scroller: true,
        scrollX: true,
        info: false,
        fixedColumns: { leftColumns: 2 },
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.SubjectId = $("#SubjectId").val();
                d.DateFrom = null;
                d.DateTo = null;
            }
        },
        order: [[1, 'desc']],
        columns: [
            {
                data: "AcKey", name: "AcKey", className: 'dt-body-center',
                render: function (data, type, full) {
                    if (type === 'display')
                        return $.fn.dataTable.render.previewWithOptions(full.Id, $("#paasPrintDocumentUrl").val(), full.Attachments, "getAttachmentsForDocument(" + full.Id + ")");
                    else
                        return "";
                }
            },
            { data: "AcKeyView", name: "AcKey", filtertype: "text", render: $.fn.dataTable.render.link('Id') },
            { data: "Subject", name: "AcSubject", filtertype: "text" },
            { data: "SubjectName", name: "AcSubjectNavigation.AcName2", filtertype: "text", render: $.fn.dataTable.render.ellipsis(30, false) },
            { data: "Date", name: "AdDate", filtertype: "dateTime" },
            { data: "DateDue", name: "AdDateDue", filtertype: "dateTime" },
            { data: "Title", name: "AcTitle", filtertype: "text" },
            { data: "DocType", name: "AcDocType", filtertype: "text" },
            { data: "Classification", name: "AnClassification.AcTypeDesc", filtertype: "text", render: $.fn.dataTable.render.ellipsis(25, false) },
            { data: "Note", name: "AcNote", filtertype: "text", render: $.fn.dataTable.render.note("Id") },
            { data: "Clerk", name: "AnClerkUser.AcTitle", orderable: false, filtertype: "text" },
            { data: "StatusName", name: "AcStatusNavigation.AcName", orderable: false, filtertype: "text" }
        ]
    });

    $dataTable.on('xhr.dt', function (e, settings, json, xhr) {
        initializeTableHeight();
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
});

function openPdfPreview(url) {
    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}

function getAttachmentsForDocument(id) {
    swapPreviewIcon(true, ("previewIcon-" + id), "fa fa-eye");
    $("#previewDropdown-" + id).empty();

    $.get($("#GetAttachmentsForDocumentUrl").val(), { qid: id })
        .done(function (response) {
            var func = $("#paasPrintDocumentUrl").val().replace("{0}", id);

            if (response.length === 1) {
                openPdfPreview($("#paasPrintDocumentUrlOnly").val().replace("{0}", id).replace("{1}", response[0].AttachmentId));
            } else {
                response.forEach(attachment => {
                    $("#previewDropdown-" + id).append("<li><a onClick=\"" + func.replace("{1}", attachment.AttachmentId) + "\">" + attachment.Name + "</a></li>");
                });
            }

            swapPreviewIcon(false, ("previewIcon-" + id), "fa fa-eye");
        });
}

function swapPreviewIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("span.eyeIcon");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
    }
}

var heightInitialized = false;
function initializeTableHeight() {

    if (heightInitialized) {
        return;
    }
    heightInitialized = true;

    var rectTop = document.getElementById("documentsGrid").getBoundingClientRect().top;
    var rectBottom = document.body.scrollHeight;

    let offset = 20;
    let dtHeight = (rectBottom - rectTop - offset) + "px";

    $(".dataTables_scrollBody").css("height", dtHeight);
    $(".dataTables_scrollBody").css("min-height", dtHeight);
}