$(function()
{
	$('div.hiddencontainer').hide();
	$('div.reply a').click(reply_click);
	function reply_click()
	{
		$('div#replyform')
		.appendTo($(this).parent().parent().parent())
		.show()
		.find('input:hidden[@name=replyto]')
		.val($(this).attr('id'))
		.end();
		$('.hiddencontainer').hide();
		$('#writecomment').html('Написать комментарий');
		return false;
	}

	var currentBlock = null;
	var ajaxFormOptions = {
		'dataType' : 'json',
		'beforeSubmit' : function()
		{
			if ($('#replyform form textarea').val() == '') {
				return false;
			}
			$('.jGrowl-notification > .close').click();
			$('#replyform input:submit').attr('disabled', true);
			return true;
		},
		'success' : function(response)
		{
			if (response.error != '') {
				$.jGrowl(response.error, {theme: 'error_message', 'header' : 'Ошибка', sticky: true});
			}
			else {
				var commentCode = "<li>"+response.comment+"</li>";
				var comment_id = /comment_([0-9]+)/.exec($(commentCode).find('.comment').attr('id'))[1];
				var childUl = $(currentBlock).find('> ul.root');
				if ( childUl.length > 0 ) {
					$(childUl).append(commentCode).find('li:last div.reply a').click(reply_click);
				}
				else {
					if ( $(currentBlock).attr('class') == 'commentstree' ) {
						$(currentBlock).prepend('<ul class="root">'+commentCode+'<\/ul>').find('ul.root > li div.reply a').click(reply_click);
					}
					else {
						$(currentBlock).append('<ul class="root">'+commentCode+'<\/ul>').find('ul.root > li div.reply a').click(reply_click);
					}
				}
				FCKeditorAPI.GetInstance('comment_content').SetHTML('');
				$('#comment_content').val('');
				$('div#replyform').appendTo('div.hiddencontainer').parent().hide();
				comment_area_visible = false;
				$('#writecomment').html('Написать комментарий');
				if ($.isFunction($.fn.apply_admin_clicks)) {
					$('#comment_'+comment_id).apply_admin_clicks();
				}
			}
			if (response.new_captcha != undefined) {
				$('#comment_captcha').html(response.new_captcha);
			}
			$('#captcha_text').val('');
			$('#replyform input:submit').removeAttr('disabled');
		}
	};

	$.fck.path = '/static/fckeditor/';
	$('#replyform form')
	.ajaxForm(ajaxFormOptions)
	.find('input:submit')
	.click(function() { currentBlock = $(this).parent().parent().parent().parent().parent(); }).end()
	.find('textarea').fck({toolbar: 'Basic', height : 150});

	var comment_area_visible = false;
	$('#writecomment').click(function()
	{
		comment_area_visible = !comment_area_visible;
		if ( !comment_area_visible ) {
			$('div.hiddencontainer').hide(100);
		}
		$('#replyform')
		.appendTo('div.hiddencontainer')
		.find('form > input:hidden[@name=replyto]')
		.val('');
		if ( comment_area_visible ) {
			$('div.hiddencontainer').show(100);
		}
		if ( comment_area_visible ) {
			$(this).text('Я не хочу писать комментарий');
		}
		else {
			$(this).text('Написать комментарий');
		}
		return false;
	});

	$('div.cb_h2 > i > a').click(hide_show_comment_click);

	$.fn.extend({
		apply_user_clicks: function()
		{
			return this.find('div.cb_h2 > i > a').click(hide_show_comment_click).end()
				.find('.cb_h span.voting:not(.selected)').click(comment_vote_click).end();
		}
	});
	
	function hide_show_comment_click()
	{
		try
		{
			var post_block = $(this).parent().parent().next().toggle();
			if ($(post_block).css('display') != 'none')
			{
				$(this).text('скрыть');
				$(post_block).prev().removeClass('cb_h2')
						    .addClass('cb_h')
						    .find('span.voting:not(.selected)')
						    .click(comment_vote_click);
			}
			else
			{
				$(this).text('показать');
				$(post_block).prev().removeClass('cb_h')
						    .addClass('cb_h2')
						    .find('span.voting:not(.selected)')
						    .click(function(){});
			}
		}
		finally {
			return false;
		}
	}

	function comment_vote_click()
	{
		var comment_id = /([0-9]+)$/.exec(this.id)[1];
		var comment_mark = $(this).is('.plus') ? 1 : -1;
		var elem = $(this);
		var submit_address = $('#vote_submit_address').val();
		if (submit_address.length > 0)
		{
			$.post(submit_address, {'id': comment_id, 'target': 'comment', 'mark': comment_mark}, function(response)
			{
				if (response.error != '') {
					$.jGrowl(response.error, {theme: 'error_message', 'header' : 'Ошибка'});
				}
				else {
					var threshold = parseInt($('#comment_threshold').val());

					elem.parent().children('span').each(function() {
						$(this).addClass('selected').click(function() {});
					}).parent().find('span.' + (comment_mark == 1 ? 'mins' : 'plus')).removeClass('active');

					// changing post rating
					$('#comment_rating_'+comment_id.toString()).text(response.rating.toString());
					if (response.rating < threshold)
					{
						var comment = $('#comment_'+comment_id.toString()+' > .cb_h')
						var obj = $(comment).append('<i>[рейтинг ниже порога просмотра, <a href="#">показать</a>]</i>')
											       .find('> i >a')
											       .click(hide_show_comment_click);
						$(obj).click();
					}
					$(elem).parent().find('span.voting').click(function(){});
				}
			}, 'json');
		}
	}

	$('.cb_h span.voting:not(.selected)').click(comment_vote_click);
});
