var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
var storage = window.localStorage;

// timeago初始化
jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
});

// 懒加载初始化
var lazyLoadInstance = new LazyLoad({});

// cocomessage
cocoMessage.config({
    //配置全局参数    
    duration: 500000,
});


//代码高亮
hljs.highlightAll();
hljs.initCopyButtonOnLoad();
/*================================
 Loading
================================*/

function page_loader2(){
    var html = '<div class="bouncing-loader pix-page-loader">';
        html += '<div></div>';
        html += '<div></div>';
        html += '<div></div>';
        html += '</div>';
    
        return html;
    }

function loading_start(target) {
    target.append( page_loader2() );
}

function loading_done(target) {
    target.children('.pix-page-loader').remove();
}

//导航2showup
$(function(){
    //页面初始化的时候，获取滚动条的高度（上次高度）
    var start_height = $(document).scrollTop();
    //获取导航栏的高度(包含 padding 和 border)
    var navigation_height = $('.top-header.nav2.showup').outerHeight();
    var top_nav_h = $('.top-nav-box').outerHeight();
    var mainav = $('.top-header.nav2.showup');

    //var width = $('.top-header.nav2.showup').outerWidth();
    
    $(window).scroll(function() {
        //触发滚动事件后，滚动条的高度（本次高度）
        var end_height = $(document).scrollTop();
        //触发后的高度 与 元素的高度对比
        if (end_height > top_nav_h){
            mainav.css('top', -top_nav_h);
            mainav.addClass('active');
        } else {
            mainav.css('top', '0');
            mainav.removeClass('active');
        }
        //触发后的高度 与 上次触发后的高度
        if (end_height < start_height){
            mainav.css('top', '0');
            mainav.removeClass('active');
        }
        //再次获取滚动条的高度，用于下次触发事件后的对比
        start_height = $(document).scrollTop();
    });
});

//导航5 菜单折叠
$("#left_menu li.menu-item-has-children > a").on("click", function(i){
    i.preventDefault();
    if( ! $(this).parent().hasClass("active-nav") ){
        $("#left_menu li ul").slideUp(200);
        $(this).next().slideToggle(200);
        $("#left_menu li").removeClass("active-nav");
        $(this).parent().addClass("active-nav");
    }
    else{
        $(this).next().slideToggle(200);
        $("#left_menu li").removeClass("active-nav");
        }
});

// 灯箱 fancybox 5.0
Fancybox.bind("[data-fancybox]", {
    
});


//顶部菜单链接
$(".primary-nav.high li ul li , .primary-nav.main_high #primary_menu > li , .classic-nav.main_high #classic_menu > li").hover(function(){
    $(this).siblings().css('opacity','.4');
},function(){
    $(this).siblings().css('opacity','1');
});


//pix按钮点击跳转
$('body').on('click','.pix-btn',function(){
    var url = $(this).attr('href');
    window.open(url,'_blank');
});

/*================================
 ajax加载内容 文章|片刻
================================*/
var PixMomentListOptimizer = (function() {
    var desktopLimit = 60;
    var desktopKeep = 42;
    var mobileLimit = 36;
    var mobileKeep = 24;
    var desktopSectionSize = 20;
    var mobileSectionSize = 16;
    var observer = null;

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, function(char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function ensureObserver() {
        if (observer || !('IntersectionObserver' in window)) return observer;
        observer = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    restore($(entry.target));
                }
            });
        }, {
            rootMargin: '900px 0px'
        });
        return observer;
    }

    function restore($placeholder) {
        if (!$placeholder || !$placeholder.length || !$placeholder.hasClass('moment-virtual-placeholder')) return;
        var htmlList = $placeholder.data('momentHtmlList');
        var html = $placeholder.data('momentHtml');
        if (!htmlList && html) {
            htmlList = [html];
        }
        if (!htmlList || !htmlList.length) return;
        var $items = $(htmlList.join(''));
        var currentHeight = $placeholder.outerHeight();
        if (currentHeight) {
            $items.first().css('min-height', currentHeight + 'px');
        }
        if (observer) {
            observer.unobserve($placeholder[0]);
        }
        $placeholder.replaceWith($items);
        window.setTimeout(function() {
            $items.first().css('min-height', '');
            if (window.lazyLoadInstance && typeof lazyLoadInstance.update === 'function') {
                lazyLoadInstance.update();
            }
            if (window.ReadMore) {
                ReadMore.init('.ppo-rich-text-content');
            }
            if ($.fn.timeago) {
                $items.find('time.timeago').timeago();
            }
        }, 30);
    }

    function canCollapse($item) {
        if (!$item || !$item.length || $item.hasClass('is-moment-virtualized')) return false;
        if ($item.find('.moment_comments_wrap:visible').length) return;
        if ($item.find('.uk-dropdown.uk-open, .uk-drop.uk-open, .jconfirm').length) return;
        return true;
    }

    function collapseSection($items, sectionIndex, listType) {
        $items = $items.filter(function() {
            return canCollapse($(this));
        });
        if (!$items.length) return;

        var height = 0;
        var htmlList = [];
        var firstTitle = '';
        $items.each(function(index) {
            var $item = $(this);
            height += Math.max(180, Math.ceil($item.outerHeight() || 0));
            htmlList.push($item.prop('outerHTML'));
            if (!index) {
                firstTitle = $.trim($item.find('.momoent_title a').text() || $item.find('.entry-title a').text() || $item.find('.mos-content p').text() || '内容');
            }
        });

        var $placeholder = $('<div class="moment-virtual-placeholder moment-virtual-section" role="button" tabindex="0"></div>');
        $placeholder.css('min-height', height + 'px');
        $placeholder.data('momentHtmlList', htmlList);
        $placeholder.attr('data-list-type', listType);
        $placeholder.attr('data-count', htmlList.length);
        $placeholder.html('<div class="moment-virtual-inner"><i class="ri-stack-line"></i><span>已折叠第 ' + sectionIndex + ' 段，共 ' + htmlList.length + ' 条较早' + (listType === 'post' ? '文章' : '片刻') + '</span><small>' + escapeHtml(firstTitle.substring(0, 28)) + '</small></div>');

        $items.first().before($placeholder);
        $items.remove();
        var io = ensureObserver();
        if (io) io.observe($placeholder[0]);
    }

    function collapseTargets($targets, sectionSize, listType) {
        var group = [];
        var sectionIndex = 1;

        function flushGroup() {
            if (!group.length) return;
            collapseSection($(group), sectionIndex, listType);
            sectionIndex++;
            group = [];
        }

        $targets.each(function() {
            var $item = $(this);
            if (!canCollapse($item)) {
                flushGroup();
                return;
            }

            group.push(this);
            if (group.length >= sectionSize) {
                flushGroup();
            }
        });

        flushGroup();
    }

    function run(selector) {
        var $box = $(selector || '#moment-item');
        if (!$box.length) return;
        var $items = $box.children('.moment_item, .post-item');
        var isMobile = window.matchMedia && window.matchMedia('(max-width: 640px)').matches;
        var isPostList = $items.first().hasClass('post-item');
        var limit = isPostList ? (isMobile ? 36 : 60) : (isMobile ? mobileLimit : desktopLimit);
        var keep = isPostList ? (isMobile ? 24 : 42) : (isMobile ? mobileKeep : desktopKeep);
        var sectionSize = isPostList ? (isMobile ? 12 : 18) : (isMobile ? mobileSectionSize : desktopSectionSize);
        if ($items.length <= limit) return;

        var collapseCount = $items.length - keep;
        var $targets = $items.slice(0, collapseCount);
        collapseTargets($targets, sectionSize, isPostList ? 'post' : 'moment');
    }

    return {
        run: run,
        restore: restore
    };
})();

$('body').on('click keydown', '.moment-virtual-placeholder', function(event) {
    if (event.type === 'keydown' && event.key !== 'Enter' && event.key !== ' ') return;
    event.preventDefault();
    PixMomentListOptimizer.restore($(this));
});

$('body').on('click','.loadmore-btn',function(){
    var t = $(this),
        append_box = t.attr('data-append'),
        max_page = parseInt(t.attr('data-max'), 10) || 1,
        current_page = parseInt(t.attr('data-paged'), 10) || parseInt(Theme.current_page, 10) || 1,
        action = t.attr('data-action'),
        cat = t.attr('data-cat'),
        data = {
            'action': action,
            'paged': current_page,
            'max': max_page,
            'cat': cat,
        };

    if(action == 'cls_load_moments'){
        data.security = Theme.moment_nonce;
        data.filter_type = $('.moment-cat-filter .filter-item.active').attr('type') || 'new';
    } else if(action == 'cls_load_posts'){
        data.security = Theme.post_nonce;
    }
        
    if(t.hasClass('protect')){
        return false;
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: Theme.ajaxurl,
        data: data,
        beforeSend: function () {
            t.text('LOADING..').addClass('protect');
            $('.pager-info .go-top a').hide();
            $('.pager-info .go-top').append('<div class="pager-loader" uk-spinner="ratio: 0.6"></div>');
		},
        success: function (data) {
            if( data && data.content ) { 
                var result = $(data.content);
                t.text( '加载更多' ).removeClass('protect'); 
                $(append_box).append(result.fadeIn(300));

                $('.pager-info .go-top a').show().siblings('.pager-loader').remove();

                //$body.animate({scrollTop: result.offset().top - 58}, 500 );
                lazyLoadInstance.update(); //重载懒加载
                $("time.timeago").timeago(); //重载时间
                if (action == 'cls_load_moments' && window.ReadMore) {
                    ReadMore.init('.ppo-rich-text-content');
                }
                if (action == 'cls_load_moments') {
                    PixMomentListOptimizer.run(append_box);
                } else if (action == 'cls_load_posts') {
                    PixMomentListOptimizer.run(append_box);
                }
                current_page++; //页面增加
                Theme.current_page = current_page;
                $('.paged-number .current').text(current_page);
                t.attr('data-paged',current_page);
                if ( current_page >= max_page ) {
                    t.hide().before('<div class="no-more">暂无更多</div>');
                    
                }
               

            } else {
                t.hide().before('<div class="no-more">暂无更多</div>');
            }
        },
        error: function () {
            t.text('加载更多').removeClass('protect');
            $('.pager-info .go-top a').show().siblings('.pager-loader').remove();
            if (typeof toastfy === 'function') {
                toastfy('加载失败，请稍后重试', 'error');
            }
        }
    });
}); 

/*================================
 文章 片刻 无限加载
================================*/
if(Theme.moment_nav == 'scroll' && $('.loadmore-btn[data-action="cls_load_moments"]').length > 0 ){
    $window = $(window);
$(window).scroll(function(){
    var $btn = $('.loadmore-btn[data-action="cls_load_moments"]:visible').first(),
    max_page = parseInt($btn.attr('data-max'), 10) || 1,
    paged = parseInt($btn.attr('data-paged'), 10) || 1;
    if(!$btn.length || $btn.hasClass('protect')) return;
    if( $window.scrollTop() + $window.height() > $(document).height() - 500 && paged < max_page ){
       $btn.trigger('click');
    }
}); 
}

if(Theme.post_nav == 'scroll' && $('.loadmore-btn[data-action="cls_load_posts"]').length > 0 ){
    $window = $(window);
    $(window).scroll(function(){
    var $btn = $('.loadmore-btn[data-action="cls_load_posts"]:visible').first(),
    max_page = parseInt($btn.attr('data-max'), 10) || 1,
    paged = parseInt($btn.attr('data-paged'), 10) || 1;
    if(!$btn.length || $btn.hasClass('protect')) return;
    if( $window.scrollTop() + $window.height() > $(document).height() - 500 && paged < max_page ){
       $btn.trigger('click');
    }
}); 
}

/*================================
 文章 片刻 页码加载
================================*/
$('body').on('click','.pagination-box .page-numbers li a',function(e){
    e.preventDefault();
    var t = $(this),
        action = t.parents('.pagination-box').attr('data-action'),
        box = t.parents('.pagination-box');
        url = t.attr('href'),
        match = url.match(/\/page\/(\d+)\/?/) || url.match(/[?&]paged=(\d+)/),
        paged = match ? match[1] : 1,
        filter_type = $('.filter-item.active').attr('type'),
        baseurl = window.location.href;
        
        cat = box.attr('data-cat'),
        max_page = box.attr('data-max'),
        append_box = box.attr('data-append'),
        data = {
            'action': action,
            'paged': paged,
            'max':max_page,
            'cat': cat,
            'filter_type': filter_type,
            'baseurl': baseurl,
        };

        if(action == 'cls_load_moments'){
            data.security = Theme.moment_nonce;
        } else if(action == 'cls_load_posts'){
            data.security = Theme.post_nonce;
        }
        
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: Theme.ajaxurl,
            data: data,
            beforeSend: function () {
                
            },
            success: function (data) {
                if( data ) { 
                    
                    var result = $(data.content);
                    $(append_box).html(result.fadeIn(300));
                    $('.pagination-box').html(data.pagenav);
                    $body.animate({scrollTop: result.offset().top - 300}, 300 );
                    lazyLoadInstance.update(); //重载懒加载
                    $("time.timeago").timeago(); //重载时间
                    if(action == 'cls_load_posts'){
                        PixMomentListOptimizer.run(append_box);
                    }
                    
                   
    
                } else {
                    t.remove(); 
                }
            }
        });
        
});




/*================================
 文章分类筛选
================================*/
var pixPostFilterRequest = null;
var pixPostFilterSeq = 0;
var pixPostFilterTimer = null;
var pixPostFilterQueued = null;

function render_post_filter_error(message){
    message = message || '文章加载失败，请稍后重试';
    return '<div class="no-moment post-filter-error"><img src="'+Theme.ppo_url+'/img/empty.png"><p>'+message+'</p><button type="button" class="post-filter-retry">重试</button></div>';
}

function is_post_filter_running(){
    return pixPostFilterRequest && pixPostFilterRequest.readyState !== 4;
}

function run_post_filter($item, forceRetry){
    var t = $item,
        append_box = '#blog-item',
        load_btn = '.loadmore-btn[data-action="cls_load_posts"]',
        cat = t.attr('data'),
        baseurl = window.location.href;

    if(!t.length){
        return;
    }

    if(t.hasClass('active') && !forceRetry && !$('.cls-blog-cat-filter').data('filterFailed') && !$('.cls-blog-cat-filter').hasClass('is-filtering')){
        return;
    }

    t.addClass('active');
    t.parent().siblings().children().removeClass('active');

    if(pixPostFilterTimer){
        clearTimeout(pixPostFilterTimer);
        pixPostFilterTimer = null;
    }

    var requestSeq = ++pixPostFilterSeq;
    $('.cls-blog-cat-filter').addClass('is-filtering').removeData('filterFailed');

    if(is_post_filter_running()){
        pixPostFilterQueued = t;
        return;
    }

    pixPostFilterTimer = setTimeout(function(){
        pixPostFilterTimer = null;
        $(append_box).empty();

        var currentRequest = null;
        currentRequest = pixPostFilterRequest = $.ajax({
            type: 'POST',
            dataType: 'json',
            url: Theme.ajaxurl,
            timeout: 15000,
            data: {
                action: 'cls_filter_posts',
                security: Theme.post_nonce,
                cat: cat,
                baseurl: baseurl
            },
            beforeSend: function () {
                $(load_btn).parents('.pagenav-box').hide();
                loading_start($(append_box));
            },
            success: function (data) {
                if(requestSeq !== pixPostFilterSeq){
                    return;
                }

                loading_done($(append_box));
                if(!data || typeof data.content === 'undefined'){
                    $('.cls-blog-cat-filter').data('filterFailed', true);
                    $(append_box).html(render_post_filter_error());
                    $('.pagenav-box').hide();
                    if(typeof toastfy === 'function'){
                        toastfy('文章加载失败，请稍后重试','error');
                    }
                    return;
                }

                Theme.current_page = 1;
                Theme.max_page = data.max_page;

                if(Theme.post_nav == 'pagenav'){
                    $('.pagination-box').attr({
                        'data-cat':cat,
                        'data-max':data.max_page,
                    });

                    if ( data.max_page < 2 ) {
                        $('.pagination-box').empty();
                    } else {
                        $('.pagination-box').html(data.pagenav);
                    }
                } else {
                    $(load_btn).parents('.pagenav-box').show();
                    $(load_btn).attr({
                        'data-max':data.max_page,
                        'data-paged':'1',
                        'data-cat':cat,
                    });
                    $(load_btn).show().siblings('.no-more').remove();
                    $('.paged-number .current').text('1');
                    $('.paged-number .total').text(data.max_page);

                    if ( data.max_page < 2 ) {
                        $('.pagenav-box').hide();
                    } else {
                        $('.pagenav-box').show();
                    }
                }

                var result = $(data.content);
                $(append_box).append(result.fadeIn(300));

                lazyLoadInstance.update();
                $("time.timeago").timeago();
                PixMomentListOptimizer.run(append_box);
            },
            error: function(xhr){
                if(requestSeq !== pixPostFilterSeq || (xhr && xhr.statusText === 'abort')){
                    return;
                }
                loading_done($(append_box));
                $('.cls-blog-cat-filter').data('filterFailed', true);
                var msg = xhr && xhr.statusText === 'timeout' ? '文章筛选请求超时，请重试' : '文章加载失败，请稍后重试';
                $(append_box).html(render_post_filter_error(msg));
                $('.pagenav-box').hide();
                if(typeof toastfy === 'function'){
                    toastfy(msg,'error');
                }
            },
            complete: function(){
                if(currentRequest !== pixPostFilterRequest){
                    return;
                }

                pixPostFilterRequest = null;

                if(pixPostFilterQueued && pixPostFilterQueued.length){
                    var queuedItem = pixPostFilterQueued;
                    pixPostFilterQueued = null;
                    run_post_filter(queuedItem, true);
                    return;
                }

                if(requestSeq === pixPostFilterSeq){
                    loading_done($(append_box));
                    $('.cls-blog-cat-filter').removeClass('is-filtering');
                }
            }
        });
    }, 120);
}

$('body').off('click.postFilter', '.posts_cat_nav ul li a').on('click.postFilter','.posts_cat_nav ul li a',function(e){
    e.preventDefault();
    run_post_filter($(this), false);
});

$('body').off('click.postFilterRetry', '.post-filter-retry').on('click.postFilterRetry', '.post-filter-retry', function(){
    run_post_filter($('.posts_cat_nav ul li a.active').first(), true);
});

//片刻评论提交
$(document).on("submit", "#t_commentform , #commentform",function(){
	var t = $(this);
	var parent = t.find('#comment_parent').val();
	var pid = t.find('#comment_post_ID').val();
    var com_type = t.attr('com-type');

    if($('input#push_comment').hasClass('protect')){
        //cocoMessage.error('无法提交');
        return false;
    }

    if(t.attr('id') == 't_commentform'){
        var respond = $("#t_commentform");
    } else {
        var respond = $(".comment-respond");
    }

    var pixCommentUploader = t.find('.pix-comment-uploader').data('pixUploader');
    if (pixCommentUploader && typeof window.syncPixCommentUploaderField === 'function') {
        window.syncPixCommentUploaderField(t, pixCommentUploader.value());
    }
	
    var $scope = t.closest('.comments-area');
    var $commentBox = $scope.find('.commentshow').first();
    if (!$commentBox.length) {
        $commentBox = t.closest('.commentshow');
    }
	var _list = $commentBox.length ? $commentBox.find('.comment-list').first() : $scope.find('.comment-list').first();
	var cancel = t.find('#cancel-comment-reply-link');
	$.ajax({
		url:Theme.ajaxurl,
		data: $(this).serialize() + "&action=ajax_comment",
		type: $(this).attr('method'),	

		beforeSend: function () {
            toastfy("提交中....","info");
		},
		error: function(request) {
            toastfy(request.responseText,"error");
		},
		success: function(data){
            if (pixCommentUploader) {
                pixCommentUploader.setItems([], 'image');
                t.find('input[name="comt-uploaded-urls"]').val('');
                t.find('.img-box-drop').hide();
                updateCommentImageBadge(t);
            }
            if(com_type == 'reply'){
                toastfy("回复成功","success");
                $('textarea#comment').val('');
                return;
            }

			if(parent !='0'){
				respond.before('<ul class="children">' + data + '</ul>');
			} else if(!_list.length){
                if ($commentBox.length) {
                    $commentBox.html('<ul class="comment-list">' + data + '</ul>');
                } else {
                    respond.after('<ul class="comment-list">' + data + '</ul>');
                }
			} else {
				_list.prepend(data);
			}
            lazyLoadInstance.update();
			toastfy("提交成功","success");
            if (window.PixMomentCommentCache && pid) {
                PixMomentCommentCache.remove(pid);
            }
            if (cancel.length) {
                cancel.click();
            }
            if ($commentBox.length) {
                $commentBox.find(".comment-list .nodata").remove();
            } else {
                $(".comment-list .nodata").remove();
            }
		}	
	});
	return false;
});	

//回复按钮
$(document).on('click','.comment-reply-link',function(event){
	var t = $(this);
	event.preventDefault();
    $('.comment-respond').addClass('respond-reply');
    var comid = t.attr('data-commentid');
    var at = t.parents(".commeta").find(".author a").text();
    var type = t.parents('.comments-area').attr('data');
    
    if(type == 'normal'){
        var form = $(".comment-respond").prop('outerHTML');
        $(".comment-respond").remove();
    } else {
        var form = $("#t_commentform").prop('outerHTML');
        t.parents(".toi_comments_main").find("#t_commentform").remove();
        
    } 
	
	var pid = t.attr('data-postid');
	var cancel = $("#cancel-comment-reply-link");
	$("#comment-"+comid+"").after(form);
	$("#comment_parent").val(comid);
	$("textarea#comment").focus().attr('placeholder','回复'+at);
    $('.com-footer').slideDown(100);
    $('.cancel-comment-textarea').hide();
	$("#cancel-comment-reply-link").css("display","");	
    update_comt_img('reset');
});	

//取消回复
$(document).on('click','#cancel-comment-reply-link',function(event){
	var t = $(this);
	event.preventDefault();
    var author = $('.com-author input').val();
    var email = $('.com-email input').val();
    var url = $('.com-url input').val();

    $('.comment-respond').removeClass('respond-reply');
    $('.cancel-comment-textarea').show();
    var pid = $("#comment_post_ID").val();
    var cancel = $("#cancel-comment-reply-link");
    var type = t.parents('.comments-area').attr('data');
    if(type == 'normal'){
        var form = $(".comment-respond").prop('outerHTML');
        var respond_box = $("#respond_box"); 
        var temp = $("#wp-temp-form-div");
        t.parents(".comment-respond").remove();
        respond_box.append(form);
        $("#cancel-comment-reply-link").css("display","none");
        $("#comment_parent").val('0');
        $("textarea#comment").focus().attr('placeholder','不准备说点什么？');

    }else {
        var form = $("#t_commentform").prop('outerHTML');
        var respond_box = $(".toi_respond_"+pid+"");
        t.parents("form").remove();
        respond_box.append(form);
        $("#cancel-comment-reply-link").css("display","none");
        $("#comment_parent").val('0');
        $("textarea#comment").focus().attr('placeholder','不准备说点什么？');
    } 

    $('.com-author input').val(author)
    $('.com-email input').val(email);
	$('.com-url input').val(url);
    update_comt_img();
});	


$(document).on('input propertychange','textarea#comment',function(event){ 
    // 自动调整textarea的高度
    this.style.height = '50px';
    if($(this).hasClass('mo-com-textarea')){
        this.style.height = '40px';
    }
    this.style.height = (this.scrollHeight) + 'px';

    if($(this).val().length > 1){
        $('#push_comment').removeClass('protect');
    } else {
        $('#push_comment').addClass('protect');
    }
  });

$(document).on('focus','textarea#comment',function(event){ 
    $('.com-footer').slideDown(100);
    if($('#comment-author-info input#email').val() == '' || $('#comment-author-info input#author').val() == ''){
        $('#comment-author-info-wrap').slideDown(100);
        $('a.edit-visitor-info').text('确认修改');
    }
});

$(document).on('click','.cancel-comment-textarea',function(event){ 
    $('.com-footer').slideUp(100);
});

$(document).on('click','a.edit-visitor-info',function(){
    var author = $('.com-author input').val();
    var email = $('.com-email input').val();
    if ($(this).text() === '修改资料') {
        $(this).text('确认修改');
      } else {
        if(author == '' || email == ''){
            toastfy('请填写必要信息，昵称和邮箱','error');
            return;
        }
        $(this).text('修改资料');
        $('.visitor-title span').text(author);
      }
      $('#comment-author-info-wrap').slideToggle(100);
});

//ajax获取有课评论头像
$(document).on('blur','.com-email input#email',function(){
	var _email = $(this).val();
    var _name = $(".com-author input#author").val();
	if (_email != '') {
		$.ajax({
			type: "POST",
			url: Theme.ajaxurl,
            dataType:  'json',
			data: {
				action: 'ajax_avatar_get', 
				email: _email,
                name:_name,
			},
			success: function(data) {
				$('.v-avatar').attr('src', data.avatar); // 替换头像链接到img标签
                //$('a.edit-profile small').text(data.name+" , 编辑");
			}
		}); // end ajax
	} else {
        $('.v-avatar').attr('src', Theme.de_ava);
    }

	});

// ajax自定义翻页
$('body').on('click', '.ppo-pagenav a', function(){
    var baseUrl = $(this).attr("href"),
    Holder = $(this).parent().attr("data-holder"),
    action = $(this).parent().attr("data-action"),
    page = 1,
    queryString = baseUrl.split('?')[1],
    regex = /current_page=(\d+)/;

    if(regex.test(queryString)){
        page = queryString.match(regex)[1];
    }

    var ajax_data = {
        action: action,
        paged: page
    };

    $('.ppo-pagenav').prev('div').html('');
    $.ajax({
        url : Theme.ajaxurl, // AJAX handler, declared before
        data : ajax_data,
        type : 'POST',
        beforeSend : function ( xhr ) {
            loading_start($('.ppo-pagenav').prev('div'));
        },
        success : function( data ){
            loading_done($('.ppo-pagenav').prev('div'));
            $('.'+Holder).html(data);
            $("time.timeago").timeago();
            lazyLoadInstance.update();
            
            
            }
    });
    return false;
    
});

//ajax评论翻页
$(document).on("click", ".commentnav a",
    function() {
        var t = $(this),
        baseUrl = t.attr("href"),
        $nav = t.closest('.commentnav'),
        commentsHolder = $nav.closest(".commentshow"),
        id = $nav.data("fuck"),
        page = 1,
        concelLink = $("#cancel-comment-reply-link");
        if (!commentsHolder.length) {
            commentsHolder = $nav.closest(".comments-area");
        }
        /comment-page-/i.test(baseUrl) ? page = baseUrl.split(/comment-page-/i)[1].split(/(\/|#|&).*jQuery/)[0] : /cpage=/i.test(baseUrl) && (page = baseUrl.split(/cpage=/)[1].split(/(\/|#|&).*jQuery/)[0]);
        concelLink.click();
        var ajax_data = {
            action: "ajax_comment_page_nav",
            post_id: id,
            paged: page,
            security: Theme.moment_nonce
        };
        var $list = commentsHolder.find('ul.comment-list').first();
		$list.html('');
        
        $.ajax({
            url : Theme.ajaxurl, // AJAX handler, declared before
            data : ajax_data,
            type : 'POST',
            beforeSend : function ( xhr ) {
                loading_start($list.length ? $list : commentsHolder);
            },
            success : function( data ){
                commentsHolder.html(data);
                $("time.timeago").timeago();
                lazyLoadInstance.update();
                //remove loading
                if (commentsHolder.length) {
                    $("body, html").animate({
                        scrollTop: commentsHolder.offset().top - 50
                    },
                    1e3)
                }
                }
        });
        return false;
    });    


//ajax评论翻页
$(document).on("click", ".commentmore-btn",
function() {
    var t = $(this);
    if (t.data('loading')) {
        return false;
    }
    var post_id = t.attr('post_id');
    var page = parseInt(t.attr('data-page') || t.attr('cpage') || '1', 10) || 1;
    var nextPage = page + 1;
    var $commentsHolder = t.closest('.commentshow');
    if (!$commentsHolder.length) {
        $commentsHolder = t.closest('.comments-area');
    }
    var $list = $commentsHolder.find('ul.comment-list').first();

    $.ajax({
        url : Theme.ajaxurl, // AJAX handler, declared before
        dataType: 'json',
        data : {
            'action': 'cloadmore', // wp_ajax_cloadmore
            'post_id': post_id, // the current post
            'page' : nextPage, // next comment page
            'security': Theme.moment_nonce
        },
        type : 'POST',
        beforeSend : function ( xhr ) {
            t.data('loading', true).addClass('is-loading');
            t.text('Loading...'); // preloader here
        },
        success : function( data ){
            if( data && data.status == 1 && data.html ) {
                t.attr('data-page', data.page);
                $list.append( $(data.html).hide().fadeIn() );
                lazyLoadInstance.update(); //重载懒加载
                $("time.timeago").timeago(); //重载时间
                if (data.has_more) {
                    t.text('加载更多');
                } else {
                    t.parent('.commentmore').remove();
                }
            } else {
                t.parent('.commentmore').remove();
            }
        },
        error: function () {
            if (typeof toastfy === 'function') {
                toastfy('分页加载失败，请稍后重试', 'error');
            }
            t.text('加载更多');
        },
        complete: function () {
            t.data('loading', false).removeClass('is-loading');
        }
    });
    return false;
});



// 评论表情
$(document).on('click','.com-emoji-btn',function(event){
    event.preventDefault();
    var $btn = $(this);
    var $box = $btn.closest('.com-emoji-box').find('.emoji-box').first();
    var $inner = $box.find('.emoji-inner').first();
    $box.fadeToggle(100);
    if ($inner.find('.add-smily').length) {
        return;
    }
    $.ajax({
        url : Theme.ajaxurl, // AJAX handler, declared before
        data : {
            'action': 'showemoji', // wp_ajax_cloadmore
        },
        type : 'POST',
        beforeSend : function ( xhr ) {
            if(!$inner.find('.add-smily').length){
                loading_start($inner);
            }
            //loading_start($('.emoji-inner'));
        },
        success : function( data ){
            $inner.html(data.html);
        }
    });
});

$(document).on('click','a.add-smily',function(){
    var data = $(this).attr('data-smilies');
    var emoji = "[s="+data+"]";
    var textarea = $(this).closest('form').find('.comarea textarea#comment');
    if (!textarea.length) {
        textarea = $('.comarea textarea#comment').first();
    }
    var content = textarea.val();
	textarea.val(content+emoji);
	textarea.focus();
});
window.update_comt_img = window.update_comt_img || function() {};

// 评论图片上传 PixUploader 2.0
if (typeof window.PixUploader !== 'undefined') {
    function pixCommentFormFromNode(node) {
        var $form = $(node).closest('form');
        return $form.length ? $form : $('#t_commentform, #commentform').first();
    }

    function syncCommentUploaderField($form, value) {
        if (!$form || !$form.length) return;
        var urls = [];
        if (value && value.items && value.items.length) {
            value.items.forEach(function(item) {
                if ((item.kind || item.type) === 'image' && item.url) {
                    urls.push(item.url);
                }
            });
        }

        var $field = $form.find('input[name="comt-uploaded-urls"]');
        if (!$field.length) {
            $field = $('<input type="hidden" name="comt-uploaded-urls" class="comt-uploaded-urls">');
            $form.find('.comment-tools').append($field);
        }
        $field.val(urls.join(','));
        updateCommentImageBadge($form);
    }
    window.syncPixCommentUploaderField = syncCommentUploaderField;

    function commentUploadSettings() {
        var settings = window.Theme && Theme.comment_upload ? Theme.comment_upload : {};
        return {
            enabled: settings.enabled !== false,
            limit: Math.max(1, Math.min(12, parseInt(settings.limit, 10) || 4)),
            maxSize: Math.max(1, Math.min(20, parseInt(settings.max_size, 10) || 2))
        };
    }

    function getCommentUploader($form) {
        if (!$form || !$form.length) return null;
        return $form.find('.pix-comment-uploader').data('pixUploader') || null;
    }

    function getCommentUploadCount($form) {
        var uploader = getCommentUploader($form);
        if (!uploader) return 0;
        return uploader.activeItems().filter(function(item) {
            return item.status !== 'error';
        }).length;
    }

    function updateCommentImageBadge($form) {
        if (!$form || !$form.length) return;
        var count = getCommentUploadCount($form);
        var $btn = $form.find('.com-img-btn').first();
        if (!$btn.length) return;
        var $badge = $btn.find('.pix-comment-image-badge');
        if (count > 0) {
            if (!$badge.length) {
                $badge = $('<em class="pix-comment-image-badge"></em>');
                $btn.append($badge);
            }
            $badge.text(count);
            $btn.addClass('has-uploaded-image').attr('title', '已添加 ' + count + ' 张图片');
        } else {
            $badge.remove();
            $btn.removeClass('has-uploaded-image').removeAttr('title');
        }
    }

    function initPixCommentUploader($form) {
        if (!$form || !$form.length) return null;
        var settings = commentUploadSettings();
        if (!settings.enabled) {
            pixToast('评论图片上传已关闭', 'error');
            return null;
        }
        var $box = $form.find('.comt-upload-box').first();
        if (!$box.length) return null;
        $form.find('.img-box-drop').first().addClass('is-pix-comment-upload');

        var $mount = $box.find('.pix-comment-uploader').first();
        if (!$mount.length) {
            $box.html('<div class="pix-comment-uploader"></div>');
            $mount = $box.find('.pix-comment-uploader').first();
        }

        var existing = $mount.data('pixUploader');
        if (existing) {
            existing.activeKind = 'image';
            return existing;
        }

        var uploader = new window.PixUploader($mount[0], {
            context: 'comment_image',
            type: 'image',
            limit: settings.limit,
            maxSize: settings.maxSize,
            multiple: true,
            accept: 'image/*',
            allowExternal: false,
            allowLibrary: true,
            allowBili: false,
            allowCard: false,
            allowedKinds: ['image'],
            libraryContext: '',
            preventOutsideClose: true,
            nonce: Theme.upload_nonce || Theme.comt_nonce || '',
            onChange: function(value) {
                syncCommentUploaderField($form, value);
            }
        });
        uploader.activeKind = 'image';
        $mount.data('pixUploader', uploader);
        syncCommentUploaderField($form, uploader.value());
        return uploader;
    }

    window.update_comt_img = function() {
        initPixCommentUploader($('#t_commentform, #commentform').first());
    };

    $(document).on('click', '.com-img-btn', function(event) {
        event.preventDefault();
        if (!commentUploadSettings().enabled) {
            pixToast('评论图片上传已关闭', 'error');
            return;
        }
        var $form = pixCommentFormFromNode(this);
        initPixCommentUploader($form);
        $form.find('.img-box-drop').first().fadeToggle(100);
        updateCommentImageBadge($form);
    });

    if (!commentUploadSettings().enabled) {
        $('.com-img-box').hide();
    }

    $(document).on('click', '.com-code-btn', function(event) {
        event.preventDefault();
        pixCommentFormFromNode(this).find('.code-box-drop').first().fadeToggle(100);
    });

    function adjustTextareaHeight() {
        var textarea = $('.comarea textarea#comment');
        if (!textarea.length) return;
        textarea.height(0);
        textarea.height(textarea[0].scrollHeight);
    }

    $(document).on('click', '.insert-code', function() {
        var code = $(this).prev('textarea').val();
        var insert = "\n[code]\n" + code + "\n[/code]\n";
        var textarea = pixCommentFormFromNode(this).find('.comarea textarea#comment');
        var content = textarea.val();
        textarea.val(content + insert);
        adjustTextareaHeight();
        textarea.focus();
    });

    $('body').on('click', function(event) {
        var target = $(event.target);
        var elementToHide = $('.comt-tool-box');
        if (!target.is(elementToHide) && !target.closest(elementToHide).length) {
            elementToHide.hide();
        }
    });

    $(window).on('beforeunload', function(event) {
        var hasPendingCommentImages = false;
        $('#t_commentform, #commentform').each(function() {
            if (getCommentUploadCount($(this)) > 0) {
                hasPendingCommentImages = true;
                return false;
            }
        });
        if (hasPendingCommentImages) {
            event.preventDefault();
            event.returnValue = '';
            return '';
        }
    });
}

// 评论图片上传（旧 FileUploader fallback，仅在 PixUploader 2.0 未加载时启用）
//var comt_img = $('#comt-img').fileuploader(comt_config);

if (typeof window.PixUploader === 'undefined' && typeof $.fn.fileuploader !== 'undefined') {

var comt_config = {
    limit: 4,
    extensions: ['image/*'],
    fileMaxSize: 2,
    addMore: true,
    enableApi: true,
    changeInput: '<div class="comt-input-box">' +
					      '<div class="fileuploader-input-inner">' +
						      '<div class="comt-upload-icon"><i class="ri-upload-2-line"></i></div>' +
							  '<span>${captions.feedback}</span>' +
							  '<span class="or">${captions.or}</span>' +
							  '<span class="comt-up-btn">${captions.button}</span>' +
						  '</div>' +
					  '</div>',
        theme: 'dragdrop',
		upload: {
            url: Theme.ajaxurl + "?action=upload_comment_img&nonce=" + Theme.comt_nonce,
            data: null,
            type: 'POST',
            enctype: 'multipart/form-data',
            start: true,
            synchron: true,
            beforeSend: null,
            onSuccess: function(result, item, listEl, parentEl, newInputEl, inputEl) {
                var api = $.fileuploader.getInstance(inputEl),
                    data = {};
				
                // get data
				if (result && result.files)
                    data = result;
                else
					data.hasWarnings = true;
                
				// if success
                if (data.isSuccess && data.files[0]) {
                    item.name = data.files[0].name;
					item.html.find('.column-title > div:first-child').text(data.files[0].name).attr('title', data.files[0].name);
                }
				
				// if warnings
				if (data.hasWarnings) {
					for (var warning in data.warnings) {
						alert(data.warnings[warning]);
					}
					
					item.html.removeClass('upload-successful').addClass('upload-failed');
					// go out from success function by calling onError function
					// in this case we have a animation there
					// you can also response in PHP with 404
					return this.onError ? this.onError(item) : null;
				}


                item.html.find('.fileuploader-action-remove').addClass('fileuploader-action-success');
                setTimeout(function() {
                    item.html.find('.progress-bar2').fadeOut(400);
                }, 400);
            },
            onError: function(item) {
				var progressBar = item.html.find('.progress-bar2');
				
				if(progressBar.length) {
					progressBar.find('span').html(0 + "%");
                    progressBar.find('.fileuploader-progressbar .bar').width(0 + "%");
					item.html.find('.progress-bar2').fadeOut(400);
				}
                
                item.upload.status != 'cancelled' && item.html.find('.fileuploader-action-retry').length == 0 ? item.html.find('.column-actions').prepend(
                    '<button type="button" class="fileuploader-action fileuploader-action-retry" title="Retry"><i class="fileuploader-icon-retry"></i></button>'
                ) : null;
            },
            onProgress: function(data, item) {
                var progressBar = item.html.find('.progress-bar2');
				
                if(progressBar.length > 0) {
                    progressBar.show();
                    progressBar.find('span').html(data.percentage + "%");
                    progressBar.find('.fileuploader-progressbar .bar').width(data.percentage + "%");
                }
            },
            onComplete: function(listEl, parentEl, newInputEl, inputEl, jqXHR, textStatus) {
                // 将上传完成的图片放进input
                var api = $.fileuploader.getInstance(inputEl);
                var upload_list = api.getFileList(false, 'url');
                $('.comment-tools').append('<input type="hidden" class="comt-uploded-files" name="comt-uploded-files" value="'+upload_list+'">');
                //console.log(upload_list);
            },
        },
		onRemove: function(item) {
			$.post('./php/ajax_remove_file.php', {
				file: item.name
			});
		},
		captions: $.extend(true, {}, $.fn.fileuploader.languages['zh_CN'], {
            feedback: '拖拽文件至此',
            feedback2: '拖拽文件至此',
            drop: '拖拽文件至此',
            or: '或',
            button: '上传文件',
        }),
	};

    //window.api = $.fileuploader.getInstance(comt_img);

    $(document).on('click','.com-img-btn',function(){
        if(!$('.fileuploader-items-list li').length > 0){
            update_comt_img();
        }
        $('.img-box-drop').fadeToggle(100);
    });

    //重载评论图片上传
    function update_comt_img(type){
        var input = '<input type="file" name="comt-img" id="comt-img" class="comt-img">';
        $('.comt-upload-box').html(input);
        var comt_img = $('#comt-img').fileuploader(comt_config);

    }

    $(document).on('click','.com-code-btn',function(){
        $('.code-box-drop').fadeToggle(100);
    }); 

    function adjustTextareaHeight() {
        var textarea = $('.comarea textarea#comment');
        textarea.height(0); // 先将高度设置为 0，以便重新计算高度
        var scrollHeight = textarea[0].scrollHeight; // 获取内容的实际高度
        textarea.height(scrollHeight); // 设置 textarea 的高度为实际高度
      }

    $(document).on('click','.insert-code',function(){
        var code = $(this).prev('textarea').val();
        var insert = "\n[code]\n"+code+"\n[/code]\n";
        var textarea = $('.comarea textarea#comment');
        var content = textarea.val();
        textarea.val(content+insert);
        adjustTextareaHeight();
        textarea.focus();
    }); 
    
    

    $('body').on('click', function(event) {
        var target = $(event.target);
        var elementToHide = $('.comt-tool-box');
        
        // 判断点击目标元素是否是要隐藏的元素或其子元素
        if (!target.is(elementToHide) && !target.closest(elementToHide).length) {
          elementToHide.hide();
        }
      });

} // endif fileuploader

// 上传组件翻译
if (typeof $.fn.fileuploader !== 'undefined') {
$.extend($.fn.fileuploader.languages, {
    zh_CN: {
        button: function(options) {
            return '本地' + (options.limit == 1 ? '文件' : '文件');
        },
        feedback: function(options) {
            return '选择' + (options.limit == 1 ? '文件' : '文件') + '上传';
        },
        feedback2: function(options) {
            return options.length + ' ' + (options.length > 1 ? '文件' : '文件') + '被选择';
        },
        edit: '编辑',
        upload: '上传',
        remove: '移除',
        confirm: '确认',
        cancel: '取消',
        name: '名称',
        type: '类型',
        size: '大小',
        dimensions: '方面',
        duration: '期间',
        crop: '裁剪',
        rotate: '旋转',
        sort: '排序',
        download: '下载',
        remove: '删除',
        drop: '拖拽文件到此处上传',
        paste: '<div class="fileuploader-pending-loader"></div> 粘贴文件，单击此处取消.',
        removeConfirmation: '你确定要移除此文件?',
        errors: {
            filesLimit: '只允许上传1个图像',
            filesLimit: function(options) {
                return '只允许 ${limit} ' + (options.limit == 1 ? '文件' : '文件') + ' 上传.'
            },
            filesType: '只允许 ${extensions} 文件被上传.',
            fileSize: '${name} 尺寸太大! 请选择文件低于 ${fileMaxSize}MB.',
            filesSizeAll: '文件总尺寸太大! 所选文件大小需低于 ${maxSize} MB.',
            fileName: '相同名称文件 ${name} 已被选择.',
            remoteFile: '不允许远程文件.',
            folderUpload: '此文件夹不被允许.'
        },
    }
  });

} // endif fileuploader languages

// vip权限展开
/* new Readmore('.vip-limits', {
    speed: 75,
    collapsedHeight: 300,
    moreLink: '<a  class="vipmore" href="#"><i class="ri-arrow-down-s-line"></i>更多权益</a>',
    lessLink: '<a class="vipless" href="#"><i class="ri-arrow-up-s-line"></i>收起</a>'
}); */

// 付费预览图切换
$('body').on('click','.dd-box-gals', function(){
    var t = $(this);
    var img = t.find('img').attr('src');
    t.siblings().removeClass('picked');
    t.addClass('picked');
    $('.dd-box-fea').attr('href',img);
    $('.dd-box-fea').find('img').attr('src',img);
    
});

// 模态框基础
function ppo_modal(object){
    var html = '<div id="'+object+'" uk-modal="bg-close:false;esc-close:false">';
        html += '<div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical '+object+' uk-animation-scale-up uk-animation-fast">';
        html += '<div class="inner"></div>';
        html += ' <button class="uk-modal-close-default" type="button" uk-close></button>';
        html += '</div></div>';

        return html;
}

// 付费下载模态框
function ppo_down_modal(){
    var html = '<div id="ppo-down-modal" uk-modal="bg-close:false;esc-close:false">';
        html += '<div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical ppo-down-modal uk-animation-scale-up uk-animation-fast">';
        html += '<div class="inner" uk-overflow-auto></div>';
        html += ' <button class="uk-modal-close-default" type="button" uk-close></button>';
        html += '</div></div>';

        return html;
}

// 文章底部工具栏
$(document).ready(function(){
    if(Theme.pid){
        var $target = $('.single-footer');
        if (!$target.length) return;
        var width = $target.width();
        $(window).on('scroll.stickyFooter', function() {
            var offset = $target.offset();
            if (!offset) return;
            var targetTop = offset.top;
            var scrollTop = $(window).scrollTop();
            var d = $(window).height();

            if (scrollTop + d > targetTop) {
                $target.removeClass('sticky', true);
            } else {
                $target.toggleClass('sticky', true);
                $target.children().css('width', width);
            }
        });
    }
});

new ClipboardJS('.code-copy');
$('body').on('click','.code-copy', function(){
    //cocoMessage.info('复制成功');
    toastfy('复制成功','success');
});
  //instantclick预加载
  //InstantClick.init(50);

// 骨架屏模板
var skeletonTemplates = {
    "normal-list": `
    <div class="uk-width-1-1@m">
      <div class="skeleton-container">
        <div class="skeleton skeleton-full-box"></div>
      </div>
    </div>    
    `,
    "follow-list": `
    <div class="uk-width-1-3@m">
      <div class="skeleton-container">
      <div class="skeleton-row">
        <div class="skeleton skeleton-avatar-square"></div>
        <div class="skeleton-text-group">
            <div class="skeleton skeleton-text-line"></div>
            <div class="skeleton skeleton-text-line short"></div>
        </div>
        </div>
      </div>
    </div>    
    `,
    "post-list": `
    <div class="uk-width-1-3@m">
      <div class="skeleton-container">
          <div class="skeleton skeleton-image"></div>
         <div class="skeleton skeleton-text-line"></div>
         <div class="skeleton skeleton-text-line short"></div>
      </div>
    </div>
    `,
    "user-comment": `
      <div class="uk-width-1-2@m">
       <div class="skeleton-row">
        <div class="skeleton-text-group">
            <div class="skeleton skeleton-text-line"></div>
            <div class="skeleton skeleton-text-line short"></div>
        </div>
        <div class="skeleton skeleton-avatar-square"></div>
        </div>
      </div>
    `,
    "moments-list": `
      <div class="uk-width-1-3@m">
       <div class="skeleton-container">
          <div class="skeleton skeleton-image"></div>
      </div>
      </div>
    `,
    "moment-list": `
    <div class="uk-width-1-2@m">
      <div class="skeleton-container">
      <div class="skeleton-row">
        <div class="skeleton skeleton-avatar-square"></div>
        <div class="skeleton-text-group">
            <div class="skeleton skeleton-text-line"></div>
            <div class="skeleton skeleton-text-line short"></div>
        </div>
        </div>
          <div class="skeleton skeleton-image"></div>
         <div class="skeleton skeleton-text-line"></div>
         <div class="skeleton skeleton-text-line short"></div>
      </div>
    </div>
    `,
  };

document.body.addEventListener("htmx:beforeRequest", function (e) {
    const triggerEl = e.target;
    const skeletonType = triggerEl.getAttribute("data-skeleton");
    const targetSelector = triggerEl.getAttribute("hx-target");
    const container = document.querySelector(targetSelector);
  
    if (skeletonType && skeletonTemplates[skeletonType] && container) {
      // 根据类型插入多份骨架（根据需要调整数量）
      container.innerHTML = '<div class="skeleton-grid uk-grid-small" uk-grid>'
                          + skeletonTemplates[skeletonType]
                          + skeletonTemplates[skeletonType]
                          + skeletonTemplates[skeletonType]
                          + '</div>';
    }
    //e.preventDefault();
  }); 

 
  // htmx 加载完成后重新初始化组件
  document.body.addEventListener("htmx:afterSwap", function(event) {
    if (lazyLoadInstance) {
      lazyLoadInstance.update(); // 更新实例，识别新加载的 lazy 图片
    }
    $("time.timeago").timeago();
    
    $('.follow-list-btn')
    .popup({
        inline     : true,
        hoverable  : true,
        position   : 'bottom center',
    });

    var url = event.detail.xhr?.responseURL || '';

    /* // ✅ 判断是否是签到接口
    if (url.includes('action=ppo_checkin')) {
        var $checink = $('.user-signed-btn');
        if (!$checink.length) return;

        var xp = $checink.attr('data-xp');
        var point = $checink.attr('data-point');

        Toastify({
            text: `签到成功！经验+${xp}， 积分+${point}`,
            className: "info",
            style: {
              background: "linear-gradient(to right, #00b09b, #96c93d)",
            }
          }).showToast();
    } */

  });

  $('.follow-list-btn')
    .popup({
        inline     : true,
        hoverable  : true,
        position   : 'bottom center',
    });

$('body').on('click','.ppo-navtab a',function(){
    var t = $(this);
    t.addClass('active').siblings().removeClass('active');
});

// 封装toastfy
function toastfy(msg, type) {
  var background;
  var color = '#ffffff';

  switch(type){
    case 'error':
        background = 'linear-gradient(to right, #ff3a3a, #ff5656)'; // 红色
        break;
    case 'info':
        background = 'linear-gradient(to right, #1f213b, #292a3c)'; // 默认
        break;
    case 'success':
        background = 'linear-gradient(to right, #03c956, #3ebe6e)';
        break;
    case 'normal':
        background = 'linear-gradient(to right, #ffffff, #ffffff)'; // 默认
        color = '#454545';
        break;    
  }
  

  Toastify({
    text: msg,
    duration: 5000,
    position: "center",
    stopOnFocus: true,  
    style: {
      background: background,
      color:color
    }
  }).showToast();
}

// 海报模态
$('body').on('click','.poster-btn',function(){
	 var t = $(this),
		pid = Theme.pid;
		
		$.ajax({
			type: "post",
			url:Theme.ajaxurl,
			dataType:  'json',
			data: {
				'action':'load_poster_modal',
				pid: pid,
			},	
		beforeSend: function () {
			loading_start($('.poster-canvas'));
		},
		success: function(data) {
			loading_done($('.poster-canvas'));
			$('.poster-canvas').html(data.html);
		 },
	});
		
});

// 生成海报
$('body').on('click','.download-poster',function(){
	var element = document.querySelector('.poster-canvas');
	html2canvas(element,{useCORS: true}).then(canvas => {
		// 将canvas转换为Data URL
		var imgData = canvas.toDataURL('image/png');
		var filename = $('.poster-trim h4').text();

		var link = document.createElement('a');
		link.download = filename+'.png';
		link.href = imgData;
		link.click();
	});
});

// 侧边栏固定
if (typeof $.fn.hcSticky !== 'undefined' && Theme.nav_height) {
  $( '.widget_inner , .user-left-nav' ).hcSticky( {
    top: parseInt(Theme.nav_height) || 72,
  } );
}

// const scroller = new SmoothScroll({
//     lerp: 0.12,              // 平滑系数 (0.08~0.15 最舒适)
//     wheelMultiplier: 1.2,   // 滚轮灵敏度
//     touchMultiplier: 1.5,   // 触摸灵敏度
//     offset: 0               // 目标偏移量（如固定导航栏高度）
//   });

$(document).on('click','.pix-sign-tab',function(){
    var t = $(this);
    t.addClass('active').siblings().removeClass('active');
    $('.pix-sign-rank-list[data-tab="'+t.data('tab')+'"]').show().siblings('.pix-sign-rank-list').hide();
});

