$(document).ready(function (){
	var item_id = $('#comments_item_id').val();
	var commentsList = new CommentsList({item_id : item_id});
	var commentsForm = new CommentsForm();
	commentsForm.setCommentsList(commentsList);
});


function CommentsForm(){
	this.errorMessages = {
		name	: 'Campul nume este obiligatoriu.',
		mail	: 'Adresa de email este incorecta sau necompletata.',
		message : 'Nu ati completat mesajul.',
		captcha : 'Introdu codul din imaginea de verificare.'
	};
	this.isLoggedIn = false;

	this.commentsList = null;
	this.formContainer = '#comment_form';
	this.itemIdContainer = '#comments_item_id';
	this.messagingSubscribeContainer = '#messaging_subscribe';
	this.nameContainer = '#user_name';
	this.mailContainer = '#user_mail';
	this.messageContainer = '#message';
	this.captchaContainer = '#captcha';


	this.messages = new Array;

	this.setUserData();

	this.setCaptcha();

	this.setSubmitAction();

	var _this = this;

	$(this.captchaContainer).siblings('a').click(function (){
		_this.setCaptcha();
	});
};

CommentsForm.prototype.setUserData = function (){
	var _this = this;
	var response = null;
	$.ajax({
		async	: false,
		url	: baseURL + 'comments_controller/ajax_get_user_data',
		dataType: 'json',
		success	: function (data){
			response = data;
		}
	});
	if (response != null){
		if (response.isLoggedIn != false){
			_this.isLoggedIn = response.isLoggedIn;
			if ($(this.nameContainer).val() == ""){
				$(this.nameContainer).val(response.userName);
			}	
			if ($(this.mailContainer).val() == ""){
				$(this.mailContainer).val(response.userEmail);
			}	
		}
	
	}
};

CommentsForm.prototype.setCaptcha = function (){
	if (this.isLoggedIn == true) {
		$('div.captcha').remove();
	} else {
		var _this = this;
		var postData = {'item_id' : this.getItemId()};
		$.ajax({
			url		: baseURL + 'comments_controller/ajax_generate_captcha',
			async		: false,
			cache 		: false,
			data		: postData,
			dataType	: 'html',
			type 		: 'post',
			success		: function(data){
				$(_this.captchaContainer).siblings('a').html('');
				$(_this.captchaContainer).siblings('a').append(data);
				$(_this.captchaContainer).val('');
			}
		});
	}
};

CommentsForm.prototype.submitComment = function (){
	$('div.comment-message').remove();

	if (this.validate() == false) {
		this.showErrorMessages();
		return false;
	}
	var postData = this.getFormData();
	var _this = this;

	$(this.formContainer).hide();

	$.ajax({
		url			: baseURL + 'comments_controller/ajax_submit_comment',
		async		: true,
		cache 		: false,
		data		: postData,
		dataType	: 'json',
		type 		: 'post',
		success		: function(data){
			var message = null;
			if (data.status != undefined && data.status == true){
				message = data.message;
				$(_this.messageContainer).val('');
				$(_this.setCaptcha());
				_this.commentsList.showList(_this.commentsList.getLastPage());
			} else if(data.status != undefined && data.status == false){
				message = data.message;
			} else {
				message = 'Comentariul nu a fost postat din cauza unei probleme tehnice.';
			}

			$('#comments_list_container').after($(document.createElement('div')).addClass('comment-message').text(message));

			setTimeout(function(){
				$('div.comment-message').remove();
			}, 3000);

			setTimeout(function(){
				$(_this.formContainer).show();
			}, 1000);
		},
		error		: function (XMLHttpRequest, textStatus, errorThrown){
				message = 'Comentariul nu a fost postat din cauza unei probleme tehnice.';
				$(_this.commentsList.container).after($(document.createElement('div').addClass('comment-message').text(message)));
				setTimeout(function(){
					$(_this.formContainer).show();
				}, 1000);
				setTimeout(function(){
					$('div.comment-message').remove();
				}, 3000);
		}
	
	});
};

CommentsForm.prototype.showErrorMessages = function (){
	if (this.messages.length > 0) {
		alert(this.messages.join("\n"));
	}
}

CommentsForm.prototype.validate = function (){
	this.messages = new Array();

	this.validateName();
	this.validateMail();
	this.validateMessage();
	this.validateCaptcha();

	if (this.messages.length > 0) {
		return false;
	}

	return true;
};

CommentsForm.prototype.validateName = function (){
	var name = this.getName();
	if (name == "" || name == undefined){
		this.messages.push(this.errorMessages.name);	
	} 
};

CommentsForm.prototype.validateMail = function (){
	var mail  = this.getMail();
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(mail)) {
		this.messages.push(this.errorMessages.mail);
	}
};

CommentsForm.prototype.validateMessage = function (){
	var message = this.getMessage();
	if (message == "" || message == undefined){
		this.messages.push(this.errorMessages.message);	
	}
}

CommentsForm.prototype.validateCaptcha = function (){
	if (this.isLoggedIn == true){
		return true;
	}
	var postData = {
		item_id	: this.getItemId(),
		captcha	: this.getCaptcha()
	};

	var result = null;
	$.ajax({
		url			: baseURL + 'comments_controller/ajax_validate_captcha',
		async		: false,
		cache 		: false,
		data		: postData,
		dataType	: 'json',
		type 		: 'post',
		success		: function(data){
			result = data;
		}
	});

	if (result == null || result == false){
		this.messages.push(this.errorMessages.captcha);
	}
}


CommentsForm.prototype.getFormData = function (){
	var data = {
		item_id : this.getItemId(),
		name	: this.getName(),
		mail	: this.getMail(),
		message	: this.getMessage(),
		captcha : this.getCaptcha()
	};
	if (this.getMessagingSubscribe() != null){
		data.messaging_subscribe = this.getMessagingSubscribe();
	}
	return data;
};

CommentsForm.prototype.setCommentsList = function (commentsList){
	this.commentsList = commentsList;
};

CommentsForm.prototype.setSubmitAction = function (){
	var _this = this;
	$(this.formContainer).submit(function (event){
		_this.submitComment();
		event.preventDefault();
	});
};

CommentsForm.prototype.getItemId = function (){
	return $(this.itemIdContainer).val();
};
CommentsForm.prototype.getName = function (){
	return $(this.nameContainer).val();
};
CommentsForm.prototype.getMail = function (){
	return $(this.mailContainer).val();
};
CommentsForm.prototype.getMessage = function (){
	return $(this.messageContainer).val();
};
CommentsForm.prototype.getCaptcha = function (){
	return $(this.captchaContainer).val();
};
CommentsForm.prototype.getMessagingSubscribe = function (){
	if ($(this.messagingSubscribeContainer).attr('checked')){
		return $(this.messagingSubscribeContainer).val();
	}
	return null;
};
function CommentsList(params){
	this.container = '#comments_zone .comment_list';
	this.paginationContainer = '#commentsPagination';
	this.start = 0;
	this.limit = 10;
	this.page = params.page != undefined ? params.page : 0;
	this.item_id = params.item_id != undefined ? params.item_id : -1;

	this.showList();
};

CommentsList.prototype.showList = function(page){
	page = page != undefined ? page : 1;
	this.setPage(page);
	this.getComments();
	this.showPagination();
};

CommentsList.prototype.getLastPage = function (){
	var result = 1;
	var _this = this;
	$.ajax({
		url			: baseURL + 'comments_controller/ajax_get_last_page',
		async		: false,
		cache 		: false,
		data		: {item_id : _this.item_id, limit : _this.limit},
		dataType	: 'json',
		type 		: 'post',
		success		: function(data){
			result = data;
		}
	});
	return result;
};

CommentsList.prototype.setPage = function (page){
	this.page = page;
	this.start = (page * this.limit) - this.limit;
};

CommentsList.prototype.showPagination = function (){
	var _this = this;
	$.ajax({
		url			: baseURL + 'comments_controller/ajax_get_pagination',
		async		: true,
		cache 		: false,
		data		: {item_id : _this.item_id, page : _this.page, limit : _this.limit},
		dataType	: 'html',
		type 		: 'post',
		success		: function(data){
			$(_this.paginationContainer).html(' ');
			$(_this.paginationContainer).append(data);
			$(_this.paginationContainer).find('a').click(function (event){
				var page = $(this).attr('href');
				if (page.indexOf('javascript://p') != -1){
					page = page.replace('javascript://p', '');
					_this.showList(page);
				}
				event.preventDefault();
			});
		}
	});
};

CommentsList.prototype.displayComments = function (comments){
	var _this = this;

	this.resetContainer();
	$('#comments_list_container').css('display', 'block');

	if (comments.length < 1) {
		$('#comments_zone h2').after($(document.createElement('h3')).text('Nu exista comentarii pe acest articol.'));
		$('#comments_list_container').css('display', 'none');
	} else { 
		$('#comments_list_container').css('display', 'block');
		$.each(comments, function (i, n){
			$(_this.container).append(_this.renderComment(n, i));
		});
	}
};

CommentsList.prototype.renderComment = function (comment, index){
	var background = (index % 2) == 0 ? '#FFF' : '';
	return $(document.createElement('li')).css('background-color', background)
				.append($(document.createElement('strong')).text(" " + comment.name + " "))
				.append($(document.createElement('span')).text(" " + comment.time + " "))
				.append($(document.createElement('strong')).text(' în ' + comment.date + " "))
				.append(
					$(document.createElement('div')).addClass('dark')
					.append($(document.createElement('div')).text(' '))
					.append($(document.createElement('img')).attr('src', comment.gravatar).attr('style', 'width: 32px; height: 32px').attr('alt', 'gravatar'))
					.append($(document.createElement('p')).html(comment.message))
				);
};

CommentsList.prototype.resetContainer = function (){
	$(this.container).html(' ');
};

CommentsList.prototype.getComments = function (){
	var _this = this;
	$.ajax({
		url			: baseURL + 'comments_controller/ajax_get_comments',
		async		: true,
		cache 		: false,
		data		: {item_id : _this.item_id, start : _this.start, limit : _this.limit},
		dataType	: 'json',
		type 		: 'post',
		success		: function(data){
			_this.displayComments(data);
		}
	});
};

