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

var txt = '';
var txt_quot = '';
var last_name = '';
var quote_name = '';
var quote = '';

//глобальный массив, заполняется из PHP сода по мере вывода комментов
//ключ массива - comment_id
//каждый элемент - объект с полями name и gender
var user_names = new Array();

function insertAtCaret(textObj, textFieldValue)
{
	if (document.all)
	{
		if (textObj.createTextRange && textObj.caretPos && !window.opera)
		{
			var caretPos = textObj.caretPos;
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?textFieldValue + ' ' : textFieldValue;
		}
		else
		{
			textObj.value += textFieldValue;
		}
	}
	else
	{
		if (textObj.selectionStart)
		{
			var rangeStart = textObj.selectionStart;
			var rangeEnd = textObj.selectionEnd;
			var tempStr1 = textObj.value.substring(0, rangeStart);
			var tempStr2 = textObj.value.substring(rangeEnd, textObj.value.length);
			textObj.value = tempStr1 + textFieldValue + tempStr2;
			textObj.selectionStart = textObj.selectionEnd = rangeStart + textFieldValue.length;
		}
		else
		{
			textObj.value += textFieldValue;
		}
	}
}

function insert_text(open, close, endline)
{
	msgfield = document.getElementById('comment');
	// IE support
	if (document.selection && document.selection.createRange)
	{
		msgfield.focus();
		sel = document.selection.createRange();
		sel.text = open + sel.text + close;
		msgfield.focus();
	}
	// Moz support
	else if (msgfield.selectionStart || msgfield.selectionStart == '0')
	{
		var startPos = msgfield.selectionStart;
		var endPos = msgfield.selectionEnd;
		msgfield.value = msgfield.value.substring(0, startPos) + open + msgfield.value.substring(startPos, endPos) + close + msgfield.value.substring(endPos, msgfield.value.length);
		p = endPos + open.length + close.length;
		if (endline)
		{
			p -= 9 + quote_name.length;
		}
		if (startPos == endPos)
		{
			p -= close.length;
		}
		msgfield.selectionStart = msgfield.selectionEnd = p;
		msgfield.focus();
	}
	// Fallback support for other browsers
	else
	{
		msgfield.value += open + close;
		msgfield.focus();
	}
	return;
}

function get_selected_text()
{
	var msgfield = document.getElementById('comment');
	var s = '';
	if (document.selection && document.selection.createRange)
	{
		s = document.selection.createRange().text;
	}
	else if (msgfield.selectionStart || msgfield.selectionStart == '0')
	{
		s = msgfield.value.substring(msgfield.selectionStart, msgfield.selectionEnd);
	}	
	return s;
}

function copy_quote(cid)
{
	name = user_names[cid].name;
	gender = user_names[cid].gender;
	txt = '';
	if (document.getSelection)
	{
		txt = window.getSelection();
	}
	else if (document.selection)
	{
		txt = document.selection.createRange().text;
	}else if (window.getSelection)
	{
		txt = window.getSelection().toString();
	} 
	txt_quot = txt;
	if (gender != '')
	{
		name += '|' + gender;
	}
	txt = '[quote=' + name + ']' + txt + '[/quote]\n';
	last_name = name;
}

function paste_quote()
{
	if (txt_quot != '' && document.getElementById('comment'))
	{
		e = document.getElementById('comment');
		insertAtCaret(e, txt);
		e.focus();
		quote_name = last_name;
	}
	else
	{
		alert('Выделите мышью текст, который хотите процитировать!');
	}
}

function hide_all_boards()
{
	$('#colorboard').hide();
	$('#sizeboard').hide();
	$('#attrboard').hide();
	$('#smileboard1').hide();
	$('#smileboard2').hide();
}

function tag_emotion(emo)
{
	insert_text(' ' + emo + ' ', "", false);
	hide_all_boards();
}

function open_board(n)
{
	c = $('#'+n);
	if (c.css('display') == 'none')//check first, than - hide_all()!
	{
		hide_all_boards();
		c.show();
	}
	else
	{
		hide_all_boards();
	}
}

function tag_color(color)
{
	insert_text("[color=" + color + "]", "[/color]", false);
	hide_all_boards();
}

function tag_size(size)
{
	insert_text("[size=" + size + "]", "[/size]", false);
	hide_all_boards();
}

function tag_attr(attr)
{
	insert_text("["+attr+"]", "[/"+attr+"]", false);
	hide_all_boards();
}

function tag_quot()
{
	insert_text("[quot]", "[/quot]", false);
}

function tag_url()
{	
	var seltext = get_selected_text();
	var u = prompt("URL ссылки", (seltext.indexOf('http://') >= 0) ? seltext : 'http://');
	if (!u) return;
	if (seltext == '')
	{
		var n = prompt("Название страницы", 'ссылка');
		if (!n) return;
		insert_text("[url=" + u + "]" + n + "[/url]", "", false);
	}
	else
	{
		insert_text("[url=" + u + "]", "[/url]", false);
	}
}

function tag_img()
{
	var seltext = get_selected_text();
	var u = prompt("URL изображения", (seltext.indexOf('http://') >= 0) ? seltext : 'http://');
	if (u)
	{
		(seltext == '') ? insert_text("[img]" + u + "[/img]", "", false) : insert_text("[img]", "[/img]", false);
	}
}

function replay_to(n, cid)
{
	t = document.getElementById('comment');
	if (t.value != '') t.value += "\n";
	t.value = t.value + '(' + n + '#' + user_names[cid].name + '):';
	scroll_to_comment();
}

function scroll_to_comment()
{
	c = document.getElementById('comment');
	if (c)
	{
		window.scrollTo(0, getBounds(c).top);
		c.focus();
	}
}

function split_quote()
{
	if (quote_name == '')
	{
		alert('Процитируйте хоть кого-нибудь! Разбивается последняя цитата.');
	}
	else
	{
		insert_text("[/quote]\n\n[quote="+quote_name+"]", "", true);
	}
}



///////// new AJAX versions


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!');
		}		
	}
}

