var _comment_base_url_ = "http://happy.xiaoi.com";
var content_limit=430;
var reply_box_width=315;
var reply_box_height=100;
var comment_box_width=515;
var comment_box_height=110;
$=function(id) {
	return document.getElementById(id);
}

h=function(id) {
	$(id).style.display="none";
}
s=function(id) {
	$(id).style.display="";
}

String.prototype.Trim = function(){
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
}
String.prototype.LTrim = function(){
	return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function(){
	return this.replace(/(\s*$)/g, ""); 
}

var commentWidget;

function CommentWidget(pPid,pComponentId,pObjectCreaterPid,pObjectId,pObjectName,pObjectUrl) {
	
	this.UserAction=false;
	this.GroupAction=false;
	this.SystemMessage=false;

	this.userActionTemplate="";
	this.groupActionTemplate="";
	this.systemMessageTemplate="";

	this.userActionData="";
	this.groupActionData="";
	this.systemMessageData="";

	this.pid=pPid;
	this.componentId=pComponentId;

	this.objectCreaterPid=pObjectCreaterPid;
	this.objectId=pObjectId;
	this.objectName=pObjectName;
	this.objectUrl=pObjectUrl;

	this.listCommentPath=_comment_base_url_+"/comment/listComment.do";
	this.saveCommentPath=_comment_base_url_+"/comment/saveComment.do";
	this.replyCommentPath=_comment_base_url_+"/comment/saveComment.do";
	this.deleteCommentPath=_comment_base_url_+"/comment/deleteComment.do";
	this.deleteReplyPath=_comment_base_url_+"/comment/deleteComment.do";

	this.showCommentsID="comment";
	this.showCommentEditorID="commentEditor";
	commentWidget=this;
}

CommentWidget.prototype.setSystemMessageTemplate=function(template){
	this.systemMessageTemplate=template;
}

CommentWidget.prototype.setUserActionTemplate=function(template){
	this.userActionTemplate=template;
}

CommentWidget.prototype.setGroupActionTemplate=function(template){
	this.groupActionTemplate=template;
}

CommentWidget.prototype.setSystemMessageData=function(data){
	this.systemMessageData=data;
}

CommentWidget.prototype.setUserActionData=function(data){
	this.userActionData=data;
}

CommentWidget.prototype.setGroupActionData=function(data){
	this.groupActionData=data;
}


CommentWidget.prototype.showCommentList=function(){
	var url = this.listCommentPath+"?comment.componentId=" + this.componentId+"&comment.objectId="+this.objectId+"&comment.receiverpId="+this.objectCreaterPid+"&t="+Math.random();
	var script_ = document.createElement("script");
	script_.type = 'text/javascript';
	script_.src = url + "&callback=getCommentListResult_cl"
	window.getCommentListResult_cl = function (data) {
		commentWidget.commentListShow(data);
	}
	document.getElementsByTagName("HEAD")[0].appendChild(script_);
}

CommentWidget.prototype.commentListShow=function(data){
	if(data.length == 0){return;}
	var html = "";
	for (var i=0;i<data.length;i++)
	{
		try
		{
			html += this.getCommentHtml(data[i]);}
		catch(e){
			//console.debug(e.message)
		}
	}
	$("comment").innerHTML = html + $("comment").innerHTML;
	
}

CommentWidget.prototype.getCommentHtml=function(comment)
{
	if(comment.stealthy) {
		if(this.pid != comment.pid && this.pid != this.objectCreaterPid) {
			return "";
		}
	}
	
	var html =  '<div class="friendMov" style="width:510px" id="commentDiv_' + comment.uuid + '">'
	html += '<div class="userphotoInfoCom" style="float:left;" ><div class="pic48BoxbgCom"><div class="pic48BoxCom"><a href="http://happy.xiaoi.com/home.do?pid=' + comment.pid + '"><img src="'+ comment.authorPp +'" style="display: block;" width="48px" height="48px" /></a></div></div></div><div class="details" style="width:325px;">'

	if(comment.stealthy) {
		html += '<span style="color: red; font-size:12px;">【悄悄话】</span><br>'
	}
	html += '<a target="_top" href="http://happy.xiaoi.com/home.do?pid=' + comment.pid + '">';
	if(this.pid == comment.pid) {
		html += '我';
	} else {
		html += comment.author ;
	}
	html+='</a> 说：<br/>';
	html += '<p style="margin-bottom:10px;">'+comment.content + '</p>';
	if(((typeof comment.responseComments) != "undefined") && (comment.responseComments.length > 0)) {
		html += '<div id=replydiv_'+comment.uuid+'>';
		for (var i=0; i<comment.responseComments.length; i++)
		{
			html += this.getCommentReplyHtml(comment.responseComments[i]);
		}
		html += '</div>';
	} else {
		html += '<div id=replydiv_'+comment.uuid+' style="display:none;"></div>';
	}
	
	if(this.pid == comment.pid || this.pid == this.objectCreaterPid) {
		html += '<p><a href="javascript:commentWidget.replyComment(\'' + comment.uuid + '\','+comment.pid+');">回复</a> ┊ <a href="'+_comment_base_url_+'/shortmsg/toSendPage.do?pid='+comment.pid+'" target="_top">短消息</a> ┊ <a href="javascript:commentWidget.deleteComment(\'' + comment.uuid + '\')">删除</a>';
	} else {
		html += '<p><a href="javascript:commentWidget.replyComment(\'' + comment.uuid + '\','+comment.pid+');">回复</a> ┊ <a href="'+_comment_base_url_+'/shortmsg/toSendPage.do?pid='+comment.pid+'" target="_top">短消息</a>';
	}
	
	html += '<div id=replyEditor_'+comment.uuid+'></div></p></div><div class="time">'+ comment.sendTime +'</div><div style="clear:both"></div></div>';
	
	return html;
}

CommentWidget.prototype.getCommentReplyHtml=function(comment) {

	var html = '<div class="replyDiv" id="reply_' + comment.uuid + '">';
	html += '<p class="titbg">';
	
	if(this.pid == comment.pid) {
		html += '<span style="float:left;"><a href="http://happy.xiaoi.com/home.do">我</a> 的回复</span>';
	} else {
		html += '<span style="float:left;"><a href="http://happy.xiaoi.com/home.do?pid=' + comment.pid + '">' + comment.author + '</a> 的回复</span>';
	}
	
	if(this.pid == comment.pid || this.pid == this.objectCreaterPid) {
		html += '<span class="replyClose" style="float:right;"><a href="javascript:commentWidget.deleteReply(\''+comment.uuid+'\')"><img src="http://static1.xiaoi.net/images/blank.gif" width="16" height="16"/></a></span>';
	} else {
		html += '<span class="replyClose" style="float:right;"></span>';
	}
	html += '<span style="font-size:10px; float:right; margin-right:20px; color:#8f8f8f;">' + comment.sendTime + '</span>';
	
	html += '<div style="clear:both;"></div>'
	html += '</p>';
	html += '<div class="answer">' + comment.content + '</div>';
	html += '</div>';
	return html;
}

 String.prototype.replaceAll  = function(s1,s2){   
 	return this.replace(new RegExp(s1,"gm"),s2);   
 } 
 
CommentWidget.prototype.addReplySubmit=function(ruuid,pid) {
	if(typeof this.pid == "undefined" || this.pid == 0) {
		//alert("发表评论回复请先登陆！");
		var lul = "";
		if(typeof locurl_ != "undefined") {
			lul = locurl_;
		}
		window.location.href = _comment_base_url_ + "/login.do?aid=30001&appid=30001&redurl=" + lul;
		return ;
	}

	var content = this.getEditorContent("content_" + ruuid);
	content=processContent_(content);
	if (content.length == 0)
	{
		alert("请输入回复内容。");
		var eid="content_" + ruuid;
		this.setEditorEmpty(eid);
		this.setEditorFocus(eid);
		return;
	}
	
	if (dataLength(content) > 280) {
		alert('抱歉，输入内容不能超过140个汉字！');
		return;
	}
	
	$("replybtn_" + ruuid).disabled = true;
	
	var url = this.replyCommentPath+"?comment.componentId=" + this.componentId+
	"&comment.objectId="+this.objectId+"&comment.receiverpId="+this.objectCreaterPid+"&comment.content="+encodeURIComponent(content)+
	"&comment.objectName="+encodeURIComponent(this.objectName)+
	"&comment.objectUrl="+encodeURI(this.objectUrl)+"&comment.rootUuid="+ruuid+"&comment.createrPid="+pid+"&t="+Math.random();
	var script_ = document.createElement("script");
	script_.type = 'text/javascript';
	script_.src = url + "&callback=getReplySubmitResult_cl"
	window.getReplySubmitResult_cl = function (data) {
		commentWidget.replyShow(data);
	}
	document.getElementsByTagName("HEAD")[0].appendChild(script_);

}

CommentWidget.prototype.replyShow=function(data)
{
	var ruuid = data.comment.rootUuid;
	$("replybtn_" + ruuid).disabled = false;
	//if($("replyprompt_" + ruuid)) h("replyprompt_" + ruuid);

	var r = data.result;
	if(r == "0")
	{
		alert("回复失败");
		return;
	}
	
	var html = this.getCommentReplyHtml(data.comment);
	var ruuid = data.comment.rootUuid;
	var rcid = "replydiv_" + ruuid;
	$(rcid).innerHTML = $(rcid).innerHTML+html;
	s(rcid);
	this.setEditorEmpty("content_"+ruuid);
	h("replyEditor_" + ruuid)
	
	commentWidget.afterReplyAdded(data);
}

 function dataLength(fData) {
    var intLength = 0;
    for (var i=0;i<fData.length;i++) {
        if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
            intLength = intLength + 2;
        else
            intLength = intLength + 1;    
    }
   	return intLength;
 }
 
CommentWidget.prototype.addCommentSubmit=function(v_btn, v_prompt)
{
	if(typeof this.pid == "undefined" || this.pid == 0) {
		//alert("发表评论请先登陆！");
		var lul = "";
		if(typeof locurl_ != "undefined") {
			lul = locurl_;
		}
		window.location.href = _comment_base_url_ + "/login.do?aid=30001&appid=30001&redurl=" + lul;
		return ;
	}

	var content = this.getEditorContent("comment_content");
	content=processContent_(content);
	if (content.length == 0)
	{
		alert("请输入评论内容。");
		var eid="comment_content";
		this.setEditorEmpty(eid);
		this.setEditorFocus(eid);
		return;
	}
	
	if (dataLength(content) > 280) {
		alert('抱歉，输入内容不能超过140个汉字！');
		return;
	}

	if (v_btn) v_btn.disabled = true;
	if ($(v_prompt)) s(v_prompt);
	
	var hidden = false;
	
	if ($('comment_hidden')
		&& $('comment_hidden').checked)
	{
		hidden = true;
	}
	
	//content = content.replaceAll('#','');
	
	
	
	var url = this.saveCommentPath+"?comment.componentId=" + this.componentId+
	"&comment.objectId="+this.objectId+"&comment.receiverpId="+this.objectCreaterPid+"&comment.content="+encodeURIComponent(content)+
	"&comment.objectName="+encodeURIComponent(this.objectName)+
	"&comment.objectUrl="+encodeURI(this.objectUrl)+"&comment.stealthy="+hidden;
	var script_ = document.createElement("script");
	script_.type = 'text/javascript';
	script_.src = url + "&callback=getCommentSubmitResult_cl&t="+Math.random();
	window.getCommentSubmitResult_cl = function (data) {
		commentWidget.commentShow(data,v_btn,v_prompt);
	}
	document.getElementsByTagName("HEAD")[0].appendChild(script_);
}

CommentWidget.prototype.commentShow=function(data, v_btn, v_prompt)
{
	if (v_btn) v_btn.disabled = false;
	if ($(v_prompt)) h(v_prompt);

	var r = data.result;
	if(r == "0")
	{
		//recentcomment = "";
		alert("发表评论失败");
		return;
	}
	
	var html = this.getCommentHtml(data.comment);

	$("comment").innerHTML = html + $("comment").innerHTML;
	
	this.setEditorEmpty("comment_content");
	$('comment_hidden').checked = false;
	
	commentWidget.afterCommentAdded(data);
}

CommentWidget.prototype.deleteComment=function(commentId)
{
	if (confirm("你确认要删除这条留言和它的所有回复吗？"))
	{
		var url = this.deleteCommentPath+"?comment.receiverpId="+this.objectCreaterPid+"&comment.uuid="+commentId+"&t="+Math.random();
		var script_ = document.createElement("script");
		script_.type = 'text/javascript';
		script_.src = url + "&callback=getCommentDeleteResult_cl"
		window.getCommentDeleteResult_cl = function (data) {
			commentWidget.deleteCommentShow(data);
		}
		document.getElementsByTagName("HEAD")[0].appendChild(script_);
	
	}
}

CommentWidget.prototype.deleteCommentShow=function(data)
{
	var uuid = data.uuid;
	if(uuid=="0") {
		return;
	}
	h('commentDiv_'+data.uuid);
	
	commentWidget.afterCommentDeleted(data);
}


CommentWidget.prototype.deleteReply=function (commentId)
{
	if (confirm("你确认要删除这条回复吗？"))
	{
		var url = this.deleteReplyPath+"?comment.receiverpId="+this.objectCreaterPid+"&comment.uuid="+commentId+"&t="+Math.random();
		var script_ = document.createElement("script");
		script_.type = 'text/javascript';
		script_.src = url + "&callback=getReplyDeleteResult_cl"
		window.getReplyDeleteResult_cl = function (data) {
			commentWidget.deleteReplyShow(data);
		}
		document.getElementsByTagName("HEAD")[0].appendChild(script_);
	}
}

CommentWidget.prototype.deleteReplyShow=function(data){
	var uuid = data.uuid;
	if(uuid=="0") {
		return;
	}
	h('reply_'+data.uuid);
	
	commentWidget.afterReplyDeleted(data);
}

CommentWidget.prototype.replyComment=function(commentId,pid) {
	//if($("replyEditor_" + commentId).style.display=="none") {
		var html = '<div>' ;
		html += '<div id="editor_'+commentId+'"></div>'
		html += '<div style="text-align:left;padding:5px 50px 0 0;">';
		html += '<input type="button" class="btnBig" style="margin-left:10px;" id="replybtn_' + commentId + '" value="回复" onclick="commentWidget.addReplySubmit(\''+ commentId +'\','+pid+')" />'
		html += '<input type="button" class="btnBig" style="margin-left:10px;" value="取消" onclick="commentWidget.cancleReplyComment(\''+ commentId +'\');" />'
		//html+='<span id="content_'+commentId+'_count" style="margin-left:65px; font-size:12px;">0</span><span id="content_'+commentId+'_total" style=" font-size:12px;">/400字</span>';
		html += '</div>';
		html += '</div>';
		$("replyEditor_" + commentId).innerHTML = html;
		s("replyEditor_" + commentId);
		this.newEditor("content_" + commentId,"editor_" + commentId,reply_box_width,reply_box_height);
		commentWidget.afterShowReplyBox();
	//}
}

CommentWidget.prototype.cancleReplyComment=function(ruuid) {
	this.setEditorEmpty("content_"+ruuid);
	h("replyEditor_" + ruuid);
	commentWidget.afterHideReplyBox();
}

CommentWidget.prototype.emptyComment=function(){
	$("comment").innerHTML="";
}

CommentWidget.prototype.drawCommentDiv=function() {

	var html='<div><div id="editorDiv"></div>';
	html+='<div style="text-align:left; padding:5px; width:520px; border-bottom:1px solid #ddd;">';
	html+='<input type="button" class="btnBig" value="发表评论" onclick="commentWidget.addCommentSubmit(this, \'addcommentprompt\');" />';
	html+='<input id="comment_hidden" name="comment_hidden" type="checkbox" style="border:none;margin-left:20px;  vertical-align:middle;" /><span style="font-size:12px;">悄悄话</span>';
	//html+='<span id="comment_content_count" style="margin-left:230px;font-size:12px;">0</span><span id="comment_content_total" style="font-size:12px;">/400字</span>';
	html+='<div id="addcommentprompt" style="display:none;" class="c6 p010 mt15">提交中...</div></div></div><div id="comment" class="c_wrap" style="margin: 0pt; width: 500px;"></div>';
	
	$("commentDiv").innerHTML=html;
	this.newEditor("comment_content","editorDiv",comment_box_width,comment_box_height);
}

CommentWidget.prototype.newEditor=function(id,editorAreaId,width,height){
	eval(id+'=new webEditor("'+id+'" , $("'+editorAreaId+'") , '+width+', '+height+', "");');
	eval(id + ".init('');");
}

CommentWidget.prototype.getEditorContent=function(id){
	var content = eval(id+".getHtml();");
	return content;
}

CommentWidget.prototype.setEditorFocus=function(id){
	eval(id+".getFocus();");
}

CommentWidget.prototype.setEditorEmpty=function(id){
	eval(id+".setContent('');")
}


CommentWidget.prototype.afterReplyDeleted=function(data) {}

CommentWidget.prototype.afterCommentDeleted=function(data) {}

CommentWidget.prototype.afterReplyAdded=function(data) {}

CommentWidget.prototype.afterShowReplyBox=function() {}

CommentWidget.prototype.afterHideReplyBox=function() {}

CommentWidget.prototype.afterCommentAdded=function(data) {}

function processContent_(content) {
	content = replaceImg_(content);
	content = replaceP_(content);
	content = replaceBr_(content);
	content = replaceAllHtml_(content,"");
	content = replaceImgBack_(content);
	content = replaceBrBack_(content);
	if(content.length > content_limit) {
		content = content.substring(0,content_limit);
		content=checkContent_(content);
	}
	content = replaceRN_(content.Trim());
	content=structImg_(content);
	return content;
}

function replaceRN_(content) {
	var rr=new RegExp('\r',"g");
	var nr=new RegExp('\n',"g");
	content = content.replace(rr,"");
	content = content.replace(nr,"");
	return content;
}

function checkContent_(content) {
	var xr=new RegExp('<[^>]*$');
	var r=content.match(xr);
	if(r){
		var idd = content.lastIndexOf(r[0]);
		return content.substring(0,idd);
	} 
	return content;
}

function replaceAllHtml_(content,repl) {
	var re0 = new RegExp('<[^>]+>',"g");
	var re1 = new RegExp('<[^>]+',"g");
	var re2 = new RegExp('&nbsp;',"g");
	var tem = content.replace(re0,repl);
	tem = tem.replace(re1,repl);
	tem = tem.replace(re2,repl);
	return tem;
}

function replaceImg_(content) {
//	var imgre=new RegExp('<[^>]*src="[^>]*face/([0-9]{1,2})\.gif"[^>]*disabled[^>]*>',"g");
	var imgre=new RegExp('<[^>]*src="[^>]*face/([0-9]{1,2})\.gif"[^>]*>',"g");
	content=content.replace(imgre,'【img:$1】');
	return content;
}

function replaceImgBack_(content) {
	var imgre = new RegExp('【img:([0-9]{1,2})】',"g")
	return content.replace(imgre,'<img:$1                                                       >');
}

function structImg_(content) {
	var imgre = new RegExp('<img:([0-9]{1,2})                                                       >',"g")
	content=content.replace(imgre,'<img src="http://static1.xiaoi.net/images/face/$1.gif" border=0>');
	return content;
}

function replaceP_(content) {
	var pre0 = new RegExp('<[\\s]*?p[^>]*?>([\\s\\S]*?)<[\\s]*?\\/[\\s]*?p[\\s]*?>',"g")
	var pre1 = new RegExp('<[\\s]*?P[^>]*?>([\\s\\S]*?)<[\\s]*?\\/[\\s]*?P[\\s]*?>',"g")
	content=content.replace(pre0,'$1【br】')
	content=content.replace(pre1,'$1【br】')
	return content;
}

function replaceBr_(content) {
	var brre0 = new RegExp('<br[^>]*>',"g")
	var brre1 = new RegExp('<BR[^>]*>',"g")
	content=content.replace(brre0,'【br】')
	content=content.replace(brre1,'【br】')
	
	return content;
}

function replaceBrBack_(content) {
	var bre = new RegExp('【br】',"g")
	var tem = content;
	tem = tem.replace(bre,"");
	if(tem.Trim()=="") {
		return "";
	}
	
	return content.replace(bre,'<br/>');
}
