var lazyImgs = $(".lazyimg");
if (lazyImgs.length > 0) {
    if (lazyImgs.lazyload) {
        lazyImgs.lazyload({ effect: "fadeIn" });
    }
}
var popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
var popoverLength = popoverTriggerList.length;
if (popoverLength > 0) {
    var popoverList = [...popoverTriggerList].map((popoverTriggerEl, i) => {
        popoverTriggerEl.id = 'popover' + i;
        new bootstrap.Popover(popoverTriggerEl);
    });
    for (var i = 0; i < popoverLength; i++) {
        popoverTriggerList[i].addEventListener('click', function () {
            for (var j = 0; j < popoverLength; j++) {
                if (popoverTriggerList[j].id != this.id) {
                    var popover = bootstrap.Popover.getOrCreateInstance('#popover' + j);
                    if (popover) {
                        popover.hide();
                    }
                }
            }
        });
    }
}

function postJson(url, data, success, error) {
    $.ajax({
        type: "post",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: success,
        error: error
    });
}
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
}
String.prototype.endWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substring(this.length - str.length) == str)
        return true;
    else
        return false;
    return true;
}
String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}

function searchArticle() {
    var searchWord = $('#searchArticleWord').val().trim();
    if (searchWord != '') {
        document.location = '/Articles/Search?wd=' + encodeURIComponent(searchWord);
    } else {
        $('#searchArticleWord').val('');
    }
}

function searchArticleEnter() {
    if (event.keyCode == '13') {
        searchArticle();
    }
}
function searchPost() {
    var searchWord = $('#searchPostWord').val().trim();
    if (searchWord != '') {
        document.location = '/Forums/Search?wd=' + encodeURIComponent(searchWord);
    } else {
        $('#searchPostWord').val('');
    }
}

function searchPostEnter() {
    if (event.keyCode == '13') {
        searchPost();
    }
}

var curr = 0;
var fiLength = 0;
function run() {
    if (curr >= fiLength - 1) {
        $('.flashimages-container a:eq(' + curr + ')').hide();
        $('.flashimages-container a:eq(0)').show();
        $('.flashimages-description span:eq(' + curr + ')').hide();
        $('.flashimages-description span:eq(0)').show();
    } else {
        $('.flashimages-container a:eq(' + curr + ')').hide();
        $('.flashimages-container a:eq(' + (curr + 1) + ')').show();
        $('.flashimages-description span:eq(' + curr + ')').hide();
        $('.flashimages-description span:eq(' + (curr + 1) + ')').show();
    }
    curr++;
    if (curr >= fiLength) curr = 0;
    setTimeout(run, 3000);
}
$(function () {
    fiLength = $('.flashimages .flashimages-container a').length;
    if (fiLength > 1) {
        setTimeout(run, 3000);
    }
    var contentImages = $('.content-image');
    if (contentImages.length > 0) {
        var imageModelEl = document.getElementById('images-modal');
        contentImages.click(function () {
            if (imageModelEl) {
                const imagesModal = new bootstrap.Modal(imageModelEl);
                var imageId = $(this).attr('data-image-id');
                $('#images-modal .carousel-indicators button').removeClass('active');
                $('#images-modal .carousel-indicators button').eq(imageId).addClass('active');
                $('#images-modal .carousel-indicators button').removeAttr('aria-current');
                $('#images-modal .carousel-indicators button').eq(imageId).attr('aria-current', true);
                $('#images-modal .carousel-item').removeClass('active');
                $('#images-modal .carousel-item').eq(imageId).addClass('active');
                imagesModal.show();
            } else {
                var src = $(this).attr('src');
                if (src) {
                    window.open(src);
                }
            }
        });
    }
});
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

var autoLogin = true;
$('#auto-login').click(function () {
    autoLogin = true;
    $(this).hide();
    $('#auto-login-checked').show();
});
$('#auto-login-checked').click(function () {
    autoLogin = false;
    $(this).hide();
    $('#auto-login').show();
});

function login() {
    postJson("/Web/Login", { LoginId: $('#loginForm input[name="LoginId"]').val(), Password: $('#loginForm input[name="Password"]').val(), VerificationCode: $('#loginForm input[name="VerificationCode"]').val(), autoLogin: autoLogin }, function (response) {
        if (response.Success == true) {
            var from = GetQueryString('from');
            if (from != null) {
                document.location = from;
            } else {
                document.location = '/';
            }
        } else {
            refreshVerificationCode('loginForm');
            toastDanger(response.Message);
        }
    }, function () {
        toastDanger('登陆失败');
        refreshVerificationCode('loginForm');
    });
}

$('#btnLogin').click(function () {
    login();
});

function register() {
    postJson("/Web/Login/Register", { LoginId: $('#registerForm input[name="LoginId"]').val(), Password: $('#registerForm input[name="Password"]').val(), RePassword: $('#registerForm input[name="RePassword"]').val(), VerificationCode: $('#registerForm input[name="VerificationCode"]').val() }, function (response) {
        if (response.Success == true) {
            var from = GetQueryString('from');
            if (from != null) {
                document.location = from;
            } else {
                document.location = '/';
            }
        } else {
            refreshVerificationCode('registerForm');
            toastDanger(response.Message);
        }
    }, function () { toastDanger('注册失败'); refreshVerificationCode('registerForm'); });
}

$('#btnRegister').click(function () {
    register();
});

function refreshVerificationCode(id) {
    var el = $('#' + id + ' img');
    el.attr('src', '/Utility/VerificationCodeImage?v=' + Math.random());
}

function del(path, id, warn) {
    if (warn == undefined) {
        warn = '删除后无法恢复，是否继续？';
    }
    if (confirm(warn)) {
        postJson(path, { id: id }, function (response) {
            if (response.Success == true) {
                location.reload();
            } else {
                alert(response.Message);
            }
        }, function () {
            alert(response.Message);
        });
    }
}
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$('input[name="VerificationCode"]').keyup(function (event) {
    if (event.keyCode == 13) {
        var id = $(this).attr('id');
        if (id == 'loginVerificationCode') {
            login();
        } else {
            register();
        }
    }
});

$(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
        $(".to-top").fadeIn();
    }
    else {
        $(".to-top").fadeOut();
    }
});

$(".to-top").click(function () {
    if ($('html').scrollTop()) {
        $('html').animate({ scrollTop: 0 }, 500);
        return false;
    }
    $('body').animate({ scrollTop: 0 }, 500);
    return false;
});
function signIn() {
    $('#signIn').removeAttr('onclick');
    postJson('/Web/Users/SignIn', null, function (response) {
        if (response.Success == true) {
            changeBar(response.Data);
            $('#signIn').attr('class', 'badge text-bg-light');
            $('#signIn').html('已签到');
        } else {
            alert(response.Message);
        }
    });
}
function changeBar(data) {
    $('.userinfo-lv span').html('Lv' + data.Lv);
    $('.userinfo-exp span').html(data.Exp + '/' + data.NeedExp);
    var bar = $('.progress-bar');
    bar.attr('aria-valuenow', data.Exp);
    bar.attr('aria-valuemax', data.NeedExp);
    var rst = Math.floor(data.Exp * 100 / data.NeedExp);
    bar.attr('style', 'width:' + rst + '%');
    bar.html(rst + '%');
    bar.addClass('progress-bar-striped active');
    setTimeout(function () {
        bar.removeClass('progress-bar-striped active');
    }, 800);
}

function favorite(referenceId, referenceType) {
    if (!$('#btn-favorite').hasClass('disabled')) {
        $('#btn-favorite').addClass('disabled');
        $('#btn-favorite .btn-loading').removeClass('visually-hidden');
        if ($('#btn-favorite').hasClass('favorited')) {
            postJson('/Utility/Favorites/Delete', { referenceId: referenceId, referenceType: referenceType }, function (res) {
                if (res.Success) {
                    deletereferenceSuccess('btn-favorite', res.Data.Count);
                } else {
                    deletereferenceFail('btn-favorite', res.Message);
                }
            }, function (res) {
                if (res?.status == 401) {
                    deletereferenceFail('btn-favorite', '请先登陆');
                    document.location = '/login?from=' + encodeURIComponent(document.location.href);
                } else {
                    deletereferenceFail('btn-favorite', res?.Message ?? '失败了，请重试');
                }
            });
        } else {
            postJson('/Utility/Favorites', { referenceId: referenceId, referenceType: referenceType }, function (res) {
                if (res.Success) {
                    referenceSuccess('btn-favorite', res.Data.Count);
                } else {
                    referenceFail('btn-favorite', res.Message);
                }
            }, function (res) {
                if (res?.status == 401) {
                    referenceFail('btn-favorite', '请先登陆');
                    document.location = '/login?from=' + encodeURIComponent(document.location.href);
                } else {
                    referenceFail('btn-favorite', res?.Message ?? '失败了，请重试');
                }
            });
        }
    }
}
function zan(referenceId, referenceType, type) {
    if (!$('#btn-zan').hasClass('disabled')) {
        $('#btn-zan').addClass('disabled');
        $('#btn-zan .btn-loading').removeClass('visually-hidden');
        if ($('#btn-zan').hasClass('zaned')) {
            postJson('/Utility/Behaviors/Delete', { referenceId: referenceId, referenceType: referenceType, type: type }, function (res) {
                if (res.Success) {
                    deletereferenceSuccess('btn-zan', res.Data.Count);
                } else {
                    deletereferenceFail('btn-zan', res.Message);
                }
            }, function (res) {
                if (res?.status == 401) {
                    deletereferenceFail('btn-zan', '请先登陆');
                    document.location = '/login?from=' + encodeURIComponent(document.location.href);
                } else {
                    deletereferenceFail('btn-zan', res?.Message ?? '失败了，请重试');
                }
            });
        } else {
            postJson('/Utility/Behaviors', { referenceId: referenceId, referenceType: referenceType, type: type }, function (res) {
                if (res.Success) {
                    referenceSuccess('btn-zan', res.Data.Count);
                } else {
                    referenceFail('btn-zan', res.Message);
                }
            }, function (res) {
                if (res?.status == 401) {
                    referenceFail('btn-zan', '请先登陆');
                    document.location = '/login?from=' + encodeURIComponent(document.location.href);
                } else {
                    referenceFail('btn-zan', res?.Message ?? '失败了，请重试');
                }
            });
        }
    }
}
function referenceSuccess(btnId, count) {
    if (btnId == 'btn-zan') {
        $('#' + btnId).addClass('zaned');
        $('#' + btnId).addClass('btn-danger');
        $('#' + btnId).removeClass('btn-outline-danger');
    } else if (btnId == 'btn-favorite') {
        $('#' + btnId).addClass('favorited');
        $('#' + btnId).addClass('btn-warning');
        $('#' + btnId).removeClass('btn-outline-warning');
    }
    $('#' + btnId).removeClass('disabled');
    $('#' + btnId + ' .btn-loading').addClass('visually-hidden');
    $('#' + btnId + ' .btn-count').html(count);
}
function referenceFail(btnId, msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').addClass('fail');
    $('.tool-bar-msg').removeClass('success');
    $('.tool-bar-msg').removeClass('hide');
    $('#' + btnId).removeClass('disabled');
    $('#' + btnId + ' .btn-loading').addClass('visually-hidden');
}
function deletereferenceSuccess(btnId, count) {
    if (btnId == 'btn-zan') {
        $('#' + btnId).removeClass('zaned');
        $('#' + btnId).removeClass('btn-danger');
        $('#' + btnId).addClass('btn-outline-danger');
    } else if (btnId == 'btn-favorite') {
        $('#' + btnId).removeClass('favorited');
        $('#' + btnId).removeClass('btn-warning');
        $('#' + btnId).addClass('btn-outline-warning');
    }
    $('#' + btnId).removeClass('disabled');
    $('#' + btnId + ' .btn-loading').addClass('visually-hidden');
    $('#' + btnId + ' .btn-count').html(count);
}
function deletereferenceFail(btnId, msg) {
    $('.tool-bar-msg').html(msg);
    $('.tool-bar-msg').addClass('fail');
    $('.tool-bar-msg').removeClass('success');
    $('.tool-bar-msg').removeClass('hide');
    $('#' + btnId).removeClass('disabled');
    $('#' + btnId + ' .btn-loading').addClass('visually-hidden');
}
function disableSubmitBtn() {
    $('.btn-submit').attr('disabled', '');
}
function enableSubmitBtn() {
    $('.btn-submit').removeAttr('disabled');
}

$('.tool-bar-item').click(function () {
    $('.share-box').remove();
    if ($(this).hasClass('wechat-item')) {
        var html = '<div class="share-box shadow">点击微信右上角，扫一扫二维码<br />可将本文分享好友或朋友圈<div id="share-code"></div></div>';
        $(this).append(html);
        renderQRCode();
    } else if ($(this).hasClass('sina-weibo-item')) {
        var url = 'https://service.weibo.com/share/share.php?url=' + encodeURIComponent(document.location.href) + '&title=' + encodeURIComponent(document.title);
        window.open(url, '_blank');
    } else if ($(this).hasClass('qq-item')) {
        var html = '<div class="share-box shadow">手机QQ右上角，扫一扫二维码<br />可将本文分享好友或朋友圈<div id="share-code"></div></div>';
        $(this).append(html);
        renderQRCode();
    }
});
function renderQRCode() {
    new QRCode(document.getElementById("share-code"), {
        text: document.location.href,
        width: 128,
        height: 128,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
}
var bootstrapToast;
function initToast() {
    if (!bootstrapToast) {
        var toasts = document.getElementsByClassName('live-toast');
        if (toasts.length > 0) {
            bootstrapToast = bootstrap.Toast.getOrCreateInstance(toasts[0]);
        } else {
            var toastHtml = '<div data-bs-delay="2500" style="bottom: 16%;" class="toast live-toast position-fixed w-auto align-items-center border-0 start-50 translate-middle" role="alert" aria-live="assertive" aria-atomic="true">'
                + '<div class="d-flex">'
                + '<div class="toast-body"></div>'
                + '</div>'
                + '</div>';
            $('body').append(toastHtml);
            toasts = document.getElementsByClassName('live-toast');
            bootstrapToast = bootstrap.Toast.getOrCreateInstance(toasts[0]);
        }
    }
}
function toastSuccess(msg) {
    initToast();
    $('.live-toast').removeClass('text-bg-danger');
    $('.live-toast').addClass('text-bg-success');
    $('.live-toast .toast-body').html(msg);
    bootstrapToast.show();
}
function toastDanger(msg) {
    initToast();
    $('.live-toast').addClass('text-bg-danger');
    $('.live-toast').removeClass('text-bg-success');
    $('.live-toast .toast-body').html(msg);
    bootstrapToast.show();
}
function initEditForm(formId, url, validateRules, validateMessages, successMsg, failMsg) {
    if (!successMsg) {
        successMsg = '保存成功';
    }
    if (!failMsg) {
        failMsg = '保存失败';
    }
    $('#' + formId).validate({
        rules: validateRules,
        messages: validateMessages,
        submitHandler: function (form) {
            var formData = new FormData($('#' + formId)[0]);
            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    disableSubmitBtn();
                },
                success: function (res) {
                    if (res.Success) {
                        toastSuccess(successMsg);
                        setTimeout(function () {
                            var refreshUrl = url + '/' + res.Data.Id;
                            if ($('input[name="ReturnUrl"]')) {
                                refreshUrl += '?ReturnUrl=' + encodeURIComponent($('input[name="ReturnUrl"]').val());
                            }
                            window.location.href = refreshUrl;
                        }, 1000);
                    } else {
                        toastDanger(res.Message == '' ? failMsg : res.Message);
                        enableSubmitBtn();
                    }
                },
                error: function () {
                    toastDanger(failMsg);
                    enableSubmitBtn();
                }
            });
        }
    });
}

function pinToTop(postId, isTop) {
    postJson('/Forums/PinToTop', { postId: postId, isTop: isTop },
        (res) => {
            if (res.Success) {
                toastSuccess('操作成功');
                document.location.reload();
            } else {
                if (res.Message && res.Message != '') {
                    toastDanger(res.Message);
                } else {
                    toastDanger('操作失败');
                }
            }
        },
        () => { toastDanger('操作失败'); });
}
