// JavaScript Document
$(document).ready(function(){
	 if ($("#postBlogButton") != null) {
		$("#postBlogButton").bind("click",BlogComment.addNewComment);
	}
});
/**
* 刪除評論
*/
function delComment()
{
	msgBox.showTrueOrFalse2("刪除評論","你確認要刪除該評論，如有回覆也會被一起刪除的！","submitDel()");
}
function submitDel() {
	$.ajax({
	type: "POST",
	dataType: 'html',
	url: "./ajax.php",
	data: "module=ajaxService&action=delComment&blogId=" + $_('blogIdVal').value + "&commentId=" + $_("currentCommentId").value,
	success: function(html){
		if (html.indexOf("fail") != -1) {
			msgBox.showText("操作錯誤");
		} else {
			removeLine();
			$_('commentCount').innerHTML = parseInt($_('commentCount').innerHTML) - parseInt(html);
		}
	},
	error:function(html){
		msgBox.showText("對不起,刪除評論失敗,請稍後試");
	}
	});
	
	msgBox.removeMsgBox();
	return true;
}
/**
* 移除一行數據
*/
function removeLine()
{
	$("#liId" + $_('currentCommentId').value).remove();
}
/**
* 添加評論
*/
function addComment()
{
    msgBox.loadingShow();
	if ( $_('bodyVal').value == '' ) {
		msgBox.showText("評論內容不能為空");
		return false;
	}
	
	//getNewComment(57);return;
	
	$_('commentType').value = '';
	$.ajax({
	type: "POST",
	dataType: 'html',
	url: "./ajax.php",
	data: "module=ajaxService&action=addComment&blogId=" + $_('blogIdVal').value + "&content=" + foramt26str($_('bodyVal').value),
	success: function(html){
	    if (html.indexOf("fail") != -1) {
			msgBox.showText("操作錯誤");
		} else {
			getNewComment();
			$_('commentCount').innerHTML = parseInt($_('commentCount').innerHTML) + 1;
			$_('bodyVal').value = '';
			$_('bodySpan').innerHTML = '0';
			msgBox.showText("評論添加成功");
		}
		  if(parseInt(html)==9999){//黑名單錯誤碼
			   msgBox.showText("對方已設置了隱私權限，無法發表評論");
			   return false
		  }
	},
	error:function(html){
		msgBox.showText("對不起,添加評論失敗,請稍後試");
	}
	});
}
/* 發表回覆評論 */
function addReComment()
{
    msgBox.loadingShow();
	if ( $_("reContent").value == '' ) {
		msgBox.showText("對不起,評論內容不能為空");
		return false;
	}
	
	$.ajax({
	type: "POST",
	dataType: 'html',
	url: "./ajax.php",
	data: "module=ajaxService&action=addComment&blogId=" + $_('blogIdVal').value + "&parentId=" + $_('commentParentId').value + "&QtCommentId=" + $_("currentCommentId").value + "&commentType=" + $_('commentType').value + "&content=" + foramt26str($_('reContent').value),
	success: function(html){
	    if (html.indexOf("fail") != -1) {
			msgBox.showText("操作錯誤");
		} else {
			getNewComment();
			$("#msgDialog").remove(); // 隱藏回覆評論框
			$_('commentCount').innerHTML = parseInt($_('commentCount').innerHTML) + 1;
			msgBox.showText("評論添加成功");
		}
	},
	error:function(html){
		msgBox.showText("對不起,添加評論失敗,請稍後試");
	}
	});
}
/**
* 獲取最新的一條評論數據
*/
function getNewComment()
{
	$.getJSON("ajax.php?module=ajaxService&action=getNewComment&blogId=" + $_('blogIdVal').value + "&commentType=" + $_("commentType").value,
                  function(data){
					  if (data != null) {
						   $.each(data, function(i,item){
								if ($_("commentType").value == '') {
									var html = createMessageDivO(item['id'],$_('baseUrl').value,$_('loginMemberId').value,item['min_avatar'],item['name'],item['comment_date'],item['comment']);
									$("#CommentList").append(html);
								} else if ($_("commentType").value == '1' || $_("commentType").value == '2') {
									var html = createMessageDivT(item['id'],$_('commentParentId').value,$_('baseUrl').value,$_('loginMemberId').value,item['name'],item['post_time'],item['content']);
									if ( $_('CommentRe' + $_('commentParentId').value) ) {
										$("#CommentRe" +  $_('commentParentId').value).append(html);
									} else {
										html = "<div class='CommentRe' id='CommentRe" + $_('commentParentId').value + "'>" + html + "</div>";
										$("#lDiv" + $_('commentParentId').value).after(html);
									}
								}
							});
					  }
				  });
}
/**
* 創建二級評論的DIV
*/
function createMessageDivT(commentId,parentId,baseUrl,memberId,memberName,postTime,content)
{
	var html = "<div class='CommentTwo' id='liId" + commentId + "'><div class='infoConentTwo'><div class='Info'> <span class='Author'><a href='http://i." + baseUrl + "/?module=hi&visitId=" + memberId + "' class='BlueLink Bold'>" + memberName + "</a>&nbsp;&nbsp;&nbsp;<span class='DeepGray'>評論于：" + postTime + "</span> </span><div class='CommentOption'><div class='Reply'> <a class='BlueLink' href='javascript:showDilogReM(" + commentId + "," + parentId + ");'>回覆</a></div><div class='CommentOptionMenu' id='cOptionMenuDiv" + commentId + "'><a href='javascript:' onmouseover=\"showCommentOptionMenu('cOptionMenuDiv" + commentId + "','" + commentId + "','" + parentId + "');\" onmouseout='hidCommentOptionMenu();'> </a></div></div></div><div class='Content' id='contentId{$val2[id]}'>" + content + "</div><div id='lDiv" + commentId + "'></div></div></div>";
	return html;
}
/**
* 創建一級評論的DIV
*/
function createMessageDivO(commentId,baseUrl,memberId,midAvatar,memberName,postTime,content)
{
	var html = "<li class='Comment' id='liId" + commentId + "'> <div class='Photo'> <a href='http://i." + baseUrl + "/?module=hi&visitId=" + memberId + "'><img src='" + midAvatar + "'/></a> </div><div class='infoConent'><div class='Info'> <span class='Author'><a href='http://i." + baseUrl + "/?module=hi&visitId=" + memberId + "' class='BlueLink Bold'>" + memberName + "</a>&nbsp;&nbsp;&nbsp;<span class='DeepGray'>發表于：" + postTime + "</span> </span><div class='CommentOption'><div class='Reply'><a class='BlueLink' href='javascript:showDilogReM(" + commentId + "," + commentId + ");'>回覆</a></div><div class='CommentOptionMenu' id='cOptionMenuDiv" + commentId + "'>";
	
	var Request = new Object();
	Request = GetRequest();
	if ( Request['friendId'] == memberId || Request['action'] == 'readMyBlog' ) {
		html += "<a href='javascript:' onmouseover=\"showCommentOptionMenu('cOptionMenuDiv" + commentId + "','" + commentId + "','" + commentId + "');\" onmouseout='hidCommentOptionMenu();'> </a>";
	}
	
	html += "</div></div> </div><div class='Content NoLine' id='contentId" + commentId + "'>" + content + "</div><div id='lDiv" + commentId + "'></div></div></li>";
	return html;
}
function GetRequest() {
   var url = location.search; //获取url中"?"符后的字串
   var theRequest = new Object();
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
      }
   }
   return theRequest;
}

/***
* 顯示回覆評論彈出框彈出框 
* @param Int commentId 評論的編號
* @param String member_id 要回覆的留言的會員編號
* @param Int parentId 父級評論的編號
*/
function showDilogReM(commentId,parentId)
{
	hidDilogReM(); // 隱藏回覆框
	$_('commentParentId').value = parentId;
	$_('currentCommentId').value = commentId;
	$_('commentType').value = '1';
	var ihtml = _createDiv("lDiv" + commentId);
	$("#lDiv" + commentId).append(ihtml);
}
/***
* 創建留言框 
* @param String id  留言框所在div的div id
*/
function _createDiv(id)
{
	var ihtml = "<div id='msgDialog'><div>回覆評論</div> <div><textarea id='reContent' name='reContent' cols='80' rows='5'></textarea></div><div class='GbButtom'><input class='CptButtom' id='addReCommentBotton' type='button' onclick=\"addReComment();\" value='發表'>&nbsp;&nbsp;<input class='CptButtomGray' type='button' onclick=\"hidDilogReM('" + id + "');\" value='取消'></div></div>";
	return ihtml;
}
/**
* 隱藏評論回覆框
* @param String id 留言框所在div的div id
*/
function hidDilogReM(id)
{
	$_('commentParentId').value = '';
	$_('currentCommentId').value = '';
	$_('commentType').value = '';
	$("#msgDialog").remove();
}
/**
* 顯示回覆留言的下拉菜單
* @param String COmenuid 鼠標指著的物件id（用它來決定下拉菜單的位置)
* @param String currentCommentId 當前的評論的ID
* @param String parentId 父級評論的id
* @param String parent_id 回覆留言的用戶id
* @param String message_id 留言的id（用它來獲取該留言所在層的id）
*/
function showCommentOptionMenu(COmenuid,currentCommentId,parentId)
{
	if ( !$_('friendIdVal') ) {
		if ( currentCommentId == parentId ) { // 一級評論沒引用
			$("#funQtDiv").css("display","none");	
		} else {
			$("#funQtDiv").css("display","block");
		}
	} else {
		if ( currentCommentId == parentId ) {
			return false;
		} else {
			$("#funDelDiv").css("display","none");
		}
	}
	
	var objOffset = $("#" + COmenuid).offset();
	var t = objOffset.top;
	var l = objOffset.left;
	if ( window.location.href.indexOf('readFriendBlog') != -1 ) {
		t = t + 15;
		l = l - 45;
	} else {
		if(isFirefox=navigator.userAgent.indexOf("Firefox")>0) {
			if(l > 756) {
				l = l - (l - 756);
			} else if (l < 756) {
				l = l + (756 - l);
			}
			t = t - 104;
			l = l - 240;
		} else if(navigator.userAgent.indexOf("IE")>0) {
			if(l > 752) {
				l = l - (l - 752);
			} else if (l < 752) {
				l = l + (752 - l);
			}
			if ( navigator.appVersion.indexOf('MSIE 6.0') != -1 ) {
				t = t - 101;
			} else {
				t = t - 103;
			}
			
			l = l - 237;
		}
	}
	
	$("#cOptionMenu").css("left",l + "px");
	$("#cOptionMenu").css("top",t + "px");
	$("#cOptionMenu").css("display","block");
	
	$_("commentType").value = "2";
	$_("CommentOptionDivId").value = COmenuid; 
	$_("currentCommentId").value = currentCommentId;
	$_("commentParentId").value = parentId;
}
/**
* 鼠標移到下拉菜單上所調用的函數,目的是為了讓下拉菜單不隱藏
*/
function showCommentOptionMenu_2()
{
	var COmenuid = $_("CommentOptionDivId").value;
	var currentCommentId = $_("currentCommentId").value;
	var parentId = $_("commentParentId").value;
	showCommentOptionMenu(COmenuid,currentCommentId,parentId);
}
/**
* 隱藏回覆留言的下拉菜單
*/
function hidCommentOptionMenu()
{
	$("#cOptionMenu").css("display","none");
}
/**
* 顯示引用的留言框（一級留言上所顯示出來的下拉菜單的引用按鈕可以工作，二級留言上所顯示出來的下拉菜單的引用按鈕不工作）
*/
function showDlgQtOpMenu()
{
	$("#msgDialog").remove();
	
	var ihtml = _createDiv("lDiv" + $_("currentCommentId").value);
	$("#lDiv" + $_("currentCommentId").value).append(ihtml);
	
}
//获取控件的位置
function GetObjPos(ATarget)
{
    var target = ATarget;
    var pos = new CPos(target.offsetLeft, target.offsetTop);
    
    var target = target.offsetParent;
    while (target)
    {
        pos.x += target.offsetLeft;
        pos.y += target.offsetTop;
        
        target = target.offsetParent
    }
    
    return pos;
} 
function CPos(x, y)
{
    this.x = x;
    this.y = y;
}


/******************** 最新版 ************************/
var BlogComment = ({
	mouseOutColor: "#FFFFFF",
	/**
	* 打開或關閉回覆框
	* @param String comRepDigId
	**/			   
	opentOrClose: function(comRepDigId)
	{
		if ( $("#" + comRepDigId).css('display') == 'none' ) {
			$("#" + comRepDigId).show();
		} else {
			$("#" + comRepDigId).hide();
		}
	},
	/**
	* 刪除評論
	* @param Int commentId
	**/
	delComment: function(commentId) {
		msgBox.showTrueOrFalse2('刪除評論','你確認要刪除該評論嗎，如有回覆也會被一起刪除','BlogComment.submitDelComment(\'' + commentId + '\')');
	},
	submitDelComment: function(commentId) {
		
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=delComment&commentId=" + commentId + "&callback=?",
			function(data) {
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(data) ) {
					return false;
				}
				if (data != null ) {
					if(parseInt(data[0]) == -1) {
						msgBox.showText("操作錯誤");
						return false;
					}
					
					// 評論數減一
					switch($("#appIdVal").val()) {
						case '18':
							StatusComment.modCommentCount();
							break;
						case '17':
							//$_('commentCount').innerHTML = parseInt($_('commentCount').innerHTML) - 1;
							break;
						case '4':
							TestComment.modCommentCount();
							break;
						case '40':
							var a = $("#commentNums"+_DelId).text();
							$("#commentNums"+_DelId).text(parseInt(a)-1);
							break;
					}
					
					msgBox.showText("評論刪除成功");
					
					//移除一行評論
					$('#commentLine' + commentId).remove();
				}
			});
	},
	/**
	* 添加新的評論
	**/
	addNewComment: function()
	{
		var content = foramt26str($("#bodyVal").val());
		if ( content.Trim() == '' ) {
			msgBox.showText("評論內容不能為空");
			return false;
		}
		var friendId = '';
		if ( $_("friendIdVal") ) {
			friendId = $("#friendIdVal").val();
		}
		
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=addNewComment&appId=" + $("#appIdVal").val() + "&resourceId=" + $_('resourceIdVal').value + "&friendId=" + friendId + "&content=" + content + "&callback=?",
			function(data) {
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(data) ) {
					return false;
				}
				if (data != null ) {
					if(parseInt(data[0]) == -1) {
						msgBox.showText("操作錯誤");
						return false;
					}
					msgBox.showText("評論成功");
					
					//在日誌評論里才有的(評論數加一)
					if ( $("#appIdVal").val() == '17' ) {
						//$_('commentCount').innerHTML = parseInt($_('commentCount').innerHTML) + 1;
					}
					if(parseInt(data[0])==9999){//黑名單錯誤碼
						 msgBox.showText("對方已設置了隱私權限，無法發表評論");
						 return false;
					}
					BlogComment.getNewComment();
				
					//清空內容
					$("#bodyVal").val('');
				}
			});
	},
	/**
	* 回覆評論
	* @param Int commentId 一級評論的ID回覆
	* @param Int oCommentMemberId 一級評論的主人
	**/
	addReplyComment: function(commentId,oCommentMemberId) {
		var content = foramt26str($("#content" + commentId).val());
		if ( content.Trim() == '' ) {
			msgBox.showText("回覆內容不能為空");
			return false;
		}
		
		var friendId = '';
		if ( $_("friendIdVal") ) {
			friendId = $("#friendIdVal").val();
		}
		
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=addReplyComment&appId=" + $("#appIdVal").val() + "&replyIdVal=" + $("#replyIdVal").val() + "&commentId=" + commentId + "&friendId=" + friendId + "&oCommentMemberId=" + oCommentMemberId + "&content=" + content + "&callback=?",
			function(data) {
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(data) ) {
					return false;
				}
				if (data != null ) {
					if(parseInt(data[0]) == -1) {
						msgBox.showText("操作錯誤");
						return false;
					}
					// 隱藏回覆評論框
					if(parseInt(data[0])==9999){//黑名單錯誤碼
						 msgBox.showText("對方已設置了隱私權限，無法發表回覆");
						 return false;
					}
					BlogComment.opentOrClose('dialogDiv' + commentId);
					
					msgBox.showText("回覆成功");
					
					BlogComment.getNewCommentReply(commentId);
					
					//清空內容
					$("#content" + commentId).val('');
				}
			});
	},
	/**
	* 取最新的評論回覆
	* @param Int commentId
	**/
	getNewCommentReply: function(commentId)
	{
		var html = '';
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=getNewCommentReply&commentId=" + commentId + "&callback=?",
                  function(data){
			
					  // 檢測是否登陸
						if ( !ChkLoginStatus.chkLoginIn(data) ) {
							return false;
						}
					  if (data != null) {
								html += '<div class="CommentTwo" id="replyLine' + data['reply_id'] + '">';
								html += '<div class="infoConentTwo">';
								html += '<div class="Info" id="infoLine' + data['reply_id'] + '" onmouseover="BlogComment.mOverAction(' + data['reply_id'] + ');" onmouseout="BlogComment.mOutAction(' + data['reply_id'] + ');">';
								html += '<div class="FLeft LeftInfo">';
								html += ' <span class="FLeft Gray">我的回覆：</span><span class="DeepGray Time FRight">' + data['reply_comment_date'] + ' </span>';
								html += '</div>';
								html += '<div class="FRight">';
								html += '<span id="delButtonSpan' + data['reply_id'] + '" class="DelButtonSpan"><a class="DelX" href="javascript:void(0);" onclick="BlogComment.delReply(' + data['reply_id'] + ',' + commentId + ');"><b>×</b></a></span></div>';
								html += '</div>';
								html += '<div class="Content wordBreak Red" id="contentId' + data['reply_id'] + '">' + data['reply_comment'] + '</div>';
								html += '</div></div>';
								
								if ( $_("CommentRe" + commentId) ) {
									$("#CommentRe" + commentId).append(html);
								} else {
									html = '<div class="CommentRe" id="CommentRe' + commentId + '">' + html + '</div>';
									$("#funButton" + commentId).before(html);
								}
					  }
				  });
	},
	/**
	* 取最新的評論
	**/
	getNewComment: function() {
		var html = '';
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=getNewComment&appId=" + $("#appIdVal").val() + "&resourceId=" + $_('resourceIdVal').value + "&callback=?",
                  function(data){
					  // 檢測是否登陸
						if ( !ChkLoginStatus.chkLoginIn(data) ) {
							return false;
						}
					  if (data != null) {
						   
								html += '<li class="Comment" id="commentLine' + data['id'] + '">';
								html += '<div class="Photo"><a href="http://i.' + getUrl() + '/?module=hi&visitId=' + data['member_id'] + '"><img src="' +  data['min_avatar'] + '"/></a></div>';
								html += '<div class="infoConent" id="infoContent' + data['id'] + '">';
								html += '<div class="Info"> <span class="FLeft Gray">我評論道：</span><span class="DeepGray Time FRight MRight30px">' + data['comment_date'] + '</span> </div>';
								html += '<div class="Content wordBreak Red" id="contentId' + data['id'] + '">' + data['comment'] + '</div>';
								html += '<div id="funButton' + data['id'] + '"><a class="GrayLink" href="javascript:void(0)" onclick="BlogComment.opentOrClose(\'dialogDiv' + data['id'] + '\');">回覆</a> | ';
								if ($("#appIdVal").val() == 40)
								{
									html += '<a class="GrayLink" href="javascript:void(0)" onclick="deleteComment('+_DelId+',' + data['id'] + ');">刪除</a></div>';
								} else {
									html += '<a class="GrayLink" href="javascript:void(0)" onclick="BlogComment.delComment(' + data['id'] + ');">刪除</a></div>';
								}
								html += '<div class="DiaLogDiv" id="dialogDiv' + data['id'] + '">';
								html += '<div id="msgDialog' + data['id'] + '"><div><textarea id="content' + data['id'] + '" name="reContent" cols="45" rows="5"></textarea></div>';
								html += '<div class="GbButtom"><input class="CptButtom" id="addReCommentBotton" type="button" onclick="BlogComment.addReplyComment(' + data['id'] + ');" value="發表">&nbsp;&nbsp;';
								html += '<input class="CptButtomGray" type="button" onclick="BlogComment.opentOrClose(\'dialogDiv' + data['id'] + '\');" value="取消"></div></div>';
								html += '</div></div></li>';
								
								$("#CommentList").append(html);
							
					  }
				  });
	},
	/**
	* 刪除單個回覆
	* @param Int replyId
	* @param Int commentId
	**/
	delReply: function(replyId,commentId) {
		msgBox.showTrueOrFalse2('刪除回覆','你確認要刪除該回覆嗎','BlogComment.submitDelReply(\'' + replyId + '\',\'' + commentId + '\')');
	},
	submitDelReply: function(replyId,commentId) {
		
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=delReply&replyId=" + replyId + "&callback=?",
			function(data) {
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(data) ) {
					return false;
				}
				if (data != null ) {
					if(parseInt(data[0]) == -1) {
						msgBox.showText("操作錯誤");
						return false;
					}
					msgBox.showText("刪除評論回覆成功");
				
					$("#replyLine" + replyId).remove();
					
					if ( $("#CommentRe" + commentId).html().Trim() == '' ) {
						$("#CommentRe" + commentId).remove();
					}
				}
			});
	},
	/**
	* 鼠標經過的時候
	* @param String replyId
	**/
	mOverAction: function(replyId) {
		$("#infoLine" + replyId).css("background","#EEF0F4");
		$("#delButtonSpan" + replyId).show();
	},
	/**
	* @param String replyId
	**/
	mOutAction: function(replyId) {
		$("#infoLine" + replyId).css("background",BlogComment.mouseOutColor);
		$("#delButtonSpan" + replyId).hide();
	}
});

