// JavaScript Document
$(document).ready(function(){
	setCommentDivHeight();
});

/**
* 設置評論的外層DIV的高度
**/
function setCommentDivHeight() {
	// 重置評論的外層DIV的高度
	$("#squareViewDiv").css('height','auto');
	$("#oppositionViewDiv").css('height','auto');
	
	var heightY = $("#squareViewDiv").height();
	var heightN = $("#oppositionViewDiv").height();
	if ( heightY > 550 ) {
		$("#squareViewDiv").height(550);
		$("#squareViewDiv").css('overflow-y','scroll');
	}
	if ( heightN > 550 ) {
		$("#oppositionViewDiv").height(550);
		$("#oppositionViewDiv").css('overflow-y','scroll');
	}
}

var oneDebate = ({
	/**
	* 打開或關閉發表觀點的框
	**/
	openOrCloseCommentSpan: function(spanId) {
		if ( $("#" + spanId).css("display") == "none" ) {
			$("#" + spanId).css("display","block");
		} else {
			$("#" + spanId).css("display","none");
		}
	},
	
	/**
	* 參加辯論
	* @param Int viewId 觀點id
	* @param String type 觀點類型（正或反）
	**/
	joinDebate: function(viewId,type) {
		if ( type == 'Y' ) {
			msgBox.showTrueOrFalse2('辯論','你確認要支持正方觀點嗎', 'oneDebate.submitJoinDebate(' + viewId + ',\'' + type + '\');');
		} else {
			msgBox.showTrueOrFalse2('辯論','你確認要支持反方觀點嗎', 'oneDebate.submitJoinDebate(' + viewId + ',\'' + type + '\');');
		}
	},
	submitJoinDebate: function(viewId,type) {
		var debateId = $("#debateId").val();
		$.getJSON("http://debate."+getUrl()+"/debateAjax.php?action=joinDebate&debateId="+debateId+"&viewId="+viewId+"&callback=?",function(data){
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(data) ) {
					return;
				}
                if (data != null) {
                    if (data == '1') {
                        //刷新頁面
						msgBox.showText("辯論成功");
						var url = window.location.href + "&type=" + type;
						window.location.href = url;
                    } else {
                        msgBox.showText("不能辯論");
                    }
                }
            });
	},
	/**
	* 修改截止時間
	**/
	editEndDate: function() {
		var html = '<div style="width:300px;text-align:left;font-size:14px;border-bottom:1px solid #cccccc;padding:5px 5px;margin-bottom:10px;"><b>修改截止時間</b></div>';
		html += '<div style="text-align:left;padding-left:20px;margin-bottom:10px;">請設置新的截止時間：</div>';
		html += '<div style="margin-bottom:30px;">';
		
		var endDate = $("#endDate").text();
		var arr = endDate.split(' ');
		var dateArr = arr[0].split('-');
		var yearY = dateArr[0];
		var month = dateArr[1];
		var day = dateArr[2];
		var timeArr = arr[1].split(':');
		var hour = timeArr[0];
		
		var date = new Date();
		var year = date.getFullYear();
		html += '<select id="year" onchange="Debate.getDaysWithYM();">';
		for ( var i = year; i <= year + 4; i++ ) {
			html += '<option value=' + i + '>' + i + '</option>';
		}
		html += '</select>年';
		
		html += '<select id="month" onchange="Debate.getDaysWithYM();">';
		for ( var i = 1; i <= 12; i++ ) {
			num = i;
			if ( i < 10 ) num = '0' + i;
			html += '<option value=' + i + '>' + num + '</option>';
		}
		html += '</select>月';
		
		html += '<select id="day">';
		for ( var i = 1; i <= 31; i++ ) {
			num = i;
			if ( i < 10 ) num = '0' + i;
			html += '<option value=' + i + ' id="day' + i + '">' + num + '</option>';
		}
		html += '</select>日';
		
		html += '<select id="hour">';
		for ( var i = 0; i <= 23; i++ ) {
			num = i;
			if ( i < 10 ) num = '0' + i;
			html += '<option value=' + i + '>' + num + '</option>';
		}
		html += '</select>時';
		
		html += '</div>';
		html += '<div style="margin-bottom:20px;"><input type="button" value="確認" onclick="oneDebate.submitEditEndDate();" class="CptButtom" style="margin-right:5px;"><input type="button" value="關閉" class="CptButtomGray" onclick="msgBox.removeMsgBox();"></div>';
		
		msgBox.showHtml(html);
		
		//設置年份
		$("#year").val(yearY);
		
		//設置月份
		$("#month").val(month);
		
		//設置日
		$("#day").val(day);
		
		//設置時
		$("#hour").val(hour);
	},
	submitEditEndDate: function() {
		var debateId = $("#debateId").val();
		var date = $("#year").val() + '-' + $("#month").val() + '-' + $("#day").val() + ' ' + $("#hour").val() + ':00:00';
		
		if ( !Debate.chkEndDateCurentDate($("#year").val(),$("#month").val(),$("#day").val(),$("#hour").val()) ) {
			msgBox.showText('截止時間不能早於當前時間');
			return false;
		}
		
		$.ajax({
			type: "POST",
			dataType: 'html',
			url: "./debateAjax.php",
			data: "module=index&action=editEndDate&debateId=" + debateId + "&date=" + date,
			success: function(html){
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(html) ) {
					return false;
				}
				if ( html.indexOf('-1') != -1 ) {
					msgBox.showText("不能修改截止時間");
					return false;
				} 
				
				msgBox.showText("截止時間修改成功");
				//刷新頁面
				window.setTimeout("refreshPage()",2000);
			}
		});
	},
	/**
	* 發表/修改辯論說明
	**/
	editDebateInfo: function() {
		var debateInfo = $("#debateInfo").text();
		var title = '';
		if ( debateInfo == '' ) {
			title = '寫寫辯論說明';
		} else {
			title = '修改辯論說明';
		}
		var html = '<div style="width:350px;text-align:left;font-size:14px;border-bottom:1px solid #cccccc;padding:5px 5px;margin-bottom:10px;"><b>' + title + '</b></div>';
		html += '<div style="text-align:left;margin:10px 10px;">請輸入新的辯論說明：</div>';
		html += '<div style="margin-bottom:30px;"><textarea cols="" rows="" id="debateInfoArea" style="width:300px;height:200px;">' + debateInfo + '</textarea></div>';
		html += '<div style="margin-bottom:20px;"><input type="button" value="確認" onclick="oneDebate.submitVoteInfo();" class="CptButtom" style="margin-right:5px;"><input type="button" value="關閉" class="CptButtomGray" onclick="msgBox.removeMsgBox();"></div>';
		
		msgBox.showHtml(html);
	},
	submitVoteInfo: function() {
		var debateId = $("#debateId").val();
		var debateInfo = foramt26str($("#debateInfoArea").val());
		
		$.ajax({
			type: "POST",
			dataType: 'html',
			url: "./debateAjax.php",
			data: "module=index&action=editDebateInfo&debateId=" + debateId + "&debateInfo=" + debateInfo,
			success: function(html){
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(html) ) {
					return false;
				}
				if ( html.indexOf('-1') != -1 ) {
					msgBox.showText("不能修改辯論說明");
					return false;
				} 
				
				msgBox.showText("辯論說明修改成功");
				//刷新頁面
				window.setTimeout("refreshPage()",2000);
			}
		});
	},
	/**
	* 刪除辯論
	**/
	delDebate: function() {
		msgBox.showTrueOrFalse2("刪除","你確認要刪除該辯論嗎？","oneDebate.submitDelDebate()");
	},
	submitDelDebate: function() {
		var debateId = $("#debateId").val();
		
		$.ajax({
			type: "POST",
			dataType: 'html',
			url: "./debateAjax.php",
			data: "module=index&action=delDebate&debateId=" + debateId,
			success: function(html){
				// 檢測是否登陸
				if ( !ChkLoginStatus.chkLoginIn(html) ) {
					return false;
				}
				if ( html.indexOf('-1') != -1 ) {
					msgBox.showText("操作錯誤");
					return false;
				} 
				
				msgBox.showText("辯論刪除成功");
				
				window.location.href = "http://debate." + getUrl() + "/debate.php?action=myDebate";
			}
		});
	}
});

var debateComment = ({
	/**
	* 添加新的評論
	* @param Int resourceId 
	* @param String divId 包裹評論內容的DIV編號
	**/
	addNewComment: function(resourceId,contentId,divId)
	{
		var content = foramt26str($("#"+contentId).val());
		if ( content.Trim() == '' ) {
			msgBox.showText("評論內容不能為空");
			return false;
		}
		var friendId = $("#friendIdVal").val();
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=addNewComment&appId=" + $("#appIdVal").val() + "&resourceId=" + resourceId + "&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("評論添加成功");
					
					// 取新的評論
					debateComment.getNewComment(resourceId,divId);
					
					//清空內容
					$("#"+contentId).val('');
				}
			});
	},
	/**
	* 取最新的評論
	* @param Int resourceId
	* @param String divId 包裹評論內容的DIV編號
	**/
	getNewComment: function(resourceId,divId) {
		var html = '';
		$.getJSON("http://blog." + getUrl() + "/ajax.php?module=ajaxService&action=getNewComment&appId=" + $("#appIdVal").val() + "&resourceId=" + resourceId + "&callback=?",
                  function(data){
					  if (data != null) {
								
								html += '<div class="CptComment" id="commentLine' + data['id'] + '"><a href="http://i.' + getUrl() + '/?module=hi&visitId=' + data['member_id'] + '"><img src="' +  data['min_avatar'] + '"/></a>';
								html += '<div class="CptCommentBox">';
								html += '<div class="Info"> <span class="FLeft Gray">我評論道：</span><span class="DeepGray Time FRight MRight30px">' + data['comment_date'] + ' </span>';
								html += '</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> | ';
								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="40" rows="4" class="CptTextareaGray"></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>';
								
								if ( $("#" + divId).html().indexOf("暫無正方觀點") != -1 || $("#" + divId).html().indexOf("暫無反方觀點") != -1 ) {
									$("#" + divId).html('');
								}
								$("#" + divId).prepend(html);
					  }
				  });
	},
	/**
	* 翻頁
	* @param Int currentPage 當前頁數
	* @param Int totalPages 總頁數
	* @param Int appId
	* @param Int resourceId
	* @param String type 正方或反方
	**/
	getNextPreData: function(currentPage,totalPages,appId,resourceId,type) {
		// 顯示加載層
		msgBox.loadingShow();
		
		var html = '';
		$.ajax({
			type: "POST",
			dataType: 'html',
			url: "./debateAjax.php",
			data: "&action=getNextPreData&currentPage="+currentPage+"&totalPages="+totalPages+"&appId="+appId+"&resourceId="+resourceId,
			success: function(html){
					if ( html.indexOf('error-1error') != -1 || html.indexOf('error0error') != -1 ) {
						msgBox.showText("不能分頁");
						return;
					}
					var pageHtml = '';
					var nums = pageString(currentPage, totalPages, resourceId, type);
					prePage = parseInt(currentPage)-1;
					nextPage = parseInt(currentPage)+1;
					if ( currentPage == totalPages ) {
						pageHtml = '<span class="Gray"><a id="preLink" href="javascript:void(0)" onclick="debateComment.getNextPreData(' + prePage + ',' + totalPages + ',' + appId + ',' + resourceId + ',\'' + type + '\');">&nbsp;</a></span>' + nums + '<span class="disabled"> 下一頁 </span>';
					} else if ( currentPage == 1 ) {
						pageHtml = '<span class="Gray preDisable">&nbsp;</span>' + nums + '<span><a href="javascript:void(0)" id="PageNextLink" onclick="debateComment.getNextPreData(' + nextPage + ',' + totalPages + ',' + appId + ',' + resourceId + ',\'' + type + '\');"> 下一頁 </a></span>';
					} else {
						pageHtml = '<span class="Gray"><a id="preLink" href="javascript:void(0)" onclick="debateComment.getNextPreData(' + prePage + ',' + totalPages + ',' + appId + ',' + resourceId + ',\'' + type + '\');">&nbsp;</a></span>' + nums
									+ '<span><a href="javascript:void(0)" id="PageNextLink" onclick="debateComment.getNextPreData(' + nextPage + ',' + totalPages + ',' + appId + ',' + resourceId + ',\'' + type + '\');"> 下一頁 </a></span>';
					}
					if ( type == 'Y' ) {
						$("#squareViewDiv").html(html);
						$("#pageY").html(pageHtml);
					} else {
						$("#oppositionViewDiv").html(html);
						$("#pageN").html(pageHtml);
					}
					msgBox.removeMsgBox(); // 移除加載層
					setCommentDivHeight(); // 設置評論外層DIV的高度
			}
		});
	}
});

function pageString(currentPage, totalPages, resourceId, type) {
	var front   = '';
	var end     = '';
	var nums    = '';
	var current = '';
	if ( totalPages <= 7 ) {
		for ( i=1; i<=totalPages; i++ ) {
			if ( i == currentPage ) {
				current = '<span class="noLink"><span>' + i + '</span></span>';
			} else {
				current = '<a href="javascript:void(0)" onclick="debateComment.getNextPreData(' + i + ',' + totalPages + ',19,' + resourceId + ',\'' + type + '\');"> ' + i + ' </a>';
			}
			nums += current;
		}
	} else {
		for ( i=(currentPage<5 ? 1 : ((currentPage-3)>(totalPages-6) ? (totalPages-6) : (currentPage-3))); i<=((currentPage+3)>totalPages ? totalPages : ((currentPage+3)<7 ? 7 : (currentPage+3))); i++ ) {
			if ( i == currentPage ) {
				current = '<span class="noLink"><span>' + i + '</span></span>';
			} else {
				current = '<a href="javascript:void(0)" onclick="debateComment.getNextPreData(' + i + ',' + totalPages + ',19,' + resourceId + ',\'' + type + '\');"> ' + i + ' </a>';
			}
			nums += current;
		}
		if ((currentPage-3) > 1) {
			front = '...';
		}
		if ((currentPage+3) < totalPages) {
			end = '...';
		}
	}
	return front + nums + end;
}

//刷新頁面
function refreshPage() {
	location.reload();
}