/**
 * Support library for article comments
 * Glenn Hisdal
 * TV 2 AS
*/
var ArticleComments = {
	/**
	 * Gets the comment thread formatted as html
	 * threadId: The id of the comment thread (as specified in the article_comment_id field)
	 * 				DEPRECATED - Still present for backwards compatibility. Set to -1 in new code
	 *
	 * articleId: The id of the commented article
	 * containerId: The id of the html element which is to display the comments
	*/
	getComments : function(threadId, articleId, containerId, prefix, pagenum, sortOrder) {
		// compatibility fix
		if(prefix === null) {
			prefix = "tv2article_";
		}
		if(sortOrder === null) {
			sortOrder = "desc";
		}
		// - end compatibility fix

		jQuery.ajax({
			url: '/community/articlecomments/listComments.jsp?thread=' +
					threadId + '&article=' + articleId + '&container=' +
					containerId + '&page=' + pagenum + '&prefix=' + prefix + '&sortOrder=' + sortOrder,
			cache: false,
			dataType: "text",
			success: function(data, status) {
				var element = document.getElementById(containerId);
				if(element !== null) {
					element.innerHTML = data;
				}
			},
			error: function(request, status, error) {
				//alert("Failed to get comments!");
			}
		});
	},

	/**
	 * Posts a comment
	 * commentForm: The html form element containing the comment data.
	 * threadId: The id of the comment thread
	 * articleId: The id of the commented article
	 * commentsConainerId: The id of the html element displaying the comments
	 * messageContainerId: The id of the html element used for displaying status or error messages
	 *
	 * This method is normally called from a form obtained by a call to getCommentForm(...).
	*/
	postComment : function(commentForm, commentsContainerId, messageContainerId, threadId, articleId) {
		// display loader
		jQuery("#tv2_comments_submit_" + articleId).css("display", "none");
		jQuery("#tv2_comments_submit_loader_" + articleId).css("display", "inline");
		
		var messageContainer = document.getElementById(messageContainerId);
		var formData = jQuery(commentForm).serialize();
		var shareOnFacebook = false;
		if(typeof(commentForm.elements['shareOnFacebook']) != 'undefined') {
			shareOnFacebook = commentForm.elements['shareOnFacebook'][0].checked;
		}

		var articleImageUrl = '';
		if(typeof(commentForm.elements['articleImageUrl']) != 'undefined') {
			commentForm.elements['articleImageUrl'].value;
		}
		var articleTitle = commentForm.elements['threadTitle'].value;
		var commentBody = commentForm.elements['body'].value;
		
		jQuery.ajax({
			type: 'POST',
			data: formData,
			dataType: 'text',
			url: commentForm.action,
			success: function(data, status){
				if(messageContainer !== null) {
					var firstComment = jQuery("#" + commentsContainerId + " .first_comment");
					
					messageContainer.innerHTML = data;
					var myComment = jQuery("#tv2_articlecomments_mycomment");
					if(myComment.html() !== null) {
						var commentCount = jQuery("#" + commentsContainerId + " .comments_header span");
						if(commentCount.html() !== null) {
							commentCount.html(parseInt(commentCount.html())+1);
						}
						
						if(firstComment.html() !== null) {
							firstComment.removeClass("first_comment");
							firstComment.before(myComment.html());
						}
						else {
							// this is the first comment
							jQuery("#" + commentsContainerId).append(myComment.html());
						}
						myComment.remove();
						
						if(shareOnFacebook) {
							var frameUrl = "http://www.tv2.no/community/fbconnect/fbshare.jsp?domain=" + encodeURIComponent(location.hostname) + 
											"&title=" + encodeURIComponent(articleTitle) +
											"&articleUrl=" + encodeURIComponent(location.href) +
											"&articleImageUrl=" + encodeURIComponent(articleImageUrl) +
											"&comment=" + encodeURIComponent(commentBody);
							
							var html = "<div id='tv2_fb_share_dialog' style='position: absolute; top: " + getScrollY() + "px; left: 0px; z-index: 2147483647;'><iframe src='" + frameUrl + "' width='700' height='700' frameborder='0' style='background: transparent;' allowtransparency='true'>&nbsp;</iframe></div>";
							jQuery("body").prepend(html);
						}
						
					}
				}
			},
			error: function(response, status, error) {
				alert("Kommunikasjon med kommentarsystem feilet. Vennligst prøv igjen.");
			}
		});
	},
	
	/**
	 * Posts a form using ajax
	 * commentForm: The html form element containing the comment data.
	 * threadId: The id of the comment thread
	 * articleId: The id of the commented article
	 * commentsConainerId: The id of the html element displaying the comments
	 * messageContainerId: The id of the html element used for displaying status or error messages
	 *
	 * This method is normally called from a form obtained by a call to getCommentForm(...).
	*/
	postForm : function(commentForm, commentsContainerId, messageContainerId, threadId, articleId) {
		var messageContainer = document.getElementById(messageContainerId);
		var formData = jQuery(commentForm).serialize();
		jQuery.ajax({
			type: 'POST',
			data: formData,
			dataType: 'text',
			url: commentForm.action,
			success: function(data, status){
				if(messageContainer !== null) {
					messageContainer.innerHTML = data;
				}
			},
			error: function(response, status, error) {
				alert("Kommunikasjon med kommentarsystem feilet. Vennligst prøv igjen.");
			}
		});
	},

	
	/**
	 * threadId: The id of the comment thread (if specified in article)
	 * articleId: The id of the commented article
	 * articleTitle: Title of the commented article
	 * containerId: The id of the html element where we are to put the form
	 * messageContainerId: The id of the html element displaying status messages when submitting the form
	 * commentsContainerId: The id of the html element displaying the comments
	 * requireLogin: Set to true if only logged in users are allowed to post comments
	*/
	getCommentForm : function(forumId, threadId, articleId, articleTitle, containerId, commentsContainerId, requireLogin, prefix, articleImageUrl) {
		// compatibility fix
		if(prefix === null) {
			prefix="tv2article_";
		}
		else if(prefix == 'false') {
			commentsContainerId = requireLogin;
			requireLogin = prefix;
			prefix = "tv2article_";
		}
		// - end compatibility fix

		var formUrl = "/community/articlecomments/forms/commentform_nologin.jsp";
		if(requireLogin == 'true') {
			formUrl = "/community/articlecomments/forms/commentform_facebook.jsp";
		}
		
		jQuery.ajax({
			url: formUrl + "?articleId="+articleId+"&threadTitle="+articleTitle+"&threadId="+threadId+"&r=" + requireLogin +
				"&msgId=" + containerId + "&commentsId=" + commentsContainerId + "&forumId=" + forumId + "&prefix=" + prefix +
				"&domain=" + location.hostname + "&articleImageUrl=" + articleImageUrl,
			dataType: "text",
			cache: false,
			success: function(data, status) {
				var formContainer = document.getElementById(containerId);
				if(formContainer !== null) {
					formContainer.innerHTML = data;
				}
			}
		});
	},

	/**
	 * User has selected to flag a comment
	 * commentId: The id of the comment to flag
	 * update: true if the html is about to be updated
	*/
	flagComment : function(commentId, update) {
		window.open('/community/articlecomments/forms/commentform_complaint.jsp?complaintSource=' + commentId, 'tv2_comment_complaint', 'width=400,height=340,resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no');
	},
	/*
	logout : function(userType, forumId, threadId, articleId, articleTitle, containerId, commentsContainerId, requireLogin, prefix) {
		ArticleComments.getCommentForm(forumId, threadId, articleId, articleTitle, containerId, commentsContainerId, requireLogin, prefix, 'logout');
	},
	*/

	/**
	 * Inserts both the comment form and the actual comment thread
	 *
	 * forumId: The id of the forum holding the comment threads
	 * threadId: Set to -1 in new code - only provided for compatibility with older comments
	 * articleId: Id of the content to comment
	 * articleTitle: This will become the name of the forum thread
	 * containerId: html id of the element going to hold the form for submitting comments
	 * commentsContainerId: html id of the element holding the actual comments
	 * requireLogin: Set to true if only logged in users are allowed to comment
	 * prefix: A prefix used internally to identify the thread
	 * 				Note: The string obtained by concatenating prefix+articleId must be unique for all threads.
	 */
	insertComments : function(forumId, threadId, articleId, articleTitle, containerId, commentsContainerId, requireLogin, prefix, articleImageUrl) {
		ArticleComments.getCommentForm(forumId, threadId, articleId, articleTitle, containerId, commentsContainerId, requireLogin, prefix, articleImageUrl);
		ArticleComments.getComments(threadId, articleId, commentsContainerId, prefix, 1, "desc", (requireLogin == 'true' ? '2' : '1'));
	},
	
	/**
	 * Gets the comment thread formatted as html for monkeys
	 * threadId: The id of the comment thread (as specified in the article_comment_id field)
	 * 				DEPRECATED - Still present for backwards compatibility. Set to -1 in new code
	 *
	 * articleId: The id of the commented article
	 * containerId: The id of the html element which is to display the comments
	*/
	getMonkeyComments : function(threadId, articleId, containerId, prefix, pagenum) {
		// compatibility fix
		if(prefix === null) {
			prefix = "tv2article_";
		}
		// - end compatibility fix

		jQuery.ajax({
			url: '/community/articlecomments/listComments.jsp?thread=' +
					threadId + '&article=' + articleId + '&container=' +
					containerId + '&page=' + pagenum + '&prefix=' + prefix,
			cache: false,
			dataType: "text",
			success: function(data, status) {
				// Monkey want a banana!
				var element = document.getElementById(containerId);
				var comments = document.createElement('div');
				comments.innerHTML = data;
				if(element !== null) {
					element.appendChild(comments);
				}
			},
			error: function(request, status, error) {
				//alert("Failed to get comments!");
			}
		});
	}
};

function selectCommentFormField(element, defaultText, isFocus) {
	if(isFocus) {
		if(element.value == defaultText) {
			element.value = "";
		}
	}
	else {
		if(element.value == "") {
			element.value = defaultText;
		}
	}
}

function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}


