function convertDateToString(unixTimestamp) {
    var m = moment(unixTimestamp);
    //是否是今天
    var c = moment(new Date());
    if (m.isSame(c, 'day')) {
        //时间部分:11:30
        return m.format("HH:mm");
    }
    if (m.isSame(c, 'month')) {
        //{}天前
        return (c.date() - m.date()) + '天前';
    }
    if (m.isSame(c, 'year')) {
        //{}月{}日
        return (m.month() + 1) + '月' + m.date() + '日';
    }
    //{}年{}月{}日
    return m.format('YYYY-MM-DD');
};
//弹出消息窗口
function tipDialog(config){
    var option={
            content: '', 
            type: 'blue', 
            ico: 'fa-question',
            reloaded : true
    };
    if(config.level === 'acc'){
        option.type='green';option.ico='mdi-check';
    }
    if(config.level === 'err'){
        option.type='red';option.ico='mdi-close';
    }
    if(config.level === 'ibb'){
        option.type='orange';option.ico='mdi-alert-circle-o';
    }
    if(config.message){
        option.content = config.message;
    }
    if(!isBlank(config.content)){
        option.content = config.content;
    }
    if(config.hasOwnProperty('refresh')){
        option.reloaded = config.refresh;
    }
    $.dialog({
        icon: 'ico-lg mdi '+option.ico,
        title: '',
        theme: 'modern',
        type: option.type,
        closeIcon: false,
        content: ''+option.content,
        onOpen: function () {
            var jc = this;
            setTimeout(function(){ jc.close(); }, 3000);
        },
        onClose: function(){
            if(option.reloaded){
                location.reload(true);
            }
        }
    });
};
function errorMessage(message){
    return tipDialog({"message":message, "level":"err", "refresh":false});
};
function isBlank(strParameter){
    return (!strParameter || strParameter === undefined || strParameter === "" || strParameter.length === 0);
};
function getUnixStamp(){
    return Math.round(new Date().getTime()/1000);
};
function strip_html_tags(str){
    if ((str===null) || (str==='')){
        return '';
    }else{
        str = str.toString();
        return str.replace(/<[^>]*>/g, '');
    }
};
function randomAlphaNumeric(strlen) {
    if(!strlen || parseInt(strlen)<=6){
        return;
    }
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i=0; i<strlen; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
};
//CK4的函数
function insertEditorHtml(htmlString){
    if(!!CKEDITOR.instances){
        $('[data-richEditor="CKEditor"]').focus();
    }
    if(CKEDITOR.instances.content === undefined){ // iframe embed smiley
        $('[data-richEditor="CKEditor"]', window.parent.document).focus();
        window.parent.CKEDITOR.instances.content.insertHtml(htmlString);
        return;
    }
    CKEDITOR.instances.content.insertHtml(htmlString);
};
//v:4.x.x
function initCkEditor(config){
    var options=$.extend({
        textarea: 'content', 
        plugs: 'uploadimage', 
        startupFocus: false, 
        width: 600, 
        height: 150}, 
        config);
    CKEDITOR.config.pasteFilter = null;
    CKEDITOR.config.height = options.height;
    CKEDITOR.config.width = options.width;
    
    var insConfig = {extraPlugins: options.plugs};
    if(options.startupFocus){
        insConfig.startupFocus = true;
    }
    CKEDITOR.replace(options.textarea, insConfig);
    if(options.plugs.indexOf('uploadimage') != -1){
        CKEDITOR.config.filebrowserUploadUrl = IMGSTORE+options.upload+'?type=Files';
        CKEDITOR.config.filebrowserImageUploadUrl = IMGSTORE+options.upload+'?type=Images';
        //ADD 20191026
        CKEDITOR.on('dialogDefinition', function( evt ) {
          var dialogName = evt.data.name;
          if (dialogName == 'image') {
            var uploadTab =  evt.data.definition.getContents('Upload'); // get tab of the dialog
            var browse = uploadTab.get('upload'); //get browse server button
            
            browse.onClick = function() {
              var input = this.getInputElement();
              input.$.accept = 'image/*'
            };
            
            browse.onChange = function(){
              var input = this.getInputElement();
              var fn = input.$.value; // 文件路径
              var imageReg = /\.(gif|jpg|jpeg|png)$/i;
              if(!imageReg.test(fn)){
                alert('非法的文件类型');
                input.$.value='';
              }
            };
          }
        });
    }
};
//data-params改用data-query
function parseQueryJson(dataQueryVal){
    var data = {};
    if(isBlank(dataQueryVal)){
        return data;
    }
    $.each(dataQueryVal.split(','), function(index, item){
        var tmp = item.split(':');
        data[tmp[0].trim()] = tmp[1].trim();
    })
    return data;
};
//话题的快速回复
function buildRichEditor(jqEle){
	jqEle.find('[data-richEditor="CKEditor"]').trigger('initEvent');
};
function buildEditorMessage(errJson){
    //在线吗
    var cam = getCurrentActiveMemberInfo();
    var t = '<div class="topic_posts_item main-color">'
        +'  <dl class="topic_posts_item_left">'
        +'    <dt style="padding-top: 20px;padding-left: 20px;width:180px">'
        +'      <div class="posts-member-avatar">'
        +'        <div class="avatar">'
        +'          <img class="avatar" src="'+BASE+'/avatar/empty.png" alt="User avatar" />'
        +'        </div>'
        +'      </div>'
        +'    </dt>'
        +'  </dl>'
        +'  <div class="topic_posts_item_right h260">'
        +'    <div class="posts-body">'
        +'      <h5 class="hl45 default-txt-color">快速回复</h5>'
        +'      <div id="block-paper">'
        +'        <p>'+errJson.message;
        if(jQuery.isEmptyObject(cam) || parseInt(cam.id) < 1){
          t += ' &nbsp; <a href="'+BASE+'/member/login">登录</a>&nbsp; | &nbsp;<a href="'+BASE+'/member/register">注册</a>';
        }
        t += '      </p></div>'
          +'    </div>'
          +'  </div>'
          +'</div>'
    $('#quick_reply_posts').removeClass('ld-over running').find('div.ld').remove();
    $('#quick_reply_posts').append(t);
}
//底部的版块导航
function buildBoardNavigateSelect(json){
    //生成select
    var selectEleWrox = $('#'+json.element);
    var selectEle = $('<select class="form-control" aria-hidden="true"></select>').appendTo(selectEleWrox);
    //
    var selectData=new Array(); 
    $.each(json.result, function(key,value){
        var dataItem ={};
            dataItem.text = key;
            dataItem.children = new Array();
        $.each(value, function(innerIndex,innerObj){
            $.each(innerObj, function (attrName, attrValue) {
                dataItem.children.push({id: attrName, text: attrValue});
            });
        });
        selectData.push(dataItem);
    });
    var sob = selectEle.select2({
        theme: 'bootstrap4',
        data: selectData
    });
    sob.on("select2:select", function (e) {
        //选中的值是?
        var selectBoard = e.params.data.id;
        if(selectBoard && !isBlank(selectBoard)){
            window.location.href = BASE+'/board/'+selectBoard+'.xhtml';
        }
    });
    //显示
    selectEleWrox.find('p.board-navigator-select').remove();
    sob.select2("open");
};
//话题移动时的版块jsonp的回调
function buildBoardFormTemp(json){
    if($('#'+json.element).length === 0){
        return;
    }
    var data='';
    $.each(json.result, function(index,item){
        data += '<option value="%ID%">%T%</option>'.replace('%T%', item.title).replace('%ID%', item.id);
    });
    $('#'+json.element).append(data).select2({theme: 'bootstrap4'});
};
//顶部的会员面板@20200502
function drawMemberPanel(json, jqueryEle){ //[NW]
    if(jQuery.isEmptyObject(json) || parseInt(json.id) <= 0){ //游客跳过
        return; 
    }
    var I = '<a href="{APP}/message/" role="button" class="btn btn-light">'
          + '<i class="mdi mdi-notifications" aria-hidden="true"></i>'
          + '<sup id="notification" class="d-none badge">0</sup>'
          + '</a>'
          + '<a role="button" class="btn btn-light" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" href="{APP}">{nickname}</a>'
          + '<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">'
          + '<span class="sr-only">Toggle Dropdown</span>'
          + '</button>'
          + '<div class="dropdown-menu">'
          + '<a class="dropdown-item" href="{APP}/member/home/">个人中心</a>'
          + '<div class="dropdown-divider"></div>'
          + '<a class="dropdown-item" href="{APP}/member/home/profile">帐户设置</a>'
          + '<a class="dropdown-item" href="{APP}/message/">消息</a>'
          + '<div class="dropdown-divider"></div>'
          + '<a class="dropdown-item" href="{APP}/member/offline.xhtml?trace=msa">注销</a>'
          + '</div>';
    Mustache.parse(I, ['{', '}']);
    var rs = $.extend(json, {"APP":BASE});
    jqueryEle.attr('data-ux', getUnixStamp()).find('a.forum_member_defat_link').remove();
    jqueryEle.append(Mustache.render(I, rs)).attr('data-member', json.id);
    //开始消息通知
    $('#notification').bind('initDataEvent', noticeHandler).trigger('initDataEvent');
    //[HMP]检查客户端缓存是否存在
    var cacheData = store.get('member'+json.verify); 
    if(jQuery.isEmptyObject(cacheData)){
        store.set('member'+json.verify, json);
    }
};
//是否要去拉取数据,客户端缓存的cookie标记是否过期了
function getMemberVerify(){
    var verify = Cookies.get('msa') || -1; 
    return verify;
};
//客户端缓存的cookie标记未过期时更新会员的信息到哪取
function getCacheMemberInfo(verify, jqEle){
    var cacheData = store.get('member'+verify) || {};
    return drawMemberPanel(cacheData, jqEle);
};
//设置客户端缓存的cookie标记
function setMemberVerify(verify){
    var in30Minutes = 1/48; //这个值是有效期,还标志着更新的频率
    Cookies.set('msa', verify, {expires: in30Minutes});
};
//当前活跃的会员信息
function getCurrentActiveMemberInfo(){
    var verify = getMemberVerify();
    if(verify === -1){
        return {};
    }
    return store.get('member'+verify) || {};
};
//部分页面的右侧边栏的会员信息
function drawMemberInfo(json, jqueryEle){
    var F = ''
        +'<div style="padding-top:30px;">'
        +'  <div class="text-center" style="height:auto;">'
        +'     <a href="{APP}/member/{id}.xhtml" title="会员主页"><img class="img-circle" src="{APP}/member/avatar/{id}.png" style="width:100px;height:100px"/></a>'
        +'  </div>'
        +'  <div class="text-center member_embed_info">'
        +'    <h5><a href="{APP}/member/home/" title="会员中心" class="member-{style}">{nickname}</a></h5>'
        +'    <div class="row">'
        +'    <dl class="col-xs-6 col-sm-4"><dt>{status}</dt><dd>状态</dd></dl>'
        +'    <dl class="col-xs-6 col-sm-4"><dt>{group}</dt><dd>组</dd></dl>'
        +'    <dl class="col-xs-6 col-sm-4"><dt>{role}</dt><dd>角色</dd></dl>'
        +'    </div>'
        +'  </div>'
        +'</div>';
    Mustache.parse(F, ['{', '}']);
    var rs = $.extend(json, {"APP":BASE});
    jqueryEle.find('form').remove();
    jqueryEle.append(Mustache.render(F, rs));
}
//主页侧边栏的版块统计[NW][1]
function buildIndexSideBoardStats(json, element){
    var data ={};
    data.result = json;
    var T = '{#result}'
          +'<div class="side-stats-item">'
          +'  <a href="{APP}{link}">{title}</a> <span class="float-right">{topices}/{postses}</span>'
          +'</div>'
          +'{/result}';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
};
//版块列表边栏的会员标兵[NW][2]
function buildModelMember(json, element){
    var data ={};
    data.result = json;
    var T ='{#result}'
          +'<div class="side-stats-item">'
          +'  <a href="{URI}">{title}</a><span class="float-right">{value}</span>'
          +'</div>'
          +'{/result}';
    var rs={
            URI : function(){
                return BASE+'/member/'+this.id+'.xhtml';
            }
    };
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, rs)));
};
//部分页面右侧边栏的话题列表[NW][3]
function buildRightSectionTopic(json, element){
    var data ={};
    data.result = json;
    var T ='{#result}'
          +'<div class="side-topic-item">'
          +'  <a class="side-topic-item-link" href="{APP}{link}">{title}</a>'
          +'  <span class="sidebar-recent-author"><a href="{APP}/member/{author}.xhtml">{authorNames}</a></span>'
          +'  <span class="sidebar-recent-content">&#187; {date}</span>'
          +'</div>'
          +'{/result}';

    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
};
//搜索结果页右侧
function buildRightSectionTag(json, element){
    var data ={};
    data.result = json;
    var T ='{#result}'
          +'<div class="side-stats-item">'
          +'  <a href="{URI}">{title}</a><span class="float-right">{id}</span>'
          +'</div>'
          +'{/result}';
    var rs={
            URI : function(){
                return BASE+'/search/?word='+this.title;
            }
    };
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, rs)));
}
//话题内容页中的
function buildRelateSectionTopic(json, element){
    var data ={};
    data.result = json;
    var T ='<p>相关的话题</p>'
        +'<ul>{#result}'
        +'<li>'
        +'  <sub>{ranking}</sub>'
        +'  <a href="{APP}{link}">{title}</a>'
        +'  <span class="d-none">{analogy}</span>'
        +'</li>'
        +'{/result}</ul>';

    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
}
//会员中心的话题[NW][4]
function drawDynamicTopic(json,element){
    if(jQuery.isEmptyObject(json)){
        return;
    }
    $('#forumlist').removeClass('sectionbox');
    var data ={};
    data.result = json;
    var T='{#result}'
    +'<div class="media mc-topic">'
    +'  <div class="media-left">'
    +'    <a href="{APP}/member/{author}.xhtml" title="{authorNames}">'
    +'        <img class="media-object img-circle" src="{APP}/member/avatar/{author}.png" style="width: 64px; height: 64px;">'
    +'    </a>'
    +'  </div>'
    +'  <div class="media-body mc-topic-body">'
    +'    <a href="{APP}{link}" class="forum-article-header">{title}</a>'
    +'    <p><a href="{APP}/member/{author}.xhtml" title="会员主页">{authorNames}</a>&nbsp;&#187;&nbsp;{date}'
    +'       <span class="float-right">&nbsp;<a href="{APP}{boardLink}">{boardTitle}</a></span>'
    +'    </p>'
    +'    <div class="mc-topic-body-txt">{description}</div>'
    +'  </div>'
    +'</div>{/result}';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
}
//会员个人中心的版块收藏[NW]
function buildMemberFavoriteBoard(json, element){
    if(jQuery.isEmptyObject(json)){
        return;
    }
    var data ={};
    data.result = json;
    var T =''
        +'<ul class="fav-board-collect">{#result}'
        +'  <li class="fav-board-item" id="fav-board-{connect}">'
        +'    <div class="fav-board-logo">'
        +'        <img src="{APP}/board/ico/{id}.png" />'
        +'        <p><a href="{link}">{title}</a></p>'
        +'    </div>'
        +'    <div class="fav-board-stats">'
        +'      <dl><dt>话题</dt><dd>{topices}</dd></dl>'
        +'      <dl><dt>回复</dt><dd>{postses}</dd></dl>'
        +'    </div>'
        +'  </li>'
        +'{/result}</ul>';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
};
//会员主页的版块星标[NW][5]
function buildMemberStarBoard(json, element){
    if(jQuery.isEmptyObject(json)){
        return;
    }
    $('#forumlist').removeClass('sectionbox');
    var data ={};
    data.result = json;
    var T =''
        +'<ul class="list-inline">{#result}'
        +'  <li class="list-inline-item"><a href="{APP}{link}" class="focus-board">{title}</a></li>'
        +'{/result}</ul>';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
}
//版块内容页的版主列表[NW][6]
function drawBoardModeratorList(json, element){
    var data ={};
    data.result = json;
    var T =''
        +'<ul class="list-inline" id="board-moderator">{#result}'
        +'  <li><a href="{APP}/member/{id}.xhtml">{title}</a></li>'
        +'{/result}</ul>';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
}
//大版主列表
function drawBoardGroupModeratorList(json, element){
    var data ={};
    data.result = json;
    var T =''
        +'{#result}'
        +'  <dl class="d-inline-block p-2"><dt><img src="{APP}/member/avatar/{id}.png" width="32px" height="32px"/></dt><dd><a href="{APP}/member/{id}.xhtml">{title}</a></dd></dl>'
        +'{/result}';
    Mustache.parse(T, ['{', '}']);
    $(element).append(Mustache.render(T, $.extend(data, {"APP":BASE})));
}
//版块内容页的置顶话题列表[NW][7]
function drawBoardTopSectionTopic(data, element){
    var currentId = "dynamic-section-"+randomAlphaNumeric(8);
    $(element).attr('id', currentId);
    $.each(data, function(index, item){
        drawUpdatedTopics(item, currentId, false);
    });
}
// 聊天页中的历史记录[NW][8]
function drawLetterHistoryMessage(json, jqEle){
    var T=''
        +'<div class="media{#master} media-master{/master}" id="letter-{id}">'
        +'  <div class="media-avatar media-left">'
        +'    <a href="javascript:;">'
        +'        <img class="media-object img-circle" src="{APP}/member/avatar/{sender}.png" style="height:64px;width:64px;">'
        +'    </a>'
        +'  </div>'
        +'  <div class="media-body">'
        +'    <div class="media-bubble">'
        +'        <h6 class="media-heading"><small>{datetime}</small></h6>'
        +'        {#SM}<strong>{subject}</strong>{/SM}'
        +'        <p>{&body}</p>'
        +'    </div>'
        +'  </div>'
        +'</div>';
    var rs={
            SM : function(){
                return this.sender == 0;
            },
            APP : BASE
    };
    Mustache.parse(T, ['{', '}']);
    var ext = $.extend(json, rs);
    //
    $(Mustache.render(T, ext)).insertAfter($('#'+jqEle).find('p.text-center'));
}
//新话题列表推送回调
function updateNewsTopices(sockplaindata){
    var jsonArray = $.parseJSON(sockplaindata);
    if(jQuery.isEmptyObject(jsonArray)){
        return;
    }
    $('#board_topic_collect').attr('data-ux', getUnixStamp());
    $.each(jsonArray, function(index, item){
        drawUpdatedTopics(item, 'board_topic_collect', true);
    });
};
//最新类推送回调
function drawUpdatedTopics(json, jqEle, isPushed){
    var topicItemCS = isPushed?'dynamic-topic-record fadeout-anim':'updated-rows';
    var UT='' 
          +'<li class="board_item '+topicItemCS+'">' 
          +'  <dl class="icon topic_{status}">' 
          +'    <dt>' 
          +'      <div class="board_item_title">' 
          +'        <article class="forum-article-header">' 
          +'          {#top}<span class="label" title="置顶话题">&#x1F4CC</span> {/top}' 
          +'          {#best}<span class="label" title="精华话题">&#x1F48E</span> {/best}' 
          +'          {#image}<span class="label" title="图片话题">&#x1F304</span> {/image}' 
          +'          {#hot}<span class="label" title="很火噢">&#x1F525</span> {/hot}'
          +'          <a href="{APP}{boardLink}?category={categoryKey}">[{category}]</a> '
          +'          <a href="{APP}{link}" class="forumtitle">{title}</a>' 
          +'        </article>' 
          +'        <a class="txtline" href="{APP}/member/{author}.xhtml">{authorNames}</a> &#187; {date}' 
          +'      </div>' 
          +'    </dt>' 
          +'    <dd class="replies wp10 stats-item">{replies}<dfn>Replies</dfn></dd>' 
          +'    <dd class="views wp10 stats-item">{views}<dfn>Views</dfn></dd>' 
          +'    <dd class="latest">{#recent}' 
          +'      <span class="last-posts-avatar"><img src ="{APP}/member/avatar/{recentAuthor}.png" width="32px" height="32px"/></span>' 
          +'      <span class="last-posts"><a href="{APP}/member/{recentAuthor}.xhtml" class="latest-member-color">{recentAuthorNames}</a> ' 
          +'      <br/>{recentDate}</span>{/recent}' 
          +'    </dd>' 
          +'  </dl>' 
          +'</li>';
    var UE='' 
          +'<li class="board_item '+topicItemCS+'">' 
          +'  <dl class="icon topic_{status}">' 
          +'    <dt>' 
          +'      <div class="board_item_title">' 
          +'        <article class="forum-article-header">' 
          +'          {#top}<span class="label" title="置顶话题">&#x1F4CC</span> {/top}' 
          +'          {#best}<span class="label" title="精华话题">&#x1F48E</span> {/best}' 
          +'          {#image}<span class="label" title="图片话题">&#x1F304</span> {/image}' 
          +'          {#hot}<span class="label" title="很火噢">&#x1F525</span> {/hot}'
          +'          <a href="{APP}{boardLink}?category={categoryKey}">[{category}]</a> '
          +'          <a href="{APP}{link}" class="forumtitle">{title}</a>' 
          +'        </article>' 
          +'        <a class="txtline" href="{APP}/member/{author}.xhtml">{authorNames}</a> &#187; {date}' 
          +'      </div>' 
          +'    </dt>' 
          +'    <dd class="replies wp10 stats-item">{replies}<dfn>Replies</dfn></dd>' 
          +'    <dd class="views wp10 stats-item">{views}<dfn>Views</dfn></dd>' 
          +'    <dd class="latest"></dd>' 
          +'  </dl>' 
          +'</li>';
    var extRS={
            recent : function(){
                return parseInt(this.recentAuthor) > 0;
            },
            APP : BASE
    };
    var T = (json.recentAuthorNames !== '0.0.0.*')?UT:UE;
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(json, extRS);
    //
    $('#'+jqEle).prepend(Mustache.render(T, rs));
};
//加载版块的统计
function loadBoardStatsResult(json, element){
    if(jQuery.isEmptyObject(json.result)){
        return;
    }
    $.each(json.result, function(index, item){
        var tb = $('[data-board="'+item.board+'"]');
            tb.find('.threads').html(item.topices);
            tb.find('.replies').html(item.postses);
            tb.find('.today-counter').html('('+item.todayTopics+')');
        if(parseInt(item.recentAuthor)>0){
            var T = ''
                  +'<dfn>Last posts</dfn>'
                  +'<a href="{APP}{recentLink}" title="{recentTitle}" class="lastsubject">{recentTitle}</a> '
                  +'<a href="{APP}/member/{recentAuthor}.xhtml" class="latest-member-color">{recentAuthorNames}</a> &#187; {recentDate}';
            Mustache.parse(T, ['{', '}']);
            var rs = $.extend(item, {"APP":BASE});
            tb.find('.latest').append(Mustache.render(T, rs));
        }
    });
};
//版块主页的 汇总统计
function getBoardStats(pURI){
    var def = $.Deferred();
    $.getJSON(pURI, function( json ){
        $('#online-list-stats').find('#stats-replies').html(json.replies);
        $('#online-list-stats').find('#stats-threads').html(json.threads);
        
        def.resolve();
    });
    return def.promise();
};
//版块主页的 会员统计
function getMemberStats(pURI){
    $.getJSON(pURI, function( json ){
        $('#online-list-stats').find('#stats-member').html(json.members);
        $('#stats-onlines').html(json.onlines);
        $('#stats-onlines-member').html(json.onlines);
        var rm = $.parseJSON(json.recentMember);
        
        if(!$.isEmptyObject(rm)){
            var T='<a href="/member/%MID%.xhtml" class="username">%MN%</a>'.replace('%MID%', rm.id).replace('%MN%', rm.title);
            $('#online-list-stats').find('#stats-recent-member').html(T);
        }
    });
};
function quickLoginCallFun(responseMsg){
    //出错了
    if(responseMsg.hasOwnProperty('level')){
        return tipDialog(responseMsg)
    } 
    if(responseMsg.hasOwnProperty('id') && parseInt(responseMsg.id)>0){
        // 顶部的
        drawMemberPanel(responseMsg, $('#header_member_panel'));
        // 登录区
        drawMemberInfo(responseMsg, $('#right_member_info'));
        // 重新设置客户端缓存的标记
        setMemberVerify(responseMsg.verify);
    }
    return;
};
//
function updateUnReadMessages(sockplaindata){
    var json = $.parseJSON(sockplaindata);
    if(jQuery.isEmptyObject(json)){
        return;
    }
    if(parseInt(json.result)>0){
        $('#notification').removeClass('d-none');
        $('#notification').html(json.result);
    }else{
        $('#notification').addClass('d-none');
    }
    $('#header_member_panel').attr('data-ux', getUnixStamp());
};
var noticeHandler = function(e){
    var self = $(this);
    var memberId = $('#header_member_panel').attr('data-member');
    try{
        $('#header_member_panel').letterSocket({"callFunctionExp": 'updateUnReadMessages', 'remote': $('#topmenu').attr('data-socket-uri')}, 30000);
    }catch(e){ console.log('letter socket file lost');}
};
//chat界面的响应
function drawMessageItem(json){
    if(jQuery.isEmptyObject(json)){
        return;
    }
    var T=''
        +'<div class="media media-master" id="letter-{id}">'
        +'  <div class="media-avatar media-left">'
        +'    <a href="javascript:;">'
        +'        <img class="media-object img-circle" src="{APP}/member/avatar/{sender}.png" style="height:64px;width:64px;">'
        +'    </a>'
        +'  </div>'
        +'  <div class="media-body">'
        +'    <div class="media-bubble">'
        +'        <h6 class="media-heading"><small>{datetime}</small></h6>'
        +'        <p>{body}</p>'
        +'    </div>'
        +'  </div>'
        +'</div>';
    
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(json, {"APP":BASE});
    var targetEleSelector = '#message-'+json.receiver+'-box';
    $(targetEleSelector).append(Mustache.render(T, rs)).scrollTop($(targetEleSelector)[0].scrollHeight);
    $('#send-message-form').find('.form-control').val('');
    $('#send-message-form').find('.send-message-action').removeClass('disabled');
};

//私信的响应
function transmitMessageResult(json){
    if(jQuery.isEmptyObject(json)){
        errorMessage("操作因异常而中止");
        return;
    }
    if(parseInt(json.id)>0){
        tipDialog({"message":"发送成功", "level":"acc", "refresh" : false});
        return;
    }
    errorMessage("消息发送失败");
};
//用户中心的移除收藏话题的回调
function removeHomeCallbackFun(jqEle){
    jqEle.parents('.home-record-item').slideUp(1000, 'linear', function(){
        $(this).remove();
    });
};
function removeHomeBoardCallbackFun(json){
    if(json.level !== 'acc'){
        errorMessage(json.message);
        return;
    }
    //删除元素
    $.map(json.affect.split(','), function(connect){
        $('#member-favorite-board').find('li#fav-board-'+connect).remove();
        //设置缓存
        if(json.hasOwnProperty('cacheModule') && json.hasOwnProperty('cacheAction') && json.hasOwnProperty('cacheValue')){
            json.cacheSequence = connect;
            putActionCacheStore(json);
        }
    });
    //
    $('#member-favorite-board').find('li.fav-focus').removeClass('fav-focus');
    $('#fav-focus-counter').html('0');
};
//版块中的两个收藏按钮
function updateBoardFavoriteCounter(jqEle){
    var cp = jqEle.parent();
    var cc = cp.find('.favoriteCounter').html();
    $('.favoriteCounter').html(parseInt(cc) + 1);
    $('.star-board').addClass('disabled').html(jqEle.html().replace("收藏","已收藏"));
};
//版块中的收藏检查
function checkBoardFavoriteStatus(jqEle, json){
    if(parseInt(json.victim) > 0){
        if(json.action === 'false' || !json.action){
            $('.star-board').addClass('disabled').html(jqEle.html().replace("收藏","已收藏"));
        }
        //设置缓存
        json.cacheValue = json.action;
        putActionCacheStore(json);
    }
};
//话题内容页中点击收藏后的回调函数
function updateFavoriteCounter(jqEle){
    var cp = jqEle.parent();
    var cc = cp.find('.favoriteCounter').html();
    cp.find('.favoriteCounter').html(parseInt(cc) + 1);
    //更新
    jqEle.addClass('disabled').html(jqEle.html().replace("收藏","已收藏"));
};
//话题内容页中点赞后的回调函数
function updateLikeCounter(jqEle){
    var cp = jqEle.parent();
    var cc = cp.find('.likeCounter').html();
    cp.find('.likeCounter').html(parseInt(cc) + 1);
    //更新
    jqEle.addClass('disabled').html(jqEle.html().replace("赞","已赞"));
};
//检查的公共回调函数
function commonCheckActionFun(jqEle, json){
    //文本
    if(parseInt(json.victim) > 0){
        if(json.action === 'false' || !json.action){
            var t = jqEle.text().trim();
            jqEle.addClass('disabled').html(jqEle.html().replace(t,"已"+t));
        }
        //设置缓存
        json.cacheValue = json.action;
        putActionCacheStore(json);
    }
};
//话题内容页中会员弹出菜单的内容
function buildMemberProfileMenu(json, jqEle){
    var MP = ''
        +'<div class="popmenu-member-header member-bg-{label}">'
        +'  <div class="popmenu-member-header-avatar"><img src="{APP}/member/avatar/{id}.png" class="img-circle" width="64px" height="64px" /></div>'
        +'  <div class="popmenu-member-header-info">'
        +'    <h6>{nickname}</h6>'
        +'    <p class="txt-sm">{levelNo}级 / {level}</p>'
        +'  </div>'
        +'</div>'
        +'<div class="popmenu-member-body">'
        +'  <ul class="list-inline"><li class="list-inline-item">{score}<span>积分</span></li><li class="list-inline-item">{threads}<span>主题</span></li><li class="list-inline-item">{replies}<span>回复</span></li></ul>'
        +'</div>'
        +'<div class="popmenu-member-footer">'
        +'  <a href="{APP}/member/{id}.xhtml" title="会员个人中心" role="button" class="btn btn-light btn-sm">'
        +'    <i class="ico-sm mdi mdi-home" aria-hidden="true"></i> 个人中心'
        +'  </a>'
        +'  <a href="javascript:;" title="发送消息" data-handler="{APP}/message/transmit?receiver={id}&names={nickname}" role="button" class="btn btn-light btn-sm message-transmit">'
        +'    <i class="ico-sm mdi mdi-email" aria-hidden="true"></i> 短消息'
        +'  </a>'
        +'</div>'
    var menuContent = '正在努力加载中...';
    if(!jQuery.isEmptyObject(json)){
        Mustache.parse(MP, ['{', '}']);
        var rs = $.extend(json, {"APP":BASE});
        menuContent = Mustache.render(MP, rs);
    }
    var linkDefaultWhiteList = $.fn.popover.Constructor.Default.whiteList;
        linkDefaultWhiteList.a=['target', 'href', 'title', 'rel', 'data-handler'];
    jqEle.popover({
        placement : 'right',
        title : '',
        trigger: 'focus',
        html : true, 
        content : menuContent
    });
    jqEle.popover('show');
};
function showTodayNotice(){
    $.getJSON(BASE+'/message/notice', function( json ){
        poperNotice(json);
    });
};
//取消gritter改用BS4自带的
function poperNotice(json){
    if(jQuery.isEmptyObject(json)){
        return;
    }
    var TC ='{#result}'
           +'<div class="toast ml-auto" role="alert" data-delay="700" data-autohide="false">'
           +'  <div class="toast-header">'
           +'    <strong class="mr-auto text-primary">{nickname}</strong>'
           +'    <small class="text-muted">{pubdate}</small>'
           +'    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">'
           +'      <span aria-hidden="true">×</span>'
           +'    </button>'
           +'  </div>'
           +'  <div class="toast-body">{content}</div>'
           +'</div>{/result}';
    var obj = {}; obj.result = json;
    Mustache.parse(TC, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE});
    $('#toast-collect').append(Mustache.render(TC, rs));
    $('.toast').toast('show');
};
function drawCarousel(json, jqEle){
    var rs={};
        rs.result = json;
        rs.size = json.length;
    var T=''
         +'<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:749px">'
         +'  <ol class="carousel-indicators">';
    for (i = 0; i < rs.size; i++) { 
        T+='    <li data-target="#carousel-example-generic" data-slide-to="'+i+'"'; 
        if(i==0){
            T+=' class="active"';
        }
        T+='></li>';
    }
    T +='  </ol>'
      +'  <div class="carousel-inner" role="listbox">{#result}'
      +'    <div class="carousel-item{#first} active{/first}">'
      +'      <img src="{imageAddr}" alt="{caption}">'
      +'      <div class="carousel-caption"><a href="{link}">{caption}</a></div>'
      +'    </div>{/result}'
      +'  </div>'
      +'  <a class="carousel-control-prev" href="#carousel-example-generic" role="button" data-slide="prev">'
      +'    <span class="carousel-control-prev-icon" aria-hidden="true"></span>'
      +'    <span class="sr-only">Previous</span>'
      +'  </a>'
      +'  <a class="carousel-control-next" href="#carousel-example-generic" role="button" data-slide="next">'
      +'    <span class="carousel-control-next-icon" aria-hidden="true"></span>'
      +'    <span class="sr-only">Next</span>'
      +'  </a>'
      +'</div>';

    Mustache.parse(T, ['{', '}']);
    jqEle.append(Mustache.render(T, rs));
    $('.carousel').carousel();
};
//回复点赞计数更新
function updateMoodCounter(jqEle){
    var cc = jqEle.find('span');
    var upC = 1;
    if(cc.length == 1){
        upC += parseInt(cc.html());
    }else{
        cc = $('<span></span>').appendTo(jqEle);
    }
    cc.html(upC);
};
//话题列表加载像册的回调
function packAlbumHoldSection(json){ 
    if(jQuery.isEmptyObject(json)){
        return;
    }
    $('div[data-album]').each(function(){
        var tmpBody = $(this);
        var aid = tmpBody.attr('data-album');
        var rs = {};
            rs.result = json[aid];
        
        var T='<ul class="list-inline album-thumb">'
            +'{#result}'
            +'   <li class="list-inline-item"><a href="{link}" data-toggle="lightbox" data-title="{caption}" data-gallery="threads-{album}-gallery" data-type="image"><img class="lazyload" src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-original="{thumbnail}"/></a></li>'
            +'{/result}'
            +' </ul>';
        Mustache.parse(T, ['{', '}']);
        tmpBody.append(Mustache.render(T, rs)).find('img.lazyload').lazyload();
    });
};
//话题|版块的工具菜单
function buildMenuList(json){
    var jqEle = $('#'+json.element);
    var T=''; var tmpSize=1; var kt = Object.keys(json.result).length;
    
    $.each(json.result, function(key, value){ //公共|私有
        $.each(value, function(index, item){ //连接
            var tmp;
            if(item.ajax){
                tmp='<a href="javascript:;" class="dropdown-item action-cmd" data-handler="%URL%">%UA%</a>';
            }else{
                tmp='<a class="dropdown-item" href="%URL%" target="_blank">%UA%</a>';
            }
            T+=tmp.replace('%URL%', BASE+item.uri).replace('%UA%', item.anchor);
        });
        if(kt > tmpSize){
            T+='<div class="dropdown-divider"></div>';
        }
        tmpSize += 1;
    });
    jqEle.append(T);
};
//话题回复的动态加载回调函数
function drawReplier(jsonArray){
    var targetEleSelector = $('#topic_posts_collect');
        targetEleSelector.find('.dynamic-posts-record').remove();
    var obj = {};
        obj.result = jsonArray;
    
    var T='{#result}'
        +'<div class="topic_posts dynamic-posts-record">'
        +'  <div class="topic_posts_item">'
        +'    <dl class="topic_posts_item_left" data-handler="{APP}/member/profile.json?id={author}">'
        +'      <dt style="padding-top: 20px;padding-left: 20px;width:180px">'
        +'        <div class="posts-member-avatar">'
        +'          <a href="javascript:;" class="avatar poper-member-menu">'
        +'            <img class="avatar" src="{APP}/member/avatar/{author}.png" alt="User avatar" />'
        +'          </a>'
        +'        </div>'
        +'        <a href="{APP}/member/{author}.xhtml" class="member-info"> <span class="member-{author}-label member-{authorStyle}">{authorNames}</span></a>'
        +'      </dt>'
        +'      <dd>{authorGroup}</dd>'
        +'      {#master}<dd><small class="badge badge-dark">楼主</small></dd>{/master}'
        +'    </dl>'
        +'    <div class="topic_posts_item_right">'
        +'      <div id="posts-{id}" class="posts-body">'
        +'        <ul class="posts-buttons">'
        +'          <li><a href="javascript:;" class="action-cmd delete-post" data-handler="{APP}/posts/delete" data-query="id:{id}"><i class="ico-sm mdi mdi-delete" aria-hidden="true"></i><span>删除</span></a></li>'
        +'          <li><a href="javascript:;" class="post-action-quote" data-handler="{APP}/posts/quote/data.json" data-query="id:{id}"><i class="ico-sm mdi mdi-quote"></i><span>回复</span></a></li>'
        +'          <li><a href="javascript:;" class="post-action-report" data-handler="{APP}/posts/report" data-query="id:{id}"><i class="ico-sm mdi mdi-flag"></i><span>举报</span></a></li>'
        +'          <li><a name="#posts-{id}">{floor}<sup>#</sup></a></li>'
        +'        </ul>'
        +'        <p class="posts-member">'
        +'          <a href="{APP}/member/{author}.xhtml">{authorNames} @u{author}</a>&nbsp;&nbsp;&#187;&nbsp;&nbsp; '
        +'          <i class="ico-sm mdi mdi-time" aria-hidden="true"></i> {date}'
        +'        </p>'
        +'        <div class="posts-body-content">'
        +'          {#block}<p class="alert alert-danger"><strong>提示:</strong> 作者被禁止发言或内容自动屏蔽</p>{/block}'
        +'          {^block}'
        +'            {&content}{&modify}'
        +'          {/block}'
        +'          <div class="mood-section" data-mood="{id}">'
        +'            <a href="javascript:;" title="支持" role="button" class="btn-light btn-sm mood-action" data-action="1" id="{id}-likes"><i class="mdi mdi-thumb-up" aria-hidden="true"></i></a>'
        +'            <a href="javascript:;" title="不赞同" role="button" class="btn-light btn-sm mood-action" data-action="2" id="{id}-hates"><i class="mdi mdi-thumb-down" aria-hidden="true"></i></a>'
        +'          </div>'
        +'        </div>'
        +'        <div class="posts-member-signature member-{author}-signature">{authorSignature}</div>'
        +'      </div>'
        +'    </div>'
        +'  </div>'
        +'</div>{/result}';
    var extRS={
        modify : function(){
            return this.modifyDate.length == 0?'':'<p class="alert alert-warning">回复最近由 '+this.modifyer+' 于 '+this.modifyDate+' 编辑</p>';
        },
        APP : BASE
    };
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, extRS);
    targetEleSelector.append(Mustache.render(T, rs));
    //图片的懒加载
    targetEleSelector.find('img.lazyload').lazyload();
};
//版块话题的动态加载回调函数
function drawThreads(jsonArray){
    var targetEleSelector = $('#board_topic_collect');
        targetEleSelector.find('.dynamic-topic-record').remove();
    var obj = {};
        obj.result = jsonArray;
    var T='{#result}'
        +'<li class="board_item dynamic-topic-record">'
        +'  <dl class="icon topic_{status}">'
        +'    <dt>'
        +'      <div class="board_item_title">'
        +'        <article class="forum-article-header">'
        +'            {#top}<span class="label" title="置顶话题">&#x1F4CC</span> {/top}'
        +'            {#best}<span class="label" title="精华话题">&#x1F48E</span> {/best}'
        +'            {#image}<span class="label" title="图片话题">&#x1F304</span> {/image}'
        +'            {#hot}<span class="label" title="很火噢">&#x1F525</span> {/hot}'
        +'            <a href="{APP}{boardLink}?category={categoryKey}">[{category}]</a> '
        +'            <a href="{APP}{link}" class="forumtitle">{title}</a>'
        +'        </article>'
        +'        <a class="txtline" href="{APP}/member/{author}.xhtml">{authorNames}</a> &#187; {date}'
        +'      </div>'
        +'    </dt>'
        +'    <dd class="replies wp10 stats-item">{replies}<dfn>Replies</dfn></dd>'
        +'    <dd class="views wp10 stats-item">{views}<dfn>Views</dfn></dd>'
        +'    <dd class="latest">{#recent}'
        +'      <span class="last-posts-avatar">'
        +'        <img src ="{APP}/member/avatar/{recentAuthor}.png" width="32px" height="32px"/>'
        +'      </span>'
        +'      <span class="last-posts">'
        +'        <a href="{APP}/member/{recentAuthor}.xhtml" class="latest-member-color">{recentAuthorNames}</a>' 
        +'        <br/>'
        +'        {recentDate}'
        +'      </span>{/recent}'
        +'    </dd>'
        +'  </dl>'
        +'</li>{/result}';
    var extRS={
        recent : function(){
            return parseInt(this.recentAuthor) > 0;
        },
        APP : BASE
    };
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, extRS);
    targetEleSelector.append(Mustache.render(T, rs));
};
//快速回复的异步回调函数
function quickReplyFillPosts(json){
    var T=''
        +'<div class="topic_posts dynamic-posts-record fadeout-anim">'
        +'  <div class="topic_posts_item">'
        +'    <dl class="topic_posts_item_left" data-handler="{APP}/member/profile.json?id={author}">'
        +'      <dt style="padding-top: 20px;padding-left: 20px;width:180px">'
        +'        <div class="posts-member-avatar">'
        +'          <a href="javascript:;" class="avatar poper-member-menu">'
        +'            <img class="avatar" src="{APP}/member/avatar/{author}.png" alt="User avatar" />'
        +'          </a>'
        +'        </div>'
        +'        <a href="{APP}/member/{author}.xhtml" class="member-info"> <span class="member-{author}-label member-{authorStyle}">{authorNames}</span></a>'
        +'      </dt>'
        +'      <dd>{authorGroup}</dd>'
        +'      {#master}<dd><small class="badge badge-dark">楼主</small></dd>{/master}'
        +'    </dl>'
        +'    <div class="topic_posts_item_right">'
        +'      <div id="posts-{id}" class="posts-body">'
        +'        <ul class="posts-buttons">'
        +'          <li><a href="javascript:;" class="action-cmd delete-post" data-handler="{APP}/posts/delete" data-query="id:{id}"><i class="ico-sm mdi mdi-delete" aria-hidden="true"></i><span>删除</span></a></li>'
        +'          <li><a href="javascript:;" class="post-action-quote" data-handler="{APP}/posts/quote/data.json" data-query="id:{id}"><i class="ico-sm mdi mdi-quote"></i><span>回复</span></a></li>'
        +'          <li><a href="javascript:;" class="post-action-report" data-handler="{APP}/posts/report" data-query="id:{id}"><i class="ico-sm mdi mdi-flag"></i><span>举报</span></a></li>'
        +'          <li><a name="#posts-{id}">{floor}<sup>#</sup></a></li>'
        +'        </ul>'
        +'        <p class="posts-member">'
        +'          <a href="{APP}/member/{author}.xhtml">{authorNames} @u{author}</a>&nbsp;&nbsp;&#187;&nbsp;&nbsp; '
        +'          <i class="ico-sm mdi mdi-time" aria-hidden="true"></i> {date}'
        +'        </p>'
        +'        <div class="posts-body-content">'
        +'          {&content}'
        +'          <div class="mood-section" data-mood="{id}">'
        +'            <a href="javascript:;" title="支持" role="button" class="btn-light btn-sm mood-action" data-action="1" id="{id}-likes"><i class="mdi mdi-thumb-up" aria-hidden="true"></i></a>'
        +'            <a href="javascript:;" title="不赞同" role="button" class="btn-light btn-sm mood-action" data-action="2" id="{id}-hates"><i class="mdi mdi-thumb-down" aria-hidden="true"></i></a>'
        +'          </div>'
        +'        </div>'
        +'        <div class="posts-member-signature member-{author}-signature">{authorSignature}</div>'
        +'      </div>'
        +'    </div>'
        +'  </div>'
        +'</div>';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(json, {"APP":BASE});
    $('#topic_posts_collect').append(Mustache.render(T, rs));
    //图片的懒加载
    $('#posts-'+json.id).find('img.lazyload').lazyload();
};
//显示回复的点赞汇总结果
function drawMoodResult(json){
    if(jQuery.isEmptyObject(json.result)){
        return;
    }
    $.each(json.result, function(index,item){
        var pid = item.posts;
        if(item.likes !== '0'){
            $('#'+pid+'-likes').append('<span>'+item.likes+'</span>');
        }
        if(item.hates !== '0'){
            $('#'+pid+'-hates').append('<span>'+item.hates+'</span>');
        }
    });
};
function gatherMood(){
    var postsIdStr = $('.dynamic-posts-record').find('.posts-body').map(function(){
        return this.id.replace('posts-', '');
    }).get().join(",");
    if(postsIdStr.length == 0){
        return;
    }
    var requestURI = '/posts/mood/list/jsonp';
    $.ajax({
        url: requestURI,
        jsonpCallback: 'drawMoodResult',
        dataType: 'jsonp',
        data: 'ids='+postsIdStr
    });
};
//删除标签后的回调
function delTagHandler(jqEle){
    console.log('remove tag callback');
    jqEle.remove();
};
//添加标签后的回调
function newTagHandler(json){
    if(json.level === 'acc'){
        //插入到标签列中
        var T = '<a href="javascript:;" class="action-cmd tag-item-anchor" data-handler="%APP%/topic/tag/delete" data-query="id:%id%" data-function="delTagHandler">%names%</a>';
            T = T.replace('%APP%', BASE).replace('%id%', json.input).replace('%names%', json.names);
        $(T).insertBefore('#tag-action-add');
        return;
    }
    if(json.level ==='err'){
        //提示错误
        errorMessage(json.message);
        return;
    }
};
//UID检查的回调
function uidDetectionHandler(nickname, jqEle){
    jqEle.find('input[name=uid]').removeAttr("disabled").removeClass('is-invalid');
    $('#suggest-uid').parents('form').find('input[name=snames]').val(nickname);
};
//获取JS.Store缓存的值
function getActionCacheStore(json){ 
    if(!json.hasOwnProperty('cacheModule') || !json.hasOwnProperty('cacheSequence') || !json.hasOwnProperty('cacheAction')){
        return;
    }
    var key = json.cacheModule+'#'+json.cacheSequence;
    var cacheData = store.get(key); 
    if(jQuery.isEmptyObject(cacheData)){
        return undefined;
    }
    return cacheData[json.cacheAction];
};
//更新JS.Store缓存的值
function putActionCacheStore(json){ 
    if(!json.hasOwnProperty('cacheModule') || !json.hasOwnProperty('cacheSequence') || !json.hasOwnProperty('cacheAction') || !json.hasOwnProperty('cacheValue')){
        return;
    }
    var key = json.cacheModule+'#'+json.cacheSequence;
    var cacheData = store.get(key); 
    
    var data = {};
    data[json.cacheAction] = json.cacheValue;
    if(jQuery.isEmptyObject(cacheData)){
        store.set(key, data); 
    }else{
        var tmp = $.extend(cacheData, data);
        store.set(key, tmp);
    }
};
//解析URL获得module,id
function parseActionURL(actionCheckUri){
    var pacu = actionCheckUri.split('/');
    //
    if(pacu.length < 4){
        return null;
    }
    var curl = location.href; var m= pacu[pacu.length - 3];
    var d = {};
        d.cacheModule = m;
        d.cacheSequence = curl.substring(curl.indexOf('/'+m+'/')+2+m.length, curl.indexOf('.xhtml'));
        d.cacheAction = pacu[pacu.length - 2];
    //
    return d;
};
//会员中心的话题|回复
function drawMHomeRecord(jsonArray){
    var targetEleSelector = $('#member-home-records');
        targetEleSelector.find('.home-record-item').remove();
    var obj = {};
        obj.result = jsonArray;
    var T ='{#result}'
          +' <div class="home-record-item">'
          +'   <div class="record-item-body">'
          +'     <h6 class="record-item-heading"><a href="{APP}{link}">{title}</a></h6>'
          +'     <span>楼主: <a href="{APP}{publisherURI}">{publisher}</a></span>'
          +'     <span>发布日期: {publishDate}</span>'
          +'     {#reply}'
          +'       <span>最近回复: <a href="{APP}{replierURI}">{replier}</a></span>'
          +'       <span>&#187; {replyDate}</span>'
          +'     {/reply}'
          +'   </div>'
          +' </div>{/result}';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE});
    targetEleSelector.append(Mustache.render(T, rs));
};
//会员中心的点赞|收藏
function drawMHomeAction(jsonArray){
    var targetEleSelector = $('#member-home-actions');
        targetEleSelector.find('.home-record-item').remove();
    var cancelURI = targetEleSelector.attr('data-action') || '#';
    var obj = {};
        obj.result = jsonArray;
    var T ='{#result}'
          +' <div class="home-record-item">'
          +'   <div class="record-item-body">'
          +'     <h6 class="record-item-heading"><a href="{APP}{link}">{title}</a></h6>'
          +'     <span>操作日期: {actionDate}</span>'
          +'   </div>'
          +'   <div class="record-item-menu">'
          +'     <a class="action-cmd" role="button" href="javascript::" data-acctip="false" data-handler="{CU}" data-query="id:{id}" data-function="removeHomeCallbackFun"><i class="mdi mdi-delete"></i>&nbsp;删除</a>'
          +'   </div>'
          +' </div>{/result}';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE, "CU":cancelURI});
    targetEleSelector.append(Mustache.render(T, rs));
};
function drawActionHistory(jsonArray){
    var targetEleSelector = $('#member-home-actions');
        targetEleSelector.find('.home-record-item').remove();
    var obj = {};
        obj.result = jsonArray;
    var T ='{#result}'
          +' <div class="home-record-item">'
          +'   <div class="record-item-body">'
          +'     <h6 class="record-item-heading"><a href="{APP}{link}">{title}</a></h6>'
          +'     <span>{actionTitle}&nbsp;&#187;&nbsp;{actionDate}</span>'
          +'   </div>'
          +' </div>{/result}';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE});
    targetEleSelector.append(Mustache.render(T, rs));
};
//个人中心的受欢迎的回调
function basicThreadTemplate(jsonArray){
    var targetEleSelector = $('#member-publish-topic');
    var obj = {};
        obj.result = jsonArray;
    var T ='{#result}'
          +' <div class="media mc-topic">'
          +'   <div class="media-left">&nbsp;</div>'
          +'   <div class="media-body mc-topic-body">'
          +'     <article class="forum-article-header"><a href="{APP}{link}" class="forumtitle">{title}</a></article>'
          +'     <p>'
          +'       <a href="{APP}{publisherURI}" title="会员主页">{publisher}</a> &#187; {publishDate}'
          +'       <span class="float-right">'
          +'         <a href="{APP}{boardURI}">{boardName}</a>'
          +'       </span>'
          +'     </p>'
          +'     <div class="topic_item_body_footer">'
          +'       <ul class="list-inline mc-topic-panel">'
          +'         <li class="list-inline-item"><span><i class="ico-sm ico-color-link mdi mdi-comment" aria-hidden="true"></i>&nbsp;&nbsp;{postses}</span></li>'
          +'         <li class="list-inline-item"><span><i class="ico-sm ico-color-teal mdi mdi-thumb-up" aria-hidden="true"></i>&nbsp;&nbsp;{likes}</span></li>'
          +'         <li class="list-inline-item"><span><i class="ico-sm ico-color-red mdi mdi-favorite" aria-hidden="true"></i>&nbsp;&nbsp;{favorites}</span></li>'
          +'         <li class="list-inline-item"><span><i class="ico-sm mdi mdi-eye" aria-hidden="true"></i>&nbsp;&nbsp;{displaies}</span></li>'
          +'       </ul>'
          +'     </div>'
          +'   </div>'
          +' </div>{/result}';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE});
    targetEleSelector.append(Mustache.render(T, rs));
};
//个人中心消息收件箱回调
function memberInboxTemplate(jsonArray){
    var targetEleSelector = $('#member-message-records');
    var obj = {};
        obj.result = jsonArray;
    var T ='<ul class="media-list" style="padding: 10px 20px;">{#result}'
          +' <li class="media letter-item">'
          +'   <div class="media-left mr-3">'
          +'     {#robot}<img style="width: 64px; height: 64px;" class="img-circle media-object" src="{APP}/member/avatar/0.png" title="message robot">{/robot}'
          +'     {^robot}<a href="{APP}{senderURI}"><img style="width: 64px; height: 64px;" class="img-circle media-object" src="{APP}/member/avatar/{sender}.png" title="{senderNickname}"></a>{/robot}'
          +'   </div>'
          +'   <div class="media-body">'
          +'     <h6 class="media-heading">{senderNickname} &nbsp;<span id="notice_{sender}" class="badge">0</span><span class="float-right"><i class="ico-sm mdi mdi-time"></i>&nbsp;{datetime}</span></h6>'
          +'     <div><a href="{APP}/message/view?sender={sender}" target="_blank">{subject}</a></div>'
          +'   </div>'
          +' </li>{/result}</ul>';
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, {"APP":BASE});
    targetEleSelector.append(Mustache.render(T, rs));
};
function unreadInboxMessageSize(){
    var requestURI = '/message/size';
    var params = $('#member-message-records').find('.badge').map(function(){
        return this.id.replace('notice_', '');
    }).get().join(",");
    //
    $.getJSON(requestURI+'?sender='+params, function( data ){
        if(jQuery.isEmptyObject(data)){
            return $('.badge').hide();
        }
        $.each(data, function(index, item) {
            $('#notice_'+item.id).addClass('badge-info').html(item.title);
        });
        //没有的
        $('.badge').not( ".badge-info").hide();
    });
};
//个人中心消息发件箱回调
function memberOutboxTemplate(jsonArray){
    var targetEleSelector = $('#member-message-records');
    var obj = {};
        obj.result = jsonArray;
        var T ='<ul class="media-list" style="padding: 10px 20px;">{#result}'
            +' <li class="media letter-item">'
            +'   <div class="media-left mr-3">'
            +'     {#everyone}<img style="width: 64px; height: 64px;" class="img-circle media-object" src="{APP}/member/avatar/0.png" title="message robot">{/everyone}'
            +'     {^everyone}<a href="{APP}{receiverURI}"><img style="width: 64px; height: 64px;" class="img-circle media-object" src="{APP}/member/avatar/{receiver}.png" title="{receiverNickname}"></a>{/everyone}'
            +'   </div>'
            +'   <div class="media-body">'
            +'     <h6 class="media-heading">{&reces} &nbsp;<small>[{category}]</small><span class="float-right"><i class="ico-sm mdi mdi-time"></i>&nbsp;{datetime}</span></h6>'
            +'     <div class="letter-item-content">'
            +'       <p>{&content}</p>'
            +'     </div>'
            +'   </div>'
            +' </li>{/result}</ul>';
    var extRS={
            reces : function(){
                  var tmp=''; var rs = this.receives;
                  for (var i = 0, len = rs.length; i < len; ++i) {
                      var rmid = rs[i].id;
                      var rmnm = rs[i].nickname;
                      tmp += '<a href="'+BASE+'/member/'+rmid+'.xhtml">'+rmnm+'</a>';
                      if(i< len -1){
                         tmp +'&nbsp;,&nbsp;';
                      }
                  }
                  return tmp;
            },
            APP : BASE
    };
    Mustache.parse(T, ['{', '}']);
    var rs = $.extend(obj, extRS);
    targetEleSelector.append(Mustache.render(T, rs));
};
jQuery(function($){
    //元素的文本节点值
    //服务于引用
    $.fn.textValue = function() {
        var str = '';
        this.contents().each(function() {
            if (this.nodeType === 3) {
                str += this.textContent || this.innerText || '';
            }
        });
        return str;
    };
    //全选
    $('#checkAll').click(function(e){
        $('input[name=id]:checkbox').each(function(){ 
            this.checked = true; 
            $(this).parents('tr').addClass('active');
        });
    });
    //反选
    $('#unCheck').click(function(e){
        $('input[name=id]:checkbox').each(function(){ 
            if(this.checked){
                this.checked = false; 
                $(this).parents('tr').removeClass('active');
            }else{
                this.checked = true; 
                $(this).parents('tr').addClass('active');
            }
        });
    });
    //
    $('input[name=id]:checkbox').on('click',function(){
        $(this).parents('tr').toggleClass('active');
    });
    //引用@20200506
    $('body').on('click', '.post-action-quote', function(){
        var self = $(this);
        var options=parseQueryJson(self.attr('data-query'));
        $.getJSON(self.attr('data-handler'), 'id='+options.id, function( json ){
            if(jQuery.isEmptyObject(json)){
                return errorMessage('读取原文内容失败');
            }
            if(json.level ==='err'){
                return errorMessage(json.message);
            }
            if(json.infoTip){
                insertEditorHtml('');
                $('#reply-tip-message').html('<strong>提示!</strong>&nbsp;'+json.infoTip);
                //插入到表单中@20200506
                $('#quick_reply_form').find('input[name=quote]').val(json.quote);
                $('#quick_reply_form').find('input[name=scale]').val(json.scale);
            }
        });
        return false;
    });
    //操作类
    $('body').on('click', '.action-cmd', function(){
        var self=$(this);
        var rawdata = {};
            rawdata.uri=self.attr('data-handler');
            rawdata.data=parseQueryJson(self.attr('data-query'));
            rawdata.callFun = self.attr('data-function');
            rawdata.tip = $.parseJSON(self.attr('data-acctip') || 'true');
        
        $.ajax({
            type: 'POST',
            url: rawdata.uri,
            data: rawdata.data,
            dataType: 'json'
        }).done(function (response) {
            if(response.level === 'acc'){
                //设置缓存
                if(!response.hasOwnProperty('cacheValue')){
                    response.cacheValue = false;
                }
                putActionCacheStore(response);
                try{
                    var fn = window[rawdata.callFun];
                    if (typeof fn === "function"){
                        fn.call(this, self, self);
                    }
                }catch(e){}
            }else{
                rawdata.tip = true;
            }
            if(rawdata.tip){
                response.refresh = false;
                tipDialog(response);
            }
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //检查类
    $('.action-check').bind('checkEvent', function(e){
        var self=$(this);
        var rawdata = {};
            rawdata.uri=self.attr('data-check-handler');
            rawdata.data=parseQueryJson(self.attr('data-check-query'));
            rawdata.callFun = self.attr('data-check-function') || 'commonCheckActionFun';
            try{
            rawdata.member = store.get('member').id || 0;
            }catch(e){
            rawdata.member = -1;
            }
        // 是否存在缓存
        var cacheParamData = parseActionURL(rawdata.uri);
        if(!isBlank(cacheParamData) && !jQuery.isEmptyObject(cacheParamData)){
            var cacheActionResult = getActionCacheStore(cacheParamData);
            if(typeof(cacheActionResult) != "undefined"){ //命中缓存了
                // 存在缓存,更新状态
                var statusUpdataResult = {};
                    statusUpdataResult.action = cacheActionResult;
                    statusUpdataResult.victim = rawdata.member;
                try{
                    var fn = window[rawdata.callFun];
                    if (typeof fn === "function"){
                        fn.call(this, self, statusUpdataResult);
                    }
                }catch(e){}
                return false;
            }
        }
        // 游客直接退出
        if(parseInt(rawdata.member) < 1){ return;}
        // 没有命中缓存,获取
        console.log('[ACC]不存在缓存去拉取数据');
        $.ajax({
                type: 'GET',
                url: rawdata.uri,
                data: rawdata.data,
                dataType: 'json'
            }).done(function (response) {
                try{
                    var fn = window[rawdata.callFun];
                    if (typeof fn === "function"){
                        fn.call(this, self, response);
                    }
                }catch(e){}
            }).fail(function(){
                errorMessage('当前操作因错误而异外中止');
            });
        return false;
    }).trigger('checkEvent');
    //快速回复[NW]@20200506
    $('#quick_reply_posts').on('submit', '#quick_reply_form', function(e){
        e.preventDefault();
        var self = $(this); 
        //
        var requestData={}
            requestData.token = self.find('input[name=token]').val();
            requestData.quote = self.find('input[name=quote]').val();
            requestData.scale = self.find('input[name=scale]').val();
        try{
            requestData.content=CKEDITOR.instances.content.getData();
        }catch(e){
            requestData.content=$(this).find('input[name=content]').val();
        }
        if(isBlank(requestData.content)){
            $.alert('请输入回复的内容');
            return false;
        }
        // 同步操作
        $.ajax({
            type: 'POST',
            url: self.attr('action'),
            data: requestData,
            dataType: 'json'
        }).done(function (response) {
            if(response.level === 'err' && !isBlank(response.message)){
                //出错了
                response.refresh = false;
                tipDialog(response);
            }else{
                quickReplyFillPosts(response);
                //清空表单的元素
                self.find('input[name=content]').val(''); 
                self.find('input[name=quote]').val('');
                self.find('input[name=scale]').val('');
                $('#reply-tip-message').html('');
                //清空编辑器的内容
                CKEDITOR.instances['content'].setData('');
            }
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //更新会员头像[NW]
    $('img.member_default_avtar').on('click', function(){
        var self = $(this);
        var v = self.attr('data-path'); 
        //
        $.ajax({
            type: 'POST',
            url: BASE+'/member/home/avatar',
            data: {"file" : v},
            dataType: 'json'
        }).done(function (response) {
            if(response.level === 'acc' ){
                self.addClass('active'); 
                response.refresh = false;
                $('img.member_default_avtar').not(self).removeClass('active');
            }
            tipDialog(response);
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //快速登录[NW]
    $('#right_member_info').on('submit', '#quick_login_form', function(e){
        var form=$(this); 
        
        var requestData = {};
            requestData.names = form.find('input[name=names]').val();
            requestData.password = form.find('input[name=password]').val();
            requestData.token = form.find('input[name=token]').val();
        if(isBlank(requestData.names) || isBlank(requestData.password)){
            form.find('input').not('[type="submit"],[type="hidden"]').each(function(){
                if(isBlank(this.value)){
                    return false;
                }
            }).first().focus();
            return false;
        }
        form.find('input[type=submit]').prop('disabled', true).val('正在登录');
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: requestData,
            dataType: 'json'
        }).done(function (response) {
            quickLoginCallFun(response); 
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //uid[NW]
    $('body').on('click', '#suggest-btn', function(e){
        var self = $('#suggest-uid');
        var p = self.parents('.form-group');
        if(isBlank(self.val())){
            self.attr('placeholder', '输入收件人的UID').focus();
            return;
        }
        self.attr("disabled","disabled");
        $.getJSON(self.attr('data-handler'), 'value='+self.val(), function( data ){
            if(data.level ==='acc'){
                uidDetectionHandler(data.message, p);
            }else{
            	 $('input[name=snames]').val('');
                self.addClass('is-invalid').removeAttr("disabled").focus();
            }
        });
    });
    //举报回复[NW]
    $('body').on('click', '.post-action-report', function(){
        var self = $(this);
        var requestParam=parseQueryJson(self.attr('data-query'));
        //
        $.confirm({
            title: '',
            closeIcon: true,
            closeIconClass: 'ico-sm mdi mdi-close',
            content: '<form action="">' +
                        '<div class="form-group">' +
                        '<label>类型</label>' +
                        '<select name="type" size="1" class="form-control">' +
                        '<option value="">请选择类型</option>' + 
                        '<option value="1">广告</option>' +
                        '<option value="2">色情</option>' +
                        '<option value="3">政治</option>' +
                        '<option value="4">暴力</option>' +
                        '<option value="5">语言暴力</option>' +
                        '<option value="6">其它</option>' +
                        '</select></div><div class="form-group"><textarea class="form-control" name="reason" required="required" rows="3" placeholder="输入举报的理由"></textarea></div></form>', 
            buttons: {
                formSubmit: {
                    text: '举报',
                    btnClass: 'btn-blue',
                    action: function () {
                        var reason = this.$content.find('textarea[name=reason]').val();
                        if(isBlank(reason)){
                            this.$content.find('textarea[name=reason]').focus();
                            return false;
                        }
                        requestParam.reason=reason;
                        requestParam.type=this.$content.find("select[name=type]").val();
                        
                        $.ajax({
                            url: self.attr('data-handler'),
                            dataType: 'json',
                            method: 'post',
                            data: requestParam
                        }).done(function (response) {
                            response.refresh = false;
                            tipDialog(response);
                        }).fail(function(){
                            errorMessage('当前操作因错误而异外中止');
                        });
                    }
                }
            },
            onContentReady: function () {
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click');
                });
            }
        });
        return false;
    });
    /*版块组与版块联动[NW]*/
    $('#asyn-volumes-select').on('select2:select', function (e) {
        var selectBoard = e.params.data.id;
        var selectChild = $('#asyn-board-select');
        
        $.getJSON(selectChild.attr('data-handler'), 'volumes='+selectBoard, function( data ){
            var optionData='';
            $.each( data, function( index, item ) {
                optionData += '<option value="%V%">%T%</option>'.replace('%V%', item.id).replace('%T%', item.title);
            });
            if(optionData.length>0){
                //清空旧值
                selectChild.find('option').remove();
                selectChild.append(optionData).find('option[value='+selectChild.attr('data-current')+']').attr("selected", true);
                $('.selectpicker').select2({theme: 'bootstrap4'});
            }
        });
    });
    //版块导航的选中跳转
    $('.board-navigator-select').on('click', function(){
        var self = $(this); self.html('正在加载数据'); 
        var currentId = "board-navigator-"+randomAlphaNumeric(8);
        var parent = self.parents('div.board-navigator-box'); parent.attr('id', currentId);
        var rawdata = {};
            rawdata.uri = parent.attr('data-handler');
            rawdata.callFun = parent.attr('data-function');
            rawdata.data = {'box':currentId};
        $.ajax({
            url: rawdata.uri,
            jsonpCallback: rawdata.callFun,
            dataType: 'jsonp', 
            data: $.param(rawdata.data)
        });
    });
    //收件箱中的消息动作
    $('.message-action').on('click', function(e){
        var requestURI = $(this).attr('data-handler');
        var idString = $('form').find('input[name=id]:checked').map(function(){
            return this.value;
        }).get().join(",");
        if(isBlank(idString)){
            return errorMessage('请选择要操作的消息');
        }
        $.ajax({
            url: requestURI,
            dataType: 'json',
            method: 'post',
            data: 'ids='+idString
        }).done(function (response) {
            response.refresh = false;
            tipDialog(response);
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //消息内容页中的全部标记为已读
    $('.readall-message-action').on('click', function(e){
        var requestURI = $(this).attr('data-handler');
        $.ajax({
            url: requestURI,
            dataType: 'json',
            method: 'post'
        }).done(function (response) {
            response.refresh = false;
            tipDialog(response);
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //聊天消息页中的发送动作
    $('.send-message-action').on('click', function(e){
        var self = $(this);
        var callFun = self.attr('data-function') || 'drawMessageItem';
        var requestParam = parseQueryJson(self.attr('data-query'));
            requestParam.content = self.parents('form').find('.form-control').val();
        //
        if(isBlank(requestParam.content)){
            self.parents('form').find('.form-control').focus();
            return false;
        }
        self.addClass('disabled');
        $.ajax({
            url: self.attr('data-handler'),
            dataType: 'json',
            method: 'post',
            data: requestParam
        }).done(function (response) {
            window[callFun].call(this, response, self);
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //会员主页的发送消息[NW]
    $('body').on('click', '.message-transmit', function(e){
        //在线吗
        var cam = getCurrentActiveMemberInfo();
        if(jQuery.isEmptyObject(cam) || parseInt(cam.id) < 1){
            return errorMessage('暂不支持游客发送消息');
        }
        var requestURI = $(this).attr('data-handler');
        $.confirm({
            title: '新消息',
            closeIcon: true,
            closeIconClass: 'ico-sm mdi mdi-close',
            content: '<form action=""><div class="form-group"><textarea class="form-control" name="content" required="required" rows="3" placeholder="输入消息的内容"></textarea></div></form>',
            buttons: {
                formSubmit: {
                    text: '发送',
                    btnClass: 'btn-blue',
                    action: function () {
                        var content = this.$content.find('textarea[name=content]').val();
                        if(isBlank(content)){
                            this.$content.find('textarea[name=content]').focus();
                            return false;
                        }
                        var requestParam={};
                        requestParam.content=content;
                        
                        $.ajax({
                            url: requestURI,
                            dataType: 'json',
                            method: 'post',
                            data: requestParam
                        }).done(function (response) {
                            transmitMessageResult(response);
                        }).fail(function(){
                            errorMessage('当前操作因错误而异外中止');
                        });
                    }
                }
            },
            onContentReady: function () {
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click');
                });
            }
        });
        return false;
    });
    try{
        $('.dropdown-toggle').dropdown();
    }catch(e){}
    try{
        $('.datetime').datetimepicker({
            locale: 'zh',
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            minView: "month"
        });
    }catch(e){}
    //返回浏览历史的上一条
    $('.historyBack').on('click', function(e){
        e.preventDefault();
        window.history.back();
        return false;
    });
    //话题内容页中会员信息弹出菜单
    $('body').on('click', 'a.poper-member-menu', function (e) {
        e.preventDefault();
        var self = $(this); 
        var rawdata = {};
            rawdata.uri = self.parents('.topic_posts_item_left').attr('data-handler');
            //本地缓存命中
            rawdata.member=$.url(rawdata.uri).param('id');
        var cacheData = store.get('member_profile#'+rawdata.member); 
        //本人的不缓存[20200118]
        if(!jQuery.isEmptyObject(cacheData)){
            buildMemberProfileMenu(cacheData, self);
            return;
        }
        //
        console.log('[MP]不存在缓存去拉取数据');
        $.getJSON(rawdata.uri, function( data ){
            store.set('member_profile#'+rawdata.member, data);
            buildMemberProfileMenu(data, self);
        });
    });
    // 收件箱内容页中的加载更多
    $('.letter-more-action').on('click', function(){
        var pbx = $(this).parents('.letter-item-collect');
        var rawdata = {};
            rawdata.uri = pbx.attr('data-handler');
            rawdata.page = parseInt(pbx.attr('data-page') || '1') +1;
            rawdata.ele = pbx.attr('id');
        //
        var self = $(this);
        self.addClass('disabled').html('正在玩命加载');
        $.getJSON(rawdata.uri+'&p='+rawdata.page, function( data ){
            //self是否显示
            if(jQuery.isEmptyObject(data)){
                return;
            }
            //遍历data.result
            $.each(data.result, function(index, item){
                drawLetterHistoryMessage(item, rawdata.ele);
            });
            pbx.attr('data-page', rawdata.page).scrollTop();
            var letter = $.parseJSON(data.letter);
            if(letter.more){
                self.removeClass('disabled').html('更多历史消息');
            }else{
                self.hide();
            }
        });
    });
    //提示
    $('[data-toggle="tooltip"]').tooltip();$('[data-toggle="popover"]').popover();
    //防止多次提交
    $('[data-submit="once"]').one('submit', function(){
        var submitBtn = $(this).find('[type="submit"]');
        submitBtn.prop('disabled', true).val(submitBtn.attr('data-submit-disabled') || '数据发送中');
        return true;
    });
    //像册放大图
    $(document).on('click', '[data-toggle="lightbox"]', function(event) {
        event.preventDefault();
        $(this).ekkoLightbox({alwaysShowClose:true});
    });
    //海报中的下载
    $('#poster-down-action').on('click', function(e){
        e.preventDefault();
        
        var self = $(this); self.addClass('disabled');
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.data = parseQueryJson(self.attr('data-query'));
        if(!jQuery.isEmptyObject(rawdata.data)){
            rawdata.data.stamp = Math.round(new Date().getTime());
            rawdata.uri += '?'+$.param(rawdata.data);
        }
        $.fileDownload(rawdata.uri, {
            httpMethod: 'get',
            prepareCallback:function(url){
               loading_control.start();
               console.log('poster start down');
            },
            successCallback:function(url){
               loading_control.stop();
            },
            failCallback: function (html, url) {
              loading_control.stop();
              console.log('poster download fail');
              errorMessage('当前操作因错误而异外中止');
            }
        });
    });
    //待消灭掉的代码开始---------------------------------------------------------------------------
    //从页中抽出来的js
    // 版块最新的话题
    $('#board_topic_collect').on('loadDataEvent', function(e){
        var self = $(this); 
            self.attr('data-ux', getUnixStamp()); //一开始的时间戳
        try{
            if(self.attr('data-socket-uri') && self.attr('data-board')){
                self.threadSocket({"module" : 'board', "callFunctionExp" : 'updateNewsTopices', "serial" : self.attr('data-board'), "remote" : self.attr('data-socket-uri')}, 60000);
            }
        }catch(e){ console.log('thread socket file lost');}
    }).trigger('loadDataEvent');
    //载入页顶的会员信息[NW]
    $('#header_member_panel').on('loadDataEvent', function(e){
        var self=$(this);
        //至少拉一次
        var mv = getMemberVerify();
        if(mv !== -1){ //不需要拉取
            return getCacheMemberInfo(mv, self);
        } 
        //没有缓存命中
        $.getJSON(self.attr('data-handler'), function( data ){
            if(!jQuery.isEmptyObject(data)){
                //[HMP]创建缓存拉取标记
                setMemberVerify(data.verify);
                //[HMP]生成会员面板
                drawMemberPanel(data, self); //怎么显示由drawMemberPanel负责
            }
        });
    }).trigger('loadDataEvent');
    
    //创建话题:初始化版块[NW]
    $('#asyn-board-select').on('initDataEvent', function(){
        var self = $(this);
        if(self.attr('data-current') === '0'){
            return; //没有选择版块,不初始化
        }
        var parentSelect = $('#asyn-volumes-select').attr('data-current');
        if(isBlank(parentSelect)){ 
            return; //没有选择版块组(卷),不初始化
        }
        $.getJSON(self.attr('data-handler'), 'volumes='+parentSelect, function( data ){
            var optionData='';
            $.each( data, function( index, item ) {
                optionData += '<option value="%V%">%T%</option>'.replace('%V%', item.id).replace('%T%', item.title);
            });
            if(optionData.length>0){
                self.append(optionData).find('option[value='+self.attr('data-current')+']').attr("selected", true);
                self.select2({theme: 'bootstrap4'});
            }
        });
    }).trigger('initDataEvent');
    //话题/回复/会员统计
    $('#online-list-stats').on('initDataEvent', function(){
        var boardStatsURI = $(this).attr('data-board');
        var memberStatsURI = $(this).attr('data-member');
        
        $.when(getBoardStats(boardStatsURI))
            .done(function(){ 
                 getMemberStats(memberStatsURI);
             })
            .fail(function(){ alert("出错啦！"); });
    }).trigger('initDataEvent');
    //加载版块组[NW]
    $('.asyn-loadate-select').on('initDataEvent', function(){
        var self = $(this); var currentOption = self.attr('data-current') || '-1';
        $.getJSON(self.attr('data-handler'), function( data ){
            var optionData='';
            $.each( data, function( index, item ) {
                optionData += '<option value="%V%">%T%</option>'.replace('%V%', item.id).replace('%T%', item.title);
            });
            if(optionData.length>0){
                self.append(optionData).find('option[value='+currentOption+']').attr("selected", true);
                self.select2({theme: 'bootstrap4'});
            }
        });
    }).trigger('initDataEvent');
    //单页的上一条下一条
    $('#page_navigate').on('initEvent', function(e){
        var self = $(this);
        var options=parseQueryJson($(this).attr('data-query'));
        
        $.getJSON(self.attr('data-handler'), options, function( data ){
             if(jQuery.isEmptyObject(data)){
                 return;
             }
             if(data.prev){
                 self.find('li.previous').removeClass('disabled').find('a').attr('href', data.prev.link).attr('title', data.prev.title);
             }
             if(data.next){
                 self.find('li.next').removeClass('disabled').find('a').attr('href', data.next.link).attr('title', data.next.title);
             }
        });
    }).trigger('initEvent');
    //单页左侧的菜单
    $('#spa-page-menu').on('initEvent', function(e){
        var self = $(this);
        
        $.getJSON(self.attr('data-handler'), function( data ){
             if(jQuery.isEmptyObject(data)){
                 return;
             }
             //
             var T = '<div id="toc">' 
                 + '  <div id="toctitle">{term}</div>' 
                 + '  <div id="tocbot">'
                 + '      <ol>'
                 + '        {#menu}<li><a href="{link}">{title}</a></li>{/menu}'
                 + '      </ol>'
                 + '  </div>'
                 + '</div>';
             var raw = {};
                 raw.term = $.parseJSON(data.parent).title;
                 raw.menu  = data.menu;
             Mustache.parse(T, ['{', '}']);
             self.html(Mustache.render(T, raw));
        });
    }).trigger('initEvent');
    //待消灭掉的代码结束---------------------------------------------------------------------------
    //抽像的加载JSONP的Loader
    $('[data-result="loader.jsonp"]').on('loadDataEvent', function(e){
        var self=$(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.callFun = self.attr('data-function');
            rawdata.data = parseQueryJson(self.attr('data-query'));
            
        if(self.attr('data-container')){
            rawdata.data.box=self.attr('data-container');
        }
        $.ajax({
            url: rawdata.uri,
            jsonpCallback: rawdata.callFun,
            dataType: 'jsonp',
            data: $.param(rawdata.data)
        });
    }).trigger('loadDataEvent');
    //抽像的加载JSON的Loader
    $('[data-result="loader.json"]').on('loadDataEvent', function(e){
        var self=$(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.data = parseQueryJson(self.attr('data-query'));
            rawdata.allowEmpty = $.parseJSON(self.attr('data-empty-show') || 'true');
            rawdata.callFun = self.attr('data-template-function');
        $.getJSON(rawdata.uri, rawdata.data, function( data ){
            if(jQuery.isEmptyObject(data)){
                if(!(rawdata.allowEmpty)) { 
                    self.parents('.section').remove();
                }
                return;
            }
            //
            self.find('.no-record-tip').remove();
            var fn = window[rawdata.callFun];
            if (typeof fn === "function"){
                fn.call(this, data, self);
            }
        });
    }).trigger('loadDataEvent');
    //点击加载
    $('[data-result="click.jsonp"]').on('click', 'button[data-toggle="dropdown"]', function(){
        var parent=$(this).parent();
        var rawdata = {};
            rawdata.uri = parent.attr('data-handler');
            rawdata.data = parseQueryJson(parent.attr('data-query'));
            rawdata.callFun = parent.attr('data-function');
            
        if(parent.attr('data-selector')){
            var currentId = "dynamic-box-"+randomAlphaNumeric(8);
            parent.find(parent.attr('data-selector')).attr('id', currentId);
            if($('#'+currentId).children().length > 0){
                return;
            }
            rawdata.data.box=currentId;
        }
        $.ajax({
            url: rawdata.uri,
            jsonpCallback: rawdata.callFun,
            dataType: 'jsonp',
            data: $.param(rawdata.data)
        });
    });
    // 批量回调
    $('[data-result="batch.jsonp"]').on('loadDataEvent', function(e){
        var self=$(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.callFun = self.attr('data-function');
            rawdata.queryParamKey = self.attr('data-param');
            rawdata.idSelector = self.attr('data-record');
            rawdata.data = parseQueryJson(self.attr('data-query'));
            
            rawdata.data[rawdata.queryParamKey] = $(rawdata.idSelector).map(function(){
                var reg = /\[(data-(.*?))\]/g;
                var dataAttrName = rawdata.idSelector.match(reg)[0].replace('[', '').replace(']', '');
                return this.getAttribute(dataAttrName);
            }).get().join(",");
        
        $.ajax({
                url: rawdata.uri,
                jsonpCallback: rawdata.callFun,
                dataType: 'jsonp',
                data: $.param(rawdata.data)
        });
    }).trigger('loadDataEvent');
    //轮播图
    $('[data-carousel="bootstrap"]').on('loadDataEvent', function(e){
        var self=$(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.data = parseQueryJson(self.attr('data-query'));
        $.getJSON(rawdata.uri, rawdata.data, function( data ){
            self.find('.ld-spin').remove();
            if(jQuery.isEmptyObject(data)){
                self.css('height','0');
                return;
            }
            
            drawCarousel(data, self);
        });
    }).trigger('loadDataEvent');
    //加载话题内的回复表单|登录表单
    $('.load_content_section').on('initDataEvent', function(){
        var self = $(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.callFun = self.attr('data-function');
            rawdata.data=parseQueryJson(self.attr('data-query'));
        
        if(!$.isEmptyObject(rawdata.data)){
            rawdata.uri += '?'+$.param(rawdata.data); 
        }
        self.addClass('ld-over running');
        self.load(rawdata.uri+' body', function(response, status, xhr){
            try{
                var err = $.parseJSON(response);
                if(err.level && err.level ==='err'){
                    return (window[self.attr('data-error-function')]).call(this, err);
                }
            }catch(e){}
            self.append(response);
            self.removeClass('ld-over running');
            try{
                var fn = window[rawdata.callFun];
                if (typeof fn === "function"){
                   fn.call(this, self, self);
                }
            }catch(e){}
        });
    }).trigger('initDataEvent');
    // 编辑器(initEvent. 设置高和宽, click. 开始实例编辑器)
    $('body').on('initEvent', '[data-richEditor="CKEditor"]', function(event){
        var self = $(this);
        var cusConfig=parseQueryJson(self.attr('data-query'));
        self.css({'width':cusConfig.width, 'height':cusConfig.height, 'background-color':'#f1f1f1', 'resize':'none', 'border':'none'}).attr('placeholder', '\n      内容在此输入');
    });
    $('body').on('focus', '[data-richEditor="CKEditor"]', function(){
        var cusConfig=parseQueryJson($(this).attr('data-query'));
        cusConfig.startupFocus = true;
        initCkEditor($.extend({}, cusConfig));
    });
    $('[data-richEditor="CKEditor"]').trigger('initEvent');
    //初始化ckeditor
    $('.richeditor').bind('initEditorEvent', function(e){
        var cusConfig=parseQueryJson($(this).attr('data-query'));
        cusConfig.startupFocus = false;
        initCkEditor($.extend({}, cusConfig));
    }).trigger('initEditorEvent');
    //话题内容页中滚动时显示的工具条
    $(document).scroll(function() {
        var scroH = $(document).scrollTop();  //滚动高度
        if(scroH < 300){
            $('#scroll-top-section').hide();
        }
        if(scroH > 300){
            $('#scroll-top-section').show();
        }
    });
    //分页加载数据
    $('.page_navigation').on('initDataEvent', function(){
        var self = $(this);
        var rawdata = {};
            rawdata.uri = self.attr('data-handler');
            rawdata.data = parseQueryJson(self.attr('data-query'));
            rawdata.callFun = self.attr('data-function');
            rawdata.defFun = self.attr('data-deferred') || null;
        if(!$.isEmptyObject(rawdata.data)){
            rawdata.uri += '?'+$.param(rawdata.data); 
        }
        //Deferred
        var def = $.Deferred();
        self.pagination({
            url: rawdata.uri, 
            ajaxBefore: function(){
                loading_control.start();
            },
            ajaxComplete: function(){
                loading_control.stop();
            },
            randerPageStruct: function(pageHtmlStruct, pnSelector){
                var extEle = $('#page_another_navigation');
                    extEle.find(pnSelector).remove();
                    extEle.append(pageHtmlStruct);
            },
            jsonCallback: function(jsonArray){
                if(jQuery.isEmptyObject(jsonArray)){
                    return;
                }
                var fn = window[rawdata.callFun];
                if (typeof fn === "function"){
                    fn.call(this, jsonArray);
                    def.resolve();
                }
            }
        });
        //
        $.when(def).done(function(){
            var fn = window[rawdata.defFun];
            if (typeof fn === "function"){
                window[rawdata.defFun].call(this);
            }
        }).fail(function(){
            console.log('[page_navigation] def fail');
        });
    }).trigger('initDataEvent');
    //图片的延迟加载
    try{
        $(".lazyload").lazyload();
    }catch(e){}
    //喜好有关的代码开始
    //回复点赞
    $('body').on('click', '.mood-section a.mood-action', function(e){
        var self=$(this); var parent=self.parents('.mood-section');
        var rawdata = {};
            rawdata.uri = '/posts/mood/like';
            rawdata.data = {id: parent.attr('data-mood')}; 
            rawdata.data.mood = self.attr('data-action');
            rawdata.callFun = 'updateMoodCounter'; 
        $.ajax({
            type: 'POST',
            url: rawdata.uri,
            data: rawdata.data,
            dataType: 'json'
        }).done(function (response) {
            if(response.level === 'acc'){
                try{
                    var fn = window[rawdata.callFun];
                    if (typeof fn === "function"){
                        fn.call(this, self, self);
                    }
                }catch(e){}
            }else{
                response.refresh = false;
                tipDialog(response);
            }
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //喜好有关的代码结束
    //文章内容中的标签
    $('body').on('mouseenter', '.tag-item-anchor', function(){
        $('<span class="tag-item-remove"><i class="mdi mdi-close"></i></span>').appendTo($(this));
    });
    $('body').on('mouseleave', '.tag-item-anchor', function(){
        $(this).find('.tag-item-remove').remove();
    });
    $('#tag-action-add').click(function(){
        var requestURI = $(this).attr('data-handler');
        $.confirm({
            title: '新标签',
            closeIcon: true,
            closeIconClass: 'ico-sm mdi mdi-close',
            content: '<form action=""><div class="form-group"><input class="form-control" name="names" required="required" placeholder="输入标签名称" /></div></form>',
            buttons: {
                formSubmit: {
                    text: '提交',
                    btnClass: 'btn-blue',
                    action: function () {
                        var names = this.$content.find('input[name=names]').val();
                        if(isBlank(names)){
                            this.$content.find('input[name=names]').focus();
                            return false;
                        }
                        var requestParam={};
                        requestParam.names=names;
                        
                        $.ajax({
                            url: requestURI,
                            dataType: 'json',
                            method: 'post',
                            data: requestParam
                        }).done(function (response) {
                        	 response.names = requestParam.names;
                            newTagHandler(response);
                        }).fail(function(){
                            errorMessage('当前操作因错误而异外中止');
                        });
                    }
                }
            },
            onContentReady: function () {
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click');
                });
            }
        });
        return false;
    });
    //会员中心的删除收藏的版块
    $('#member-favorite-board').on('click', '.fav-board-item', function(){
        $(this).toggleClass('fav-focus');
        //统计选中了几个
        var cl = $('#member-favorite-board').find('li.fav-focus').length;
        $('#fav-focus-counter').html(cl);
    });
    $('#remove-favorite-btn').click(function(e){
        e.preventDefault();var _self = $(this);
        var boardIdStr = $('#member-favorite-board').find('li.fav-focus').map(function(){
            return this.id.replace('fav-board-', '');
        }).get().join(",");
        if(boardIdStr.length == 0){
            errorMessage('请选择要删除的记录');
            return;
        }
        //
        var rawdata = {};
        rawdata.uri = _self.attr('data-handler');
        rawdata.data = {ids: boardIdStr};
        //
        $.ajax({
            url: rawdata.uri,
            dataType: 'json',
            method: 'post',
            data: rawdata.data
        }).done(function (response) {
            removeHomeBoardCallbackFun(response);
        }).fail(function(){
            errorMessage('当前操作因错误而异外中止');
        });
        return false;
    });
    //侧边栏的工具按钮
    $('#sideTool').sideToolBar();
    //加载今天的公告
    showTodayNotice();
});