$(function() {
	getComment();

	$("#commentForm").submit(function() {
		$(this).ajaxSubmit({
			beforeSubmit: function() {
				if ( $.trim($("#textContent").val()) == "" ) {
					alert("내용을 입력해주세요.");
					$("#userID").focus();
					return false;
				}
			},
			success: function(retValue) {
				if ( retValue == "SUCCESS" ) {
					getComment();
				}
			},
			clearForm: true
		});
		return false;
	});

	$("#nextPage, #prevPage").live("click" ,function() {
		var curPageNo = $(this).attr("rel");
		getComment(curPageNo);

		return false;
	});
});

var makeNavigation = function(pageNo, isNextPage, isPrevPage) {
	var nextPageNo = parseInt(pageNo) + 1;
	var prevPageNo = parseInt(pageNo) - 1;
	// 페이지 네비게이션
	var html = "";

	if ( isPrevPage == "true" ) {
		html = "<a href='/aing/?page="+prevPageNo+"' rel='"+prevPageNo+"' style='float:left;' id='prevPage'><img src='/images/aing/prev.jpg' alt='이전' /></a>";
	}
	if ( isNextPage == "true" ) {
		html += "<a href='/aing/?page="+nextPageNo+"' rel='"+nextPageNo+"' style='float:right;' id='nextPage'><img src='/images/aing/next.jpg' alt='다음' /></a>";
	}

	return html;
};

var getComment = function(pageNo) {
	var _pageNo = pageNo || 1;
	var navigationHtml = "";

	$.getJSON("controller.php", {"mode":"getComment", "pageNo":_pageNo}, function(arrRetValue) {
		var commentList = "";

		$.map(arrRetValue.comments, function(retValue) {
			var comment    = retValue.comment;
			var author     = retValue.author;
			var regDate    = retValue.regDate;
			var profileImg = retValue.profileImg;

			commentList += "<div class='commentBox' style='padding:6px 0 0 0;'>";
				commentList += "<div class='profile' style='float:left;'>";
					commentList += "<img src='"+profileImg+"' style='width:63px;position:absulute;' />";
					commentList += "<span class='authorTitle'>"+author+"</span>";
				commentList += "</div>";
				commentList += "<div class='commentBody'>";
					commentList += "<span class='text_board' style='margin:0 0 0 5px;'>"+comment+"</span>";
				commentList += "</div>";
			commentList += "</div>";
		});

		navigationHtml = makeNavigation(_pageNo, arrRetValue.isNext, arrRetValue.isPrev);

		$("#pageNavigation").html(navigationHtml);
		$("#commentList").html(commentList);
	});
}
