﻿// JavaScript 文件格式utf-8
document.write('<div id="comment" class="Comment"></div>');

// 创建jQuery对象
var CommentList = $('.Comment');
// 操作容器对象
var Comment = new Object();
// 获取Comment参数的方法
Comment.GetQueryValue = function(paramName) {  
    var s=document.getElementById("comment").src;  //comment为script文件id
    var reg = new RegExp("[?&]"+ paramName+"=([^&]*)(\s|&|$|&amp;)", "i");
    if (reg.test(s)) return RegExp.$1; else return ""; 
}
// 一些常量
Comment.pageSize = Comment.GetQueryValue('pagesize');
Comment.entityId = Comment.GetQueryValue('id');
Comment.entityType = Comment.GetQueryValue('type');
Comment.forbidComment = Comment.GetQueryValue('fc')==1;

// 字符表情数组
Comment.faces = new Array();
Comment.faces = [
    ["^_^","嘿嘿"],["\:-P","调皮"],["@_@","目瞪口呆"],["T_T","委屈掉泪"],["（＞﹏＜）","痛苦"],["-_-!","汗！"],["=_=\"","皱眉"],
    ["\\(^o^)/","可爱"],["-W-",""],["Orz","拜倒"],["囧rz","囧"]
]

// 生成导航条
Comment.buildNavBar = function(pageIndex,recordCount) {
    var totalPage = Math.ceil(recordCount / this.pageSize);
    var first = '<a href="javascript:void(0)" onclick="Comment.getCommentList(1,'+recordCount+')" style="margin-right: 5px;">首页</a><a href="javascript:void(0)" onclick="Comment.getCommentList('+(pageIndex-1)+','+recordCount+')" style="margin-right: 5px;">上一页</a>';
    var last = '<a href="javascript:void(0)" onclick="Comment.getCommentList('+(pageIndex+1)+','+recordCount+')" style="margin-right: 5px;">下一页</a><a href="javascript:void(0)" onclick="Comment.getCommentList('+totalPage+','+recordCount+')" style="margin-right: 5px;">末页</a>';
    var disFirst = '<span disabled="true" style="margin-right: 5px;">首页</span><span disabled="true" style="margin-right: 5px;">上一页</span><span style="margin-right: 5px; font-weight: bold; color: red;">1</span>';
    var disLast = '<span disabled="true" style="margin-right: 5px;">下一页</span><span disabled="true" style="margin-right: 5px;">末页</span>';
    var items = $('<div id="CommentNav" style="text-align:center; padding:5px 0;"></div>');
    if(pageIndex>totalPage) pageIndex = totalPage;
    if(totalPage==1) {
        items.append(disFirst);
        items.append(disLast);
    } else {
        var i=1;
        if(pageIndex == 1) {
            items.append(disFirst);
            for(i=2;i<=totalPage;i++) {
                items.append('<a href="javascript:void(0)" onclick="Comment.getCommentList('+i+','+recordCount+')" style="margin-right: 5px;">'+i+'</a>');
            }
            items.append(last);
        } else if(totalPage == pageIndex) {
            items.append(first);
            for(i=1;i<totalPage;i++) {
                items.append('<a href="javascript:void(0)" onclick="Comment.getCommentList('+i+','+recordCount+')" style="margin-right: 5px;">'+i+'</a>');
            }
            items.append('<span style="margin-right: 5px; font-weight: bold; color: red;">'+totalPage+'</span>');
            items.append(disLast);
        } else {
            items.append(first);
            for(i=1;i<=totalPage;i++) {
                if(pageIndex != i) {
                    items.append('<a href="javascript:void(0)" onclick="Comment.getCommentList('+i+','+recordCount+')" style="margin-right: 5px;">'+i+'</a>');
                } else {
                    items.append('<span style="margin-right: 5px; font-weight: bold; color: red;">'+i+'</span>');
                }
            }
            items.append(last);
        }
    }
    CommentList.append(items);
    CommentList.prepend('<span style="font-weight: bold;">已有'+recordCount+'条评论：</span>');
}

// 评论列表
Comment.buildCommentList = function(pageIndex,xml) {
    var items = $('<div id="commentlist"></div>');
    var i=0;
    $(xml).find('Comment').each(function(i) {
        var del = ' ';
        if($(this).children("EnableDel").text()=='True') {
            del += '<a href="javascript:void(0)" class="gray" onclick="Comment.del(\'' + $(this).children("ID").text() + '\')">删除</a> ';
        }
        var item = $('<div style="margin-top:12px;" id="c-'+$(this).children("ID").text()+'"></div>');
        item.append($('<div class="Avatar"></div>')
                .html('<a class="green" href="/user/'+$(this).children("UserName").text()+'/"><img alt="'+$(this).children("UserNickName").text()+'" src="'+$(this).children("UserIco").text()+'" /></a>'))
            .append($('<div style="float:none;width:auto;"></div>')
                .append('<div><span class="green">' + $(this).children("CreateTime").text() + '</span>　<a class="blue" href="/user/'+$(this).children("UserName").text()+'/">'+$(this).children("UserNickName").text()+'</a></div>')
                .append('<div class="Content" id="cont-'+$(this).children("ID").text()+'">'+$(this).children("Content").text()+'</div>')
                .append($('<div class="gray" style="text-align:right; border-bottom: dotted 1px #DEDEDE;"></div>')
                    //.append('IP：'+$(this).children("UserIp").text()+'　｜　')
                    .append('<a href="#comment" onclick="Comment.setReply('+ $(this).children("ID").text() +',\''+$(this).children("UserName").text()+ '\',\'' +$(this).children("UserNickName").text()+'\');">回复</a>')
                    .append(del)
                    .append(((pageIndex-1)*Comment.pageSize+i+1)+'楼 <a href="#"><img src="http://pic1.kyzhi.com/totop.gif" /></a>')));
        items.append(item);
    });
    CommentList.append(items);
}

// 评论表单
Comment.buildForm = function(isLoggedIn) {
    var form = $('<div class="NewComment"></div>');   
    
    var faces = '';
    for(var i=0;i<Comment.faces.length;i++) {
        faces+='<a class="face" href="###" onclick="document.getElementById(\'txtCommentContent\').value+=\' \'+this.innerHTML.replace(/<.+?>/gim,\'\')">'+Comment.faces[i][0]+'</a> ';
    }
    
    if(this.forbidComment) {
        form.append('<span class="green">未开放评论功能 ...</span>');
    } else if(isLoggedIn=='False') {
        form.append('<span class="green">想参加讨论，请先 [<a href="/login?ReturnUrl=' + window.location.pathname + '">登录</a>] 或 [<a href="/register">注册</a>] ...</span>');
    } else {
        form.append('<div id="comments" style="font-weight:bold;padding:5px 2px;">我的回应 ...</div>')
            .append('<div style="margin-top:10px;"><textarea rows="7" onkeydown="Comment.ctlent(event)" id="txtCommentContent" style="width:486px;"></textarea></div>')
            .append('<div>'+faces+'</div>')
            .append('<div>')
            .append('<input type="hidden" id="txtUserName"/>')
            .append('<input type="hidden" id="txtOriginalCont"/>')
            .append('<p><input type="button" value="写好了，回复" onclick="Comment.insert()" class="submit" /> <span class="gray">[Ctrl+Enter键快速提交]</span></p>')
            .append('</div>');
    }
    CommentList.append(form);
}

// 以AJAX方式获取Comment数据
Comment.getCommentList = function(pageIndex,recordCount) {
    if(arguments.length==2) {
        if(recordCount==0) {
            CommentList.append('<div class="ajaxloader" style="position: static; width: 140px; text-align:center;"><span>正在加载评论，请稍候...</span></div>');
        } else {
            $('#CommentNav').html('<div class="ajaxloader" style="position: static; width: 140px; text-align:center;"><span>正在加载评论，请稍候...</span></div>'); 
        } 
        var timer = setTimeout('Comment.getCommentList('+pageIndex+','+recordCount+',"flag")',500);
    } else {
        if(pageIndex<1) pageIndex = 1;
        var startRecordIndex = this.pageSize * (pageIndex-1)+1;
        var params = '?ID='+this.entityId;
        params += '&Type='+this.entityType;
        params += '&PageSize='+this.pageSize;
        params += '&StartRecordIndex='+startRecordIndex;
        params += '&RecordCount='+recordCount;
        $.post('/ajax/comment/getlist'+params, function(xml) {
            CommentList.html('');
            var count = $('RecordCount',xml).text();
            if(count==0) {
                CommentList.append('<span class="green">暂无评论数据 ...</span>');
            } else {
                Comment.buildCommentList(pageIndex,xml);
                Comment.buildNavBar(pageIndex, count);
            }
            Comment.buildForm($('IsLoggedIn',xml).text());
        });
    }
}

// 添加评论
Comment.insert = function() {
    var content = $.trim($('#txtCommentContent').val());
    if(content.length<2) {
        alert('至少写两个字吧'); return;
    } else if(content.length>1000) {
        alert('内容这么长? 限1000个字符'); return;
    }
    $.post('/ajax/comment/insert',{
        ID:Comment.entityId,
        Type:Comment.entityType,
        Content:content,
        EntityTitle:e_title,
        PathName:window.location.pathname,
        ReUserName:$('#txtUserName').val(),
        ReContent:$('#txtOriginalCont').val()
    }, function(xml) {
        var nc = $(xml).find('Comment');
        var html = '<div><span class="orange">添加成功！你的回复是：</span><br/>';
        html += '<div style="margin-top: 12px;" id="c-'+nc.children("ID").text()+'">';
        html += '<div class="Avatar"><a class="green" href="/user/'+nc.children("UserName").text()+'/"><img alt="'+nc.children("UserNickName").text()+'" src="'+nc.children("UserIco").text()+'"></a></div>';
        html += '<div style="float: none; width: auto;">';
        html += '<div class="Content">'+nc.children("Content").text()+'</div>';
        html += '<div class="gray" style="text-align:right;"><a href="javascript:void(0)" class="gray" onclick="Comment.del(\''+nc.children("ID").text()+'\')">删除</a> <a href="#"><img src="http://pic1.kyzhi.com/totop.gif"></a></div>';
        html += '</div>';
        $('.NewComment').before(html);
        $('#txtCommentContent').val('');
    });
}

// 回复
Comment.setReply = function(cid,username,nickname) {
	$('#txtCommentContent').val('回复 '+nickname+' ：');
	$('#txtUserName').val(username);
	$('#txtOriginalCont').val($('#cont-'+cid).html());
}

// 删除评论
Comment.del = function(cid) {
    if(!confirm('确定删除该条评论？')) return;
    $.post('/ajax/comment/delete',{ EntityId:Comment.entityId, CommentId:cid, EntityType:Comment.entityType }, function(result) {
        if(result=='True') { $('#c-'+cid).remove(); } else { alert(result); }
    });
}
// Ctrl+Enter 提交
Comment.ctlent = function(eventobject) {
	if(eventobject.ctrlKey && eventobject.keyCode==13){
		Comment.insert();
	}
}
Comment.getCommentList(1,0);