/* (c) 2008-2012, Nikiforov Vladimir aka Volod */

function toggleCommentFormConsole()
{
	$("#comment_form_console").toggle();
}

function quoteComment(comment_id)
{
	$.get('/comments/single', {quote: 1, comment_id: comment_id}, function(data)
	{		
		c = $('#CommentForm textarea[name=comment]');
		val = c.val();
		if (val != '') val += "\n\n";
		c.val(val + data + "\n").focus();
		quote_name = last_name;
	});
}

function rollbackComment(cid)
{
	$.getJSON('/comments/edit/rollback', {comment_id: cid}, function(data)
	{
		if (data['status'] == 'ok')
		{
			if (!loadComments(data['otd_id'], -1))//BUG! but I don't know, how to get _current_ PAGE!
			{
				document.location = '/comments/show?comment_id='+data['comment_id'];
				return;
			}
		}
		else	
		{
			alert(data['status']);
		}
	});
}

function afterSubmit()
{
	res = $('#comment_form_console').contents().find('body').html();
	if (res == '') return;//on page init
	data = eval('('+res+')');
	if (data['status'] == 'ok') 
	{
		loadComments(data['otd_id'], -1);//все хорошо
		if (!$('#div_comm_list').length)//div_comm_list does not exist on page
		{
			document.location = '/comments/show?comment_id='+data['comment_id'];
			return;
		}	
	}
	else if (data['status'])
	{
		alert(data['status']);//статус не ок, но хотя бы распарсился.
	}
	else
	{
		alert(res);//если там нет JSON вообще, то выводим, чё есть
	}
	f = document.getElementById('CommentForm');
	f.comment.value = '';
	if (f.c_image_file)
	{
		f.c_image_file.value = '';
	}
	if (f.file_url)
	{
		f.file_url.value = '';
	}
	addComment();
}

function editComment(c)
{
	f = document.getElementById('CommentForm');
	f.action = '/comments/edit/modify';
	f.comment_id.value = c;
	f.b1.value = 'Отправить исправленный вариант комментария';
	f.b2.style.visibility = '';
	$.get('/comments/single', {comment_id: c}, function(data)
		{
			f = document.getElementById('CommentForm');
			f.comment.value = data;
			f.comment.focus();
		});	
}

function addComment()
{
	f = document.getElementById('CommentForm');
	f.action = '/comments/edit/add';
	f.comment_id.value = 0;
	f.b1.value = 'Отправить комментарий';
	f.b2.style.visibility = 'hidden';
	f.comment.value = '';
}

function submitComment(form)
{
	//var form = document.CommentForm;
	//потому, что этот скрипт используется для создания OTD
	// у которого это поле не comment, а description (name=description id='comment' !!!)
	comment = document.getElementById('comment');
	//для незарегинных поля имя файла нет вообще и его не надо проверять
	//если оно есть И оно заполнено, то коммент можно не вводить!
	ok = false;//допустим, что все плохо
	if ((form.c_image_file != null && form.c_image_file.value != '') || form.file_url != '')//юзер авторизованный и ввел картинку
		ok = true;//хорошо
	if (comment.value != '')//ввел коммент
		ok = true;//тоже хорошо
	if (!ok)//а вот если не сделал ни того ни другого, то шиш ему
	{
		alert('Вы не ввели сообщение!');
		return false;
	}
	if (form.user_id.value == '0')
	{
		setCookie('user_name', form.user_name.value);
		setCookie('user_email', form.user_email.value);
		
		if (form.confirm_num.value == '')
		{
			alert('Вы не ввели код подтверждения!');
			return false;
		}		
		$.get('/comments/edit/checkConfirmImg', {
			confirm_num: form.confirm_num.value,
			confirm_key: form.confirm_key.value
		}, function(data){
			(data == 0) ? alert("Код подтверждения неверный") : document.CommentForm.submit();
		});
		return false;
	}
	hideCommentPreview();
	form.submit();
	return false;
}

function removeAttach(comment_id, f)
{
	$.getJSON('/comments/edit/removeAttach', {comment_id: comment_id, f: f}, function(data)
	{
		if (data['status'] == 'ok')
		{
			loadComments(data['otd_id'], -1);//BUG! but I don't know, how to get _current_ PAGE!
		}
		else
		{
			alert(data['status']);
		}
	});
}

function showCommentPreview()
{
	$('#preview_h').show();
	$('#preview').show().load('/comments/single/previewBbcode', {comment: escape($('#comment').val())});
}	

function hideCommentPreview()
{
	$('#preview_h').hide();
	$('#preview').hide();
}

function showParentComment(otd_id, comment_id, comment_n, bbcode)
{
	$('#p_c' + comment_id).fadeIn(300).load('/comments/single', {
		bbcode: bbcode,
		navigation: 1,
		ref_comment_id: comment_id,
		otd_id: otd_id, //to define comment_id by otd_id and comment_n
		comment_n: comment_n});
	return;
}

function hideParentComment(comment_id)
{
	$('#p_c' + comment_id).fadeOut(300);
}

function showHiddenComment(comment_id, ask)
{	
	e = $('#hiddencomment' + comment_id);
	if (e.height() > 0)
	{
		return;
	}
	if ((ask == 1) && !confirm("Этот комментарий может содержать оскорбительные слова или изображения. Вы уверены, что хотите его просмотреть?"))
	{
		return;
	}	
	$('#c_env' + comment_id).show();
	$('#c_hidden' + comment_id).hide();
	e.load('/comments/single', {bbcode:1, comment_id: comment_id});
}

function openCommentVisibleDialog(cid, hbl)
{
	d = $('#commenthidedialog' + cid);
	
	if (d.css('display') == 'block')
	{
		d.fadeOut(300);
	}
	else
	{
		$('.commenthidedialog').hide();
		d.show().load("/comments/edit/getHideForm", {
			cid: cid, hbl: hbl
		});
	}	
}

function hideComment(hidden, cid)
{
	hbl = document.getElementById('c' + cid + 'hidden_by_level');
	f = document.getElementById('commenthideform' + cid);
	if (f.hidden_by_level.length > 0)
	{
		for (i=0; i < f.hidden_by_level.length; i++)
			if (f.hidden_by_level[i].checked)
				hbl = f.hidden_by_level[i];
	}
	else
	{
		hbl = f.hidden_by_level;
	}
	
	$('#commenthidestatus' + cid)
		.show()
		.load('/comments/edit/hide',
		{
			comment_id: cid,
			hidden: hidden,
			hidden_by_level: hbl.value
		});
	$('#commenthidediv' + cid).fadeOut(600);
}

function removeComment(comment_id)
{
	if (1 || confirm("Уверены?"))
	{//JSON
		$.getJSON('/comments/edit/remove', {comment_id: comment_id}, function(data)
		{
		//alert(data);
			if (data['status'] == 'ok')
			{
				$('#c_env'+data['comment_id']).hide();
			}
			else
			{	
				alert(data['status']);
			}
		});
	}
}

function loadComments(id, page)
{
	changeIconAndTitle(saved_window_title, '');
	l = $('#div_comm_list');
	if (l.length)//if div_comm_exists 
	{
		if (l.html() == '') //чтобы при переходе между страницами не блЫмкало
		{
			l.html('Загружаются комментарии...<br />' + LOAD_INDICATOR);
		}
		l.load('/comments/otd?id='+id+'&page='+page);
	}
}

function loadCommentForm(id)
{
	l = $('#div_comm_form');
	if (l.html() == '') //чтобы при переходе между страницами не блЫмкало
	{
		l.html('Загружается форма...<br />' + LOAD_INDICATOR);
	}
	l.load('/comments/form?id='+id);
}

function hideTopicPreview(topic_id)
{
	$('#topic_preview_' + topic_id).hide();
}

function showTopicPreview(topic_id, comment_id, need_switch)
{
	p = $('#topic_preview_' + topic_id);
	
	if (need_switch == 1 && p.css('display') != 'none')
	{
		p.hide();	
	}
	else
	{
		p.show();
		if (comment_id > 0)
		{
			p.load('/comments/single/index', {
				bbcode: 1,
				prev_next_links: 1,				
				comment_id: comment_id
			});
		}
		else
		{
			p.load('/forum/topic/getSingle', {
				bbcode: 1,
				topic_id: topic_id
			});
			//alert('not implemented!');
		}		
	}
}

function showMessageForm(comment_id, author_id)
{
	$('#div_MessageForm_'+comment_id).show().load('/users/messages/getForm', {
		author_id: author_id,
		object_to_hide: '#div_MessageForm_'+comment_id
	});
}
