var current_page = 1;
var item_id = 0;

function comments_appreciations(){
	$('#comments_list li .appreciations .score a').click(function() {
		$.metadata.setType('attr', 'metadata');
		var metadata = $.metadata.get(this);

		var obj = $(this).parent().parent().parent().attr('id');
		
		$.ajax({
			url: serverBaseURL + '/index/ajax_appreciations_set',
			type: 'POST',
			data: 'topic_id=' + metadata.topic_id + '&comment_id=' + metadata.comment_id + '&appreciation=' + metadata.appreciation,
			dataType: 'json', 
			success: function(data) {
				if(data.length > 0) {
					$('#comments_list li#' + obj + ' .appreciations .score').fadeOut("normal");
					$('#comments_list li#' + obj + ' .appreciations .average').html('(' + data[0].appreciation + '/5)');
					$('#comments_list li#' + obj + ' .appreciations .score').fadeIn("normal");
				}
			}
		});
		
		return false; 
	});
}

function comments_ratings(){
	$('#comments_list li .ratings .plus a').click(function() {
		$.metadata.setType('attr', 'metadata');
		var metadata = $.metadata.get(this);
		
		var obj = $(this).parent().parent().parent().attr('id');
		
		$.ajax({
			url: serverBaseURL + '/index/ajax_ratings_set',
			type: 'POST',
			data: 'topic_id=' + metadata.topic_id + '&comment_id=' + metadata.comment_id + '&rating=1',
			dataType: 'json', 
			success: function(data) {
				if(data.length > 0) {
					$('#comments_list li#' + obj + ' .ratings .plus').fadeOut("normal");
					$('#comments_list li#' + obj + ' .ratings .plus-score').html(data[0].plus_rating);
					$('#comments_list li#' + obj + ' .ratings .plus').fadeIn("normal");
				}
			}
		});
		
		return false; 
	});
	
	$('#comments_list li .ratings .minus a').click(function() {
		$.metadata.setType('attr', 'metadata');
		var metadata = $.metadata.get(this);
		
		var obj = $(this).parent().parent().parent().attr('id');
		
		$.ajax({
			url: serverBaseURL + '/index/ajax_ratings_set',
			type: 'POST',
			data: 'topic_id=' + metadata.topic_id + '&comment_id=' + metadata.comment_id + '&rating=-1',
			dataType: 'json', 
			success: function(data) {
				if(data.length > 0) {
					$('#comments_list li#' + obj + ' .ratings .minus').fadeOut("normal");
					$('#comments_list li#' + obj + ' .ratings .minus-score').html(data[0].minus_rating);
					$('#comments_list li#' + obj + ' .ratings .minus').fadeIn("normal");
				}
			}
		});
		
		return false; 
	});
}

function comments_reports() {
	$('#comments_list li .reports .button a').click(function() {
		$.metadata.setType('attr', 'metadata');
		var metadata = $.metadata.get(this);
		
		obj = $(this).parent().parent().parent().attr('id');

		$.ajax({
			url: serverBaseURL + '/index/ajax_reports_set',
			type: 'POST',
			data: 'topic_id=' + metadata.topic_id + '&comment_id=' + metadata.comment_id,
			dataType: 'json', 
			success: function(data) {
				if(data.length > 0) {
					$('#comments_list li#' + obj + ' .reports .button').fadeOut("normal");
					$('#comments_list li#' + obj + ' .reports .score').html('(' + data[0].report + ')');
					$('#comments_list li#' + obj + ' .reports .button').fadeIn("normal");
				}
			}
		});
		
		return false; 
	});
}

function comments_pagination(options){
	var options = $.extend( {}, {}, options);

	var page = options.page?options.page:1;
	var total = options.total?options.total:1;
	var limit = options.limit?options.limit:1;

	var pages = Math.ceil(total/limit);

	var messagesPerPage = (page*limit < total)?page*limit:total;

	$("#comments_pagination p").html('Mesaje <span>' + messagesPerPage + '</span> / ' + total);

	$("#comments_pagination ul").empty();

	$("#comments_pagination ul").append("<li style="+((page > 1)?'':'display:none')+"><a href='javascript:void(0)' title='Mesaje mai vechi' class='prev'>Mesaje mai vechi</a></li>");
	
	var perPage = (pages <= 10)?pages:10;

	for(i = page; i < page + perPage; i++) {
		//linkClassName = (i == page)?'activ':'';
		$("#comments_pagination ul").append("<li><a href='javascript:void(0)'>" + i + "</a></li>");
	}

	$("#comments_pagination ul").append("<li style="+((page*limit < total)?'':'display:none')+"><a href='javascript:void(0)' title='Mesaje mai noi' class='next'>Mesaje mai noi</a></li>");

	$("#comments_pagination ul a").each(function(i){
		if (i == 0) {
			var p = (page <= perPage)?page-1:(page-perPage);
			var settings = $.extend({}, options, { page: p, start: (p-1)*limit });
		} else if (i == pages + 1) {
			var p = page+perPage;
			var settings = $.extend({}, options, { page: p, start: (p-1)*limit });
		} else {
			var p = (page-1) + i;
			var settings = $.extend({}, options, { page: p, start: (p-1)*limit });
		}
		$(this).attr('metadata', $.toJSON(settings));
	});

	$("#comments_pagination ul a").unbind('click');
	$("#comments_pagination ul a").click(function(event){
		event.preventDefault();

		$.metadata.setType('attr', 'metadata');
		var metadata = $.metadata.get(this);

		comments_list(metadata);
		window.location = "#comments";

		return false;
	});

	$("#comments_pagination ul a").removeClass('activ');
	obj = $('#comments_pagination ul a').get((page-1)*perPage+1);
	$(obj).addClass('activ');

	$("#comments_pagination").show();
}

function comments_list(options) {
	$("#comments_list").hide();
	$("#comments_list").empty();
	$('div#loading').show();
	
	var options = $.extend( {}, {}, options);
	
	var page = options.page?options.page:1;
	
	$.ajax({
		url: options.url,
		type: 'POST',
		data: 'start=' + options.start + '&limit=' + options.limit + '&sort_field=' + options.sort_field + '&sort_order=' + options.sort_order + '&item_id=' + options.item_id + '&cache=' + options.cache + '&cache_timeout=' + options.cache_timeout,
		dataType: 'json',
		success: function(data){
			if(data.comments.length > 0) {
				$('div#loading').hide();
				$('div#no_comment').hide();
				$("#comments_list").empty();

				var t = $.template('<dd><div class="userPic"><img src="http://www.gravatar.com/avatar/${md5_email}?s=85&amp;d=${base_url}/images/avatar.gif" style="width: 85px; height: 85px" alt="gravatar"/></div><p class="userData"><a href="${website}" title="${name}" class="userName"><strong>${name}</strong></a><small>${date} ${hour}</small></p><a href="${website}" title="">${website}</a><p>${message}</p></dd>');
				
				$("#comments_list").append('<dt>Mesaje</dt>');
				
				for(i in data.comments) {
					$("#comments_list").append(t, {
						name: data.comments[i].name,
						title: data.comments[i].title,
						website: (data.comments[i].website.substr(0, 7) == 'http://')?data.comments[i].website:'javascript:void(0)', 
						message: data.comments[i].message,
						md5_email: data.comments[i].md5_email,
						hour: data.comments[i].hour,
						date: data.comments[i].date,
						base_url: baseURL
					});
				}
			
				$("#comments_list").show();
				
				var settings = $.extend( {}, options, { total: data.total });
				
				comments_pagination(settings);
			} else {
				$('div#loading').hide();
				$('div#no_comment').show();
			}
		}
	});
}

function unblock_submit() {
	$('#sbtAddComment').removeAttr('disabled');
}

function comments_form(options) {
	var options = $.extend( {}, {}, options);
	
	$('#form_comment').validate({
		errorPlacement: function(error, element) { 
			error.appendTo(element.parent().parent().addClass("error")); 
		},
		submitHandler: function() {
			$('div#loading').hide();
			$('div#add_loading').show();

			$('#sbtAddComment').attr('disabled', 'disabled');

			$.ajax({
				url: baseURL + '/comments/add',
				type: 'POST',
				data: 'item_id=' + $('#item_id').val() + '&comment_website=' + $('#comment_website').val() + '&comment_title=' + $('#comment_title').val() + '&comment_name=' + $('#comment_name').val() + '&comment_email=' + $('#comment_email').val() + '&comment_message=' + $('#comment_message').val() + '&btnAddComment=true',
				dataType: 'json',
				success: function(data) {
					if(data.error == 0) {
						options.page = 1;
						comments_list(options);
	
						$('#comment_message').val('');
						
						setTimeout('unblock_submit()', 5000);
					} else {
						if(data.validation) {
							msg = data.message + '\n';
							
							for(i in data.validation) {
								msg += data.validation[i] + '\n';
							}
							
							alert(msg);
						} else {
							alert('A aparut o eroare.');
						}
					}
					
					$('div#add_loading').hide();
				}
			});
		},
		rules: {
			comment_name: {
				required: true,
				lettersnumericwithbasicpunc: true,
				minlength: 3,
				maxlength: 255
			},
			comment_email: {
				required: true,
				email: true
			},
			comment_message: {
				required: true,
				lettersnumericwithbasicpunc: true,
				maxlength: 1000
			}
		},
		messages: {
			comment_name: {
				required: "Câmpul <b>nume</b> este obligatoriu.",
				lettersnumericwithbasicpunc: "Câmpul <b>nume</b> trebuie să conţină doar litere, cifre şi semnele de punctuaţie <i>punct</i>, <i>cratimă</i> şi <i>linie jos</i>.",
				minlength: "Câmpul <b>nume</b> trebuie să aibă maxim 3 caractere lungime.",
				maxlength: "Câmpul <b>nume</b> trebuie să aibă maxim 255 caractere lungime."
			},
			comment_email: {
				required: "Câmpul <b>adresă de e-mail</b> este obligatorie.",
				email: "Câmpul <b>adresă de e-mail</b> trebuie să conţină o adresă de e-mail."
			},
			comment_message: {
				required: "Câmpul <b>mesaj</b> este obligatoriu.",
				lettersnumericwithbasicpunc: "Câmpul <b>mesaj</b> trebuie să conţină doar litere, cifre şi semnele de punctuaţie <i>punct</i>, <i>cratimă</i> şi <i>linie jos</i>.",
				maxlength: "Câmpul <b>mesaj</b> trebuie să aibă maxim 1000 caractere lungime."
			}
		}
	});
}
