function create_cookie(name, value, days2expire, path) {
    var date = new Date();
    date.setTime(date.getTime() + (days2expire * 24 * 60 * 60 * 1000));
    var expires = date.toUTCString();
    document.cookie = name + '=' + value + ';' +
        'expires=' + expires + ';' +
        'path=' + path + ';';
}
var countdown_viewer = function(chapId, comicId) {
    var countdown = 20;
    var countdownfunc = setInterval(function() {
        countdown--;
        if (countdown <= 0) {
            clearInterval(countdownfunc);
            $.post(`/graph/api?action=countdownUpdateviewer`, {
                comicId,
                chapId
            });
        }
        console.log(`Count Down -> ${countdown}`);
    }, 1000);
}

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
var closeADS = (_this) => $(_this).closest('div').remove();
var adsInit = (ids) => $.post('/graph/api?action=clicker-ads', {
    ids: ids
});
var tinymceLoad = function() {
    tinymce.init({
        selector: 'textarea.editor',
        menubar: false,
        height: "200",
        setup: function(editor) {
            editor.on('change', function() {
                editor.save(); // Lưu nội dung vào textarea ẩn
            });
        },
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview', 'anchor', 'searchreplace', 'visualblocks', 'fullscreen', 'insertdatetime', 'media', 'help', 'wordcount'
        ],
        toolbar: 'a11ycheck casechange blocks | bold italic backcolor | alignleft aligncenter alignright alignjustify |' +
            'image | link | media',
        images_upload_url: '/graph/api?action=upload-images',
        images_upload_handler: image_upload_handler_callback,
        content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
    });
}

function getCookies() {
    var c = document.cookie,
        v = 0,
        cookies = {};
    if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
        c = RegExp.$1;
        v = 1;
    }
    if (v === 0) {
        c.split(/[,;]/).map(function(cookie) {
            var parts = cookie.split(/=/, 2),
                name = decodeURIComponent(parts[0].trimLeft()),
                value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
            cookies[name] = value;
        });
    } else {
        c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
            var name = $0,
                value = $1.charAt(0) === '"' ?
                $1.substr(1, -1).replace(/\\(.)/g, "$1") :
                $1;
            cookies[name] = value;
        });
    }
    return cookies;
}
// Hàm để lấy dữ liệu từ LocalStorage
function getLocalStorage(key) {
    const item = localStorage.getItem(key);
    if (item) {
        return JSON.parse(item);
    }
    return null;
}

// Hàm để lưu trữ dữ liệu vào LocalStorage
function insertLocalStorage(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
}

// Hàm để xóa dữ liệu khỏi LocalStorage
function deleteLocalStorage(key) {
    localStorage.removeItem(key);
}

function get_cookie(name) {
    return getCookies()[name];
}

function isMobile() {
    const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
    return mobileRegex.test(navigator.userAgent);
}

function readURL(input, id) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#' + id).attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]); // convert to base64 string
    }
}

function scrollSmoothToBottom(id) {
    var div = document.getElementById(id);
    $('#' + id).animate({
        scrollTop: div.scrollHeight - div.clientHeight
    }, 200);
}
const image_upload_handler_callback = (blobInfo, progress) => new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = false;
    xhr.open('POST', '/dashboard/graph-api?action=upload-images');
    xhr.upload.onprogress = (e) => {
        progress(e.loaded / e.total * 100);
    };
    xhr.onload = () => {
        if (xhr.status === 403) {
            reject('Upload hình ảnh không thành công');
            return;
        }
        if (xhr.status < 200 || xhr.status >= 300) {
            reject('HTTP Error: ' + xhr.status);
            return;
        }
        const json = JSON.parse(xhr.responseText);

        if (!json || typeof json.message != 'string') {
            reject('Upload hình ảnh không thành công');
            return;
        }
        resolve(json.message);
    };
    xhr.onerror = () => {
        reject('Upload hình ảnh không thành công');
    };
    const formData = new FormData();
    formData.append('image', blobInfo.blob(), blobInfo.filename());

    xhr.send(formData);
});

function check_link() {
    link = $('.link_seo').val();
    if (link.length < 2) {
        $('.check_link').removeClass('ok');
        $('.check_link').addClass('error');
        $('.check_link').html('<i class="fa fa-ban"></i> Đường dẫn không hợp lệ');
    } else {
        $.ajax({
            url: "/graph/api",
            type: "post",
            data: {
                action: "check_link",
                link: link
            },
            success: function(kq) {
                var info = JSON.parse(kq);
                $('.link_seo').val(info.link);
                if (info.ok == 1) {
                    $('.check_link').removeClass('error');
                    $('.check_link').addClass('ok');
                    $('.check_link').html('<i class="fa fa-check-circle-o"></i> Đường dẫn hợp lệ');
                } else {
                    if ($('#link_old').length > 0) {
                        link_old = $('#link_old').val();
                        if (link_old == info.link) {
                            $('.check_link').removeClass('error');
                            $('.check_link').addClass('ok');
                            $('.check_link').html('<i class="fa fa-check-circle-o"></i> Đường dẫn hợp lệ');
                        }

                    } else {
                        $('.check_link').removeClass('ok');
                        $('.check_link').addClass('error');
                        $('.check_link').html('<i class="fa fa-ban"></i> Đường dẫn đã tồn tại');
                    }
                }
            }
        });
    }
}

function check_blank() {
    link = $('.tieude_seo').val();
    if (link.length < 2) {
        $('.check_link').removeClass('ok');
        $('.check_link').addClass('error');
        $('.check_link').html('<i class="fa fa-ban"></i> Đường dẫn không hợp lệ');
    } else {
        $.ajax({
            url: "/graph/api",
            type: "post",
            data: {
                action: "check_blank",
                link: link
            },
            success: function(kq) {
                var info = JSON.parse(kq);
                $('.link_seo').val(info.link);
                if (info.ok == 1) {
                    $('.check_link').removeClass('error');
                    $('.check_link').addClass('ok');
                    $('.check_link').html('<i class="fa fa-check-circle-o"></i> Đường dẫn hợp lệ');
                } else {
                    if ($('#link_old').length > 0) {
                        link_old = $('#link_old').val();
                        if (link_old == info.link) {
                            $('.check_link').removeClass('error');
                            $('.check_link').addClass('ok');
                            $('.check_link').html('<i class="fa fa-check-circle-o"></i> Đường dẫn hợp lệ');
                        }

                    } else {
                        $('.check_link').removeClass('ok');
                        $('.check_link').addClass('error');
                        $('.check_link').html('<i class="fa fa-ban"></i> Đường dẫn đã tồn tại');
                    }
                }
            }
        });
    }
}

function del(action, id) {
    $('.load_overlay').show();
    $('.load_process').fadeIn();
    $.ajax({
        url: "/graph/api",
        type: "post",
        data: {
            action: "del_cmt",
            id: id
        },
        success: function(kq) {
            var info = JSON.parse(kq);
            setTimeout(function() {
                $('.load_note').html(info.thongbao);
            }, 1000);
            setTimeout(function() {
                $('.load_process').hide();
                $('.load_note').html('Hệ thống đang xử lý');
                $('.load_overlay').hide();
                if (info.ok == 1) {
                    $('#tr_' + id).remove();
                } else {

                }
            }, 2000);
        }

    });
}

function confirm_del(action, id) {
    if (action == 'del_chap') {
        title = 'Xóa chap truyện';
    } else if (action == 'del_truyen') {
        title = 'Xóa truyện';
    } else {
        title = 'Xóa dữ liệu';
    }
    $('#title_confirm').html(title);
    $('#button_thuchien').attr('action', action);
    $('#button_thuchien').attr('post_id', id);
    $('#box_pop_confirm').show();
}
var serverPost = function(action, form_data) {
    return new Promise((resolve, reject) => {
        $.post(`/graph/api?action=${action}`, form_data)
            .done((res) => resolve(res || false))
            .fail((error) => reject(error));
    });
};
var leech_blocker = function(inputImagePath) {
    try {
        const canvas = document.createElement("canvas");
        canvas.style.width = '100%';
        const ctx = canvas.getContext('2d');
        const image = new Image();
        image.src = inputImagePath;
        image.onload = function() {
            const width = image.width;
            const height = image.height;

            const imageParts = [];
            const partHeight = Math.floor(height / 16);
            var height_canvas = 0;
            for (let i = 0; i < 16; i++) {
                height_canvas += partHeight;
                const startY = i * partHeight;
                const canvasPart = document.createElement('canvas');
                canvasPart.width = width;
                canvasPart.height = partHeight;
                const ctxPart = canvasPart.getContext('2d');
                ctxPart.drawImage(image, 0, startY, width, partHeight, 0, 0, width, partHeight);
                imageParts.push(canvasPart);
            }
            imageParts.reverse();
            canvas.width = width;
            canvas.height = height_canvas;
            let yOffset = 0;
            imageParts.forEach((part) => {
                ctx.drawImage(part, 0, yOffset);
                yOffset += part.height;
            });
            if ($users.username) {
                ctx.font = '10px Arial';
                ctx.fontWeight = 'bold';
                ctx.fillStyle = 'blue';
                const x = Math.floor(Math.random() * width);
                const y = Math.floor(Math.random() * height);
                ctx.fillText($users.username, x, y);
            }
        };
        return canvas;
    } catch (error) {
        console.log(error);
        return false
    }
}
var comic_load_image = async function() {
    const body = $('body');
    var server = body.attr('data-server'),
        comicId = body.attr('data-comic'),
        chapterId = body.attr('data-chapter');
    var list_images = $('.content_view_chap');
    list_images.html(`<div class="alert alert-primary mb-2">Đang tải hình ảnh vui lòng chờ</div>`);
    const { status, message } = await serverPost('comic_load_image', {
        server,
        comicId,
        chapterId
    });
    if (status == false) {
        list_images.empty();
        return;
    }

    list_images.empty();
    message.images.reverse();
    for (const image of message.images) {
        if (image) {
            if (message.lock_image >= 1) {
                const resutls = await leech_blocker(image);
                if (resutls) {
                    list_images.prepend(resutls);
                }
            } else {
                list_images.prepend(image);
            }
        }
    }

}
var loader_advertise = async function() {
    const { status, message } = await serverPost('loader_advertise');
    if (status == false) return;
    message.forEach(v => {
        append_advertise(v.type, v);
    });
}
var append_advertise = function(type, data) {
    switch (type) {
        case 'Popup giữa trang':
            $('.popupContainer').show().html(`<div class="popupBody">
                <div style="position: relative;">
                    <a onclick="adsInit(${data.id})" href="${data.redirect}" target="_blank">
                        <img src="${data.image}" alt="">
                    </a>
                    <button class="btn-popup-close">X</button>
                </div>
            </div>`);
            break;
        case "Catfish chân trang":
            $('.ads-sticky').show().append(`<div style="display: inline-block;position: relative;width: 100%">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Đầu trang":
            $('.advertise-top').append(`<div style="display: inline-block;position: relative;width: 100%">
            <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                <img src="${data.image}" style="width: 100%">
            </a>
            <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
        </div>`);
            break;
        case "Cuối trang":
            $('.advertise-bottom').append(`<div style="display: inline-block;position: relative;width: 100%">
            <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                <img src="${data.image}" style="width: 100%">
            </a>
            <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
        </div>`);
            break;
        case "Đầu trang thông tin":
            $('.advertise-info-top').append(`<div style="display: inline-block;position: relative;width: 100%">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Cuối trang thông tin":
            $('.advertise-info-bottom').append(`<div style="display: inline-block;position: relative;width: 100%">
                    <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                        <img src="${data.image}" style="width: 100%">
                    </a>
                    <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
                </div>`);
            break;
        case "Đầu trang xem truyện":
            $('.advertise-read-top').append(`<div style="display: inline-block;position: relative;width: 100%">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Cuối trang xem truyện":
            $('.advertise-read-bottom').append(`<div style="display: inline-block;position: relative;width: 100%">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Thanh sidebar":
            $('.advertise-sidebar').append(`<div style="display: inline-block;position: relative;width: 100%">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Bên trái":
            $('.ads-left').append(`<div style="position: relative;">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        case "Bên phải":
            $('.ads-right').append(`<div style="position: relative;">
                <a href="${data.redirect}" target="_blank" onclick="adsInit(${data.id})">
                    <img src="${data.image}" style="width: 100%">
                </a>
                <button onclick="closeADS(this);" style="position: absolute;top: 2px;right: 2px;border: none;border-radius: 50%;cursor: pointer;font-weight: 900;">X</button>
            </div>`);
            break;
        default:
            break;
    }
}
$(document).ready(function() {
    loader_advertise();
    try {
        scrollSmoothToBottom('list_chat');
    } catch (error) {}
    $('.btn-change-avatar').click(() => $('.choose-file-avatar').click());

    $('.choose-file-avatar').on('change', async(event) => {
        if (event.target.files && event.target.files[0]) {
            var file = event.target.files[0];
            const readers = new FileReader();
            readers.onload = function(e) {
                $(".avatarCrop").hide(150);
                $('.btn-change-avatar').hide(150);
                $('.croppie-btn').show(200);
                var cropper_avatar = $("#main-cropper").croppie({
                    viewport: { width: 200, height: 200, type: 'circle' },
                    boundary: { width: 300, height: 300 },
                    //showZoomer: true,
                    url: e.target.result,
                    enableExif: true,
                    enableOrientation: true
                });
                $("#main-cropper").croppie("bind", {
                    url: e.target.result
                });
            }
            readers.readAsDataURL(file);
        }
    }), $('.cancel-crop').click(function() {
        $(".avatarCrop").show(150);
        $('.btn-change-avatar').show(150);
        $('.croppie-btn').hide(200);
        $("#main-cropper").croppie('destroy');
    }), $('.done-crop').click(function() {
        $("#main-cropper").croppie("result", { type: 'base64' })
            .then(function(res) {
                $(".ui-avatar").attr("src", res);
                $('input[name=avatar]').val(res);
                $(".avatarCrop").show(150);
                $('.btn-change-avatar').show(150);
                $('.croppie-btn').hide(200);
                $("#main-cropper").croppie('destroy');
            });
    });
    //////////////////////
    $('.box_note .note_title i').on('click', function() {
        $('.box_note').hide();
        $('.box_note .note_content').html('');
    });
    /////////////////
    $('.toggle_chat').on('click', function() {
        if ($('.toggle_chat .fa-plus-circle').length > 0) {
            $('.toggle_chat .fa').removeClass('fa-plus-circle');
            $('.toggle_chat .fa').addClass('fa-minus-circle');
            $('.content_box_chat').animate({
                height: '500px'
            }, 500);
        } else {
            $('.toggle_chat .fa').removeClass('fa-minus-circle');
            $('.toggle_chat .fa').addClass('fa-plus-circle');
            $('.content_box_chat').animate({
                height: '267px'
            }, 500);
        }
    });
    /////////////////
    var lastScrollTop = 0,
        lastPage = 2;

    $('.list_chat').scroll(function() {
        if (lastPage == false) return;
        var st = $(this).scrollTop();
        if (st > lastScrollTop) {

        } else {
            load = $('input[name=load_chat]').val();
            loaded = $('input[name=load_chat]').attr('loaded');
            chat_id = $('.li_chat').first().attr('chat_id');
            if (st < 50 && loaded == 1 && load == 1) {
                $('.list_chat').prepend('<div class="li_load_chat"><i class="fa fa-spinner fa-spin"></i> Đang tải dữ liệu...</div>');
                $('input[name=load_chat]').attr('loaded', '0');
                setTimeout(async function() {
                    const { status, message } = await serverPost('load_chatbox', {
                        page: lastPage
                    });
                    if (status == false) {
                        apicodevn.toast({
                            title: "Thông báo từ hệ thống",
                            message: message,
                            status: "warning"
                        });
                        return;
                    }
                    $('.list_chat .li_load_chat').remove();
                    message.data ? $('.list_chat').prepend(message.data) : $('.list_chat').prepend('<div style="text-align: center;"><p style="font-weight: 600;color: #dd4c07;">Không còn dữ liệu nào khác</p></div>');
                    if (message.hasPage) {
                        lastPage += 1
                    } else {
                        lastPage = false;
                    }
                }, 1000);
            } else {

            }
        }
        lastScrollTop = st;

    });
    /////////////////
    $('.widget_right .load_more').on('click', function() {
        $(this).parent().find('ul').addClass('active');
        $(this).fadeOut(200);
    });
    $('.widget_right .list_tab .tab').on('click', function() {
        if ($(this).hasClass('active')) {

        } else {
            id = $(this).attr('id');
            $(this).parent().find('.tab').removeClass('active');
            $(this).addClass('active');
            $(this).parent().parent().find('li').hide();
            $(this).parent().parent().find('li.' + id).show();
        }
    });
    ////////////////////////
    $('#show_pop_register').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_register').fadeIn(300);
    });
    ////////////////////////
    $('#show_pop_login').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_login').fadeIn(300);
    });
    $('.show_pop_login').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_login').fadeIn(300);
    });
    $('.button_cancel').on('click', function() {
        $('.box_pop').fadeOut(300);
        $(this).parent().parent().parent().find('input').val('');
    });
    ////////////////////////
    $('.button_show_login').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_login').fadeIn(300);
    });
    ////////////////////////
    $('.button_show_register').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_register').fadeIn(300);
    });
    ////////////////////////
    $('#show_donate').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_donate').fadeIn(300);
    });
    ////////////////////////
    $('.block_content span').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_muachap').fadeIn(300);
    });
    ////////////////////////
    $('#show_report').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_report').fadeIn(300);
    });
    ////////////////////////
    $('.button_show_password').on('click', function() {
        $('.box_pop').fadeOut(300);
        $('#box_pop_password').fadeIn(300);
    });
    ////////////////////////
    $('.member_info .info').on('click', function() {
        $('.control_list').toggle();
    });
    $('.member_info .avatar').on('click', function() {
        $('.control_list').toggle();
    });
    ////////////////////////
    $('.list_tab_profile .li_tab').on('click', function() {
        $('.list_tab_profile .li_tab').removeClass('active');
        $(this).addClass('active');
        id = $(this).attr('id');
        $('.tab_profile_content .box_tab').removeClass('active');
        $('.tab_profile_content #' + id + '_content').addClass('active');
    });

    ////////////////////////
    $('input[name=input_search]').on('keyup', function() {

        key = $(this).val();
        if (key.length < 2) {
            $('.kq_search').hide();
            $('.clear-text-search').fadeOut(200);
        } else {
            $('.clear-text-search').fadeIn(200);
            $('.kq_search').show();
            $('.kq_search').html('<center><img src="/assets/images/loading.gif"></center>');
            $.ajax({
                url: '/graph/api',
                type: 'post',
                data: {
                    action: 'searchLive',
                    key: key
                },
                success: function(res) {
                    const { status, message } = res;
                    if (status == false) {
                        return;
                    }
                    $('.kq_search').html(message);
                }
            });
        }
    });
    /////////////////////////////
    $('input[name=input_search]').keypress(function(e) {
        if (e.which == 13) {
            key = $('input[name=input_search]').val();
            link = '/tim-kiem.html?key=' + encodeURI(key).replace(/%20/g, '+');
            if (key.length < 2) {
                $('input[name=input_search]').focus();
            } else {
                window.location.href = link;
            }
            return false;
        }
    });
    /////////////////////////////
    $('.box_search button[type=submit]').click(function() {
        key = $('input[name=input_search]').val();
        link = '/tim-kiem.html?key=' + encodeURI(key).replace(/%20/g, '+');
        if (key.length < 2) {
            $('input[name=input_search]').focus();
        } else {
            window.location.href = link;
        }
    });
    $('.button_menu').click(function() {
        $('.box_search').hide();
        $('.box_logo_mobile').toggle(300);
        $('.box_menu').fadeIn(300);
    });
    /////////////////////
    $('.box_logo_mobile i').click(function() {
        $('.box_logo_mobile').toggle();
        $('.box_menu').toggle(300);
        $('.li_main i').addClass('fa-angle-down');
        $('.li_main i').removeClass('fa-angle-up');
        $('.sub_menu').hide();
    });
    /////////////////////
    $('.li_main i').click(function() {
        $(this).parent().find('.sub_menu').toggle(300);
        if ($(this).hasClass('fa-angle-down')) {
            $(this).removeClass('fa-angle-down');
            $(this).addClass('fa-angle-up');
        } else {
            $(this).addClass('fa-angle-down');
            $(this).removeClass('fa-angle-up');
        }

    });
    /////////////////////
    let isBoxSearchOpen = false;
    $('.button_search').click(function() {
        if (!isBoxSearchOpen) {
            $(this).html('<i class="fa fa-close"></i>');
        } else {
            $(this).html('<i class="fa fa-search"></i>');
        }
        isBoxSearchOpen = !isBoxSearchOpen;
        $('.box_search').toggle(300);
        $('.box_logo_mobile').hide();
        $('.box_menu').hide();
    });
    /////////////////////
    $('.select_chap').on('change', function() {
        value = $(this).val();
        window.location.href = value;
    });
    ////////////////////////
    $('.light-see').click(function() {
        $('body').toggleClass('chap_view');
        if ($('body').hasClass('chap_view')) {
            $('.light-see').html('<i class="fa fa-lightbulb" style="color:#000;"></i> <span>Bật đèn</span>');
        } else {
            $('.light-see').html('<i class="fa fa-lightbulb"></i> <span>Tắt đèn</span>');
        }
    });
    $('.light-see-header').click(function() {
        $('body').toggleClass('chap_view');
        if ($('body').hasClass('chap_view')) {
            $(this).html('<i class="fa fa-lightbulb" style="color:#000"></i>');
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
            $(this).html('<i class="fa fa-lightbulb" style="color:#ee4c22;"></i>');
        }
    });
    var dataDark = getLocalStorage('dark-mode') ? getLocalStorage('dark-mode') : { dark: false };
    if (dataDark.dark == true) {
        $('.btn-dark-mode').addClass('active');
        $('.btn-dark-mode').html('<i class="fa fa-lightbulb" style="color:#1b1f53;"></i>');
        $('body').addClass('darkMode');
    }
    $('.btn-dark-mode').click(function() {
        if ($('body').hasClass('darkMode')) {
            $(this).html('<i class="fa fa-lightbulb" style="color:#ee4c22"></i>');
            $(this).removeClass('active');
            $('body').removeClass('darkMode');
            dataDark.dark = false;
        } else {
            $(this).addClass('active');
            $(this).html('<i class="fa fa-lightbulb" style="color:#1b1f53;"></i>');
            $('body').addClass('darkMode');
            dataDark.dark = true;
        }
        insertLocalStorage('dark-mode', dataDark);
    });
    ////////////////////////
    $("body").keydown(function(e) {
        if ($('.content_view_chap').length > 0) {
            if (e.keyCode == 37) {
                if ($('.link-prev-chap').length > 0) {
                    link = $('.link-prev-chap').attr('href');
                    window.location.href = link;

                }
            } else if (e.keyCode == 39) {
                if ($('.link-next-chap').length > 0) {
                    link = $('.link-next-chap').attr('href');
                    window.location.href = link;
                }
            }
        } else {

        }
    });
    ////////////////////////
    $('.list_server').on('click', 'a', function() {
        $('.list_server a').removeClass('bg_green');
        $(this).addClass('bg_green');
        truyen = $(this).attr("truyen");
        chap = $(this).attr("chap");
        server = $(this).attr("server");
        $('.content_view_chap').html('<div class="load_content"></div>');
        $.ajax({
            url: "/graph/api",
            type: "post",
            data: {
                action: "load_img",
                truyen: truyen,
                server: server,
                chap: chap
            },
            success: function(res) {
                const { status, message } = res;
                if (status == false) {
                    $('.load_note').html(message);
                    return;
                }
                setTimeout(function() {
                    $('.content_view_chap').html(message);
                }, 500);
            }
        });
    });
    $(document).on('submit', 'form[submit-server=comic]', function(e) {
        e.preventDefault();
        var _this = $(this),
            action = _this.attr('action'),
            show_message = _this.attr('show-message') || true,
            form_data = _this.serialize(),
            btn = _this.find('button[type=submit]');

        console.log(show_message);
        btn.prop('disabled', true);
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang chờ phía hệ thống xử lý ....',
            status: "loading"
        });
        $.post(`/graph/api?action=${action}`, form_data).done(function(res) {
            const { status, message } = res;
            btn.prop('disabled', false);
            if (status == false) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: message,
                    status: "warning"
                });
                return;
            }
            if (show_message == true) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: message,
                    status: "success"
                }).then(function() {
                    location.reload();
                });
            } else {
                location.reload();
            }
        });
    }), $('#button_follow').click(async function() {
        var _this = $(this),
            comicId = _this.attr('data-id');
        _this.html('Đang xử lý...');
        if ($users.fullname) {
            const { status, message } = await serverPost('followComic', {
                comicId
            });
            if (status == false) {
                _this.removeClass('bg_red').addClass('bg_follow').html('<i class="fa fa-bookmark"></i> <span>Theo dõi</span>');
                return;
            }
            _this.removeClass('bg_follow').addClass('bg_red').html('<i class="fa fa-close"></i> <span>Huỷ theo dõi</span>');
        } else {
            const followers = getLocalStorage('users_follow') ? getLocalStorage('users_follow') : [];
            if (followers.includes(comicId)) {
                _this.removeClass('bg_red').addClass('bg_follow').html('<i class="fa fa-bookmark"></i> <span>Theo dõi</span>');
                const index = followers.indexOf(comicId);
                followers.splice(index, 1);
            } else {
                followers.push(comicId);
                _this.removeClass('bg_follow').addClass('bg_red').html('<i class="fa fa-close"></i> <span>Huỷ theo dõi</span>');
            }
            insertLocalStorage('users_follow', followers);
            return;
        }


    }), $('#button_comment').click(async function() {
        var _this = $(this),
            comicId = _this.attr('data-id'),
            chapterId = _this.attr('data-chapter');
        var comment_text = $('.comment_text_value').val();
        if (!comment_text) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: 'Vui lòng nhập nội dung comment',
                status: "danger"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang xử lý comment của bạn ....',
            status: "loading"
        });
        const { status, message } = await serverPost('comment_to_comic', {
            comicId,
            chapterId,
            comment_text
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.remove_alert();
        // apicodevn.toast({
        //     title: "Thông báo từ hệ thống",
        //     message: message,
        //     status: "success"
        // }).then(function() {
        //     location.reload();
        // });
        $('.comment_text_value').val('');
        $('.list_comment').html(message);
    }), $('.list_comment').on('click', '.reply', async function() {
        const id = $(this).attr('id_comment');
        if ($(this).parent().parent().find('.text_area_sub').length > 0) {
            $(this).parent().parent().find('.text_area_sub').remove();
        } else {
            $('.list_comment .text_area_sub').remove();
            $(this).parent().after('<div class="text_area_sub"><textarea class="sub_comment_text" placeholder="Nội dung bình luận..."></textarea><svg id="button_sub_comment" id_comment="' + id + '" class="svg-inline--fa fa-paper-plane fa-w-16" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="paper-plane" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M476 3.2L12.5 270.6c-18.1 10.4-15.8 35.6 2.2 43.2L121 358.4l287.3-253.2c5.5-4.9 13.3 2.6 8.6 8.3L176 407v80.5c0 23.6 28.5 32.9 42.5 15.8L282 426l124.6 52.2c14.2 6 30.4-2.9 33-18.2l72-432C515 7.8 493.3-6.8 476 3.2z"></path></svg><button type="button" class="btn-emjoi" data-type="subComment" style="bottom: 8px;"><img src="/assets/images/725107.png" alt=""></button></div>');
        }
    }), $('.list_comment').on('click', '#button_sub_comment', async function() {
        var _this = $(this),
            replyId = _this.attr('id_comment'),
            comment_text = _this.parent().find('.sub_comment_text').val();
        if (!comment_text) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: 'Vui lòng nhập nội dung comment',
                status: "danger"
            });
            return;
        }
        const { status, message } = await serverPost('replyComment', {
            replyId,
            comment_text
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        _this.parent().parent().parent().find('.list_sub_comment').html(message);
        const area_sub = _this.closest(".text_area_sub");
        area_sub.hide(300).remove();
    }), $('.show_reply').click(async function() {
        var commentId = $(this).attr('id_comment');
        const { status, message } = await serverPost('getCommentReply', {
            commentId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        $(this).parent().parent().parent().find('.list_sub_comment').html(message);
        $(this).hide(300).remove();
    }), $('.list_comment').on('click', '.del_sub_comment', async function() {
        var commentId = $(this).attr('id_comment');
        const { status, message } = await serverPost('deleteComment', {
            commentId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        $(this).closest(".li_sub_comment").hide(300).remove();
    }), $('.list_comment').on('click', '.del_comment', async function() {
        var commentId = $(this).attr('id_comment');
        const { status, message } = await serverPost('deleteComment', {
            commentId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        $(this).closest(".li_comment").hide(300).remove();
    }), $('.list_comment').on('click', '.commentEditor', function() {
        if (!$users.fullname) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: `Bạn chưa đăng nhập`,
                status: "info"
            });
            return;
        }
        var commentId = $(this).attr('id_comment');
        if ($(this).closest(".li_sub_comment").hasClass("li_sub_comment")) {
            var comment_text = $(this).closest(".li_sub_comment").find('.text_sub_comment');
        } else {
            var comment_text = $(this).closest(".li_comment").find('.text_comment');
        }
        apicodevn.toast({
            title: "Chỉnh sửa comment",
            message: `<div style="text-align: center;"><textarea class="commentEdit" placeholder="Nội dung bình luận...">${comment_text.text()}</textarea><button type="button" class="btn-update-comment" data-comment="${commentId}">Cập nhật</button></div>`,
            status: "warning"
        });

        $(document).on('click', '.btn-update-comment', async function() {
            $(this).prop('disabled', true);
            var commentId = $(this).attr('data-comment'),
                comment_value = $(this).closest('div').find('.commentEdit').val();
            apicodevn.remove_alert();
            const { status, message } = await serverPost('updateCommentUsers', {
                commentId,
                comment_value
            });
            if (status == false) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: message,
                    status: "warning"
                });
                return;
            }
            comment_text.text(comment_value);
        });

    }), $('#chat_text').on('keypress', async function(e) {
        if (e.keyCode == 13) {
            var noidung = $(this).val();
            if (noidung.length > 250) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: 'Nội dung bạn nhập quá dài tối đa 250 ký tự',
                    status: "danger"
                });
                return;
            }
            if (!noidung) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: 'Vui lòng nhập nội dung bạn muốn chat',
                    status: "danger"
                });
                return;
            }
            $(this).val('Đang xử lý ....');
            const { status, message } = await serverPost('chatbox_send', {
                noidung
            });
            $(this).val('');
            if (status == false) {
                apicodevn.toast({
                    title: "Thông báo từ hệ thống",
                    message: message,
                    status: "warning"
                });
                return;
            }
            $('.list_chat').append(message);
            scrollSmoothToBottom('list_chat');
        }
    }), $('#boxChat-btn').click(async function() {
        var noidung = $('#chat_text').val();
        var _this = $(this);
        if (noidung.length > 250) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: 'Nội dung bạn nhập quá dài tối đa 250 ký tự',
                status: "danger"
            });
            return;
        }
        if (!noidung) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: 'Vui lòng nhập nội dung bạn muốn chat',
                status: "danger"
            });
            return;
        }
        $('#chat_text').val('');
        _this.prop('disabled', true);
        const { status, message } = await serverPost('chatbox_send', {
            noidung
        });
        _this.prop('disabled', false);
        $('#chat_text').val('');
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        $('.list_chat').append(message);
        scrollSmoothToBottom('list_chat');
    }), $('.btnChangerServer').click(async function() {
        const server = $(this).attr('data-server');
        $('body').attr('data-server', server);
        if ($(this).hasClass('active-server')) {
            return;
        }
        $('.btnChangerServer').removeClass('active-server');
        $(this).addClass('active-server');
        comic_load_image();

    }), $('#add_premium').click(async() => {
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang xử lý gói cước của bạn vui lòng chờ ....',
            status: "loading"
        });
        var pricingId = $('select[name=pricing_premium]').val();
        const { status, message } = await serverPost('pricing_update', {
            pricingId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });
    }), $('.upload_button').click(function() {
        var _this = $(this),
            results = _this.attr('data-result');
        var file_input = $('<input>');
        file_input.attr('type', "file");
        file_input.click();
        file_input.on('change', async function(event) {
            $(results).val('Đang xử lý vui lòng chờ.....');
            var files = event.target.files;
            if (files.length === 0) {
                $(results).val('');
                return;
            }
            var uploadData = new FormData();
            uploadData.append('image', files[0]);
            _this.prop('disabled', true);
            $(results).prop('readonly', true);
            $.ajax({
                url: '/graph/api?action=upload-images',
                type: 'post',
                data: uploadData,
                contentType: false,
                processData: false,
                success: function(res) {
                    _this.prop('disabled', false);
                    const { status, message } = res;
                    if (status == false) {
                        $(results).prop('readonly', false).val('Tải lên không thành công');
                        _this.prop('disabled', false);
                        return
                    }
                    _this.hide(200);
                    $(results).val(message);
                },
                error: function() {
                    $(results).prop('readonly', false).val('Tải lên không thành công');
                    _this.prop('disabled', false);
                }
            });
        });
    }), $('.btn-removeComic').click(async function() {
        const comicId = $(this).attr('data-id');
        const { status, message } = await serverPost('removeComic', {
            comicId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });

    }), $('.btn-removeChapter').click(async function() {
        const chapterId = $(this).attr('data-id');
        const { status, message } = await serverPost('removeChapters', {
            chapterId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });

    }), $('.btn-removeServerChapter').click(async function() {
        const serverId = $(this).attr('data-id');
        const chapterId = $(this).attr('data-chapter');
        const { status, message } = await serverPost('removeChapterServer', {
            chapterId,
            serverId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });

    }), $('.btn-add-server').click(function() {
        var chapterId = $(this).attr('data-id');
        var lock_images = $(this).attr('data-lock');
        apicodevn.toast({
            title: "Thêm server mới",
            message: `<form submit-server="comic" action="add_chapter_server" class="mb-4">
                        <input type="hidden" name="chapterId" value="${chapterId}">
                        <div class="li_input">
                            <label for="">Tên server:</label>
                            <input type="text" class="form-control" name="server_name">
                        </div>
                        <div class="li_input relative">
                            <label for="">Danh sách hình ảnh:</label>
                            <textarea type="text" class="form-control" style="height: 100px;" name="server_data" placeholder="Mỗi dòng 1 link ảnh"></textarea>
                            <button type="button" class="btn-upload-server" data-type="storage-cdn" data-lock="${lock_images}" chapterId="${chapterId}"><i class="fa-solid fa-cloud-arrow-up"></i> SERVER 1</button>
                            <button type="button" style="right: 9em;" class="btn-upload-server" data-type="localfile" data-lock="${lock_images}" chapterId="${chapterId}"><i class="fa-solid fa-cloud-arrow-up"></i> SERVER 2</button>
                        </div>
                        <div class="li_input">
                            <button type="submit" class="btn btn-success">Thêm server mới</button>
                        </div>
                    </form>`,
            status: "info"
        });
    }), $('.btn-add-chapter').click(function() {
        var comicId = $(this).attr('data-id');
        var chapnumb = $(this).attr('data-numb');
        apicodevn.toast({
            title: "Thêm chapter mới",
            message: `<form submit-server="comic" action="add_chapter_comic" class="mb-4">
                        <input type="hidden" name="comicId" value="${comicId}">
                        <div class="form-group col-lg-12 mb-2">
                            <label for="">Số thứ tự</label>
                            <input type="number" class="form-control" name="numb" step="any" value="${chapnumb}" required>
                        </div>
                        <div class="li_input">
                            <label for="">Tên Chapter:</label>
                            <input type="text" class="form-control" name="chapter_name">
                        </div>
                        <div class="li_input">
                            <label for="">Level yêu cầu</label>
                            <input type="number" class="form-control" name="block_level" value="0" required>
                        </div>
                        <div class="li_input">
                            <label for="">Chỉ mua mới được xem:</label>
                            <select class="form-control" name="onlyPurchase">
                                <option value="0">Không</option>
                                <option value="1">Có</option>
                            </select>
                        </div>
                        <div class="li_input">
                            <label for="">Số coin mua chap:</label>
                            <input type="number" class="form-control" name="coin">
                        </div>
                        <div class="li_input">
                            <label>Ẩn / Hiện</label>
                            <select class="form-control" name="chapterType">
                                <option value="1">Hiển thị</option>
                                <option value="0">Ẩn</option>
                            </select>
                        </div>
                        <div class="li_input">
                            <label>Mã hoá hình ảnh</label>
                            <select class="form-control" name="leechBlock">
                                <option value="0">Không</option>
                                <option value="1">Có</option>
                            </select>
                        </div>
                        <div class="li_input">
                            <button type="submit" class="btn btn-success">Thêm chapter mới</button>
                        </div>
                    </form>`,
            status: "info"
        });
    }), $('.purchaseChapter').click(async function() {
        const chapterId = $(this).attr('data-id');
        const { status, message } = await serverPost('purchaseChapter', {
            chapterId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });
    }), $(window).on('scroll', function() {
        var scrollTop = $(window).scrollTop();
        var windowHeight = $(window).innerHeight();
        (scrollTop > (windowHeight / 2) ? $('.btn-scrool-top').fadeIn(300) : $('.btn-scrool-top').fadeOut(300));
        try {
            var hide_fixed = hidenFixed;
        } catch (error) {
            var hide_fixed = false;
        }
        if (!hide_fixed) {
            if (scrollTop > 0) {
                $('.box_header').addClass('fixed-menu'); // Thêm lớp CSS khi cuộn trang
            } else {
                $('.box_header').removeClass('fixed-menu'); // Xóa lớp CSS khi không cuộn trang
            }
        }
    }), $('.btn-scrool-top').on('click', function() {
        $(this).fadeOut(300);
        $('html, body').animate({ scrollTop: 0 }, 300); // Cuộn lên đầu trang khi click vào nút Scroll to Top
    }), $('.reload_chat').click(async function() {
        $(this).addClass('fa-spin');
        const { status, message } = await serverPost('load_chatbox', {
            page: 1
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        $('.list_chat .li_load_chat').remove();
        message.data ? $('.list_chat').html(message.data) : $('.list_chat').html('<div style="text-align: center;"><p style="font-weight: 600;color: #dd4c07;">Không còn dữ liệu nào khác</p></div>');
        scrollSmoothToBottom('list_chat');
        $(this).removeClass('fa-spin');
    }), $(document).on('click', function(event) {
        var target = $(event.target);
        if (!target.closest('.box_search').length) {
            $('.kq_search').slideUp(300).empty();
        }
        if (!target.closest('.control_list').length && !target.closest('.member_info').length) {
            $('.control_list').slideUp(300);
        }
        if ($(document).width() + 13 <= 1022) {
            if (!target.closest('.main_menu').length && !target.closest('.button_menu').length) {
                $('.box_menu').fadeOut(200);
                $('.box_logo_mobile').fadeOut(200);
            }
        }
    }), $('.box_pop').click(function(event) {
        var target = $(event.target);
        if (!target.closest('.box_pop_content').length) {
            $('.box_pop').fadeOut(200);
        }
    }), $('.clear-text-search').click(function() {
        $('input[name=input_search]').val('');
        $(this).fadeOut(200);
        $('.kq_search').slideUp(200);
    }), $('.view-more-comment').click(async function() {
        var page = parseInt($(this).attr('data-page'));
        var comicId = $('body').attr('data-id');
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang chờ phía hệ thống xử lý ....',
            status: "loading"
        });
        const { status, message } = await serverPost('load_comment_page', {
            page,
            comicId
        });
        apicodevn.remove_alert();
        if (status == false) return;
        if (message.hasNext) {
            page++;
            $(this).attr('data-page', page);
        } else {
            $(this).fadeOut(200);
        }
        $('.list_comment').append(message.data);
    }), $('.view-more-reply').click(async function() {
        var page = parseInt($(this).attr('data-page'));
        var commentId = $(this).attr('data-id');
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang chờ phía hệ thống xử lý ....',
            status: "loading"
        });
        const { status, message } = await serverPost('load_reply_page', {
            page,
            commentId
        });
        apicodevn.remove_alert();
        if (status == false) return;
        if (message.hasNext) {
            page++;
            $(this).attr('data-page', page);
        } else {
            $(this).fadeOut(200);
        }
        $(this).closest(".list_sub_comment").append(message.data);
    }), $('.boxchat-reply').click(function() {
        var username = $(this).attr('data-username');
        $('#chat_text').val(`@${username}  `);
    }), $('.scrool-element').click(function() {
        var element = $(this).attr('data-element');
        $('html, body').animate({
            scrollTop: $(element).offset().top
        }, 800);
    }), $('.filter-loads-comment').click(async function() {
        var page = parseInt($(this).attr('data-page') || 1);
        var chapterId = $(this).attr('data-id');
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang chờ phía hệ thống xử lý ....',
            status: "loading"
        });
        $('.view-more-comment').hide();
        $('.filter-loads-viewmore').show();
        const { status, message } = await serverPost('filter-chapter-comment', {
            page,
            chapterId
        });
        $(this).fadeOut(150);
        apicodevn.remove_alert();
        if (status == false) return;
        if (message.hasNext) {
            page++;
            $(this).attr('data-page', page);
        } else {
            $(this).fadeOut(200);
        }
        $('.list_comment').empty().append(message.data);
    }), $('.filter-loads-viewmore').click(async function() {
        var page = parseInt($(this).attr('data-page') || 1);
        var chapterId = $(this).attr('data-id');
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang chờ phía hệ thống xử lý ....',
            status: "loading"
        });
        $('.view-more-comment').hide();
        $('.filter-loads-viewmore').show();
        const { status, message } = await serverPost('filter-chapter-comment', {
            page,
            chapterId
        });
        apicodevn.remove_alert();
        if (status == false) return;
        if (message.hasNext) {
            page++;
            $(this).attr('data-page', page);
        } else {
            $(this).fadeOut(200);
        }
        if (page <= 1) {
            $('.list_comment').empty().append(message.data);
        } else {
            $('.list_comment').append(message.data);
        }
    }), $('.btn-load-comment').click(async function() {
        var _this = $(this);
        const comicId = _this.attr('data-id');
        _this.addClass('fa-spin');
        const { status, message } = await serverPost('load_comment_page', {
            page: 1,
            comicId
        });
        _this.removeClass('fa-spin');
        if (status == false) return;
        $('.list_comment').html(message.data);
    }), $('.btn-right-comment').click(async function() {
        var _this = $(this);
        _this.addClass('fa-spin');
        const { status, message } = await serverPost('load_comment_sidebar');
        _this.removeClass('fa-spin');
        if (status == false) return;
        $('.comment-sidebar').html(message.data);
    }), $('.show-password').click(function() {
        var _this = $(this);
        if (_this.hasClass('show')) {
            _this.find('i').removeClass('fa-eye-slash').addClass('fa-eye');
            var password = _this.parent().find('.passwordHind');
            password.attr('type', 'password');
            _this.removeClass('show');
            password.removeClass('passwordHind');
            return
        }
        _this.find('i').removeClass('fa-eye').addClass('fa-eye-slash');
        var password = _this.parent().find('input[type=password]');
        _this.addClass('show');
        password.addClass('passwordHind');
        password.attr('type', 'text');
    }), $('.btn-upload-image').click(function() {
        var _this = $(this);
        var results = $('input[name=transCover]');
        var file_input = $('<input>');
        file_input.attr('type', 'file').attr('name', 'image').attr('accept', 'image/*');
        file_input.click();
        file_input.on('change', async function(event) {
            $(results).val('Đang xử lý vui lòng chờ.....');
            var files = event.target.files;
            if (files.length === 0) {
                $(results).val('');
                return;
            }
            var uploadData = new FormData();
            uploadData.append('image', files[0]);
            _this.prop('disabled', true);
            $(results).prop('readonly', true);
            $.ajax({
                url: '/graph/api?action=upload-images',
                type: 'post',
                data: uploadData,
                contentType: false,
                processData: false,
                success: function(res) {
                    _this.prop('disabled', false);
                    const { status, message } = res;
                    if (status == false) {
                        $(results).prop('readonly', false).val('Tải lên không thành công');
                        _this.prop('disabled', false);
                        return
                    }
                    _this.hide(200);
                    $(results).val(message);
                },
                error: function() {
                    $(results).prop('readonly', false).val('Tải lên không thành công');
                    _this.prop('disabled', false);
                }
            });
        });
    }), $(document).on('click', '.btn-popup-close', function() {
        $('.popupContainer').fadeOut(300);
    });
    try {
        new FgEmojiPicker({
            trigger: ['.btn-emjoi'],
            position: ['bottom', 'right'],
            emit(obj, button) {
                console.log(button);
                const typeCmt = $(button).attr('data-type');
                const emoji = obj.emoji;
                if (typeCmt == 'commentInfo') {
                    const input = $(button).closest('.text_area').find('.comment_text_value');
                    $(input).val($(input).val() + emoji);
                } else if (typeCmt == 'chat_box') {
                    const input = $(button).closest('.input_chat').find('#chat_text');
                    $(input).val($(input).val() + emoji);
                } else if (typeCmt == 'subComment') {
                    const input = $(button).closest('.text_area_sub').find('.sub_comment_text');
                    $(input).val($(input).val() + emoji);
                }

            }
        });
    } catch (error) {}
    $(document).on('click', '.sendComment', async function() {
        var _this = $(this),
            postId = _this.attr('data-id'),
            content = $('textarea[name=content]').val();

        if (content == '') {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: 'Vui lòng điền nội dung cần bình luận',
                status: "warning"
            });
            return;
        }
        _this.prop('disabled', true).html('Đang xử lý ...');
        const { status, message } = await serverPost('formComment-add', {
            postId,
            content
        });
        _this.prop('disabled', false).html(`<i class="fa-solid fa-paper-plane"></i> Gửi bình luận`);
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        tinymce.activeEditor.setContent("");
        $('.comment-forum-list').html(message);
    }), $(document).on('click', '.forum-cmt-reply', async function() {
        var _this = $(this);
        var action = _this.closest('.action');
        var commentId = _this.attr('data-id');

        if (_this.hasClass('activeReply')) {
            action.find('.comment-forum-editor').remove();
            _this.removeClass('activeReply');
            return;
        }

        if (action.find('.comment-forum-editor').length >= 1) return;
        action.append(`<div class="comment-forum-editor">
                            <textarea type="text" class="form-control editor" name="content" placeholder="Vui lòng nhập bình luận của bạn vào đây ...."></textarea>
                            <button type="button" class="mt-1 send_reply_comment" data-id="${commentId}">Gửi bình luận</button>
                        </div>`);
        tinymceLoad();
        _this.addClass('activeReply');

        $(document).on('click', '.send_reply_comment', async function() {
            var _this1 = $(this),
                commentId = _this1.attr('data-id'),
                content = action.find('textarea[name=content]').val();
            if (content == '') {
                apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Vui lòng điền nội dung cần bình luận', status: "warning" });
                return;
            }
            tinymce.activeEditor.setContent("");
            action.find('.comment-forum-editor').remove();
            _this.removeClass('activeReply');
            _this1.prop('disabled', true).html('Đang xử lý ...');
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ..', status: "loading" });
            const { status, message } = await serverPost('formComment-repTo', {
                commentId,
                content
            });
            _this1.prop('disabled', false).html('Gửi trả lời');
            if (status == false) {
                apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
                return;
            }
            apicodevn.remove_alert();
            tinymce.activeEditor.setContent("");
            action.closest('.comment-forum-infor').find('.comment-forum-list:eq(0)').html(message);
            _this.removeClass('activeReply');
        });

    }), $(document).on('click', '.forum-cmt-remove', async function() {
        var _this = $(this),
            commentId = _this.attr('data-id');
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: 'Đang thực hiện xoá',
            status: "loading"
        });
        const { status, message } = await serverPost('formComment-remove', {
            commentId
        });
        if (status == false) {
            apicodevn.toast({
                title: "Thông báo từ hệ thống",
                message: message,
                status: "warning"
            });
            return;
        }
        apicodevn.remove_alert();
        _this.closest('.comment-forum-item').remove();
    }), $(document).on('click', '.forum-cmt-edit', async function() {
        var _this = $(this),
            commentId = _this.attr('data-id'),
            content = _this.parent().parent().find('.content').html(),
            action = _this.closest('.action');

        if (_this.hasClass('activeReply')) {
            action.find('.comment-forum-editor').remove();
            _this.removeClass('activeReply');
            return;
        }

        if (action.find('.comment-forum-editor').length >= 1) return;

        action.append(`<div class="comment-forum-editor">
                        <textarea type="text" class="form-control editor" name="content" placeholder="Vui lòng nhập bình luận của bạn vào đây ....">${content}</textarea>
                        <button type="button" class="mt-1 UpdateComment" data-id="${commentId}">Cập nhật chỉnh sửa</button>
                    </div>`);
        tinymceLoad();
        _this.addClass('activeReply');

        $(document).on('click', '.UpdateComment', async function() {
            var bodyUpdate = $(this),
                commentId = bodyUpdate.attr('data-id'),
                content = action.find('textarea[name=content]').val();

            if (content == '') {
                apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Vui lòng điền nội dung cần bình luận', status: "warning" });
                return;
            }
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ..', status: "loading" });
            const { status, message } = await serverPost('formComment-update', { commentId, content });
            if (status == false) {
                apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
                return;
            }
            apicodevn.remove_alert();
            bodyUpdate.closest('.comment-forum-infor').find('.content:eq(0)').html(message);
            action.find('.comment-forum-editor').remove();
            _this.removeClass('activeReply');
        });
    }), $('.toogle-button').click(function() {
        var _this = $(this),
            text_btn = _this.text(),
            toogleBody = _this.attr('data-body');
        if (_this.hasClass('active')) {
            $(toogleBody).slideUp(300);
            _this.removeClass('active');
            _this.html(`${text_btn} <img class="icon" src="/images/4115426.png">`);
            return;
        }
        $(toogleBody).slideDown(300);
        _this.addClass('active');
        _this.html(`${text_btn} <img class="icon" src="/images/4115431.png">`);
    }), $(document).on('click', '.button-action', async function() {
        var actionText = $(this).attr('action'),
            dataId = $(this).attr('data-id');
        apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ....', status: "loading" });
        const { status, message } = await serverPost(actionText, {
            dataId
        });
        if (status == false) {
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
            return;
        }
        apicodevn.remove_alert();
        if (actionText == 'remove-topic') {
            $(this).closest('.label-item').remove();
        } else if (actionText == 'edit-topic') {
            var editor = $(this).closest('.label-info');
            editor.html(`<form submit-server="comic" action="update-topic">
                <input type="text" style="display: none;" name="topicId" value="${message.id}">
                <div class="form-group">
                    <label for="">Tên chủ đề</label>
                    <input type="text" class="form-control" name="name" value="${message.name}">
                </div>
                <div class="form-group">
                    <label for="">Mô tả chủ đề</label>
                    <input type="text" class="form-control" name="description" value="${message.description}">
                </div>
                <div class="form-group">
                    <label for="">Liên kết hình ảnh</label>
                    <input type="text" class="form-control" name="icon" value="${message.icon}">
                </div>
                <div class="form-group">
                    <label for="">Pin top</label>
                    <select class="form-control" name="pin">
                        <option value="1" ${message.pin == 1 ? 'selected' : ''}>Có</option>
                        <option value="0" ${message.pin == 0 ? 'selected' : ''}>Không</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="">Ai có thể đăng bài viết</label>
                    <select class="form-control" name="is_admin">
                        <option value="1" ${message.is_admin == 1 ? 'selected' : ''}>Chỉ admin</option>
                        <option value="0" ${message.is_admin == 0 ? 'selected' : ''}>Mọi người</option>
                    </select>
                </div>
                <div class="form-group text-center">
                    <button type="submit" class="btn-g btn-gradient">Cập nhật</button>
                </div>
            </form>`);
        }
    }), $(document).on('click', '.post-edit', async function() {
        var dataId = $(this).attr('data-id');
        $(this).remove();
        apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ....', status: "loading" });
        const { status, message } = await serverPost('post-editer', {
            dataId
        });
        if (status == false) {
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
            return;
        }
        apicodevn.remove_alert();
        $('#editor-post').fadeIn(200).html(`<form submit-server="comic" action="update-post-arcile">
                    <input type="text" style="display: none;" name="postId" value="${message.id}">
                    <div class="form-group">
                        <label for="">Tiêu đề bài viết</label>
                        <input type="text" class="form-control" name="title" value="${message.title}">
                    </div>
                    <div class="form-group">
                        <label for="">Ảnh mô tả</label>
                        <input type="text" class="form-control" name="image" placeholder="Liên kết hình ảnh" value="${message.image}">
                    </div>
                    <div class="form-group">
                        <label for="">Nội dung</label>
                        <textarea type="text" class="form-control editor" name="content" placeholder="Nội dung cần chia sẻ">${message.content}</textarea>
                    </div>

                    <div class="form-group text-center mt-1">
                        <button type="submit" class="btn-g btn-gradient">Cập nhật bài viết</button>
                    </div>
                </form>`);
        tinymceLoad();
    }), $(document).on('click', '.post-remove', async function() {
        var dataId = $(this).attr('data-id');
        apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ....', status: "loading" });
        const { status, message } = await serverPost('post-remove', {
            dataId
        });
        if (status == false) {
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        }).then(function() {
            location.reload();
        });
    }), $(document).on('click', '.btnDiemdanh', async function() {
        $(this).prop('disabled', true);
        apicodevn.toast({ title: "Thông báo từ hệ thống", message: 'Đang xử lý vui lòng chờ ....', status: "loading" });
        const { status, message } = await serverPost('diem-danh-hang-ngay');
        if (status == false) {
            apicodevn.toast({ title: "Thông báo từ hệ thống", message: message, status: "warning" });
            $(this).html(`Đã điểm danh <img class="icon" src="/images/5290058.png"/>`);
            return;
        }
        apicodevn.toast({
            title: "Thông báo từ hệ thống",
            message: message,
            status: "success"
        });
        $(this).html(`Đã điểm danh <img class="icon" src="/images/5290058.png"/>`);
    });
    var current_server = 1;
    $('.server-change').click(function() {
        var _this = $(this);
        var body = $('body');
        var button_server = $('.btnChangerServer');
        button_server.removeClass('active-server');
        if (count_server <= 0) return;
        if (current_server >= count_server) {
            current_server = 1;
            body.attr('data-server', current_server);
            _this.find('span').text(current_server);
            button_server.eq(current_server - 1).addClass('active-server');
        } else {
            current_server++;
            body.attr('data-server', current_server);
            _this.find('span').text(current_server);
            button_server.eq(current_server - 1).addClass('active-server');
        }
        comic_load_image();
    });
});