window.zender = {
    aos: () => {
        AOS.init();
    },

    active: () => {
        if ("//" + location.hostname + location.pathname == site_url + "/dashboard")
            $("li [zender-nav][href^=\"" + "//" + location.hostname + location.pathname + "?\"]").addClass("active");
        else
            $("li [zender-nav][href^=\"" + "//" + location.hostname + location.pathname + "\"]").addClass("active");
    },

    action: () => {
        $(document).on("click", "[zender-action]", function(e) {
            e.preventDefault();

            switch ($(this).attr("zender-action")) {
                case "logout":
                    $.get(site_url + "/ajax/index/logout", (response) => {
                        try {
                            var response = JSON.parse(response);
                            if (response.status == 200) {
                                alert.success(response.message, true);
                            }
                        } catch (e) {
                            alert.danger(lang_response_went_wrong);
                        }
                    });
                    break;
                default:
                    alert.danger("Unknown action method!");
            }
        });
    },

    translate: () => {
        $("body").append(
            `<ul class="mfb-component--br mfb-slidein-spring" data-mfb-toggle="hover">
                <li class="mfb-component__wrap">
                    <a href="#" class="mfb-component__button--main bg-dark" zender-scroll-top>
                        <i class="mfb-component__main-icon--resting la la-language la-lg text-white"></i>
                        <i class="mfb-component__main-icon--active la la-arrow-up la-lg text-white"></i>
                    </a>
                    <ul class="mfb-component__list" zender-languages></ul>
                </li>
            </ul>`
        ).ready(() => {
            $.get(site_url + "/ajax/index/languages", function(response) {
                try {
                    var response = JSON.parse(response);

                    $("[zender-languages]").html(response.data);
                } catch (e) {
                    alert.danger(lang_response_went_wrong);
                }
            });

            $(document).on("click", "[zender-language]", function(e) {
                e.preventDefault();

                $.get(site_url + "/ajax/index/language/" + $(this).attr("zender-language"), function(response) {
                    try {
                        var response = JSON.parse(response);

                        if (response.status == 200) {
                            alert.success(response.message, true);
                        } else {
                            alert.warning(response.message);
                        }
                    } catch (e) {
                        alert.danger(lang_response_went_wrong);
                    }
                });
            });

            zender.scroll();
        });
    },

    codeflask: () => {
        if ($("[zender-codeflask]").length) {
            window.codeflask = new CodeFlask("[zender-codeflask]", {
                lineNumbers: false
            });

            codeflask.updateCode(he.decode(codeflask.getCode()));
        }
    },

    autonavbar: () => {
        if ($(".navbar-right").width() > 750) {
            $("header div:first").addClass("container-fluid");
            $("header div .navbar div:first").addClass("container-fluid");
            $("header div:first").removeClass("container");
            $("header div .navbar div:first").removeClass("container");
        }
    },

    creditcard: () => {
        if ($("zender-creditcard").length) {
            $("[zender-form]").card({
                container: "zender-creditcard",
            });
        }
    },

    clipboard: (destroy = false) => {
        if (!destroy) {
            if ($("[zender-clipboard]").length) {

                window.clipboard = new ClipboardJS("[zender-clipboard]");

                clipboard.on("success", (e) => {
                    e.clearSelection();
                    alert.success(lang_copy_data);
                });

            }
        } else {
            if (window.clipboard)
                clipboard.destroy();
        }
    },

    disabled: (disabled = true) => {
        if (disabled)
            $(".form-control, .input, button[type=submit]").attr("disabled", "");
        else
            $(".form-control, .input, button[type=submit]").removeAttr("disabled");
    },

    scroll: () => {
        $("[zender-scroll-top]").on("click", function(e) {
            e.preventDefault();
            $("html, body").animate({
                scrollTop: "0px"
            }, 300);
        });

        $("[zender-scroll]").on("click", function(e) {
            e.preventDefault();
            $(window).stop(true).scrollTo(this.hash);
        });
    },

    qrcode: (data, width, height) => {
        new QRCode("zender-qrcode", {
            text: data,
            width: width,
            height: height
        });
    },

    redirect: (path) => {
        window.location.href = path;
    },

    ripple: () => {
        Waves.init();
        Waves.attach(".btn");
    },

    iframe: () => {
        if ($("[zender-iframe]").length) {
            $("[zender-iframe]").each(function(i) {
                $(this).attr("src", $(this).attr("zender-iframe"));
                $(this).on("load", function() {
                    setTimeout(() => {
                        $(this).iFrameResize({
                            resizeFrom: "child"
                        });
                    }, 500);
                });
            });
        }
    },

    datepicker: () => {
        if ($("[zender-datepicker]").length) {
            var ranges = [];
            ranges[lang_date_today] = [moment(), moment()];
            ranges[lang_date_yesterday] = [moment().subtract(1, "days"), moment().subtract(1, "days")];
            ranges[lang_date_7days] = [moment().subtract(6, "days"), moment()];
            ranges[lang_date_30days] = [moment().subtract(29, "days"), moment()];
            ranges[lang_date_month] = [moment().startOf("month"), moment().endOf("month")];
            ranges[lang_date_lmonth] = [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")];

            $(".daterangepicker").remove();
            $("[zender-datepicker]").daterangepicker({
                opens: "left",
                startDate: moment().subtract(29, "days"),
                endDate: moment(),
                ranges: ranges,
                locale: {
                    customRangeLabel: lang_date_custom
                }
            });
        }
    },

    autocomplete: () => {
        if ($("[zender-autocomplete]").length) {
            $(".autocomplete-suggestions").remove();
            $.get(site_url + "/ajax/suggest/" + ($("[zender-autocomplete]").attr("zender-autocomplete") ? $("[zender-autocomplete]").attr("zender-autocomplete") : false), function(response) {
                try {
                    var response = JSON.parse(response);

                    switch (response.status) {
                        case 200:
                            $("[zender-autocomplete]").autocomplete({
                                lookup: response.data,
                                onSelect: function(suggestion) {
                                    $(this).val(suggestion.data);
                                }
                            });
                            break;
                        case 302:
                            alert.warning(response.message, true);
                            break;
                        default:
                            alert.danger(response.message);
                    }
                } catch (e) {
                    alert.danger(lang_response_went_wrong);
                }
            });
        }
    },

    select: () => {
        if ($("[zender-form] select").length) {
            $("[zender-form] select").selectpicker();
        }

        if ($("[zender-select-template]").length) {
            $("[zender-select-template]").on("changed.bs.select", function(e, clickedIndex, isSelected, previousValue) {
                var temp = $(this).find("option:selected");
                var format = (temp.data("format") ? temp.data("format") : false);

                if (format)
                    $("textarea[name=message]").val(format);
                else
                    $("textarea[name=message]").val("");
            });
        }
    },

    build: () => {
        $(document).on("click", "[zender-build]", function(e) {
            $.get(site_url + "/ajax/index/build", function(response) {
                try {
                    var response = JSON.parse(response);

                    switch (response.status) {
                        case 200:
                            alert.success(response.message);
                            break;
                        case 302:
                            alert.warning(response.message, true);
                            break;
                        default:
                            alert.danger(response.message);
                    }
                } catch (e) {
                    alert.danger(lang_response_went_wrong);
                }
            });
        });
    },

    delete: () => {
        $(document).on("click", "[zender-delete]", function(e) {
            e.preventDefault();
            var param = ($(this).attr("zender-delete") ? $(this).attr("zender-delete") : false);
            iziToast.question({
                title: lang_delete_title,
                message: lang_delete_tagline,
                titleLineHeight: "25px",
                backgroundColor: "linear-gradient(30deg, rgb(197, 23, 23), rgb(255, 125, 33))",
                position: "center",
                icon: false,
                drag: false,
                timeout: false,
                close: false,
                overlay: true,
                layout: 1,
                zindex: 1024,
                buttons: [
                    ["<button class=\"text-white\">Confirm</button>", function(instance, toast, button, e, inputs) {
                        $.ajax({
                            url: site_url + "/ajax/delete/" + param,
                            type: "GET",
                            beforeSend: function() {
                                instance.hide({
                                    transitionOut: "fadeOut"
                                }, toast, "button");
                            },
                            success: function(response) {
                                try {
                                    var response = JSON.parse(response);

                                    switch (response.status) {
                                        case 200:
                                            if (response.data.vars.table)
                                                zender.tables(response.data.vars.table);

                                            alert.success(response.message);
                                            break;
                                        case 302:
                                            alert.warning(response.message, true);
                                            break;
                                        default:
                                            alert.danger(response.message);
                                    }
                                } catch (e) {
                                    alert.danger(lang_response_went_wrong);
                                }
                            }
                        });
                    }, true],
                    ["<button class=\"text-white\">Cancel</button>", function(instance, toast, button, e) {
                        instance.hide({
                            transitionOut: "fadeOut"
                        }, toast, "button");
                    }]
                ]
            });
        });
    },

    charts: (chart) => {
        parent.jQuery.get(parent.site_url + "/ajax/chart/" + chart, function(chart) {
            try {
                var chart = JSON.parse(chart);

                window.apex = new ApexCharts(
                    document.querySelector("#chart"), {
                        chart: {
                            type: "area",
                            height: 300,
                            foreColor: "#999",
                            stacked: true,
                            dropShadow: {
                                enabled: true,
                                enabledSeries: [0],
                                top: -2,
                                left: 2,
                                blur: 5,
                                opacity: 0.06
                            },
                            toolbar: {
                                show: true,
                                tools: {
                                    download: false
                                }
                            }
                        },
                        colors: chart.data.vars.colors,
                        stroke: {
                            curve: "smooth",
                            width: 4
                        },
                        dataLabels: {
                            enabled: false
                        },
                        series: chart.data.vars.series,
                        markers: {
                            size: 0,
                            strokeColor: "#fff",
                            strokeWidth: 3,
                            strokeOpacity: 1,
                            fillOpacity: 1,
                            hover: {
                                size: 6
                            }
                        },
                        xaxis: {
                            type: "datetime",
                            axisBorder: {
                                show: false
                            },
                            axisTicks: {
                                show: false
                            },
                            labels: {
                                datetimeUTC: false
                            }
                        },
                        yaxis: {
                            labels: {
                                offsetX: -10,
                                offsetY: 0
                            },
                            tooltip: {
                                enabled: true
                            }
                        },
                        grid: {
                            padding: {
                                left: -5,
                                right: 5
                            }
                        },
                        tooltip: {
                            x: {
                                format: "MMMM dd yyyy"
                            }
                        },
                        legend: {
                            position: "top",
                            horizontalAlign: "left"
                        },
                        fill: {
                            type: "gradient",
                            gradient: {
                                shadeIntensity: 1,
                                opacityFrom: 0.7,
                                opacityTo: 0.9,
                                stops: [0, 90, 100]
                            }
                        },
                    });

                apex.render();
            } catch (e) {
                parent.alert.danger(parent.lang_response_went_wrong);
            }
        });
    },

    tables: (table) => {
        $.get(site_url + "/table/" + table, function(response) {
            try {
                var response = JSON.parse(response);

                if ($.fn.DataTable.isDataTable("[zender-table]"))
                    $("[zender-table]").DataTable().destroy();

                zender.clipboard(true);

                switch (response.status) {
                    case 200:
                        $("[zender-table]").on("error.dt", () => {
                            alert.danger(lang_response_went_wrong);
                        }).DataTable({
                            data: response.data.data,
                            lengthMenu: [10, 25, 50, 75, 100],
                            pageLength: 10,
                            sPaginationType: "full_numbers",
                            oLanguage: {
                                sSearch: "<i class=\"la la-search\"></i> " + response.data.search.text,
                                sSearchPlaceholder: response.data.search.placeholder
                            },
                            aaSorting: [
                                [0, "desc"]
                            ],
                            columns: response.data.columns,
                            language: {
                                infoPostFix: "",
                                processing: lang_datatable_processing,
                                lengthMenu: lang_datatable_length,
                                info: lang_datatable_info,
                                infoEmpty: lang_datatable_empty,
                                infoFiltered: lang_datatable_filtered,
                                loadingRecords: lang_datatable_loading,
                                zeroRecords: lang_datatable_zero,
                                emptyTable: lang_datatable_null,
                                paginate: {
                                    first: lang_datatable_first,
                                    previous: lang_datatable_prev,
                                    next: lang_datatable_next,
                                    last: lang_datatable_last
                                }
                            }
                        });

                        zender.clipboard();
                        break;
                    case 302:
                        alert.warning(response.message, true);
                        break;
                }
            } catch (e) {
                alert.danger(lang_response_went_wrong);
            }
        });
    },

    tabs: (initial = true, def = true) => {
        if (initial) {
            $(document).on("click", "[zender-tab]", function(e) {
                e.preventDefault();
                topbar.show();

                $.get(site_url + "/widget/tab/dashboard/" + ($(this).attr("zender-tab") ? $(this).attr("zender-tab") : false), (tab) => {
                    try {
                        var tab = JSON.parse(tab);

                        switch (tab.status) {
                            case 200:
                                $("[zender-tab]").removeClass("active");
                                $("zender-tab-content").html(tab.data.tpl);
                                $("zender-tab-content").children(":first").addClass("animated fadeIn");
                                $(this).addClass("active");

                                if (tab.data.vars.table)
                                    zender.tables(tab.data.vars.table);


                                zender.ripple();
                                zender.select();
                                zender.iframe();
                                break;
                            case 302:
                                alert.warning(tab.message, true);
                                break;
                            default:
                                alert.danger(tab.message);
                        }
                    } catch (e) {
                        alert.danger(lang_response_went_wrong);
                    }

                    topbar.hide();
                });
            });
        }

        if (def) {
            $("[zender-tab-default]").each(function(i) {
                if (i < 1) {
                    $.get(site_url + "/widget/tab/dashboard/" + ($(this).attr("zender-tab") ? $(this).attr("zender-tab") : false), (tab) => {
                        try {
                            var tab = JSON.parse(tab);

                            switch (tab.status) {
                                case 200:
                                    $("zender-tab-content").html(tab.data.tpl);
                                    $("zender-tab-content").children(":first").addClass("animated fadeIn");

                                    if (tab.data.vars.table)
                                        zender.tables(tab.data.vars.table);

                                    zender.select();
                                    zender.ripple();
                                    zender.iframe();
                                    break;
                                case 302:
                                    alert.warning(tab.message, true);
                                    break;
                                default:
                                    alert.danger(tab.message);
                            }
                        } catch (e) {
                            alert.danger(lang_response_went_wrong);
                        }
                    });
                }
            });
        }
    },

    modals: () => {
        $("body").append(
            `<zender-modal class="modal fade">
                <div class="modal-dialog" role="document">
                    <zender-modal-content></zender-modal-content>
                </div>
            </zender-modal>`
        ).ready(() => {
            $(document).on("click", "[zender-toggle]", function(e) {
                e.preventDefault();
                topbar.show();

                $.get(site_url + "/widget/modal/" + template + "/" + ($(this).attr("zender-toggle") ? $(this).attr("zender-toggle") : false), (modal) => {
                    try {
                        var modal = JSON.parse(modal);

                        switch (modal.status) {
                            case 200:
                                $("zender-modal").removeClass("left right");
                                $("zender-modal .modal-dialog").removeClass("modal-dialog-centered modal-sm modal-md modal-lg modal-xl");

                                if (modal.data.vars.position) {
                                    $("zender-modal").addClass(modal.data.vars.position);
                                } else {
                                    $("zender-modal .modal-dialog").addClass("modal-dialog-centered");
                                }

                                if (modal.data.vars.size) {
                                    $("zender-modal .modal-dialog").addClass("modal-" + modal.data.vars.size);
                                } else {
                                    $("zender-modal .modal-dialog").addClass("modal-sm");
                                }

                                $("zender-modal-content").html(modal.data.tpl);
                                $("zender-modal").modal({
                                    backdrop: "static",
                                    keyboard: false
                                });

                                if (modal.data.vars.iframe)
                                    zender.iframe();

                                zender.ripple();

                                if (modal.data.vars.type) {
                                    zender.autocomplete();
                                    zender.datepicker();
                                    zender.creditcard();
                                    zender.codeflask();
                                    zender.select();

                                    $("[zender-form]").on("submit", function(e) {
                                        e.preventDefault();

                                        var data = new FormData(this);

                                        if (modal.data.vars.id)
                                            data.append("id", modal.data.vars.id);

                                        if (window.codeflask) {
                                            data.append("content", codeflask.getCode());
                                            delete window.codeflask;
                                        }

                                        $.ajax({
                                            url: site_url + "/ajax/" + modal.data.vars.type + "/" + modal.data.vars.tpl,
                                            type: "POST",
                                            data: data,
                                            contentType: false,
                                            processData: false,
                                            beforeSend: () => {
                                                if (modal.data.vars.require) {
                                                    var filter = modal.data.vars.require.split("<=>");
                                                    for (var i = 0; i <= filter.length; i++) {
                                                        if (typeof filter[i] !== "undefined") {
                                                            var values = filter[i].split("|");
                                                        }
                                                        try {
                                                            if (data.get(values[0]).length < 1) {
                                                                alert.warning(values[1] + ", " + lang_validate_cannotemp);
                                                                return false;
                                                            }
                                                        } catch (e) {
                                                            if (data.getAll(values[0] + "[]").length < 1) {
                                                                alert.warning(values[1] + ", " + lang_validate_cannotemp);
                                                                return false;
                                                            }
                                                        }
                                                    }
                                                }

                                                zender.disabled();
                                            },
                                            success: (response) => {
                                                try {
                                                    var response = JSON.parse(response);

                                                    switch (response.status) {
                                                        case 200:
                                                            if (modal.data.vars.table)
                                                                zender.tables(modal.data.vars.table);

                                                            $("zender-modal").modal("hide");
                                                            alert.success(response.message);
                                                            break;
                                                        case 301:
                                                            $("zender-modal").modal("hide");
                                                            alert.success(response.message, true);
                                                            break;
                                                        case 302:
                                                            $("zender-modal").modal("hide");
                                                            alert.warning(response.message, true);
                                                            break;
                                                        default:
                                                            if (modal.data.vars.recaptcha)
                                                                grecaptcha.reset();

                                                            alert.danger(response.message);
                                                    }
                                                } catch (e) {
                                                    alert.danger(lang_response_went_wrong);
                                                }

                                                zender.disabled(false);
                                            }
                                        });
                                    });
                                }

                                break;
                            case 302:
                                alert.warning(modal.message, true);
                                break;
                            default:
                                alert.danger(modal.message);
                        }
                    } catch (e) {
                        alert.danger(lang_response_went_wrong);
                    }

                    topbar.hide();
                });
            });
        });
    }
}

window.alert = {
    setup: () => {
        iziToast.settings({
            title: lang_alert_attention,
            titleSize: "18px",
            titleLineHeight: "25px",
            messageSize: "17px",
            icon: false,
            timeout: 2000,
            animateInside: true,
            titleColor: "#f5f5f5",
            messageColor: "#f5f5f5",
            iconColor: "#f5f5f5",
            transitionIn: "fadeInRight",
            transitionOut: "fadeOutRight",
            position: "topLeft",
            displayMode: "replace",
            layout: 2,
            maxWidth: "300px",
            close: false
        });
    },

    primary: (message, redirect = false) => {
        iziToast.info({
            backgroundColor: "linear-gradient(30deg, rgb(16, 107, 181), rgb(79, 193, 238))",
            message: message,
            onClosed: () => {
                if (redirect)
                    location.reload();
            }
        });
    },

    success: (message, redirect = false) => {
        iziToast.success({
            backgroundColor: "linear-gradient(30deg, rgb(74, 117, 16), rgb(51, 199, 55))",
            message: message,
            onClosed: () => {
                if (redirect)
                    location.reload();
            }
        });
    },

    warning: (message, redirect = false) => {
        iziToast.warning({
            backgroundColor: "linear-gradient(30deg, rgb(179, 103, 24), rgb(243, 168, 32))",
            message: message,
            onClosed: () => {
                if (redirect)
                    location.reload();
            }
        });
    },

    danger: (message, redirect = false) => {
        iziToast.error({
            backgroundColor: "linear-gradient(30deg, rgb(197, 23, 23), rgb(255, 125, 33))",
            message: message,
            onClosed: () => {
                if (redirect)
                    location.reload();
            }
        });
    }
}

window.titansys = {
    chat: () => {
        $.get(site_url + "/ajax/index/livechat", function(response) {
            try {
                var response = JSON.parse(response);

                if (response.status == 200) {
                    var Tawk_API = Tawk_API || {};
                    Tawk_API.visitor = {
                        name: response.data
                    };

                    var Tawk_LoadStart = new Date();
                    (function() {
                        var s1 = document.createElement("script"),
                            s0 = document.getElementsByTagName("script")[0];
                        s1.async = true;
                        s1.src = "https://embed.tawk.to/5ead66fc10362a7578be5356/default";
                        s1.charset = "UTF-8";
                        s1.setAttribute("crossorigin", "*");
                        s0.parentNode.insertBefore(s1, s0);
                    })();
                }
            } catch (e) {
                alert.danger(lang_response_went_wrong);
            }
        });
    },

    forums: () => {
        $(document).on("click", "[zender-forums]", function(e) {
            $.get(site_url + "/ajax/index/forums", function(response) {
                try {
                    var response = JSON.parse(response);

                    switch (response.status) {
                        case 200:
                            alert.success(response.message);

                            setTimeout(() => {
                                zender.redirect(response.data);
                            }, 3000);
                            break;
                        case 302:
                            alert.warning(response.message, true);
                            break;
                        default:
                            alert.danger(response.message);
                    }
                } catch (e) {
                    alert.danger(lang_response_went_wrong);
                }
            });
        });
    }
}