$(document).ready(function () {

    window.applyuserSearch = function applyuserSearch(usersTable) {
        $('.search-filter').click(function () {
            usersTable.column(0).search($('#userName-search').val());
            usersTable.column(1).search($('#fullname-search').val());
            usersTable.column(2).search($('#email-search').val());
            usersTable.column(3).search($('#group-search').val());
            usersTable.column(4).search($('#status-search').val());
            usersTable.column(5).search($('#emailConfirmation-search').val());
            usersTable.draw();

        });


    }

    window.clearuserSearch = function clearuserSearch(usersTable) {
        $('#users-pane').on('click', '.reset-filter', function () {
            $('#userName-search').val("");
            $('#fullname-search').val("");
            $('#email-search').val("");
            $('#group-search option:first').prop('selected', true);
            $('#status-search option:first').prop('selected', true);
            $('#emailConfirmation-search option:first').prop('selected', true);

            usersTable.columns().search("").draw();
        });

    }


    window.clearGroupsSearch = function clearGroupsSearch(groupsTable) {
        $('#groups-pane').on('click', '.reset-filter', function () {
            $('#search-groups').val("");
            groupsTable.search("").draw();
        });
    }

    window.clearCategoriesSearch = function clearCategoriesSearch(categoriesTable) {
        $('.container').on('click', '.reset-filter', function () {
            $('#search-categories').val("");
            categoriesTable.search("").draw();
        });
    }


    window.sendAjaxRequest = function sendAjaxRequest(formId, fields, successElementID, errorElementID, callback, callbackParams, appendResponse = false) {

        var form = document.getElementById(formId);
        let url = $(`#${formId}`).attr('data-url');
        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(form),
            contentType: false,
            processData: false,
            dataType: "json",
            success: function (response) {
                if (response.message) {

                    $(`#${successElementID}`).text(response.message).show();
                    $(`#${errorElementID}`).hide();
                    if (callback && appendResponse) {
                        callback(...callbackParams, response);
                    }
                    else if (callback) {
                        callback(...callbackParams);
                    }
                }

                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    $(`#demo-modal`).modal('show');
                }
            },
            error: function (response) {
                response = response.responseJSON;

                if (response.message) {
                    $(`#${errorElementID}`).text(response.message).show();
                    $(`#${successElementID}`).hide();
                }
                if (response.errors) {
                    fields.every(error => {
                        if (response.errors[error]) {

                            $(`#${errorElementID}`).text(response.errors[error][0]).show();

                            $(`#${successElementID}`).hide();

                            return false;
                        }
                        return true;

                    });

                }

                $(`#${successElementID}`).hide();
            }
        });

    }

    window.sendTestConnectionAjaxRequest = function sendTestConnectionAjaxRequest(formId, buttonID, fields, successElementID, errorElementID, callback, callbackParams = []) {

        var form = document.getElementById(formId);
        let url = $(`#${buttonID}`).attr('data-test');
        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(form),
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {
                $('#global-loader').css('opacity', '0.5');
                $('#global-loader').show();
            },

            success: function (response) {
                if (response.message) {
                    $(`#${successElementID}`).text(response.message).show();
                    $(`#${errorElementID}`).hide();
                    if (callback)
                        callback(...callbackParams);
                }
                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    // $(`.modal`).modal('hide');

                    $(`#demo-modal`).modal('show');
                }

            },
            error: function (response) {

                response = response.responseJSON;
                if (response.message) {
                    $(`#${errorElementID}`).text(response.message).show();
                }
                if (response.errors) {
                    fields.every(error => {
                        if (response.errors[error]) {

                            $(`#${errorElementID}`).text(response.errors[error][0]).show();

                            $(`#${successElementID}`).hide();

                            return false;
                        }
                        return true;

                    });

                }
                $("#saveBtn-add-dataconnection").attr("disabled", true);
                $(`#${successElementID}`).hide();
            }, complete: function () {
                $('#global-loader').css('opacity', '1');

                $('#global-loader').hide();

            }
        });

    }

    window.afterTestConnectionSuccess = function afterTestConnectionSuccess() {
        $("#saveBtn-add-dataconnection").attr("disabled", false);
    }

    window.afterEditTestConnectionSuccess = function afterEditTestConnectionSuccess() {
        $("#saveBtn-edit-dataconnection").attr("disabled", false);
        $("<input type='hidden' name='_method' value='PUT' />").appendTo('#edit-dataconnection-form');

    }



    window.sendAjaxRequestWithSuccess = function sendAjaxRequestWithSuccess(formId, modelToHide, callback, callbackParams, appendResponse = false) {

        var form = document.getElementById(formId);
        let url = $(`#${formId}`).attr('data-url');
        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(form),
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {
                $('#global-loader').css('opacity', '0.5');
                $('#global-loader').show();
            },
            success: function (response) {
                if (response.message) {

                    $(`#${modelToHide}`).modal('hide');
                    $(`#success-modal`).find('h5').text(response.message).show();
                    $(`#success-modal`).modal('show');
                    if (callback && appendResponse)
                        callback(...callbackParams, response);
                    else if (callback) {
                        callback(...callbackParams);
                    }
                }

                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    // $(`.modal`).modal('hide');

                    $(`#demo-modal`).modal('show');
                }


            }, error: function (response) {
                $(`#${modelToHide}`).modal('hide');
                $(`#success-modal`).find('h5').text(response.responseJSON.message).show();
                $(`#success-modal`).modal('show');

            }, complete: function () {
                $('#global-loader').css('opacity', '1');

                $('#global-loader').hide();

            }
        });

    }



    window.reloadForm = function reloadForm(formId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                $(`#${formId}`).html($(data).find(`#${formId}`).html());

                $('[data-toggle="tooltip"]').tooltip({
                    boundary: 'window'
                })
            }
        });
    }

    window.reloadWithClass = function reloadWithClass(elementClass, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                $(`.${elementClass}`).html($(data).find(`.${elementClass}`).html());
            }
        });
    }

    window.reloadUsersTable = function reloadUsersTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let usersTable = $('#users').DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 6,
                        "orderable": false
                    },
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No data matches your search criteria",
                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                applyuserSearch(usersTable);
                clearuserSearch(usersTable);

            }
        });
    }


    window.reloadGroupTable = function reloadGroupTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let groupsTable = $(`#${tableId}`).DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": false,
                    "order": [[1, "desc"]],
                    "columnDefs": [{
                        "targets": 3,
                        "orderable": false
                    },
                    {
                        "targets": [1, 2, 3],
                        "searchable": false
                    }
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No records matches your search criteria",
                        "emptyTable": "No groups to preview"

                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                window.applyGroupSearch(groupsTable);
                window.clearGroupSearch(groupsTable);
            }
        });
    }

    window.applyGroupSearch = function applyGroupSearch(groupsTable) {
        $('.search-filter').click(function () {
            groupsTable.column(0).search($('#search-groups').val());
            groupsTable.draw();

        });

    }

    window.clearGroupSearch = function clearGroupSearch(groupsTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#search-groups').val("");
            groupsTable.columns().search("").draw();
        });

    }

    // categories
    window.reloadCategoryTable = function reloadCategoryTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let categoryTable = $(`#${tableId}`).DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 3,
                        "orderable": false
                    },
                    {
                        "targets": [1, 2, 3],
                        "searchable": false
                    }
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No records matches your search criteria",
                        "emptyTable": "No categories to preview"

                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                window.applyCategorySearch(categoryTable);
                window.clearCategorySearch(categoryTable);
            }
        });
    }


    window.applyCategorySearch = function applyCategorySearch(categoriesTable) {
        $('.search-filter').click(function () {
            categoriesTable.column(0).search($('#search-categories').val());
            categoriesTable.draw();

        });


    }

    window.clearCategorySearch = function clearCategorySearch(categoriesTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#search-categories').val("");
            categoriesTable.columns().search("").draw();
        });

    }


    // data connections
    window.applyDataConnectionSearch = function applyDataConnectionSearch(dataConnectionTable) {
        $('.search-filter').click(function () {
            dataConnectionTable.column(0).search($('#connection-name-search').val());
            dataConnectionTable.column(1).search($('#db-type-search').val());
            dataConnectionTable.column(2).search($('#servers-search').val());
            dataConnectionTable.column(3).search($('#databases-search').val());
            dataConnectionTable.draw();

        });


    }

    window.clearDataConnectionSearch = function clearDataConnectionSearch(dataConnectionTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#connection-name-search').val("");
            $('#db-type-search option:first').prop('selected', true);
            $('#servers-search option:first').prop('selected', true);
            $('#databases-search option:first').prop('selected', true);

            dataConnectionTable.columns().search("").draw();
        });

    }


    window.reloadDataConnectionTable = function reloadDataConnectionTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let DataConnectionTable = $('#data-connections').DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 5,
                        "orderable": false
                    },
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No data matches your search criteria",
                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                applyDataConnectionSearch(DataConnectionTable);
                clearDataConnectionSearch(DataConnectionTable);

            }
        });
    }


    window.sendTestSMTPConnectionAjaxRequest = function sendTestSMTPConnectionAjaxRequest(formId, buttonID, fields, successElementID, errorElementID, callback, callbackParams = []) {

        var form = document.getElementById(formId);
        let url = $(`#${buttonID}`).attr('data-test');
        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(form),
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {

                $("#global-loader").css('opacity', '0.5');
                $("#global-loader").fadeIn();
            },
            success: function (response) {
                if (response.message) {
                    $(`#${successElementID}`).text(response.message).show();
                    $(`#${errorElementID}`).hide();
                    if (callback)
                        callback(...callbackParams);
                    $("#saveBtn-smtp-server").attr("disabled", false);
                }

                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    $(`#demo-modal`).modal('show');
                }


            },
            error: function (response) {

                response = response.responseJSON;
                if (response.message) {
                    $(`#${errorElementID}`).attr('title', response.message);
                    $(`#${errorElementID}`).text(prepareMessage(response.message, 100).truncatedMsg).show();
                }
                if (response.errors) {
                    fields.every(error => {
                        if (response.errors[error]) {

                            $(`#${errorElementID}`).attr('title', response.errors[error][0]);

                            $(`#${errorElementID}`).text(response.errors[error][0]).show();

                            $(`#${successElementID}`).hide();

                            return false;
                        }
                        return true;

                    });

                }
                $("#saveBtn-smtp-server").attr("disabled", true);
                $(`#${successElementID}`).hide();
            },
            complete: function () {
                $("#global-loader").css('opacity', '1');

                $("#global-loader").fadeOut();
            },

        });

    }


    window.sendSMTPConnectionAjaxRequest = function sendSMTPConnectionAjaxRequest(formId, fields, successElementID, errorElementID, callback, callbackParams) {

        var form = document.getElementById(formId);
        let url = $(`#${formId}`).attr('data-url');
        $.ajax({
            type: "POST",
            url: url,
            data: new FormData(form),
            contentType: false,
            processData: false,
            dataType: "json",
            beforeSend: function () {

                $("#global-loader").css('opacity', '0.5');
                $("#global-loader").fadeIn();
            },

            success: function (response) {
                if (response.message) {
                    $(`#${successElementID}`).text(response.message).show();
                    $(`#${errorElementID}`).hide();
                    if (callback)
                        callback(...callbackParams);
                }

                if (response.demo) {
                    $(`#demo-modal`).find('h5').text(response.demo).show();
                    $(`#demo-modal`).modal('show');
                }

            },
            error: function (response) {
                response = response.responseJSON;

                if (response.message === "need-confirmation") {
                    $('#smtp-confirm-modal').modal('show')
                }

                else {
                    if (response.message) {
                        $(`#${errorElementID}`).text(response.message).show();
                        $(`#${successElementID}`).hide();
                    }
                    if (response.errors) {
                        fields.every(error => {
                            if (response.errors[error]) {

                                $(`#${errorElementID}`).text(response.errors[error][0]).show();

                                $(`#${successElementID}`).hide();

                                return false;
                            }
                            return true;

                        });

                    }
                }

                $(`#${successElementID}`).hide();
            },
            complete: function () {
                $("#global-loader").css('opacity', '1');

                $("#global-loader").fadeOut();
            },
        });

    }


    // reports

    window.applyReportsSearch = function applyReportsSearch(reportsTable) {
        $('.search-filter').click(function () {
            reportsTable.column(0).search($('#report-name-search').val());
            reportsTable.column(1).search($('#category-search').val());
            reportsTable.column(2).search($('#creator-search').val());
            reportsTable.draw();
        });

    }


    window.clearReportsSearch = function clearReportsSearch(reportsTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#report-name-search').val("");
            $('#category-search option:first').prop('selected', true);
            $('#creator-search option:first').prop('selected', true);

            reportsTable.columns().search("").draw();
        });

    }



    window.reloadReportTable = function reloadReportTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let reportsTable = $('#reports').DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 5,
                        "orderable": false
                    },
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No records matches your search criteria",
                        "emptyTable": "No reports to preview"
                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                applyReportsSearch(reportsTable);
                clearReportsSearch(reportsTable);

            }
        });
    }


    window.applyScheduledReportsSearch = function applyScheduledReportsSearch(scheduledReportsTable) {
        $('.search-filter').click(function () {
            scheduledReportsTable.column(0).search($('#title-search').val());
            scheduledReportsTable.column(1).search($('#frequency-search').val());
            scheduledReportsTable.draw();
        });

    }

    window.clearScheduledReportsSearch = function clearReportsSearch(scheduledReportsTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#title-search').val("");
            $('#frequency-search option:first').prop('selected', true);

            scheduledReportsTable.columns().search("").draw();
        });

    }

    window.reloadScheduledReportsTable = function reloadScheduledReportsTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let scheduledReportsTable = $('#scheduled-reports').DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 5,
                        "orderable": false
                    },
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No records matches your search criteria",
                        "emptyTable": "No scheduled reports to preview"
                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                applyScheduledReportsSearch(scheduledReportsTable);
                clearScheduledReportsSearch(scheduledReportsTable);

            }
        });
    }


    window.applyDashboardsSearch = function applyDashboardsSearch(DashboardsTable) {
        $('.search-filter').click(function () {
            DashboardsTable.column(0).search($('#name-search').val());
            DashboardsTable.column(1).search($('#title-search').val());
            DashboardsTable.draw();
        });

    }

    window.clearDashboardsSearch = function clearDashboardsSearch(DashboardsTable) {
        $('.wrapper').on('click', '.reset-filter', function () {
            $('#name-search').val("");
            $('#title-search').val("");

            DashboardsTable.columns().search("").draw();
        });

    }


    window.reloadDashboardsTable = function reloadDashboardsTable(tableId, location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                // Destroy the existing DataTable
                $(`#${tableId}`).DataTable().destroy();

                // Update the HTML content
                $(`#${tableId}`).html($(data).find(`#${tableId}`).html());

                // Reinitialize the DataTable
                let DashboardsTable = $('#dashboards').DataTable({
                    "dom": "lrtip",
                    "paging": true,
                    "pageLength": 10,
                    "lengthChange": false,
                    "searching": true,
                    "ordering": true,
                    "order": [],
                    "columnDefs": [{
                        "targets": 4,
                        "orderable": false
                    },
                    ],
                    "info": true,
                    "autoWidth": false,
                    "responsive": true,
                    "language": {
                        "zeroRecords": "No records matches your search criteria",
                        "emptyTable": "No dashboards stored for this user account"

                    },
                    drawCallback: function (settings) {
                        var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
                        pagination.toggle(this.api().page.info().pages > 1);
                    }

                });

                applyDashboardsSearch(DashboardsTable);
                clearDashboardsSearch(DashboardsTable);

            }
        });
    }



    window.reloadChartPage = function reloadChartPage(location = window.location.href) {
        $.ajax({
            url: location,
            type: "GET",
            dataType: "html",
            success: function (data) {
                window.location.href = window.location.href;

            }
        });
    }

    window.reloadPagePartially = function reloadPagePartially(formId = null, reloadedPart, reloadedIn, isQuery = false, url = window.location.href) {

        console.log(url);
        if (!isQuery)
            url = url.split("?")[0];

        if (formId)
            var form = $(`#${formId}`);
        $.ajax({
            type: "GET",
            url: url,
            data: formId ? form.serialize() : "",
            dataType: "html",
            beforeSend: function () {
                $(reloadedIn).css("visibility", "hidden");
                $(".c3-legend-item").css("visibility", "hidden")
                $(reloadedIn).parent().addClass('spinner');
            },
            success: function (data) {

                let response = $(data).find(reloadedPart).html();
                $(reloadedIn).html(response);
                $(reloadedIn).css("visibility", "visible");
                $(".c3-legend-item").css("visibility", "visible");


                $(window).trigger('resize');

                // reload custom tooltip
                $('[data-toggle="custom-tooltip"]').tooltip({
                    html: true,
                    template: '<div class="tooltip custom-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
                });
            },
            complete: function () {
                $(reloadedIn).parent().removeClass('spinner');
            },

            error: function () {

            }
        });

    }


    window.reloadPageWithSearch = function reloadPageWithSearch(formId = null, reloadedPart, reloadedIn, isQuery = false, url = window.location.href) {

        console.log(url);
        if (!isQuery)
            url = url.split("?")[0];

        if (formId)
            var form = $(`#${formId}`);
        $.ajax({
            type: "GET",
            url: url,
            data: formId ? form.serialize() : "",
            dataType: "html",
            beforeSend: function () {
                $(reloadedIn).css("visibility", "hidden");
                $(".c3-legend-item").css("visibility", "hidden")
                $(reloadedIn).parent().addClass('spinner');
            },
            success: function (data) {

                let response = $(data).find(reloadedPart).html();
                $(reloadedIn).html(response);
                $(reloadedIn).css("visibility", "visible");
                $(".c3-legend-item").css("visibility", "visible");


                $(window).trigger('resize');

                // reload custom tooltip
                $('[data-toggle="custom-tooltip"]').tooltip({
                    html: true,
                    template: '<div class="tooltip custom-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
                });
            },
            complete: function () {
                $(reloadedIn).parent().removeClass('spinner');
            },

            error: function () {

            }
        });

    }



    window.reloadChartPagePartially = function reloadChartPagePartially(reloadedPart, reloadedIn, lastPage) {

        url = window.location.href;
        try {
            currentPage = url.split("?")[1].split("=")[1];
        } catch (error) {
            currentPage = 1;

        }

        if (lastPage != null) {
            if (lastPage < +currentPage) {
                const newUrl = new URL(window.location);

                url = typeof lastPage === 'object' ? url + "?page=" + lastPage.last_page : url + "?page=" + lastPage;

                typeof lastPage === 'object' ? newUrl.searchParams.set('page', lastPage.last_page) : newUrl.searchParams.set('page', lastPage)

                window.history.replaceState({}, document.title, newUrl);
            }
        } else {
            currentPage = 1;
            url = url + "?page=" + currentPage;
        }

        $.ajax({
            type: "GET",
            url: url,
            dataType: "html",
            beforeSend: function () {
                $(reloadedIn).css("visibility", "hidden");
                $(reloadedIn).parent().addClass('spinner');
            },
            success: function (data) {
                let response = $(data).find(reloadedPart).html();
                $(reloadedIn).html(response);
                $(reloadedIn).css("visibility", "visible");

                $(window).trigger('resize');

                // reload custom tooltip
                $('[data-toggle="custom-tooltip"]').tooltip({
                    html: true,
                    template: '<div class="tooltip custom-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
                });

            },
            complete: function () {
                $(reloadedIn).parent().removeClass('spinner');
            },

            error: function () {

            }
        });


    }




    window.reloadMetricPagePartially = function reloadMetricPagePartially(reloadedPart, reloadedIn, goToLast = true, lastPage = null) {

        url = window.location.href;
        try {
            currentPage = url.split("?")[1].split("=")[1];
        } catch (error) {
            currentPage = 1;

        }

        url = url.split("?")[0];

        if (lastPage != null) {
            if (lastPage < +currentPage || goToLast) {
                const newUrl = new URL(window.location);

                url = typeof lastPage === 'object' ? url + "?page=" + lastPage.last_page : url + "?page=" + lastPage;

                typeof lastPage === 'object' ? newUrl.searchParams.set('page', lastPage.last_page) : newUrl.searchParams.set('page', lastPage)

                window.history.replaceState({}, document.title, newUrl);
            }
        }

        $.ajax({
            type: "GET",
            url: url,
            dataType: "html",
            beforeSend: function () {
                $(reloadedIn).css("visibility", "hidden");
                $(".c3-legend-item").css("visibility", "hidden")
                $(reloadedIn).parent().addClass('spinner');
            },
            success: function (data) {

                let response = $(data).find(reloadedPart).html();
                $(reloadedIn).html(response);
                $(reloadedIn).css("visibility", "visible");
                $(".c3-legend-item").css("visibility", "visible");


                $(window).trigger('resize');

                // reload custom tooltip
                $('[data-toggle="custom-tooltip"]').tooltip({
                    html: true,
                    template: '<div class="tooltip custom-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
                });

            },
            complete: function () {
                $(reloadedIn).parent().removeClass('spinner');
            },

            error: function () {

            }
        });

    }


    window.reloadHomePagePartially = function reloadHomePagePartially(reloadedPart, reloadedIn, goToLast = true, lastPage = null) {

        url = window.location.href;
        try {
            currentPage = url.split("?")[1].split("=")[1];
        } catch (error) {
            currentPage = 1;

        }
        url = url.split("?")[0]

        if (lastPage != null) {

            lastPage = typeof lastPage === 'object' ? lastPage.last_page : lastPage;

            if (lastPage < +currentPage || goToLast) {
                const newUrl = new URL(window.location);

                url = url + "?page=" + lastPage;

                newUrl.searchParams.set('page', lastPage)

                window.history.replaceState({}, document.title, newUrl);


            } else {

                url = url + "?page=" + currentPage;

            }
        }

        $.ajax({
            type: "GET",
            url: url,
            dataType: "html",
            beforeSend: function () {
                $(reloadedIn).css("visibility", "hidden");
                $(".c3-legend-item").css("visibility", "hidden")
                $(reloadedIn).parent().addClass('spinner');
            },
            success: function (data) {

                let response = $(data).find(reloadedPart).html();
                $(reloadedIn).html(response);
                $(reloadedIn).css("visibility", "visible");
                $(".c3-legend-item").css("visibility", "visible");


                $(window).trigger('resize');

                // reload custom tooltip
                $('[data-toggle="custom-tooltip"]').tooltip({
                    html: true,
                    template: '<div class="tooltip custom-tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
                });

            },
            complete: function () {
                $(reloadedIn).parent().removeClass('spinner');
            },

            error: function () {

            }
        });

    }



    window.sendStartTourRequest = function sendStartTourRequest() {
        let url = $('#start-tour').data('start');
        $.ajax({
            url: url,
            type: 'POST',
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            success: function () {
            },
            error: function (xhr, status, error) {
            }
        });

    }

    window.sendStopTourRequest = function sendStopTourRequest() {
        let url = $('#start-tour').data('stop');
        $.ajax({
            url: url,
            type: 'POST',
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            success: function () {
            },
            error: function (xhr, status, error) {
            }
        });

    }

    window.sendTourStepRequest = function sendTourStepRequest(step) {
        let url = $('#start-tour').data('step');
        $.ajax({
            url: url,
            type: 'POST',
            data: { 'step': step },
            headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
            success: function () {
            },
            error: function (xhr, status, error) {
            }
        });

    }



    window.prepareMessage = function prepareMessage(msg, length) {

        if (msg.length > length)
            return {
                fullMsg: msg,
                truncatedMsg: `${msg.substring(0, length)}...`
            };
        else {
            return {
                fullMsg: msg,
                truncatedMsg: msg,
            };
        }

    }


    window.vh = function vh(percent) {
        var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
        return (percent * h) / 100;
    }
    window.vw = function vw(percent) {
        var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
        return (percent * w) / 100;
    }


    window.adjustModalHeight = function adjustModalHeight(id) {
        var iFrameID = document.getElementById(id);

        function setIframeHeight(event) {
            // Check if the event target is a textbox, textarea, or select box
            if (event && (
                (event.target.tagName === "INPUT" && event.target.type === "text") ||
                (event.target.tagName === "INPUT" && event.target.type === "radio") ||
                event.target.tagName === "TEXTAREA" || event.target.tagName === "SELECT"
                || event.target.tagName === "OPTION" || event.target.tagName === "DIV"
            )) {
                return; // Do not adjust height if clicking inside a textbox, textarea, or select box
            }

            iFrameID.style.height = "200px"; // Set a default height
            iFrameID.style.height = (iFrameID.contentWindow.document.body.scrollHeight) + "px";
        }

        if (iFrameID) {
            // Initial height setting
            setIframeHeight();

            // Event listeners for commonly used events (you can adjust this based on your needs)
            iFrameID.contentWindow.addEventListener("load", setIframeHeight); // Adjust on load
            iFrameID.contentWindow.addEventListener("click", setIframeHeight); // Adjust on click

            const iframeBody = iFrameID.contentDocument.body;

            // ResizeObserver to continuously monitor changes
            const ro = new ResizeObserver(function () {
                if (iframeBody.scrollHeight < vh(10)) {
                    iFrameID.style.height = "500px"; // Set a minimum height
                } else {
                    iFrameID.style.height = `${iframeBody.scrollHeight}px`;
                }
            });

            ro.observe(iframeBody);
        }
    };


    window.setCookie = function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    window.getCookie = function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    window.eraseCookie = function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }
});
