
// ==============
// Manage Permits
// ==============

$(document).ready(function () {

    var $application = $("#APPLICATION_MNEMONIC").val(), $sessionStorage = JSON.parse(sessionStorage.getItem($application) || "{}");

    // --------------------
    // Initialize Dropdowns
    // --------------------

    $("#permits_per_page").val($sessionStorage.permits_per_page || "20");

    // -----------
    // Find Button
    // -----------

    $(".btnFind").on("click", function () {

        $sessionStorage.action = "Permits.managePermits";
        $sessionStorage.pagination = "first";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    $("#find_permit").on("keyup", function (e) {
        if (e.key === "Enter") {
            $(".btnFind").trigger("click");
        }
    });

    // -----------------
    // Clear Find Button
    // -----------------

    $(".btnClearFind").on("click", function () {

        $("#find_permit").val("").trigger("change");

        $sessionStorage.action = "Permits.managePermits";
        $sessionStorage.pagination = "first";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    // ---------------
    // Per Page Change
    // ---------------

    $("#permits_per_page").on("change", function () {

        $sessionStorage.permits_per_page = $(this).val();
        $sessionStorage.action = "Permits.managePermits";
        $sessionStorage.pagination = "first";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    // ------------------
    // Pagination Buttons
    // ------------------

    $(".btnPagination").on("click", function () {

        $sessionStorage.action = "Permits.managePermits";
        $sessionStorage.pagination = $(this).data("pagination");

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

        delete $sessionStorage.pagination;

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

    });

    // ----------
    // Add Button
    // ----------

    $(".btnAdd").on("click", function () {

        $sessionStorage.action = "Permits.addPermit";
        $sessionStorage.addPermit = "Permits.managePermits";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // -----------
    // Done Button
    // -----------

    $(".btnDone").on("click", function () {

        formSubmit({action: ""});

    });

    // --------------
    // Refresh Button
    // --------------

    $(".btnRefresh").on("click", function () {

        $sessionStorage.action = "Permits.managePermits";
        $sessionStorage.pagination = "first";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    // ---------------
    // Permits Summary
    // ---------------

    $("#permits-table tbody td:not('.selection-checkboxes')").on("click touch", function (e) {

        e.preventDefault();

        $sessionStorage.action = "Permits.editPermit";
        $sessionStorage.permit_serial = $(e.target).closest("tr").data("permit-serial");
        $sessionStorage.editPermit = "Permits.managePermits";
        $sessionStorage.deletePermit = "Permits.managePermits";

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        formSubmit($sessionStorage);

    });

    // -------------------
    // Column Heading Sort
    // -------------------

    if (($sessionStorage.permits_order_by || "") !== "") {

        $("th[data-order-by = '" + ($sessionStorage.permits_order_by || "") + "']").append('<i class="' + ($sessionStorage.permits_order_icon || "") + ' text-danger ms-1 me-0"/>');

    }

    $("th.sortable").on("click", function (e) {

        if ($(e.target).data("order-by") !== ($sessionStorage.permits_order_by || "")) {  // New Column

            $sessionStorage.permits_order_by = $(e.target).data("order-by");
            $sessionStorage.permits_order_direction = "asc";
            $sessionStorage.permits_order_icon = "bi bi-arrow-up";

        } else {

            switch ($sessionStorage.permits_order_direction) {

                case "" :

                    $sessionStorage.permits_order_by = $(e.target).data("order-by");
                    $sessionStorage.permits_order_direction = "asc";
                    $sessionStorage.permits_order_icon = "bi bi-arrow-up";
                    break;

                case "asc" :

                    $sessionStorage.permits_order_by = $(e.target).data("order-by");
                    $sessionStorage.permits_order_direction = "desc";
                    $sessionStorage.permits_order_icon = "bi bi-arrow-down";
                    break;

                case "desc" :

                    $sessionStorage.permits_order_by = "";
                    $sessionStorage.permits_order_direction = "";
                    $sessionStorage.permits_order_icon = "";
                    break;

            }

        }

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

        $("#spinner-dialog").modal("show");

        formSubmit($sessionStorage);

    });

    // -----------------
    // Select All Button
    // -----------------

    $(".btnSelectAll").on("click", function (e) {

        e.preventDefault();

        $(".selection-checkbox:input:checkbox").prop("checked", true);

        $(".btnDeselectAll, .btnPrintSelected").removeClass("d-none");

    });

    // -------------------
    // Deselect All Button
    // -------------------

    $(".btnDeselectAll").on("click", function (e) {

        e.preventDefault();

        $(".selection-checkbox:input:checkbox").prop("checked", false);

        $(".btnDeselectAll, .btnPrintSelected").addClass("d-none");

    });

    // ------------------------
    // Toggle a Select Checkbox
    // ------------------------

    $(".permit-row").on("click touch", function (e) {

        if (!($(e.target).hasClass("selection-area"))) {
            return false;
        }
        ;

        e.preventDefault();

        var $this = $(e.target), checked = ($this.closest("tr").find("input[name='selected[]']").prop("checked"));

        // Toggle the selected Checkbox.

        $this.closest("tr").find("input[name='selected[]']").prop("checked", !checked);

        if ($("input[name='selected[]']:checked").length === 0) {
            $(".btnDeselectAll, .btnPrintSelected").addClass("d-none");
        } else {
            $(".btnDeselectAll, .btnPrintSelected").removeClass("d-none");
        }

    });

    // ---------------------------------
    // Print Selected Work Orders Button
    // ---------------------------------

    $(".btnPrintSelected").on("click", function (e) {

        e.preventDefault();

        window.open("", "PrintTab");

        var selected = $("input[name='selected[]']:checked").map(function () {
            return $(this).val();
        }).get();

        $("input[name = 'action']", "#PrintPermitForm").val("print");
        $("input[name = 'selected_permits']", "#PrintPermitForm").val(selected);
        $("#PrintPermitForm").submit();

    });



    // -------------------
    // Save Changed Inputs
    // -------------------

    $(".autosave").on("change", function (e) {

        switch (e.target.type) {

            case "text"       :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "radio"      :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "checkbox"   :
                $sessionStorage[e.target.name] = $(this).prop("checked");
                break;
            case "select-one" :
                $sessionStorage[e.target.name] = $(this).val();
                break;
            case "hidden"     :
                $sessionStorage[e.target.name] = $(this).val();
                break;

            default           :
                $sessionStorage[e.target.name] = $(this).val();
                break;

        }

        sessionStorage.setItem($application, JSON.stringify($sessionStorage));

    });

    // ----------------
    // Initalize Inputs
    // ----------------

    $.each($sessionStorage, function (name, value) {

        var $input = $(":input").filter("[name='" + name + "']");

        if ($input.length > 0) {

            switch ($input.prop("type")) {

                case "text"       :
                    $input.val(value);
                    break;
                case "radio"      :
                    $input.filter("[value=" + value + "]").prop("checked", true);
                    break;
                case "checkbox"   :
                    $input.prop("checked", value);
                    break;
                case "select-one" :
                    $input.val(value);
                    break;
                case "hidden"     :
                    $input.val(value);
                    break;

                default           :
                    $input.val(value);
                    break;

            }

        }

    });

    // ------------------
    // Save preset Inputs
    // ------------------

    $("input[type=radio]:checked").trigger("change");

    // -----------------
    // Per Page Dropdown
    // -----------------

    $("#permits_per_page").on("change", function () {

        $(".btnFind").trigger("click");

    });

});