//verify to see if we have defined the global namespace.
if (typeof Haaretz === 'undefined') {
	Haaretz = {};
}
var mainTalkbackFormBoxId = "mainTalkbackFormBox";
var mainCommentsReplyAgainId = "callbackMsg0";
var banner468x60id = "dclk_objects_15";

jQuery(document).ready(function() {

	jQuery("span.rateCommentPlus").click(function() {
		try {
			Haaretz.Comment.storeCommentRate(this, "plus");
		} catch (e) {
		}// TODO:print to console
			return false;
		});

	jQuery("span.rateCommentMinus").click(function() {
		try {
			Haaretz.Comment.storeCommentRate(this, "minus");
		} catch (e) {
		}// TODO:print to console
			return false;
		});

	jQuery("a.replyComment").click(function() {
		// open the comment form
			var commentId = Haaretz.Comment.getCommentId(this);
			var parentId = Haaretz.Comment.getParentId(this);
			Haaretz.Comment.showTalkbackForm(commentId, parentId, this);
			return false; // Avoid the browser following the link
		});

	/** Open comment to view its details */
	jQuery("a.commentTitle").click(function() {
		var commentId = Haaretz.Comment.getCommentId(this);
		Haaretz.Comment.toggleComment(commentId, this);
		return false; // Avoid the browser following the link
		});

	jQuery("#openCloseComments").click(function() {
		Haaretz.Comment.toggleAllComments();
	});

	jQuery("form.form-talkbacks").submit(function() {
		var form = jQuery(this);
		Haaretz.Comment.saveComment(form);
		return false;
	});

	jQuery("#mainCommentsReplyAgain a").click(function() {
		jQuery("." + mainCommentsReplyAgainId).hide();
		jQuery("#" + mainTalkbackFormBoxId).show();
		return false; // Avoid the browser following the link
		});

	jQuery("a.displayAnonymous").click(function() {
		Haaretz.Comment.displayAnonymous(jQuery(this));
		return false; // Avoid the browser following the link
		});

	jQuery("a.displayFacebookData").click(function() {
		Haaretz.Comment.displayFacebookData(jQuery(this));
		return false; // Avoid the browser following the link
		});

	/**
	 * Binds sort function to onclick event of comments tabs li elements.
	 * Notice: there is additional binding of the a elements of each li element
	 * in initTabs function in haaretz_main.js (this binding responsible for
	 * hidding/showing the tabs in the tabset - a general function, relevant for
	 * all 'tabset's on the site)
	 */
	jQuery("#commentsTabset li").each(function() {
		var tabset = jQuery(this);
		if (tabset.attr('id') != 'toggle_open') {
			tabset.click(function() {
				Haaretz.Comment.sortComments(tabset);
			})
		}
	});

	Haaretz.Comment.initCommentFormName();
	// verify that the talkback form submit button is enabled
	Haaretz.Comment.enableTalkbackSubmit();
});

Haaretz.Comment = function() {

	var STATISTICS_SERVER_URL = "/logger/p.gif";
	var errorMsgs = {
		addCommentError : [
				"serverError",
				"There has been a problem delivering your talkback to the system. Please try again later." ],
		commentAuthorEmpty : [ "authorError", "Please enter your name" ],
		commentTitleEmpty : [ "titleError", "Please fill in the 'subject' box" ]
	};

	/** contentId of comments element, initialized on page load */
	var _serviceInstanceId;
	/** content ids path of current article, initialized on page load */
	var _articlePath;
	/**
	 * if true the comments views and rating counts will be updated on
	 * statistics server (defined by article 'age' in
	 * PrepareCommentListCommand.java)
	 */
	var _continueToUpdateStatisticsServer;

	return {
		initialize : function(id, articlePath, continueToUpdateStatisticsServer) {
			_serviceInstanceId = id;
			_articlePath = articlePath;
			_continueToUpdateStatisticsServer = continueToUpdateStatisticsServer;
		},

		/**
		 * retrive comment id concatenated at the end of the tag id attribute
		 * (assumes id is always of the following format ...-contentId)
		 */
		getCommentId : function(tagObj) {
			var id = jQuery(tagObj).get(0).id.split("-");
			var commentId = id[id.length - 1];// commentid is the last value
												// of the tag id
			return commentId;
		},

		getParentId : function(tagObj) {
			var parentid = "";
			var id = jQuery(tagObj).get(0).id.split("-");
			for ( var i = 0; i < id.length; i++) {
				if (id[i] == "parentid") {
					parentid = id[i + 1];
				}
			}
			return parentid;
		},
		saveComment : function(form) {
			// disable the send button to avoid multiple form submissions
			Haaretz.Comment.toggleButton(form);
			// display in progress gif
			jQuery("img.inProgress", form).show();
			// in case of server response failure, hide the progress image
			setTimeout(function(form) {
				Haaretz.Comment.hideInProgressImg(form);
				// verify that the talkback form submit button is enabled
				Haaretz.Comment.enableTalkbackSubmit();
			}, 2000, form);

			// clean the error messages from the form
			jQuery(".commentError", form).each(function() {
				jQuery(this).html("");
			});
			// TODO:validate the form

			// save the comment
			this.storeCommentOnServer(form);
		},
		/**
		 * enable/disable the talkback submit button to avoid multiple sending of talkback form
		 */
		toggleButton : function(formObj) {
			var button = jQuery('.btn-send', formObj);
			var disabled = button.attr('disabled');
			if(disabled == true){
				button.removeAttr('disabled');

			}
			else {
				button.attr('disabled', true);
			}
		},

		enableTalkbackSubmit : function() {
			// goes over all the forms in the page and set their disabled state to false
			$('form').each(	function() {
				$(this).find('.btn-send').removeAttr('disabled')
				}
			);
		},
		/**
		 * submit the comment.
		 */
		storeCommentOnServer : function(formObj) {

			var userStatus = Haaretz.Facebook.getUserStatus();
			switch (userStatus) {
			case FACEBOOK_LOGGED_IN:
				// get comment author name, add it to the hidden form data.
				var username = jQuery("h4 a", formObj).html();
				var facebookid = Haaretz.Facebook.getFacebookId();
				jQuery("#comment_author", formObj).val(username);
				// get facebook id of the currently logged in user, add it to the hidden form data
				jQuery("#facebookUID", formObj).val(facebookid);
				Haaretz.Facebook.submitComment(formObj);
				break;
			case FACEBOOK_LOGGED_0UT:
				// get comment author name, add it to the hidden form data.
				jQuery("#comment_author", formObj).val(
						jQuery(".loggedOut", formObj).val());
				break;
			case ANONYMOUS:
				// get comment author name, add it to the hidden form data.
				jQuery("#comment_author", formObj).val(
						jQuery(".anonymous", formObj).val());
				break;
			default:
				alert("user status not found");
			}

			// get all input form data in current form
			var inputs = formObj.serialize();

			// submit the comment
			try {
				jQuery.ajax( {
					cache : false,
					url : "/cmlink/" + _serviceInstanceId,
					data : inputs,
					type : "POST",
					success : function(data, status) {
						storeCommentCallback(data, status);
					},
					timeout : 3000,
					dataType : 'json'
				});
			} catch (e) {
				// TODO: do something
			}
		},

		/**
		 * update view count of given comment on statistic server TODO: remove
		 * view count servlet
		 */
		updateCommentViewStatus : function(commentId) {
			if (_continueToUpdateStatisticsServer){
				jQuery.ajax( {
					data : {
						type : "COMMENTS_VIEWS",// comment views analyzer
												// message type (see
												// ConfigInstances.properties)
						a : _articlePath,
						comment : commentId
					},
					error : function() {},
					success : function(data, status) { /*
														 * alert(data + " | " +
														 * status);
														 */ },
					timeout : 3000,
					type : "GET",
					// url : "/comments/viewcounter"
					url: STATISTICS_SERVER_URL
				});
			}
		},

		/** updates given comment rating, liked/not liked */
		storeCommentRate : function(comment, ratingType) {
			var commentId = this.getCommentId(comment);
			// update rating only if the article is new (currently two week old)
			if (_continueToUpdateStatisticsServer){
				jQuery.ajax( {
					cache : false,
					data : {
						type : "COMMENTS_RATINGS",
						a : _articlePath,
						group : ratingType,
						comment : commentId
					},
					success : function(data, status) {
						storeCommentRateCallback(data, status, commentId, ratingType);
					},
					timeout : 3000,
					type : "GET",
					// url : "/cmlink/" + _serviceInstanceId
					url : STATISTICS_SERVER_URL
				});
			}else{
				// if the article is old, update the client display only without
				// really sending the data.
				storeCommentRateCallback("", "success", commentId, ratingType)
			}
		},

		/** display a reply form near the clicked comment */
		showTalkbackForm : function(commentId, parentId, talkback) {

			// Get the parent tag that will host the reply form
			var parent = jQuery(talkback).parents('div.slide');
			jQuery("p.thankYou", parent).hide();// hide thank you message

			var form = jQuery('#innerTalkbackFormTemplate');
			// Clear the form
			jQuery('input[type=reset]', form).click();
			// Close currently open form, by removing it from dom
			form.remove();
			// Append it to the new position.
			parent.append(form);
			// re-bind a submit event (lost when form is removed from the DOM)!!!
			form.submit(function() {
				Haaretz.Comment.saveComment(form);
				return false;
			});
			// re-bind all click events (lost while form is removed from the DOM)!!!
			jQuery("a.displayAnonymous", form).click(function() {
				Haaretz.Comment.displayAnonymous(jQuery(this));
				return false; // Avoid the browser following the link
				});
			jQuery("a.displayFacebookData", form).click(function() {
				Haaretz.Comment.displayFacebookData(jQuery(this));
				return false; // Avoid the browser following the link
				});

			// set comment parent id
			var parentCommentId = jQuery('[id=parentCommentId]', form);
			if (parentCommentId) {
				parentCommentId.val(parentId);
			}
			var callbackMsgId = jQuery('[id=callbackMsgId]', form);
			if (callbackMsgId) {
				callbackMsgId.val(commentId);
			}
			form.show();
		},

		/** show/hide comment details (like comment text) */
		toggleComment : function(commentId, talkback) {
			// Get the parent - div: post-holder
			var parent = jQuery(talkback).parent().parent().parent();
			if (jQuery(parent).hasClass("active")) {
				jQuery(parent).removeClass("active");
				jQuery(parent).find("#" + banner468x60id).hide();
			} else {
				// display comment details
				jQuery(parent).addClass("active");
				// update comment view status
				this.updateCommentViewStatus(commentId);
				// show comment banner
				if (jQuery(parent).attr('class').indexOf('post-holder') != -1) {
					if (jQuery(parent).find("#" + banner468x60id).length == 0) {
						jQuery("#" + banner468x60id).insertAfter(
								jQuery(parent).children().last());
					}
					jQuery("#" + banner468x60id).show();
				}
			}
		},

		/** open/close all comments details on the page */
		toggleAllComments : function() {
			if (jQuery("#openCloseComments").html() == "Open all") {

				jQuery(".talkback .post .commentItem").each(function() {
					jQuery(this).addClass("active");
				});
				if (jQuery(".talkback .post .commentItem").first().find(
						"#" + banner468x60id).length == 0) {
					jQuery("#" + banner468x60id).insertAfter(
							jQuery(
									jQuery(".talkback .post .commentItem")
											.first()).children().last());
				}
				jQuery("#" + banner468x60id).show();
				jQuery("#openCloseComments").html("Close all");

			} else {

				jQuery(".talkback .post .commentItem").each(function() {
					jQuery(this).removeClass("active");
				});
				jQuery("#" + banner468x60id).hide();
				jQuery("#openCloseComments").html("Open all");
			}
		},
		/**
		 * init the name field of the talkback form. If user facebook logged in,
		 * display his/her picture and name, otherwise display facebook connect
		 * button.
		 */
		initCommentFormName : function() {
			Haaretz.Facebook.initFaceBook();
		},

		/** show comment anonymous name field (other than his/her facebook name) */
		displayAnonymous : function(displayAnonymousBtn) {
			var form = displayAnonymousBtn.parents("form");
			jQuery(".facebookUserLoggedIn", form).hide();
			jQuery(".facebookAnonymousUser", form).show();
			Haaretz.Facebook.setUserStatus(ANONYMOUS);
		},

		/** show client facebook name and picture hidden on the page */
		displayFacebookData : function(displayFacebookDataBtn) {
			var form = displayFacebookDataBtn.parents("form");
			jQuery(".facebookAnonymousUser", form).hide();
			jQuery(".facebookUserLoggedIn", form).show();
			Haaretz.Facebook.setUserStatus(FACEBOOK_LOGGED_IN);
		},
		hideInProgressImg : function(form) {
			jQuery("img.inProgress", form).hide();
		},
		sortComments : function() {
			var sortedTab = arguments[0];
			if (sortedTab) {
				var sortKey = sortedTab.attr('id');
				var myList = jQuery('#commentsTab ul.post>li');
				jQuery.tinysort.defaults.order = "desc";
				myList.tsort( {
					attr : sortKey
				});
			}
		}
	};// return

	function storeCommentCallback(data, status) {
		var formId = data.formId;

		if (formId) {
			var form = jQuery("#" + formId);
			Haaretz.Comment.toggleButton(form);// enable the submit button
			Haaretz.Comment.hideInProgressImg(form);
			if (data.hasCommentError) {
				// display the error messages
				var errorList = eval(data.errorList);
				for ( var i in errorList) {
					var error = errorMsgs[errorList[i]];
					var errorLabelName = error[0];
					var errorMsg = error[1];
					var errorLabel = jQuery("." + errorLabelName, form);
					errorLabel.html(errorMsg);
					errorLabel.show();
				}
			} else {
				var responseMsg = "Your talkback has been submitted successfully. <br/>If selected for publication, it will appear as soon as possible on Haaretz.com.";
				// find where to show the response
				if (formId.indexOf('innerTalkback') != -1) {
					// its an inner form (comment on comment)
					form.hide();
					var callbackMsgBox = "callbackMsg" + data.callbackMsgId;
					jQuery("[class*='" + callbackMsgBox + "']").each(
							function() {
								jQuery(this).html(responseMsg);
								jQuery(this).show();
							});// show thank you message
				} else {
					// its a main form
					jQuery('input[type=reset]', form).click();// Clear the form
					jQuery("#" + mainTalkbackFormBoxId).hide();// hide the form
					var thankYouObj = jQuery("." + mainCommentsReplyAgainId);
					jQuery("p", thankYouObj).html(responseMsg);
					thankYouObj.show();// show thank you message
				}
			}
		}
	}


	function storeCommentRateCallback(data, status, commentId, ratingType) {
		// alert(status + " | " + commentId + " | " + ratingType);
		 if (status != "success"){

			 var errorMsg = "Your rating has not been registered due to a technical glitch. Please try again later.";
			 var callbackMsgBox = "callbackMsg" + commentId;
			 jQuery("[class*='" + callbackMsgBox + "']").each(function() {
					jQuery(this).html(errorMsg);
					jQuery(this).show();
			});

		 }else{

			var thankYou = "<h3>Thank you for rating</h3>";
			// update the rating value
			var ratingCountId = "rating" + ratingType + commentId;
			jQuery("[class*='" + ratingCountId + "']").each(function() {
				var ratingValue = jQuery(this).html();
				ratingValue++;
				jQuery(this).html(ratingValue);
			});
			// disable the click event on the used rating button
			// to prevent repeated rating of the same talkback
			var ratingBtn = "ratingBtn" + commentId;
			var messageAttached = false;
			jQuery("[class*='" + ratingBtn + "']").each(function() {
				jQuery(this).unbind('click');
				jQuery(this).addClass("disabled");

				if (messageAttached == false) {
					var parent = jQuery(this).parents('div.slide');
					// parent.append(thankYou);
					jQuery("p.thankYou", parent).html(thankYou);
					jQuery("p.thankYou", parent).show();// show thank you
														// message
					messageAttached = true;
				}
			});
		 }
	}
}();

