var current_mo_data = {};

function pix_moment_plain_text(value){
    var text = String(value || '');
    text = text.replace(/\[link\s+([^\]]*)\]/gi, function(match, attrs){
        var title = '';
        attrs.replace(/(\w+)=(["'])(.*?)\2/g, function(all, key, quote, val){
            if(key === 't') title = val;
            return all;
        });
        return title || '';
    });
    text = text.replace(/\[s=[^\]]+\]/gi, '表');
    var node = document.createElement('div');
    node.innerHTML = text;
    return (node.textContent || node.innerText || '').replace(/\u00a0/g, '').trim();
}

$(document).ready(function() {
	
    $('#moment_content').on('blur keyup input', function(){
        var editor = document.querySelector('[data-pix-editor][data-input="moment_content"]');
        var text = editor ? (editor.textContent || '').replace(/\u00a0/g, '').trim() : pix_moment_plain_text($(this).val());
        var emojiCount = editor ? editor.querySelectorAll('.pix-editor-emoji').length : 0;
        var count = text.length + emojiCount;
        $('.mo-num').text(count);
    });

	// Legacy uploaders are kept for compatibility, but PixUploader 2.0 no longer renders these inputs.
    var $legacyGalleryInput = $('input[name="gallery_mo"]');
    if ($legacyGalleryInput.length && $.fn.fileuploader) {
	$legacyGalleryInput.fileuploader({
		limit: 9,
		fileMaxSize: 5,
	
        extensions: ['image/*'],
		changeInput: ' ',
		theme: 'thumbnails',
        enableApi: true,
		addMore: true,
		thumbnails: {
			box: '<div class="fileuploader-items">' +
                      '<ul class="fileuploader-items-list">' +
					      '<li class="fileuploader-thumbnails-input"><div class="fileuploader-thumbnails-input-inner"><i>+</i></div></li>' +
                      '</ul>' +
                        '<div class="gallery-link-box"><textarea id="moment_gallery_link" name="moment_gallery_link" placeholder="支持多个外链，一行一个" style="overscroll-behavior: contain;"></textarea><div class="btn-group"><a class="insert">插入</a><a class="cancel"><i class="ri-close-line"></i></a></div></div>' +
                    '</div>',
			item: '<li class="fileuploader-item mo-gallery-item">' +
				       '<div class="fileuploader-item-inner">' +
                           '<div class="type-holder">${extension}</div>' +
                           '<div class="actions-holder">' +
						   	   '<button type="button" class="fileuploader-action fileuploader-action-remove" title="${captions.remove}"><i class="fileuploader-icon-remove"></i></button>' +
                           '</div>' +
                           '<div class="thumbnail-holder">' +
                               '${image}' +
                               '<span class="fileuploader-action-popup"></span>' +
                           '</div>' +
                           //'<div class="content-holder"><h5>${name}</h5><span>${size2}</span></div>' +
                           '<div class="ppo-short-holder"></div>' +
                       	   '<div class="progress-holder">${progressBar}</div>' +
                       '</div>' +
                  '</li>',
			item2: '<li class="fileuploader-item mo-gallery-item gallery-link-item">' +
				       '<div class="fileuploader-item-inner">' +
                           '<div class="type-holder">${extension}</div>' +
                           '<div class="actions-holder">' +
						   	   '<button type="button" class="fileuploader-action fileuploader-urlitem-remove fileuploader-action-remove" title="${captions.remove}"><i class="fileuploader-icon-remove"></i></button>' +
                           '</div>' +
                           '<div class="thumbnail-holder">' +
                               '${image}' +
                               '<span class="fileuploader-action-popup"></span>' +
                           '</div>' +
                           '<div class="ppo-short-holder"><button type="button" class="fileuploader-action fileuploader-action-sort" title="${captions.sort}"><i class="fileuploader-icon-sort"></i></button></div>' +
                           //'<div class="content-holder"><h5>${name}</h5><span>${size2}</span></div>' +
                       	   '<div class="progress-holder">${progressBar}</div>' +
                       '</div>' +
                   '</li>',
			startImageRenderer: false,
            canvasImage: false,
			_selectors: {
				list: '.fileuploader-items-list',
				item: '.fileuploader-item',
                sort: '.ppo_sort',
				start: '.fileuploader-action-start',
				retry: '.fileuploader-action-retry',
                sorter: '.fileuploader-action-sort',
				remove: '.fileuploader-action-remove'
			},
			onItemShow: function(item, listEl, parentEl, newInputEl, inputEl) {
				var plusInput = listEl.find('.fileuploader-thumbnails-input'),
                    api = $.fileuploader.getInstance(inputEl.get(0));
				
                plusInput.insertAfter(item.html)[api.getOptions().limit && api.getChoosedFiles().length >= api.getOptions().limit ? 'hide' : 'show']();
				
				if(item.format == 'image') {
					item.html.find('.fileuploader-item-icon').hide();
				}
                
               
			},
            onItemRemove: function(html, listEl, parentEl, newInputEl, inputEl) {
                var plusInput = listEl.find('.fileuploader-thumbnails-input'),
				    api = $.fileuploader.getInstance(inputEl.get(0));
            
                html.children().animate({'opacity': 0}, 200, function() {
                    html.remove();
                    
                    if (api.getOptions().limit && api.getChoosedFiles().length - 1 < api.getOptions().limit)
                        plusInput.show();
                });
            }
            
		},
        dragDrop: {
			container: '.fileuploader-thumbnails-input'
		},
		afterRender: function(listEl, parentEl, newInputEl, inputEl) {
			var plusInput = listEl.find('.fileuploader-thumbnails-input'),
                btnIput = $('.mo-img-btn.upload'),
				api = $.fileuploader.getInstance(inputEl.get(0));
		
			plusInput.on('click', function() {
				api.open();
			});
            btnIput.on('click', function() {
                if($(this).hasClass('disabled')) return;
                if($(this).hasClass('upload')){
                    api.open();
                    $(this).removeClass('upload');
                }
			
			});
            api.getOptions().dragDrop.container = plusInput;

            // 插入外链图
            $('.gallery-link-box .insert').on('click', function() {
                var url_data = $('#moment_gallery_link').val();

                if(url_data == ''){
                    toastfy('请输入外链地址!','error');
                    return;
                }

                var gallery_num = current_mo_data.gallery_num ? current_mo_data.gallery_num : api.getOptions().limit;

                var url_list = url_data.split('\n').map(function(line) {
                    return line.trim();
                });

                if(($('.mo-gallery-item').length + url_list.length) > gallery_num){
                    toastfy('最多只能上传'+gallery_num+'张图片!','error');
                    return false;
                }

                $.each(url_list, function(index, value) {
                    var filename = value.substring(value.lastIndexOf('/') + 1); // 获取文件名
                    var extension = filename.substring(value.lastIndexOf('.') + 1); // 获取文件后缀
                    var file = {
                        name:filename,
                        file:value,
                        size:200,
                        type:'image/'+extension

                    };
                    var item = api.append(file);
                    item.html.attr('data-src',value);
                    item.html.attr('data-thum',value);
                });   

                $('#moment_gallery_link').val('');
            
            });
		},


         beforeSelect: function(item, listEl, parentEl, newInputEl, inputEl) {
            var api = $.fileuploader.getInstance(inputEl.get(0));
            if(!Theme.tid){
                var image_allow = current_mo_data.mo_user_power['gallery'];
                api.setOption('limit', current_mo_data.gallery_num);
                if(!image_allow){
                    toastfy('您没有权限上传图片!','error');
                    return false;
                }
            }
        }, 
        
		upload: {
			url: Theme.ajaxurl + "?action=upload_mo_img&security=" + Theme.moment_nonce,
            data: null,
            type: 'POST',
            enctype: 'multipart/form-data',
            start: true,
            synchron: true,
            beforeSend: null,
            onSuccess: function(data, item) {
				item.html.find('.fileuploader-action-remove').addClass('fileuploader-action-success');
                item.html.attr('attac_id',data.attac_id);
                item.html.attr('data-thum',data.large);
                item.html.attr('data-src',data.full);
				setTimeout(function() {
					item.html.find('.progress-holder').hide();
					item.renderThumbnail();
                    
                    item.html.find('.fileuploader-action-popup, .fileuploader-item-image').show();
                    //item.html.find('.fileuploader-action-remove').before('<button type="button" class="fileuploader-action fileuploader-action-sort" title="Sort"><i class="fileuploader-icon-sort"></i></button>');
                    item.html.find('.ppo-short-holder').append('<button type="button" class="fileuploader-action fileuploader-action-sort" title="Sort"><i class="fileuploader-icon-sort"></i></button>');
                }, 400);
            },
            onError: function(item) {
				item.html.find('.progress-holder, .fileuploader-action-popup, .fileuploader-item-image').hide();
            },
            onProgress: function(data, item) {
                var progressBar = item.html.find('.progress-holder');
				
                if(progressBar.length > 0) {
                    progressBar.show();
                    progressBar.find('.fileuploader-progressbar .bar').width(data.percentage + "%");
                }
                
                item.html.find('.fileuploader-action-popup, .fileuploader-item-image').hide();
            },
        },
        sorter: {
			selectorExclude: null,
			placeholder: null,
			scrollContainer: window,
			onSort: function(list, listEl, parentEl, newInputEl, inputEl) {
                var api = $.fileuploader.getInstance(inputEl.get(0)),
                    fileList = api.getFileList(),
                    _list = [];
                
                $.each(fileList, function(i, item) {
                    _list.push({
                        name: item.name,
                        index: item.index
                    });
                });
                
                /* $.post('php/ajax_sort_files.php', {
                    _list: JSON.stringify(_list)
                }); */
			}
		},
        onRemove: function(item) {
			/* $.post('php/ajax_remove_file.php', {
				file: item.name
			}); */
            //console.log(item.html)
            if(item.html.hasClass('gallery-link-item')){
                return false;
            }
            $.ajax({
                type: "post",
                url:Theme.ajaxurl,
                dataType:  'json',
                data: {
                    'action':'delete_moment_file',
                    'security': Theme.moment_nonce,
                    file: item.name,
                    attac_id:item.html.attr('attac_id')
                    },	
        
                beforeSend: function () {
                    
                },
                success: function(data){
                    if(data.code == 1){
                        toastfy(data.msg,'success');
                    } else {
                        toastfy(data.msg,'error');
                    } 
                }	
            });
		},
		captions: $.extend(true, {}, $.fn.fileuploader.languages['zh_CN'], {
        }),
	});
    }

    $('body').on('click','.add-gallery-link a',function(){
        $('.gallery-link-box').slideToggle(200);
        $('textarea#moment_gallery_link').focus();
    });

    $(document).on('input propertychange','textarea#moment_gallery_link',function(event){ 
        // 自动调整textarea的高度
        this.style.height = '60px';
        this.style.height = (this.scrollHeight) + 'px';
     
    });

    $('body').on('click','.gallery-link-box .btn-group a.cancel',function(){
        $('.gallery-link-box').slideToggle(200);
    });

    $('body').on('click','.fileuploader-urlitem-remove',function(){
        $(this).parents('.fileuploader-item').remove();
    }); 

    //视频上传

    var $legacyVideoInput = $('input[name="video_mo"]');
    if ($legacyVideoInput.length && $.fn.fileuploader) {
    $legacyVideoInput.fileuploader({
        limit: 1,
		fileMaxSize: 10,
        extensions: ['video/*'],
        enableApi: true,
        //changeInput: '<div class="video-upload-btn"><i class="ri-video-upload-line"></i> 上传视频</div>',
        thumbnails: {
            //itemPrepend: true,
            useObjectUrl: true,
			canvasImage: true,
            onImageLoaded: function(item, listEl, parentEl, newInputEl, inputEl) {
                //console.log(item);
                
                if(!item.data.action == 'edit' || !item.data.action){
                    var cover_blob = Base64ToBlob(item.reader.frame,"image/png");
                    var pre_cover = URL.createObjectURL(cover_blob)
                    
                    //$('.mo-video-box .video-poster').html('<div class="video-poster-inner"><img src="'+thum.url+'" class="video-preview"></div>');
                    //console.log(item);

                    var formData = new FormData();
                    var blob_name = new Date().getTime() + '.png';
                    formData.append("blob_cover", cover_blob , blob_name);
                    $.ajax({
                        type: "POST",
                        url:Theme.ajaxurl + "?action=moment_cover_upload",
                        dataType:  'json',
                        data: formData,	
                        processData : false,
                        contentType : false,	
                        beforeSend: function () {
                        
                        },
                        success: function(data){
                            item.html.attr('cover_attac_id',data.attac_id);
                    
                        }	
                    });
                } else {
                    var pre_cover = item.data.thumbnail;
                    ;
                }
                item.html.addClass('mo-video-item');
                item.html.find('.fileuploader-item-image').html('<img src="'+pre_cover+'" class="video-preview">');
                
            },
        },

        beforeSelect: function(item, listEl, parentEl, newInputEl, inputEl) {
            if(!Theme.tid){
                var video_allow = current_mo_data.mo_user_power['video'];
                if(!video_allow){
                    toastfy('您没有权限上传视频!','error');
                    return false;
                }
            }
        }, 

        onSelect: function(item) {
            //var thum = item.reader;
            //var thum = Base64ToBlob(frame,"image/jpeg");
            //var imgDataURL = URL.createObjectURL(item.file);
            
            //console.log(item);
           // if (!item.html.find('.fileuploader-action-start').length)
           var preview_html = '<div id="mo-video-poster" class="hint--top hint--rounded" data-hint="更换封面">' +
                                   '<input type="file" name="upload-movideo-poster" id="upload-movideo-poster">' +
                                   '<button type="button" class="edit-poster"><i class="ri-image-edit-line"></i></button>' +
                                '</div>';
            item.html.find('.fileuploader-action-remove').before(preview_html);
        },
		upload: {
            url: Theme.ajaxurl + "?action=upload_mo_video",
            data: null,
            type: 'POST',
            enctype: 'multipart/form-data',
            start: true,
            synchron: true,
            beforeSend: function(item) {
				var input = $('#custom_file_name');
				
				// set the POST field
				if(input.length)
					item.upload.data.custom_name = input.val();
				
				// reset input value
				input.val("");
			},
            onSuccess: function(result, item) {
                var data = {};
				
				if (result && result.files)
                    data = result;
                else
					data.hasWarnings = true;
				
				// get the new file name
                if(data.isSuccess && data.files[0]) {
                    item.html.attr('attac_id',data.attac_id);
                    item.name = data.files[0].name;
                    item.html.find('.column-title div').animate({opacity: 0}, 400);
                }
                
                item.html.find('.fileuploader-action-remove').addClass('fileuploader-action-success');
                setTimeout(function() {
					item.html.find('.column-title div').attr('title', item.name).text(item.name).animate({opacity: 1}, 400);
                    item.html.find('.progress-bar2').fadeOut(400);
                }, 400);
            },
            onError: function(item) {
				var progressBar = item.html.find('.progress-bar2');
				
				// make HTML changes
				if(progressBar.length > 0) {
					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');
				
				// make HTML changes
                if(progressBar.length > 0) {
                    progressBar.show();
                    progressBar.find('span').html(data.percentage + "%");
                    progressBar.find('.fileuploader-progressbar .bar').width(data.percentage + "%");
                }
            },
            onComplete: null,
        },
		onRemove: function(item, listEl, parentEl, newInputEl, inputEl) {
			// send POST request
            /* console.log(item.html);
            if(item.html.hasClass('gallery-link-item')){
                return false;
            } */
            $.ajax({
                type: "post",
                url:Theme.ajaxurl,
                dataType:  'json',
                data: {
                    'action':'delete_moment_file',
                    'security': Theme.moment_nonce,
                    file: item.name,
                    attac_id:item.html.attr('attac_id')
                    },	
        
                beforeSend: function () {
                    
                },
                success: function(data){
                    if(data.code == 1){
                        toastfy(data.msg,'success');
                    } else {
                        toastfy(data.msg,'error');
                    } 

                }	
            });
		},
        captions: $.extend(true, {}, $.fn.fileuploader.languages['zh_CN'], {
        }),
	});
    }

    // 上传视频封面
    $('body').on('change','#upload-movideo-poster',function(){
        var t = $(this);
        var file = this.files[0];
        var imageURL = URL.createObjectURL(file);

        if(!Theme.tid){
            var video_allow = current_mo_data.mo_user_power['video'];
            if(!video_allow){
                toastfy('您没有权限上传视频封面!','error');
                return false;
            }
        }
        //console.log(file);
        $('.mo-video-item').find('.fileuploader-item-image img').attr('src', imageURL);
        var formData = new FormData();
        formData.append('blob_cover',file);

        $.ajax({
            type: "POST",
            url:Theme.ajaxurl + "?action=moment_cover_upload",
            dataType:  'json',
            data: formData,	
            processData : false,
            contentType : false,	
            beforeSend: function () {
               toastfy('上传封面中..','info');
            },
            success: function(data){
                if(data.isSuccess && data.files[0]) {
                    t.parents('.mo-video-item').attr('cover_attac_id',data.attac_id);
                    toastfy('上传成功','success');
                }
        
            }	
        });
    });
    


    //文件上传

    var $legacyFileInput = $('input[name="file_mo"]');
    if ($legacyFileInput.length && $.fn.fileuploader) {
    $legacyFileInput.fileuploader({
        limit: 3,
		fileMaxSize: 10,
        extensions: ['text/plain','pdf','doc','docx','xls','xlsx','ppt','pptx','zip'],
        enableApi: true,
        //changeInput: '<div class="video-upload-btn"><i class="ri-video-upload-line"></i> 上传视频</div>',
        onSelect: function(item) {
            item.html.addClass('mo-file-item');
            //if (!item.html.find('.fileuploader-action-start').length)
                //item.html.find('.fileuploader-action-remove').before('<button type="button" class="fileuploader-action fileuploader-action-start" title="Upload"><i class="fileuploader-icon-upload"></i></button>');
        },
        afterRender: function(listEl, parentEl, newInputEl, inputEl) {
            // callback will go here
        },
		upload: {
            url: Theme.ajaxurl + "?action=moment_file_upload",
            data: null,
            type: 'POST',
            enctype: 'multipart/form-data',
            start: true,
            synchron: true,
            beforeSend: function(item) {
				var input = $('#custom_file_name');
				
				// set the POST field
				if(input.length)
					item.upload.data.custom_name = input.val();
				
				// reset input value
				input.val("");
			},
            onSuccess: function(result, item) {
                var data = {};
				
				if (result && result.files)
                    data = result;
                else
					data.hasWarnings = true;
				
				// get the new file name
                if(data.isSuccess && data.files[0]) {
                    item.html.attr('attac_id',data.attac_id);
                    //item.name = data.files[0].name;
                    item.html.find('.column-title div').animate({opacity: 0}, 400);
                }
                

                item.html.find('.fileuploader-action-remove').addClass('fileuploader-action-success');
            
                setTimeout(function() {
					item.html.find('.column-title div').attr('title', item.name).text(item.name).animate({opacity: 1}, 400);
                    item.html.find('.progress-bar2').fadeOut(400);
                }, 400);
            },
            onError: function(item) {
				var progressBar = item.html.find('.progress-bar2');
				
				// make HTML changes
				if(progressBar.length > 0) {
					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');
				
				// make HTML changes
                if(progressBar.length > 0) {
                    progressBar.show();
                    progressBar.find('span').html(data.percentage + "%");
                    progressBar.find('.fileuploader-progressbar .bar').width(data.percentage + "%");
                }
            },
            onComplete: null,
        },

        beforeSelect: function(item, listEl, parentEl, newInputEl, inputEl) {
            var api = $.fileuploader.getInstance(inputEl.get(0));
            if(!Theme.tid){
                var file_allow = current_mo_data.mo_user_power['file'];
                api.setOption('limit', current_mo_data.file_num);
                if(!file_allow){
                    toastfy('您没有权限上传文件!','error');
                    return false;
                }
            }
        }, 
        
		onRemove: function(item) {
			// send POST request
            $.ajax({
                type: "post",
                url:Theme.ajaxurl,
                dataType:  'json',
                data: {
                    'action':'delete_moment_file',
                    'security': Theme.moment_nonce,
                    file: item.name,
                    attac_id:item.html.attr('attac_id')
                    },	
        
                beforeSend: function () {
                    
                },
                success: function(data){
                    if(data.code == 1){
                        toastfy(data.msg,'success');
                    } else {
                        toastfy(data.msg,'error');
                    } 
                }	
            });
		},
        captions: $.extend(true, {}, $.fn.fileuploader.languages['zh_CN'], {
        }),
	});
    }
	
});

function has_pix_moment2_attachments(){
    var uploader = $('#pix-moment-uploader').data('pixUploader');
    if(!uploader || !uploader.items){
        return false;
    }
    if(typeof uploader.hasItems === 'function'){
        return uploader.hasItems();
    }
    return uploader.items.some(function(item){
        return item.status !== 'removing';
    });
}

function has_moment_cards(){
    return $('.card-wrap .mo-card-item, .card-wrap .card-box').length > 0;
}

// 片刻类型
$(document).on('click','.mo-btn',function(){
    var t = $(this);
    var type = t.attr('data');
    var box = $('.mo-'+type+'-box');

    if(t.hasClass('disabled')){
        toastfy('此圈子未开启该功能','error');
        return;
    }

    if(type == 'card'){
        var uploader = $('#pix-moment-uploader').data('pixUploader');
        if(uploader && typeof uploader.openCardForm === 'function'){
            if(uploader.activeKind && uploader.activeKind !== 'card'){
                toastfy('当前片刻已添加其他附件，请先移除附件后再添加卡片','error');
                return;
            }
            $('.mo-toggle-box').slideUp(200);
            $('.mo-btn').removeClass('active');
            t.addClass('active');
            $('.pix-moment-attach-trigger').removeClass('is-active');
            uploader.openCardForm();
            $('.push-mo-btn').attr('type','text');
            return;
        }
        if(has_pix_moment2_attachments()){
            toastfy('当前片刻已添加附件，请先移除附件后再添加卡片','error');
            return;
        }
    }

    if(t.hasClass('active')){
        box.slideUp(200);
        t.removeClass('active');
        $('.push-mo-btn').attr('type','text');
    } else {
        t.addClass('active');
        t.siblings().removeClass('active');
        box.siblings('.mo-toggle-box').slideUp(200);
        box.slideDown(200);
        $('.push-mo-btn').attr('type',type);
    }

});

$(document).on('click','.cancel-toggle-box i',function(){
    var t = $(this);
    $('.push-mo-btn').attr('type','text');
    t.parents('.mo-toggle-box').slideUp(200);
    $('.mo-btn').removeClass('active');
});

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

function apply_current_moment_data(data){
    current_mo_data = data || {};

    if(current_mo_data.joined == false){
        toastfy('您没有加入该圈子！','error');
        $('.mo-tool-nav .left-tool').css('opacity',1);
        return false;
    }

    var user_power = current_mo_data.mo_user_power || {};
    $.each(user_power, function(i,val){
        if(val){
            $('.mo-'+i+'-btn').removeClass('disabled');
        } else {
            $('.mo-'+i+'-btn').addClass('disabled');
        }
    });

    if(current_mo_data.gallery_link){
        $('.add-gallery-link').show();
        $('.pix-uploader-external').show();
    } else {
        $('.add-gallery-link').hide();
        $('.pix-uploader-external').hide();
    }

    $('.mo-tool-nav .left-tool').css('opacity',1);
    return true;
}

// 圈子选择
$(document).on('click','.mo-circle-item',function(){
    var t = $(this);
        cat_name = t.find('.title').text(),
        cat_id = t.attr('catid'),
        cat_img = t.find('.left').html();
        btn = $('.mo-cir-btn');
        arr = ppo_user_data[0];
        
        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                action:'get_current_mo_data',
                security: Theme.moment_nonce,
                term_id:cat_id
            },
            beforeSend: function () {
            $('.mo-tool-nav .left-tool').css('opacity',0.2);
        },
        success: function(data){
            if(apply_current_moment_data(data) === false){
                return false;
            }

            btn.find('span').text(cat_name);
            btn.find('.cat-thum').html(cat_img);
            
            btn.addClass('active');
            $('.push-mo-btn').attr('catid',cat_id);

            
        }
        
    });


        
});


function get_pix_moment2_payload(){
    var uploader = $('#pix-moment-uploader').data('pixUploader');
    if(!uploader || typeof uploader.value !== 'function'){
        return null;
    }

    var value = uploader.value();
    if(!value || !value.items || !value.items.length){
        return null;
    }

    var first = value.items[0],
        kind = first.kind || value.type;

    if(kind == 'image'){
        return {
            type: 'gallery',
            data: value.items.map(function(item){
                return {
                    src: item.url,
                    thum: item.thumb || item.url,
                    source: item.source || 'upload',
                    attach_id: item.attachment_id || 0
                };
            })
        };
    }

    if(kind == 'video'){
        if(first.source === 'bili'){
            return {
                type: 'video',
                data: [{
                    bvid: first.bvid,
                    type: 'bili'
                }]
            };
        }

        return {
            type: 'video',
            data: [{
                attach_id: first.attachment_id || first.id || 0,
                cover: first.poster_id || 0,
                cover_url: first.poster || '',
                type: 'local'
            }]
        };
    }

    if(kind == 'card'){
        return {
            type: 'card',
            data: value.items.map(function(item){
                return item.pid || item.attachment_id || item.id;
            }).filter(Boolean)
        };
    }

    return {
        type: 'file',
        data: value.items.map(function(item){
            return {
                attach_id: item.attachment_id || item.id || 0,
                file_title: item.title || '附件'
            };
        })
    };
}

function get_pix_moment2_ready_error(){
    var uploader = $('#pix-moment-uploader').data('pixUploader');
    if(!uploader || !has_pix_moment2_attachments()){
        return '';
    }
    if(typeof uploader.getBlockingStatus === 'function'){
        var status = uploader.getBlockingStatus();
        return status && !status.ok ? status.message : '';
    }

    var hasBusy = uploader.items.some(function(item){
        return item.status === 'queued' || item.status === 'uploading';
    });
    if(hasBusy){
        return '附件仍在上传中，请稍后发布';
    }
    return '';
}

// 发布片刻
$(document).on('click','.push-mo-btn',function(){
    var t = $(this);
    
        content = $("#moment_content").val(),
        title = $("#moment-title").val(),
        moment_type = t.attr('type'),
        tagid = t.attr('tagid');
        action_type = t.attr('action');
        pid = t.attr('pid') ? t.attr('pid') : 0;

        if(t.hasClass('protect')){
            toastfy('操作过快！','error');
            return;
        }

        //console.log(Theme.tid);
        if(Theme.tid){
            var catid = $('.mo-cir-btn').attr('catid');
        } else {
            var catid = t.attr('catid') || $('.mo-cir-btn').attr('catid');
        }


        if(!catid){
            toastfy('请选择圈子！','error');
            return;
        }

        if(has_pix_moment2_attachments() && has_moment_cards()){
            toastfy('卡片和上传附件不能同时发布，请保留其中一种','error');
            return;
        }

        var uploadError = get_pix_moment2_ready_error();
        if(uploadError){
            toastfy(uploadError,'error');
            return;
        }

        var pixPayload = get_pix_moment2_payload();
        if(pixPayload){
            moment_type = pixPayload.type;
            moment_data = pixPayload.data;
        } else {
            if(get_moment_error(moment_type) === false){
                moment_type = 'text';
            }
            get_moment_data(moment_type);
        }

        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                action: 'push_moment',
                'security': Theme.moment_nonce,
                content:content,
                catid:catid,
                tagid:tagid,
                moment_data:moment_data,
                title:title,
                moment_type:moment_type,
                action_type:action_type,
                pid:pid
                },	
    
            beforeSend: function () {
                t.addClass('is-loading protect').attr('aria-busy','true').data('old-text', t.text()).html('<i class="ri-loader-4-line"></i><span>发布中</span>');
            },
            success: function(data){
                if(data.status == '0') {
                    toastfy(data.msg,'error');
                    return false;
                } 
                toastfy(data.msg || '发布成功！','success');

                if(action_type === 'edit'){
                    window.setTimeout(function(){
                        window.location.href = data.post_status === 'pending'
                            ? (data.term_url || data.url || document.referrer || window.location.href)
                            : (data.url || document.referrer || window.location.href);
                    }, 650);
                    return;
                }

                if(data.html && $('#moment-item').length){
                    $('#moment-item .no-moment').remove();
                    $('#moment-item').prepend(data.html);
                    if (window.lazyLoadInstance && typeof lazyLoadInstance.update === 'function') {
                        lazyLoadInstance.update();
                    }
                    if (window.UIkit && UIkit.update) {
                        UIkit.update($('#moment-item')[0]);
                    }
                    if (window.ReadMore) {
                        ReadMore.init('.ppo-rich-text-content');
                    }
                } else if(data.post_status === 'pending') {
                    toastfy('审核通过后会显示在列表中','info');
                } else {
                    window.setTimeout(function(){
                        window.location.reload();
                    }, 500);
                }

                reset_moment_form_after_publish();
                
            
            },
            error: function(){
                toastfy('发布失败，请稍后重试','error');
            },
            complete: function(){
                var oldText = t.data('old-text') || '发布';
                t.removeClass('is-loading protect').removeAttr('aria-busy').text(oldText);
            }
        });

    // 初始化 ReadMore 文本截断
    if (window.ReadMore) {
        ReadMore.init('.ppo-rich-text-content');
    }

});

$(function(){
    var defaultCatId = $('.mo-cir-btn').attr('catid');
    if(defaultCatId){
        $('.push-mo-btn').attr('catid', defaultCatId);
    }
});

function reset_moment_form_after_publish(){
    $('#moment-title').val('');
    $('#moment_content').val('');
    var editor = $('#pix-moment-editor').data('pixEditor');
    if(editor && typeof editor.setContent === 'function'){
        editor.setContent('', {});
    } else if(editor && editor.el){
        editor.el.innerHTML = '';
        if(typeof editor.sync === 'function'){
            editor.sync();
        }
    }
    $('.mo-num').text('0');
    $('.mo-toggle-box').slideUp(200);
    $('.mo-btn').removeClass('active');
    $('.card-wrap').empty();
    $('input#mo_card_link, .netease_mo').val('');
    $('.audio-preview-box').empty();
    $('.mo-tag-btn span').text('话题');
    $('.mo-tag-btn').removeClass('active');
    $('.remove-motag').remove();
    $('.push-mo-btn').attr('type','text').removeAttr('pid').removeAttr('tagid');

    var uploader = $('#pix-moment-uploader').data('pixUploader');
    if(uploader){
        uploader.items.forEach(function(item){
            if(item.removeTimer){
                clearInterval(item.removeTimer);
            }
        });
        uploader.items = [];
        uploader.activeKind = '';
        uploader.render();
        uploader.changed();
    }
}

// 片刻错误提醒
function get_moment_error(type){

    switch (type) {
        case "gallery":
            var image_item = $('.mo-gallery-item');
            var image_url = $('#moment_gallery_link').val();
            if(!image_item.length > 0 && !image_url){
                return false;
            }

            break;
    
        case "video":
            var video_mode = $('span.mov-type.active').attr('type');
            var video_item = $('.mo-video-item');
            if(video_mode == 'local'){
                if(!video_item.length > 0 ){
                    return false;
                }
            } else {
                var bvid = $('input.bili_mo').val();
                if(!bvid){
                    return false;
                }
            }


            break;    
            
        case "file":
            var file_item = $('.mo-file-item');
            if(!file_item.length > 0 ){
                return false;
            }

            break;   

        case "card":
            var file_item = $('.mo-card-item');
            if(!file_item.length > 0 ){
                return false;
            }

            break;      
        
    }

}

// 获取片刻数据
function get_moment_data(type){
    moment_data = [];  
    switch (type) {
        case "gallery":

            $(".mo-gallery-item").each(function(){
                var attach_id = $(this).attr('attac_id'),
                    src = $(this).attr('data-src'),
                    thum = $(this).attr('data-thum');
                var obj = {
                    src:src,
                    thum:thum
                }
                moment_data.push(obj); //图片
            });
            break;

        case "video":
                var video_mode = $('span.mov-type.active').attr('type');

                if(video_mode == 'local'){
                    var v = $(".mo-video-item"),
                        attach_id = v.attr('attac_id'),
                        cover = v.attr('cover_attac_id');
                    var obj = {
                        attach_id:attach_id,
                        cover:cover,
                        type: 'local'
                        }
                } else {
                    var bvid = $('input.bili_mo').val();
                    var obj = {
                        bvid:bvid,
                        type: 'bili'
                    }
                }
                
                moment_data.push(obj); 
            
            break;    

        case "file":
            $(".mo-file-item").each(function(){
                //var v = $(".mo-file-item"),
                    attach_id = $(this).attr('attac_id');
                    file_title = $(this).find('.column-title div').text();
                var obj = {
                    attach_id:attach_id,
                    file_title:file_title 
                }
                moment_data.push(obj); 
            });
            break;    
            
        case "card":

                var v = $(".card-wrap .mo-card-item");
                v.each(function(){
                    var pid = $(this).attr('pid');
                    moment_data.push(pid); 
                });
            
            break;      

        case "audio":

                var aid = $(".netease_mo").val();
                var obj = {
                    aid:aid
                }
                moment_data.push(obj);
            
            break;         
    
        default:
            break;
    }
}

// 删除片刻
$('body').on('click','.mo-delete',function(){
  var pid = $(this).parent().attr('pid'),
      t = $(this),
      action = 'moment_delete';
  $.confirm({
    title: '删除片刻',
    titleClass: 'moment-delete-title',
    content: '片刻删除后将移至回收站，是否继续？',
    boxWidth: '350px',
    useBootstrap: false,
    scrollToPreviousElement: false,
    buttons: {   
        ok: {
            text: "确定",
            btnClass: 'delete-moment-sure',
            keys: ['enter'],
            action: function(){
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: Theme.ajaxurl,
                    data: {
                        'action': action,
                        'security': Theme.moment_nonce,
                        'pid': pid,
                    },
                    beforeSend: function () {
                        toastfy('正在删除..','info');
                    },
                    success: function (data) {
                        if(data.code == 1){
                            toastfy(data.msg,'success');
                            t.parents('.moment_item').remove();
                            //window.location.reload();
                        } else {
                            toastfy(data.msg,'error');
                        }
                    }
                });
            }
        },
        close: {
            text: "取消",
        },
    }
});
   
});

// 置顶片刻
$('body').on('click','.mo-edit-top',function(){
    var pid = $(this).parent().attr('pid'),
        state = $(this).attr('state'),
        t = $(this),
        action = 'moment_top';
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: Theme.ajaxurl,
        data: {
            'action': action,
            'security': Theme.moment_nonce,
            'pid': pid,
            'state': state
        },
        beforeSend: function () {
           
        },
        success: function (data) {
            if(data.state == 1){
                toastfy(data.msg,'success');
                t.parents('.moment_item').prependTo('#moment-item');
                t.attr('state','unstick');
                t.html('<i class="ri-arrow-up-line"></i>取消置顶');
                t.parents('.moment_item').find('.moment-footer .right').prepend('<span class="sticky_m_icon"><i class="ri-fire-line"></i>置顶</span>');
            } else {
                toastfy(data.msg,'info');
                window.location.reload();
                /* t.attr('state','stick');
                t.html('<i class="ri-arrow-up-line"></i>置顶片刻');
                t.parents('.moment_item').find('.moment-footer .right .sticky_m_icon').remove(); */
            }
        }
    });
});

// 片刻加精
$('body').on('click','.mo-edit-hot',function(){
    var pid = $(this).parent().attr('pid'),
        state = $(this).attr('state'),
        t = $(this),
        action = 'moment_hot';
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: Theme.ajaxurl,
        data: {
            'action': action,
            'security': Theme.moment_nonce,
            'pid': pid,
            'state': state
        },
        beforeSend: function () {
           
        },
        success: function (data) {
            if(data.state == 1){
                toastfy(data.msg,'success');
                t.attr('state','unhot');
                t.html('<i class="ri-vip-diamond-line"></i>取消加精');
                t.parents('.moment_item').find('.moment-footer .right').prepend('<span class="hot_m_icon"><i class="ri-vip-diamond-line"></i>精华</span>');
            } else {
                toastfy(data.msg,'info');
                t.parents('.moment_item').find('.moment-footer .right .hot_m_icon').remove();
                t.html('<i class="ri-vip-diamond-line"></i>加精');
                t.attr('state','hot');
                //window.location.reload();
                /* t.attr('state','stick');
                t.html('<i class="ri-arrow-up-line"></i>置顶片刻');
                t.parents('.moment_item').find('.moment-footer .right .sticky_m_icon').remove(); */
            }
        }
    });
});

//base64转blob
function Base64ToBlob(base64,contentType){
    var arr = base64.split(',')  //去掉base64格式图片的头部
    var bstr = atob(arr[1])   //atob()方法将数据解码
    var leng = bstr.length
    var u8arr = new Uint8Array(leng)
    while(leng--){
       u8arr[leng] =  bstr.charCodeAt(leng) //返回指定位置的字符的 Unicode 编码
    }
    var blob = new Blob([u8arr],{type:contentType})
    var blobImg = {}
    //blobImg.url = URL.createObjectURL(blob)  //创建URL
   // blobImg.name = new Date().getTime() + '.png'
    return blob 	
}

//话题表情
$(document).on('click','.mo-smile-btn',function(){
    //UIkit.dropdown('.emoji-box').show();
    if(!$('.mo-smile-drop .add-smily').length > 0){
    $.ajax({
        url : Theme.ajaxurl, // AJAX handler, declared before
        data : {
            'action': 'showemoji', // wp_ajax_cloadmore
            'security': Theme.moment_nonce,
        },
        type : 'POST',
        beforeSend : function ( xhr ) {

            loading_start($('.mo-smile-inner'));
            
            //loading_start($('.emoji-inner'));
        },
        success : function( data ){
            $('.mo-smile-inner').html(data.html);
        }
    });
    }
});

// 圈子选取
$('body').on('click','.moment-tags-item',function(){
    $('.mo-circle-content').empty();
    var t = $(this),
        tag = t.attr('data');

        if ((tag === 'join' || tag === 'create') && typeof ppo_require_login === 'function' && !ppo_require_login('请先登录后查看圈子列表')) {
            loading_done($('.mo-circle-content'));
            return false;
        }

        $('.moment-tags-item').removeClass('active');
        t.addClass('active');

       /*  var moveX = t.parent().position().left + $(this).parents('.uk-slider-items').scrollLeft();
        var pageX = $('.uk-slider-items').width();
        var blockWidth = $(this).width();
        var left = moveX - (pageX / 2) + (blockWidth / 2);
       
            $(".uk-slider-items").css({
                'transform': 'translate3d(-'+left+'px, 0px, 0px)',
                'transition-duration': '200ms'
            }); */
        

        //console.log(left);

        $.ajax({
            url : Theme.ajaxurl, 
            data : {
                'action': 'get_mocat_list', 
                'security': Theme.moment_nonce,
                tag:tag,
            },
            type : 'POST',
            beforeSend : function ( xhr ) {
    
                loading_start($('.mo-circle-content'));
                
            },
            success : function( data ){
                loading_done($('.mo-circle-content'));
                if (data && data.code === 0) {
                    toastify(data.msg || '请先登录后查看圈子列表', 'warning');
                    if (typeof ppo_open_login_modal === 'function') {
                        ppo_open_login_modal(data.msg || '请先登录后查看圈子列表');
                    }
                    $('.mo-circle-content').html(data.html || '');
                    return;
                }
                $('.mo-circle-content').html(data.html || '');
            },
            error : function(){
                loading_done($('.mo-circle-content'));
                $('.mo-circle-content').html('<div class="empty-content"><img src="'+Theme.ppo_url+'/img/empty.png"><p>圈子加载失败，请稍后重试</p></div>');
                toastify('圈子加载失败，请稍后重试', 'warning');
            }
        });

});

$(document).ready(function() {
    const $navWrapper = $('.moment-tags-nav');
    let isDragging = false;
    let startX;
    let scrollLeft;
  
    // 按住并拖动
    $navWrapper.on('mousedown', function(e) {
      isDragging = true;
      startX = e.pageX - $navWrapper.offset().left;
      scrollLeft = $navWrapper.scrollLeft();
      $navWrapper.css('cursor', 'grabbing');
      e.preventDefault(); // 防止文本选择
    });
  
    $(document).on('mousemove', function(e) {
      if (!isDragging) return;
      const x = e.pageX - $navWrapper.offset().left;
      const walk = (x - startX) * 1.5; // 滑动速度调整
      $navWrapper.scrollLeft(scrollLeft - walk);
    });
  
    $(document).on('mouseup', function() {
      isDragging = false;
      $navWrapper.css('cursor', 'grab');
    });
  
    // 点击导航项目居中
    $('.moment-tags-nav li').on('click', function() {
      const $item = $(this);
      const itemOffset = $item.offset().left;
      const wrapperOffset = $navWrapper.offset().left;
      const wrapperWidth = $navWrapper.width();
      const itemWidth = $item.outerWidth();
  
      const newScrollLeft = $navWrapper.scrollLeft() + itemOffset - wrapperOffset - (wrapperWidth / 2) + (itemWidth / 2);
  
      $navWrapper.animate({
        scrollLeft: newScrollLeft
      }, 300);
    });
  });

// 话题插入
$('body').on('click','.mo-huati-item',function(){
   var t = $(this),
       title = t.find('.title').text(),
       tagid = t.attr('tagid');

       $('.mo-tag-btn span').text(title);
       if(!$('.remove-motag').length > 0){
        $('.mo-tag-btn span').after('<a class="remove-motag"><i class="ri-close-line"></i></a>');
       }
       $('.push-mo-btn').attr('tagid',tagid);
       $('.mo-tag-btn').addClass('active');
       var editor = $('#pix-moment-editor').data('pixEditor');
       if(editor && typeof editor.insertTopic === 'function'){
            editor.insertTopic(title, tagid);
       }

});

$('body').on('click','a.remove-motag',function(){
    var t = $(this);

    t.siblings('span').text('话题');
    $('.push-mo-btn').removeAttr('tagid');
    $('.mo-tag-btn').removeClass('active');
    t.remove();
    var editor = $('#pix-moment-editor').data('pixEditor');
    if(editor && typeof editor.removeTopic === 'function'){
        editor.removeTopic();
    }
 
 });


// 表情插入
$(document).on('click','a.add-smily',function(){
    var data = $(this).attr('data-smilies');
    var editor = $('#pix-moment-editor').data('pixEditor');
    if(editor && typeof editor.insertEmoji === 'function'){
        editor.insertEmoji(data, $(this).find('img').attr('src') || '');
        return;
    }
    var emoji = "[s="+data+"]";
    var textarea = $('textarea#moment_content');
    var content = textarea.val();
	textarea.val(content+emoji);
	//textarea.focus();
});

// 阅读更多



// 片刻评论
window.PixMomentCommentCache = window.PixMomentCommentCache || (function(){
    var ttl = 2 * 60 * 1000;
    var max = 6;
    var store = {};
    var order = [];

    function touch(pid) {
        pid = String(pid || '');
        order = order.filter(function(id){ return id !== pid; });
        order.push(pid);
        while(order.length > max){
            delete store[order.shift()];
        }
    }

    return {
        get: function(pid) {
            pid = String(pid || '');
            var item = store[pid];
            if(!item || Date.now() - item.time > ttl){
                delete store[pid];
                order = order.filter(function(id){ return id !== pid; });
                return '';
            }
            touch(pid);
            return item.html;
        },
        set: function(pid, html) {
            pid = String(pid || '');
            if(!pid || !html) return;
            store[pid] = {
                html: html,
                time: Date.now()
            };
            touch(pid);
        },
        remove: function(pid) {
            pid = String(pid || '');
            delete store[pid];
            order = order.filter(function(id){ return id !== pid; });
        },
        clear: function() {
            store = {};
            order = [];
        }
    };
})();

function reset_moment_comment_runtime(exceptPid){
    $('#comment_form_tmp').empty();
    $('.moment_item').each(function() {
        var otherid = $(this).find('.moment-comment-btn').attr('pid');
        if (otherid && String(otherid) !== String(exceptPid || '')) {
            var $wrap = $(".t_com_"+otherid);
            var $form = $wrap.find('#t_commentform');
            if($form.length){
                cleanup_moment_comment_form($form);
                $('#comment_form_tmp').html($form.prop('outerHTML'));
            }
            $(".toi_respond_"+otherid).empty();
            $(".comment_box_"+otherid).remove();
            $wrap.hide();
        }
    });
}

function cleanup_moment_comment_form($form){
    if(!$form || !$form.length){
        return;
    }

    var uploader = $form.find('.pix-comment-uploader').data('pixUploader');
    if(uploader && typeof uploader.setItems === 'function'){
        uploader.setItems([], 'image');
    }

    $form.find('textarea#comment').val('').css('height', '');
    $form.find('input[name="comt-uploaded-urls"]').val('');
    $form.find('.pix-comment-image-badge').remove();
    $form.find('.com-img-btn').removeClass('has-uploaded-image').removeAttr('title');
    $form.find('.comt-tool-box, .img-box-drop, .emoji-box, .code-box-drop').hide();
    $form.find('#comment_parent').val('0');
    $form.find('#cancel-comment-reply-link').hide();
}

function normalize_moment_comment_html(html){
    var $content = $('<div></div>').html(html || '');
    var $lists = $content.children('ul.comment-list');

    if($lists.length > 1){
        $lists.slice(1).remove();
    }

    var $list = $content.find('ul.comment-list').first();
    if($list.length){
        var hasComments = $list.find('li[id^="comment-"], li.comment').length > 0;
        var $nodata = $list.find('.nodata');

        if(hasComments){
            $nodata.remove();
        } else if($nodata.length > 1){
            $nodata.slice(1).remove();
        }
    }

    return $content.html();
}

// 点击展开评论区域
$('body').off('click.momentComment', '.moment-comment-btn').on('click.momentComment','.moment-comment-btn',function(){
    var temp = $('#comment_form_tmp'),
        pid = $(this).attr('pid'),
        wrap = $(".t_com_"+pid),
        respond = $(".toi_respond_"+pid+""),
        form = $("#t_commentform").prop('outerHTML');

        reset_moment_comment_runtime(pid);
        if(wrap.hasClass('is-loading-comments')){
            return;
        }

        if(!wrap.find('form').length > 0){//判断是否存在打开的评论列表
            wrap.show();
            respond.prepend(form);
            $(".comment_box_"+pid+"").remove();
            respond.after("<div class='comment_box_"+pid+" commentshow' data-pid='"+pid+"'></div>");
            //$("textarea#comment").focus();
            temp.empty();
        } else {
            var $activeForm = wrap.find('#t_commentform');
            cleanup_moment_comment_form($activeForm);
            temp.html($activeForm.length ? $activeForm.prop('outerHTML') : form);
            respond.empty();
            $(".comment_box_"+pid+"").remove();
            wrap.hide();
            return;
        }

        var $commentBox = $(".comment_box_"+pid+"").first();
        var cached = window.PixMomentCommentCache ? PixMomentCommentCache.get(pid) : '';
        if(cached){
            $commentBox.html(normalize_moment_comment_html(cached));
            $("#comment_post_ID").val(pid);
            $("#comment_parent").val('0');
            $("#cancel-comment-reply-link").css("display","none");
            $("time.timeago").timeago();
            lazyLoadInstance.update();
            update_comt_img();
            return;
        }

        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            //dataType:  'json',
            data: {
                'action':'load_moment_comment',
                'security': Theme.moment_nonce,
                pid:pid,
                },	
    
            beforeSend: function () {
                wrap.addClass('is-loading-comments');
                loading_start($commentBox);
            },
            success: function(data){
                var dataHtml = normalize_moment_comment_html(data);
                var $box = $(".comment_box_"+pid+"").first();
                loading_done($box);
                $box.html(dataHtml);
                if(window.PixMomentCommentCache){
                    PixMomentCommentCache.set(pid, dataHtml);
                }
                $("#comment_post_ID").val(pid);
                $("#comment_parent").val('0');
                $("#cancel-comment-reply-link").css("display","none");
                $box.find('.loading_box').remove();
                $("time.timeago").timeago();
                lazyLoadInstance.update();
                update_comt_img();
            },
            error: function(){
                loading_done($commentBox);
                if(typeof toastfy === 'function'){
                    toastfy('评论加载失败，请稍后重试','error');
                }
            },
            complete: function(){
                wrap.removeClass('is-loading-comments');
            }	
        });
});

// 片刻类型筛选
var pixMomentFilterRequest = null;
var pixMomentFilterSeq = 0;
var pixMomentFilterTimer = null;
var pixMomentFilterQueued = null;
function render_moment_filter_error(message){
    message = message || '筛选加载失败，请稍后重试';
    return '<div class="no-moment moment-filter-error"><img src="'+Theme.ppo_url+'/img/empty.png"><p>'+message+'</p><button type="button" class="moment-filter-retry">重试</button></div>';
}

function is_moment_filter_running(){
    return pixMomentFilterRequest && pixMomentFilterRequest.readyState !== 4;
}

function run_moment_filter($item, forceRetry){
    var t = $item,
        append_box = '#moment-item',
        load_btn = '.loadmore-btn',
        type = t.attr('type'),
        nav_type = Theme.moment_nav,
        baseurl = window.location.href,
        cat = t.parent().attr('catid');

    if(!t.length){
        return;
    }

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

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

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

    reset_moment_comment_runtime('');
    if(window.PixMomentCommentCache){
        PixMomentCommentCache.clear();
    }

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

    var requestSeq = ++pixMomentFilterSeq;
    $('.moment-cat-filter').addClass('is-filtering');
    $('.moment-cat-filter').removeData('filterFailed');

    if(is_moment_filter_running()){
        pixMomentFilterQueued = t;
        return;
    }

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

        var currentRequest = null;
        currentRequest = pixMomentFilterRequest = $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            timeout: 15000,
            data: {
                'action':'moment_type_filter',
                'security': Theme.moment_nonce,
                type:type,
                cat:cat,
                baseurl:baseurl
            },

            beforeSend: function () {
                loading_start($(append_box));
            },
            success: function(data){
                if(requestSeq !== pixMomentFilterSeq){
                    return;
                }
                loading_done($(append_box));
                if(!data || typeof data.content === 'undefined'){
                    $('.moment-cat-filter').data('filterFailed', true);
                    $(append_box).html(render_moment_filter_error());
                    $('.pagenav-box').hide();
                    if(typeof toastfy === 'function'){
                        toastfy('筛选加载失败，请稍后重试','error');
                    }
                    return;
                }
                $('.moment-cat-filter').removeData('filterFailed');
                Theme.current_page = 1;
                Theme.posts = data.posts;
                Theme.max_page = data.max_page;
                if(nav_type == '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().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));

                if (window.ReadMore) {
                    ReadMore.init('.ppo-rich-text-content');
                }

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

                pixMomentFilterRequest = null;

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

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

$('body').off('click.momentFilter', '.moment-cat-filter a').on('click.momentFilter','.moment-cat-filter a',function(e){
    e.preventDefault();
    run_moment_filter($(this), false);
});

$('body').off('click.momentFilterRetry', '.moment-filter-retry').on('click.momentFilterRetry', '.moment-filter-retry', function(){
    run_moment_filter($('.moment-cat-filter .filter-item.active').first(), true);
});

$('body').on('click','.mo-user-box .right-btn a',function(){
    var t = $(this),
        type = t.attr('data');
        drop = '<div class="mo-user-'+type+'-drop uk-drop" uk-drop="mode: click;toggle:.mo-'+type+';target:.mo-user-inner;shift:true;animation: uk-animation-slide-top-small; animate-out: true;offset:15px">';

     //$(".mo-user-"+type+"-drop").remove();
     if(!$(".mo-user-"+type+"-drop").length > 0){
        $('.mo-user-box .right-btn').append(drop);
        UIkit.drop(".mo-user-"+type+"-drop").show(); 
     }   
       

});

// 免费圈子加入
$('body').on('click','.free-join',function(){
    var t = $(this),
        term_id = t.attr('term_id');
        
    t.addClass('protect');

        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                'action':'mo_join_free',
                'security': Theme.moment_nonce,
                term_id:term_id,
                },	
    
            beforeSend: function () {
                
            },
            success: function(data){
                if(data.code == 1){
                    toastfy(data.msg,'success');
                    location.reload();
                } else {
                    toastfy(data.msg,'error');
                } 
            }	
        });
});

// 免费圈子申请
$('body').on('click','.verify-join',function(){
    var t = $(this),
        term_id = t.attr('term_id');
        
    t.addClass('protect');

        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                'action':'mo_join_verify',
                'security': Theme.moment_nonce,
                term_id:term_id,
                },	
    
            beforeSend: function () {
                
            },
            success: function(data){
                if(data.code == 1){
                    toastfy(data.msg,'success');
                    //location.reload();
                } else {
                    toastfy(data.msg,'error');
                } 
            }	
        });
});

// 圈子订阅支付
$('body').on('click','.pay-join', function(){
	$('#ppo-pay-modal').remove();
    var term_id = $(this).attr('term_id');
    var modal = ppo_modal('ppo-pay-modal'),
        t_data = $('.mo-price-list a.price-item.active').attr('type');
    
    if(!$('.mo-price-list a.price-item.active').length > 0){
        toastfy('请选择订阅','error');
        return false;
    }    

	$('body').append(modal);
	UIkit.modal('#ppo-pay-modal').show();
	UIkit.util.on('#ppo-pay-modal', 'shown', function () {
	var content = $('.ppo-pay-modal .inner');
		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: Theme.ajaxurl,
			data: {
				'action': 'mo_pay_modal',
				'security': Theme.moment_nonce,
				'uid': Theme.uid,
                term_id:term_id,
                t_data:t_data,
			},
			beforeSend: function () {
				loading_start(content);
			},
			success: function (data) {
				loading_done(content);
				content.append(data.html);
			}
		}); 
	});

});

// 选择圈子套餐
$('body').on('click','.mo-price-list a.price-item', function(){
    var t = $(this),
        type = t.attr('type');
        t.addClass('active').siblings().removeClass('active');
});

// 我加入或创建的圈子
$('body').on('click','.mo-join , .mo-create',function(){
    var t = $(this),
     type = t.attr('data'),
     $box = $('.mo-user-'+type+'-drop');

    if(typeof ppo_require_login === 'function' && !ppo_require_login('请先登录后查看圈子列表')){
        loading_done($box);
        return;
    }

    if($box.find('.mo-topbar-list').length > 0){
        return;
    }

     $.ajax({
        type: "post",
        url:Theme.ajaxurl,
        dataType:  'json',
        data: {
            'action':'load_user_mo_join',
            'security': Theme.moment_nonce,
            type:type,
            },	
        beforeSend: function () {
            loading_start($box);
        },
        success: function(data){
            loading_done($box);
            if(data.code == 0){
                if(data.msg && data.msg.indexOf('登录') !== -1 && typeof ppo_open_login_modal === 'function'){
                    ppo_open_login_modal(data.msg);
                } else {
                    toastfy(data.msg || '加载失败，请重试','error');
                }
                return;
            }
            $box.append(data.html);
        },
        error: function(xhr){
            loading_done($box);
            var msg = '加载失败，请刷新后重试';
            if(xhr.status == 400 || xhr.status == 403){
                msg = '页面验证已过期，请刷新后重试';
            }
            toastfy(msg,'error');
        }
    });
            
});

// 插入卡片
$('body').on('click','.push_card',function(){
    var url = $(this).prev('input').val();
    if(has_pix_moment2_attachments()){
        toastfy('当前片刻已添加附件，请先移除附件后再生成卡片','error');
        return false;
    }

    if(url == ''){
        toastfy('请输入链接','error');
        return false;
    }

    var num = $('.card-wrap .card-box').length,
        max = current_mo_data.card_num;
    if(num >= max){
        toastfy('最多可上传'+max+'个卡片','error');
        return false;
    }

    $.ajax({
        type: "post",
        url:Theme.ajaxurl,
        dataType:  'json',
        data: {
            'action':'ajax_get_card_data',
            'security': Theme.moment_nonce,
            url:url,
            },	
        beforeSend: function () {
            toastfy('正在生成卡片..','info');
        },
        success: function(data){
            if(data.status == 1){
                toastfy('卡片已生成','success');
                
                $('.card-wrap').append(data.html);
                
                lazyLoadInstance.update();
                $('input#mo_card_link').val('');
            } else {
                toastfy(data.msg,'error');
            }
        }
    });
});

$('body').on('click','.de_card',function(){
    var msg = "确认删除此卡片？"; 
    var t = $(this);
    if (confirm(msg)==true){ 
        t.parent().remove();
    } else { 
     return false; 
    } 

});

// 插入音乐
$('body').on('click','.preview-music',function(){
    var aid = $(this).prev('input').val();
    if(aid == ''){
        toastfy('请输入网易云单曲ID','error');
        return false;
    }

    $.ajax({
        type: "post",
        url:Theme.ajaxurl,
        dataType:  'json',
        data: {
            'action':'ajax_preview_music',
            'security': Theme.moment_nonce,
            aid:aid,
            },	
        beforeSend: function () {
            toastfy('正在生成音乐..','info');
        },
        success: function(data){
            if(data.status == 1){
                toastfy('音乐已生成','success');
                
                $('.audio-preview-box').html(data.html);
                
                //$('input.netease_mo').val('');
            } else {
                toastfy(data.msg,'error');
            }
        }
    });
});

$('body').on('click','a.remove-audio',function(){
    var msg = "确认移除此音乐？"; 
    var t = $(this);
    if (confirm(msg)==true){ 
        t.prev().remove();
        t.remove();
    } else { 
     return false; 
    } 

});

$(document).ready(function(){

    var initTermId = 0;
    if(Theme.tid && $('body').hasClass('tax-moments')){
        initTermId = Theme.tid;
    } else if($('.mo-cir-btn').attr('catid')){
        initTermId = $('.mo-cir-btn').attr('catid');
        $('.push-mo-btn').attr('catid', initTermId);
    }

    if(initTermId){
        $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                'action':'get_current_mo_data',
                'security': Theme.moment_nonce,
                term_id:initTermId
            },
            beforeSend: function () {
                $('.mo-tool-nav .left-tool').css('opacity',0.2);
            },
            success: function(data){
                apply_current_moment_data(data);
            },
            error: function(){
                $('.mo-tool-nav .left-tool').css('opacity',1);
            }
        });
    }

});


// 视频上传类型切换
$('body').on('click','.mov-type',function(){
    var t = $(this),
        type = $(this).attr('type');

    t.addClass('active').siblings().removeClass('active');    
    if(type == 'local'){
        $('.mo-video-upbox').slideDown();
        $('.mo-video-linkbox').slideUp();
    } else {
        $('.mo-video-upbox').slideUp();
        $('.mo-video-linkbox').slideDown();
    }
});

// 创建圈子
function setCircleLocalPreview($input) {
    var file = $input[0] && $input[0].files ? $input[0].files[0] : null;
    if (!file) {
        return;
    }

    if (!/^image\//.test(file.type || '')) {
        toastfy('只能选择图片文件','error');
        $input.val('');
        return;
    }

    if (file.size > 2 * 1024 * 1024) {
        toastfy('图片大小不能超过2MB','error');
        $input.val('');
        return;
    }

    var $button = $input.closest('.upload-mos-banner, .upload-mos-logo');
    var $preview = $button.find('img').first();
    var oldUrl = $button.data('previewUrl');
    if (oldUrl) {
        URL.revokeObjectURL(oldUrl);
    }

    var imageURL = URL.createObjectURL(file);
    $button.data('previewUrl', imageURL).attr('data-url', '').addClass('has-image');
    $preview.attr('src', imageURL);
}

$('body').on('click','.publish-mos',function(){
    var t = $(this);
    if($('.circle-drop').length > 0){
        UIkit.dropdown('.circle-drop').hide(false);
    }
    var modal = '<div id="cr-moment-modal" uk-modal="bg-close:false;">'+
                    '<div class="uk-modal-dialog uk-modal-body cr-moment-modal">'+
                        '<h2 class="uk-modal-title">创建圈子</h2>'+
                        '<div class="cr-moment-box" uk-overflow-auto></div>'+
                        '<div class="cr-footer uk-modal-footer uk-text-right"><button class="uk-button uk-button-default uk-modal-close" type="button">取消</button>'+
                        '<button class="uk-button uk-button-primary cr-moment-btn" type="button">创建</button></div>'+
                    '</div>'+
                '</div>';
    if(!$('#cr-moment-modal').length > 0){
        $('body').append(modal);
    }
    UIkit.modal('#cr-moment-modal').show();     
    
    $.ajax({
        type: "post",
        url:Theme.ajaxurl,
        dataType:  'json',
        data: {
            'action':'cr_moments',
            'security': Theme.moment_nonce,
            },	
        beforeSend: function () {
           loading_start($('.cr-moment-box'));
        },
        success: function(data){
            loading_done($('.cr-moment-box'));
           if(data && data.status == 0){
                toastfy(data.msg || '您没有创建圈子的权限','error');
                UIkit.modal('#cr-moment-modal').hide();
                return;
           }
           $('.cr-moment-box').html(data.html || '');
        }
    });

});

$('body').on('click', '.upload-mos-banner, .upload-mos-logo', function(e) {
    if ($(e.target).is('input[type="file"]')) {
        return;
    }

    $(this).find('input[type="file"]').trigger('click');
});

$('body').on('change', '.mos-banner-file, .mos-logo-file', function() {
    setCircleLocalPreview($(this));
});

// 圈子创建类型选择
$('body').on('click','.mos-type-btn',function(){

    var t = $(this),
        type = t.attr('data');
   
    $('.mos-type-info[action="'+type+'"]').show().siblings().hide();    
});

$('body').on('click','.mos-btn',function(){

    var t = $(this),
        type = t.attr('data');
   
    t.addClass('active').siblings().removeClass('active');   
});

// 创建圈子提交
$('body').on('click','.cr-moment-btn',function(){

    var t = $(this),
        title = $.trim($('input#cr-mos-title').val()),
        desc = $.trim($('textarea#cr-mos-des').val()),
        slug = $.trim($('input#cr-mos-slug').val()),
        cat = $('.mos-cat-btn.mos-btn.active').attr('data'),
        type = $('.mos-type-btn.mos-btn.active').attr('data'),
        show = $('.mos-show-btn.mos-btn.active').attr('data');

        if(t.hasClass('protect')){
            return;
        }

        if(title == '' || desc == '' || slug == ''){
            toastfy('标题，别名，简介必填！','error');
            return;
        }

        var slugRegex = /^[A-Za-z]+$/;
        if (!slugRegex.test(slug)) {
            toastfy('圈子别名只能填写英文字母','error');
            return;
        }

        var base_data = {
            title:title,
            desc:desc,
            slug:slug,
        }

        var cr_data = {
            ppo_moments_tag:cat,
            mo_join_type:type,
            mo_show_type:show,
        }

        switch (type) {
            case "free":
                var join_data = $('button.mos-join-btn.mos-btn.active').attr('data');
                break;
        
            case "pay":
                var join_data = [];
                var priceInvalid = false;
                var hasPrice = false;
                $.each($('.mos-type-info[action="pay"] input'),function(){
                    var t = $(this),
                        name = t.attr('data'),
                        val = t.val();

                        var isValid = val === '' || (!isNaN(parseFloat(val)) && isFinite(val));

                            if (!isValid) {
                                toastfy('价格必须是数字！','error');
                                priceInvalid = true;
                                return; 
                            }
                            if (val !== '') {
                                hasPrice = true;
                            }

                        var obj = {
                            name:name,
                            price:val
                        }

                        join_data.push(obj);                  
                });
                if (priceInvalid) {
                    return;
                }
                if (!hasPrice) {
                    toastfy('付费圈子至少填写一个金额','error');
                    return;
                }
                break;

            case "limits":
                var join_data = $('.mos-limits-input:checked').map(function() {
                    return $(this).val();
                  }).get();
                break;
        }

        function insertCircle(img_data) {
            $.ajax({
            type: "post",
            url:Theme.ajaxurl,
            dataType:  'json',
            data: {
                'action':'insert_moments',
                'security': Theme.moment_nonce,
                base_data:base_data,
                cr_data:cr_data,
                join_data:join_data,
                uid:Theme.uid,
                img_data:img_data
            },
            beforeSend: function () {
                $('.cr-moment-btn').addClass('protect');
                toastfy('数据创建中..','info');
            },
            success: function(data){
               if(data.status == 1){
                toastfy(data.msg,'success');
                UIkit.modal('#cr-moment-modal').hide();
                if(data.term_link){
                    setTimeout(function(){
                        window.location.href = data.term_link;
                    }, 450);
                } else {
                    setTimeout(function(){
                        window.location.reload();
                    }, 450);
                }

            } else {
                toastfy(data.msg,'error');
            }
        },
            complete: function() {
                $('.cr-moment-btn').removeClass('protect');
            }


        });
        }

        function uploadCircleImagesThenInsert() {
            var bannerFileInput = $('.mos-banner-file')[0];
            var logoFileInput = $('.mos-logo-file')[0];
            var hasBanner = bannerFileInput && bannerFileInput.files && bannerFileInput.files[0];
            var hasLogo = logoFileInput && logoFileInput.files && logoFileInput.files[0];

            if (!hasBanner && !hasLogo) {
                insertCircle({
                    banner_img: Theme.ppo_url + '/img/banner.jpg',
                    logo_img: Theme.ppo_url + '/img/modef.png'
                });
                return;
            }

            var formData = new FormData();
            if (hasBanner) {
                formData.append('bannerFile', bannerFileInput.files[0]);
            }
            if (hasLogo) {
                formData.append('logoFile', logoFileInput.files[0]);
            }

            $.ajax({
                type: "POST",
                url: Theme.ajaxurl + "?action=upload_mos_img&security=" + Theme.moment_nonce,
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    toastfy('图像上传中..','info');
                    $('.cr-moment-btn').addClass('protect');
                },
                success: function(data){
                    if(data && data.status == 1){
                        insertCircle({
                            banner_img: data.banner_img || (Theme.ppo_url + '/img/banner.jpg'),
                            logo_img: data.logo_img || (Theme.ppo_url + '/img/modef.png')
                        });
                    } else {
                        $('.cr-moment-btn').removeClass('protect');
                        toastfy((data && data.msg) || '图像上传失败','error');
                    }
                },
                error: function() {
                    $('.cr-moment-btn').removeClass('protect');
                    toastfy('图像上传失败','error');
                }
            });
        }

        t.addClass('protect');
        uploadCircleImagesThenInsert();
});

// 圈子分类ajax搜索

var mo_s_delay = 400; // 延迟时间，单位为毫秒
var mo_s_timeoutId;

$('.mo-cat-search , .mo-tag-search').on('input',function(){
    var t = $(this);
    clearTimeout(mo_s_timeoutId);
    var keyword = t.val().trim();

    if(t.hasClass('mo-cat-search')){
        var $mo_s_results = $('.mos-s-content'),
            action = 'search_mo_cat';
    } else {
        var $mo_s_results = $('.mos-s-tag-content'),
            action = 'search_mo_tag';
    }

    if (keyword.length < 2) {
        $mo_s_results.empty();
        $mo_s_results.hide();
        return;
    }

    mo_s_timeoutId = setTimeout(function() {
        $.ajax({
            url: Theme.ajaxurl,
            type: 'POST',
            data: {
                action: action,
                security: Theme.moment_nonce,
                keyword: keyword,
            },
            beforeSend: function() {
                $mo_s_results.show();
                $mo_s_results.empty();
                loading_start($mo_s_results);
            },
            success: function(data) {
                loading_done($mo_s_results);
                if(data && data.status == 0 && data.msg){
                    $mo_s_results.html('<div class="error">'+data.msg+'</div>');
                    return;
                }
                $mo_s_results.html((data && data.html) ? data.html : '<div class="error">没有找到相关内容</div>');
                
            },
            error: function() {
                loading_done($mo_s_results);
                $mo_s_results.html('<div class="error">请求失败，请重试</div>');
            }
        });
    }, mo_s_delay);
});

// 片刻首页轮播
    var mySwiper = new Swiper('#top-mos-cat-slide', {
        slidesPerView : 3,
        spaceBetween : 20,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
            disabledClass: 'sw-button-disabled',
          },
          pagination: {
            el: '.swiper-pagination',
            clickable :true,
            dynamicBullets: true,
          },
          autoplay: {
            delay: 3000,
            stopOnLastSlide: false,
            disableOnInteraction: true,
            },
    });




// 圈子批准加入
$('body').on('click','.mo-allow-join , .mo-refuse-join',function(){
    var t = $(this),
        uid = t.parents('.mo-wait-item').attr('uid'),
        term_id = t.parents('.mo-wait-item').attr('term_id'),
        action = 'mo_allow_join';
        type = t.attr('action');

        $.confirm({
            title: type == 'allow' ? '批准加入' : '拒绝加入',
            titleClass: 'moment-delete-title',
            content: type == "allow" ? "批准加入后用户将可以访问圈子内容" : "拒绝后用户可再次申请加入",
            boxWidth: '350px',
            useBootstrap: false,
            scrollToPreviousElement: false,
            buttons: {   
                ok: {
                    text: "确定",
                    btnClass: 'delete-moment-sure',
                    keys: ['enter'],
                    action: function(){
                        $.ajax({
                            type: "post",
                            url:Theme.ajaxurl,
                            dataType:  'json',
                            data: {
                                'action': action,
                                'security': Theme.moment_nonce,
                                uid:uid,
                                term_id:term_id,
                                type:type,
                                },	
                            beforeSend: function () {
                                //loading_start(t);
                            },
                            success: function(data){
                                //loading_done(t);
                                if(data.status == 1){
                                    t.parents('.mo-wait-item').fadeOut(500, function() {
                                        $(this).remove();
                                    });
                                } 
                            }
                        });
                    }
                },
                close: {
                    text: "取消",
                },
            }
        });

});    

// 片刻审核功能
$('body').on('click','.mo-pending-allow , .mo-pending-remove',function(){
    var t = $(this),
        uid = Theme.uid,
        pid = t.parents('.pending-footer').attr('pid'),
        action = 'mo_pending_check',
        baseurl = window.location.href,
        type = t.attr('action');

        $.confirm({
            title: type == 'allow' ? '通过审核' : '直接删除',
            titleClass: 'moment-delete-title',
            content: type == "allow" ? "请仔细审核，以免出现合规问题" : "确认后直接删除片刻",
            boxWidth: '350px',
            useBootstrap: false,
            scrollToPreviousElement: false,
            buttons: {   
                ok: {
                    text: "确定",
                    btnClass: 'delete-moment-sure',
                    keys: ['enter'],
                    action: function(){
                        $.ajax({
                            type: "post",
                            url:Theme.ajaxurl,
                            dataType:  'json',
                            data: {
                                'action': action,
                                'security': Theme.moment_nonce,
                                uid:uid,
                                pid:pid,
                                type:type,
                                baseurl:baseurl,
                                },	
                            beforeSend: function () {
                                //loading_start(t);
                            },
                            success: function(data){
                                //loading_done(t);
                                if(data.status == 1){
                                   t.parents('.moment_item').fadeOut(200, function() {
                                        $(this).remove();
                                    }); 

                                    if($('.manage-page-title .cat-nav a.active').attr('type') == 'review_mo'){
                                        if($('.moment_item').length < 1 ){
                                            $('.mo-pending-notice').remove();
                                        }
                                    }

                                    if($('.manage-page-title .cat-nav a.active').attr('type') == 'review_join'){
                                        if($('.mo-wait-item').length < 1){
                                            $('.mo-pending-notice').remove();
                                        }
                                    }
                                    
                                } 
                            }
                        });
                    }
                },
                close: {
                    text: "取消",
                },
            }
        });

});   

// ajax圈子用户管理翻页
$('body').on('click','.gl-paginate a',function(e){
    e.preventDefault();
    var t = $(this),
        action = t.parents('.gl-paginate').attr('action'),
        content = t.parents('.gl-paginate').attr('content'),
        $content = $(content),
        term_id = t.parents('.gl-paginate').attr('term_id'),
        total = t.parents('.gl-paginate').attr('total'),
        url = t.attr('href'),
        match = url.match(/\/page\/(\d+)\/?/),
        paged = match[1],
        baseurl = window.location.href;

        $content.empty();

    $.ajax({
        url: Theme.ajaxurl,
        type: 'POST',
        dataType:  'json',
        data: {
            action: action,
            'security': Theme.moment_nonce,
            term_id: term_id,
            paged: paged,
            total: total,
            baseurl: baseurl,
        },
        beforeSend: function() {
            loading_start($content);
        },
        success: function(data) {
            loading_done($content);
            $content.html(data.html);
            lazyLoadInstance.update(); 
            $("time.timeago").timeago(); //重载时间
        }

    });

});

// 圈子管理页面导航切换
$('body').on('click','.review-page-btn',function(){
    var t = $(this),
    action = 'mo_manage_content',
    $content = $('.moment-manage-inner'),
    ajax_type = t.attr('type'),
    term_id = t.parents('.cat-nav').attr('term_id');

    t.addClass('active').siblings().removeClass('active');
    $content.empty();

    $.ajax({
        url: Theme.ajaxurl,
        type: 'POST',
        data: {
            action: action,
            'security': Theme.moment_nonce,
            term_id: term_id,
            ajax_type: ajax_type,
        },
        beforeSend: function() {
            loading_start($content);
        },
        success: function(data) {
            loading_done($content);
            $content.html(data.html);
            lazyLoadInstance.update(); //重载懒加载
            $("time.timeago").timeago(); //重载时间
        },
        error: function() {
            $content.html('<div class="error">请求失败，请重试</div>');
        }
    })
});


// 移除圈友
$('body').on('click','.mo-del-user',function(){
    var t = $(this),
        action = 'mo_remove_member',
        uid = t.attr('uid');

    $.confirm({
        title: '移除圈友',
        titleClass: 'moment-delete-title',
        content: '<span class="comfirm-text">请慎重考虑，是否将用户移除此圈子</span><input type="text" class="mo-remove-info uk-input" placeholder="移除原因备注"><small class="comfirm-tips">选填，填写后用户消息会收到原因备注</small>',
        boxWidth: '350px',
        useBootstrap: false,
        scrollToPreviousElement: false,
        buttons: {   
            ok: {
                text: "确定",
                btnClass: 'delete-moment-sure',
                keys: ['enter'],
                action: function(){
                    $.ajax({
                        type: "post",
                        url:Theme.ajaxurl,
                        dataType:  'json',
                        data: {
                            'action': action,
                            'security': Theme.moment_nonce,
                            uid:uid,
                            },	
                        beforeSend: function () {
                            //loading_start(t);
                        },
                        success: function(data){
                            //loading_done(t);
                            if(data.status == 1){
                               t.parents('.moment_item').fadeOut(200, function() {
                                    $(this).remove();
                                }); 
                            } 
                        }
                    });
                }
            },
            close: {
                text: "取消",
            },
        }
    });
})
