$(function()
{
	var controller = $('input:hidden#controller').val();

	$.fn.extend({
		apply_admin_clicks : function()
		{
			return this.find('.edit_comment').click(edit_comment_click).end()
				.find('.delete_comment, .restore_comment').click(delete_comment_click).end();
		}});
	
	function edit_comment_click()
	{
		$('.jGrowl-notification > .close').click();
		var comment_id = /comment_([0-9]+)/.exec($(this).parent().parent().parent().attr('id'))[1];
		if ($('#comment_'+comment_id).siblings('div').is('> form')) { // форма уже есть
			$('#comment_'+comment_id).siblings('div').remove();
		}
		else {
			$.getJSON(controller+'/edit_comment/'+comment_id.toString(), {}, function(response)
			{
				if (response.error != '') {
					$.jGrowl(response.error, {theme: 'error_message', 'header' : 'Ошибка', sticky: true});
				}
				else {
					ajaxFormOptions = {
							'dataType' : 'json',
							'clearForm' : true,
							'beforeSubmit' : function() 
							{
								$('.jGrowl-notification > .close').click();
								return true;
							},
							'success' : function(response)
							{
								if (response.error != '') {
									$.jGrowl(response.error, {theme: 'error_message', 'header' : 'Ошибка', sticky: true});
								}
								else {
									// заменяем новым комментом старый и скрываем форму
									$('#comment_'+comment_id).parent().find(' > #comment_edit_form, > .comment')
														 .remove()
														 .end()
														 .prepend(response.comment)
														 .find('.comment')
														 .apply_admin_clicks()
														 .apply_user_clicks();
								}
							}
					};
					$(response.form).insertAfter($('#comment_'+comment_id));
					$('#comment_edit_form > form').ajaxForm(ajaxFormOptions)
												  .find('textarea').fck({toolbar: 'Basic', height: 150});
				}
			});
		}
		return false;
	}
	
	function delete_comment_click()
	{
		var comment_id = /comment_([0-9]+)/.exec($(this).parent().parent().parent().attr('id'))[1];
		var _delete = $(this).hasClass('delete_comment');
		if (comment_id) {
			$.post(controller+'/delete_comment', {'id' : comment_id, 'delete' : _delete ? 1 : 0}, function(response)
			{
				if (response.error != '') {
					$.jGrowl(response.error, {theme: 'error_message', 'header' : 'Ошибка', sticky: true});
				}
				else {
					$('#comment_'+comment_id).parent().find('> .comment').remove()
					 .end()
					 .prepend(response.comment)
					 .find('.comment')
					 .apply_admin_clicks()
					 .apply_user_clicks();
				}
			}, 'json');
		}
		return false;
	}
	
	$('.comment_admin > .edit_comment').click(edit_comment_click);
	$('.comment_admin > .delete_comment, .comment_admin > .restore_comment').click(delete_comment_click);
});
