
// =========================
// Search Permits By Builder
// =========================

$(document).ready(function () {

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

    // =================
    // Process Enter Key
    // =================

    $(document).on('keypress', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $("#searchPermitsByBuilder").submit();
        }
    });

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

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

    // -----------
    // Input Masks
    // -----------

    $(".date-mask").inputmask({alias: "datetime",
        inputFormat: "mm/dd/yyyy",
        placeholder: "MM/DD/YYYY",
        showMaskOnHover: false});

    // ------------
    // Date Pickers
    // ------------

    $("#permit_entry_start_date").datepicker({format: "mm-dd-yyyy",
        container: "div.permit_entry_start_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#permit_entry_end_date").datepicker({format: "mm-dd-yyyy",
        container: "div.permit_entry_end_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#permit_permit_start_date").datepicker({format: "mm-dd-yyyy",
        container: "div.permit_permit_start_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    $("#permit_permit_end_date").datepicker({format: "mm-dd-yyyy",
        container: "div.permit_permit_end_date",
        keyboardNavigation: false,
        showOnFocus: false,
        autoclose: true,
        orientation: "left bottom",
        todayBtn: "linked",
        todayHighlight: true});

    // ---------------------
    // Show Calendar Buttons
    // ---------------------

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

        e.preventDefault();

        $("#permit_entry_start_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_entry_end_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_permit_start_date").focus().datepicker("show");

    });

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

        e.preventDefault();

        $("#permit_permit_end_date").focus().datepicker("show");

    });

    // ----------------
    // Filter the Rows.
    // ----------------

    $("#filter").on("keyup", function () {

        var filter = $(this).val().toLowerCase();

        $(".permit-row").hide().filter(function () {
            return $(this).find(".filterable").text().toLowerCase().indexOf(filter) > -1;
        }).show();

        if ($(".permit-row:visible").length === 0) {
            $("#permits-table thead").hide();
            $(".filter-error").removeClass("d-none");
        } else {
            $("#permits-table thead").show();
            $(".filter-error").addClass("d-none");
        }

    });

    // -------------------
    // Clear Filter Button
    // -------------------

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

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

        $sessionStorage.action = "PermitsByBuilder.searchPermits";
        $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 = "PermitsByBuilder.searchPermits";
        $sessionStorage.pagination = "first";

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

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

        formSubmit($sessionStorage);

    });


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

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

        $sessionStorage.action = "PermitsByBuilder.searchPermits";
        $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));

    });

    // ----------------
    // Display Scollbar
    // ----------------

    $(".scrollable").scroll(function () {
        if ($(this).scrollTop() > 60) {
            $("#btnTop").fadeIn();
        } else {
            $("#btnTop").fadeOut();
        }
    });

    // -------------
    // Search Button
    // -------------

    $(".btnSearch").on("click", function (e) {
        e.preventDefault();
        $("#searchPermitsByBuilder").submit();
    });

    // -------------
    // Search Button
    // -------------

    $(".btnReset").on("click", function (e) {
        e.preventDefault();

        $sessionStorage.action = "PermitsByBuilder.searchPermits";
        $sessionStorage.pagination = $(this).data("pagination");

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

        delete $sessionStorage.pagination;
        delete $sessionStorage.permit_company;
        delete $sessionStorage.permit_and_or;
        delete $sessionStorage.permit_entry_start_date;
        delete $sessionStorage.permit_entry_end_date;
        delete $sessionStorage.permit_permit_start_date;
        delete $sessionStorage.permit_permit_end_date;

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

        formSubmit($sessionStorage);
    });

    // -------------
    // Cancel Button
    // -------------

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

        $sessionStorage.action = $sessionStorage.userSubscriptions || "";

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

        formSubmit($sessionStorage);

    });

    // ---------------
    // Validate Inputs
    // ---------------

    $("#searchPermitsByBuilder").submit(function (e) {

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

        var builder = $("#permit_company"),
                permit_and_or = $("#permit_and_or"),
                permit_entry_start_date = $("#permit_entry_start_date"),
                permit_entry_end_date = $("#permit_entry_end_date"),
                permit_permit_start_date = $("#permit_permit_start_date"),
                permit_permit_end_date = $("#permit_permit_end_date"),
                form_error = $("#search-form-error");

        clearInputErrors();

        // Function to display errors and hide spinner
        function showError(message, element) {
            $("#spinner-dialog").modal("hide");
            createInputError(form_error, message);
            if (element)
                createInputError(element, "");
            return false;
        }

        // Validate required fields
        if ([builder, permit_entry_start_date, permit_entry_end_date, permit_permit_start_date, permit_permit_end_date].every(isBlank)) {
            return showError("Please provide a search criteria.");
        }

        if (isBlank(permit_entry_start_date) && !isBlank(permit_entry_end_date)) {
            return showError("Please provide an Entry From Date for range.", permit_entry_start_date);
        }

        if (isBlank(permit_permit_start_date) && !isBlank(permit_permit_end_date)) {
            return showError("Please provide a Permit From Date for range.", permit_permit_start_date);
        }

        // Validate date ranges
        if (permit_entry_end_date.val() && !checkEndingDate(permit_entry_start_date, permit_entry_end_date)) {
            return showError("Start Date must be prior to End Date");
        }

        if (permit_permit_end_date.val() && !checkEndingDate(permit_permit_start_date, permit_permit_end_date)) {
            return showError("Start Date must be prior to End Date");
        }

        e.preventDefault();

        $sessionStorage.permit_company = builder.val();
        $sessionStorage.permit_and_or = permit_and_or.val();
        $sessionStorage.permit_entry_start_date = permit_entry_start_date.val();
        $sessionStorage.permit_entry_end_date = permit_entry_end_date.val();
        $sessionStorage.permit_permit_start_date = permit_permit_start_date.val();
        $sessionStorage.permit_permit_end_date = permit_permit_end_date.val();

        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, .btnExportSelected").removeClass("d-none");

    });

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

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

        e.preventDefault();

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

        $(".btnDeselectAll, .btnExportSelected").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, .btnExportSelected").addClass("d-none");
        } else {
            $(".btnDeselectAll, .btnExportSelected").removeClass("d-none");
        }

    });

    // ------------------------
    // Export All Permits - PDF
    // ------------------------

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

        e.preventDefault();

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

        $("input[name = 'action']", "#PrintAllPermitsByBuilderPDFForm").val("print");
        $("input[name = 'subscription_serial']", "#PrintAllPermitsByBuilderPDFForm").val($sessionStorage.subscription_serial);
        $("#PrintAllPermitsByBuilderPDFForm").submit();

    });

    // --------------------------
    // Export All Permits - Excel
    // --------------------------

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

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

        $sessionStorage.action = "Export_AllPermitsByBuilderExcel.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;
        $sessionStorage.downloadReturn = "Reports.selectReport";

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

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive
    });

    // ------------------------
    // Export All Permits - CSV
    // ------------------------

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

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

        $sessionStorage.action = "Export_AllPermitsByBuilderCSV.export";
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;

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

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive

    });

    // ---------------------------------
    // 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']", "#PrintSelectedPermitsByBuilderForm").val("print");
        $("input[name = 'selected_permits']", "#PrintSelectedPermitsByBuilderForm").val(selected);
        $("input[name = 'subscription_serial']", "#PrintSelectedPermitsByBuilderForm").val($sessionStorage.subscription_serial);
        $("#PrintSelectedPermitsByBuilderForm").submit();

    });

    // -----------------------------
    // Export Selected Permits - CSV
    // -----------------------------

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

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

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

        $sessionStorage.action = "Export_SelectedPermitsByBuilderCSV.export";
        $sessionStorage.selected_permits = selected;
        $sessionStorage.subscription_reference = $sessionStorage.subscription_serial;

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

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive

    });

    // -------------------------------
    // Export Selected Permits - Excel
    // -------------------------------

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

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

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

        $sessionStorage.action = "Export_SelectedPermitsByBuilderExcel.export";
        $sessionStorage.selected_permits = selected;
        $sessionStorage.downloadReturn = "Reports.selectReport";

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

        // Submit in a new tab
        formSubmit($sessionStorage, "_blank");

        // Hide spinner immediately, since the main page isn't going anywhere
        setTimeout(function () {
            $("#spinner-dialog").modal("hide");
        }, 2000); // optional: add a slight delay so it feels responsive
    });

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

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

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

    });

});