﻿var CommentsHelper = function(config) {
	//PRIVATE VARIABLES ---------------------------------------------------------------------------------------------------------------------------------------------- 
	var _config = config;

	var _contentType = 'application/json; charset=utf-8';
	var _type = 'Post';
	var _dataType = 'json';
	var _page = '';

	var _comments;
	var _parentId = '00000000-0000-0000-0000-000000000000';
	var _callType = 'create';
	var _currentIndex = -1;
	var _lastDeletedCommentIndex = -1;


	var popup = new ModalPopup('popupComment', 'comment-mask', 'ReplyText', true); //body, mask, textCapture, container page

	//EO: PRIVATE VARIABLES ---------------------------------------------------------------------------------------------------------------------------------------------- 

	var _loadComments = function() {
		_showSpinner();

		$.getJSON(_config.PostUrl, { postId: _config.CurrentPostId }, _renderComments);
		_hideSpinner();
	}

	var _createComment = function() {
		_showSpinner();


		text = $('#users_comment').val();
		if (jQuery.trim(text).length > 0) {
			$.getJSON(_config.CreateCommentUrl, { commentText: text, parentId: '00000000-0000-0000-0000-000000000000', siblingId: '00000000-0000-0000-0000-000000000000' }, _createComment_Callback);
		} else {
			_hideSpinner();
		}

	}

	var _createComment_Callback = function(response) {
		_currentIndex = 0;
		_renderComments({ comments: $.merge([response.comment], _comments.comments) });
		$('#users_comment').val('');
		_hideSpinner();
	}

	var _createReply_Callback = function(response) {
		_updateComment_Callback(response);
	}

	var _updateComment_Callback = function(response) {
		_siblingId = '00000000-0000-0000-0000-000000000000';
		if (!response.success) {
			alert(response.message);
		} else {
			_loadComments();
		}
	}

	var _renderComments = function(response) {
		_hideSpinner();
		_comments = response;
		$('#CommentsContainer').empty();
		$('#CommentsContainer').setTemplate($("#commentResultsTable").html(), null, { filter_data: false });
		$('#CommentsContainer').processTemplate(_comments);

		$('#comment' + _currentIndex).pulse({
			backgroundColors: ['yellow'],
			textColors: ['black'],
			speed: 500,
			duration: 2000
		});
		$('#commentCountPost').text(response.commentsCount);

		_setupIcons(_comments.comments);
	}

	var _deleteComment = function(id, inx) {
		_lastDeletedCommentIndex = inx;
		$.post(_config.DelCommentUrl, { commentId: id }, _deleteComment_Callback, "json");
	}

	var _deleteComment_Callback = function(data) {
		if (data.success) {
			var cr = new Array();
			if (_lastDeletedCommentIndex > -1) {
				for (i = 0; i < _comments.comments.length; i++) {
					if (_lastDeletedCommentIndex != i && _comments.comments[i].ParentId != data.parentId)
						cr.push(_comments.comments[i]);
				}
				_comments.comments = cr;
			}
			_renderComments(_comments);
		} else {
			alert(data.message);
		}
		_lastDeletedCommentIndex = -1;
	}


	//  CREATE NEW REPLY
	var _createNewReply = function() {
		commentText = popup.CommitChanges();
		if (jQuery.trim(commentText).length > 0)
			$.getJSON(_config.CreateCommentUrl, { commentText: commentText, parentId: _parentId, siblingId: _siblingId }, _createReply_Callback);
	}

	var _updatedComment = function() {
		updatedText = popup.CommitChanges();

		if (jQuery.trim(updatedText).length > 0) {
			$.post(_config.UpdateCommentUrl, { commentId: _comments.comments[_currentIndex].CommentId, commentText: updatedText }, _updateComment_Callback, "json");
		}
	}

	var _showSpinner = function() {
		$('#spinnerSubmit').show();
	}

	var _hideSpinner = function() {
		$('#spinnerSubmit').hide();
	}

	var _setup = function() {
		$.ajaxSetup({ cache: false });
		// LOAD THE COMMENTS FROM THE SERVER //  ---------------------------------------------------------------------------------
		_loadComments();
	}

	// APPLY TEMPLATES FUNCTION //  ---------------------------------------------------------------------------------
	var _currentTemplate = '';
	function ApplyTemplate(data, template) {
		if (_currentTemplate != template) {
			_currentTemplate = template;			
			$('#CommentsContainer').setTemplate(_currentTemplate, null, { filter_data: false }); //filter data false causes html to be allowed, otherwise the <br>'s show
		}
		$('#CommentsContainer').processTemplate(data);
	}

	// AJAX CALLER
	var _executeServiceCall = function(methodName, methodParams, successCallback, failCallback, successCallbackParams) {
		if (methodParams == null || methodParams == '')
			methodParams = '{}';
		else {
			methodParams = JSON.stringify(methodParams);
		}
		$.ajax({
			type: _type,
			url: _page + methodName,
			data: methodParams,
			contentType: _contentType,
			dataType: _dataType,
			success: function(response) {
				if (successCallback != null)
					successCallback(response, successCallbackParams);
			},
			error: function(message) {
				if (failCallback != null)
					failCallback(message);
				else
					alert(message.responseText);
			}
		});
	}

	//EXPLICIT BINDINGS ---------------------------------------------------------------------------------------------------------------------------------------------- EXPLICIT BINDINGS

	$('#refreshComments').click(function() {
		_loadComments();
	});

	//CREATE A NEW COMMENT - COMMENT DIRECTLY ON POST
	$('#enterComment').click(function() {
		_createComment();
	});

	
	//REPLIED TO A SPECIFIC COMMENT
	$('#btnCommitChanges').click(function() {
		if (_callType == 'create') {
			_createNewReply();
		}
		else if (_callType == 'update') {
			_updatedComment();
		}
	});

	//CANCELLED THE REPLY
	$('#popupClose').click(function() {
		popup.CancelComment();
		_parentId = '00000000-0000-0000-0000-000000000000';
	});

	var _setupIcons = function(comments) {
		// BIND THE CALLBACK TO THEIR RESPECTIVE ELEMENTS //  ---------------------------------------------------------------------------------
		for (var i = 0; i < comments.length; i++) {
			if (_config.IsLoggedIn) {
				$('#ri_' + i).click(function() {
					var inx = _getIndexFromId(this);
					_sci(parseInt(inx) + 1);
					_parentId = comments[inx].ParentId != '00000000-0000-0000-0000-000000000000' ? comments[inx].ParentId : comments[inx].CommentId;
					_siblingId = comments[inx].ParentId != '00000000-0000-0000-0000-000000000000' ? comments[inx].CommentId : '00000000-0000-0000-0000-000000000000';

					_callType = 'create';

					popup.SetText('');
					popup.PostComment();
				});
			}


			if (_isMyComment(comments[i].UserId) || _config.IsOwner) {
				$('#ei_' + i).click(function() {
					_sci(_getIndexFromId(this));

					_callType = 'update';
					var r = /<br \/>/g;

					popup.SetText(comments[_currentIndex].Text.replace(r, '\n'));
					popup.PostComment();
				});


				$('#di_' + i).click(function() {
					if (confirm(_config.DeleteConfirm)) {
						//SHOW SPINNER
						_showSpinner();
						inx = _getIndexFromId(this);
						_sci(-1);
						_deleteComment(comments[inx].CommentId, inx);
					}
				});
			}
		}
	}

	var _sci = function(inx) { _currentIndex = inx; };

	var _getIndexFromId = function(o) {
		var inx = o.id.indexOf('_');
		if (inx > 0)
			inx++;
		return o.id.slice(inx);
	}

	var _isMyComment = function(userId) {
		return ((userId != null) && (userId == _config.UserId));
	}

	//end of: EXPLICIT BINDINGS ----------------------------------------------------------------------------------------------------------------------------------- end of: EXPLICIT BINDINGS 


	//  PUBLICS
	return {
		Setup: function() {
			_setup();
		}
	}
};
