var UserId = "";

function refreshCommentsContent( args ){
    $.get("/ajax/comments/" + args + "&rnd=" + Math.random(),function(data) {
		$("#comments_content").html(data);
		//comment_controls(UserId);
	});
	/*try{
		ajax_loadContent("comments_content", "/ajax/comments/" + args + "&rnd=" + Math.random(), ajaxWaitContent);
    }
    catch(er){}*/
}

function refreshCommentsContentFirstPage(text){
	refreshCommentsContent("?material_code=" + MaterialCode + "&page=1");
}

function disableSubmit(){
	document.getElementById("SubmitBtnId").disabled = true;
	document.getElementById("ReloadBtnId").disabled = true;
}

function enableSubmit(text){
	document.getElementById("SubmitBtnId").disabled = false;
	document.getElementById("ReloadBtnId").disabled = false;
	document.getElementById('SubmitBtnId').src = '/img/comments/send.gif';
}

function comment_controls(id){
	console.debug(id);
	UserId = id;
	var images = document.getElementsByTagName("img");
	
	for(var i = 0; i < images.length; i++){
		if(images[i].className == "comments_user"){
			console.debug(images[i].id);
			if(images[i].id != id + "_del" && images[i].id != id + "_edit"){
				 images[i].src = images[i].src.replace(/_active/,"_inactive");
				 images[i].onclick = null;
				 images[i].style.cursor = "auto";
			}
		}
	}
}

function comment_shorten(){
	try{
		var divs = document.getElementsByTagName("div");
		for(var i = 0; i < divs.length; i++){
			if(divs[i].className == "opinion" && divs[i].innerHTML.length > 350){
				if(divs[i].id.indexOf("op_") >= 0){
					id = divs[i].id.replace(/op_/,"");
					
					text = getInnerText(divs[i]).substring(0,300) + "…";
					wrapper = document.getElementById("wrapper_" + id);
					divs[i].style.display = "none";
					
					var short_item = document.createElement("div");
					short_item.id = "short_" + id;
					short_item.className = "opinion";
					short_item.innerHTML = text + "<img src='/img/comments/show_full.gif' class='shortener' alt='развернуть комментарий' caption='развернуть комментарий' onclick='showFullShortComment(\"" + id + "\",\"full\")'/>";
					wrapper.appendChild(short_item);
					
					var full_item = document.createElement("div");
					full_item.id = "full_" + id;
					full_item.innerHTML = divs[i].innerHTML + "<img src='/img/comments/show_short.gif' class='shortener' alt='свернуть комментарий' caption='свернуть комментарий' onclick='showFullShortComment(\"" + id + "\",\"short\")'/>";
					full_item.className = "opinion";
					full_item.style.display = "none";
					wrapper.appendChild(full_item);
				}
			}
		}
	}catch(ex){}	
}

function showFullShortComment(id,type){
	var shortObj = document.getElementById("short_" + id);
	var fullObj = document.getElementById("full_" + id);
	if(type == "full"){
		shortObj.style.display = "none";
		fullObj.style.display = "block";
	}
	else{
		shortObj.style.display = "block";
		fullObj.style.display = "none";
	}
}

function onCommentDeleted(text){
	if(text.indexOf("OK") >= 0){
		refreshCommentsContentFirstPage("");
		alert("Комментарий удален");
	}
	else alert("Вы не можете удалить этот комментарий");
}

function submitAjaxComment(editcode){
	code = typeof(code) != 'undefined' ? code : 42;

	/*sl = tinyMCE.activeEditor.selection;
	sl.collapse(false);
	
	tinyMCE.triggerSave(false, true);*/
	textvalue = FCKeditorAPI.GetInstance('FCKeditor1').GetXHTML(true);
	
	if(textvalue.length > 0){
		disableSubmit();
		
		text = 'text=кот.' + encodeURIComponent(textvalue);
		matcode = 'matcode=' + MaterialCode;
		edit = document.getElementById('EditCommentInputId').value;
		action = '';
		if(edit != ""){ 
			editcode = 'code=' + edit;
			action = 'action=alt';
		}
		
		makePOSTRequest('/ajax/comments/submit/Submit.aspx',matcode + '&' + text + '&' + action + '&' + editcode,onCommentSubmit);

	}
	else alert("Вы не ввели текст своего комментария");
}

function onCommentSubmit(text)
{
	if( text.indexOf("ERROR") >= 0 ) alert("Произошла ошибка при создании комментария. Попробуйте опубликовать его заново.");
	else if( text.indexOf("REGISTER") >= 0) alert("Зарегистрируйтесь на сайте, чтобы оставлять комментарии.");
	else{
		//tinyMCE.get('CommentsEditor').setContent('');
		//document.getElementById('EditCommentInputId').value = '';
		FCKeditorAPI.GetInstance('FCKeditor1').SetHTML( "" );
		refreshCommentsContentFirstPage('');
	}
	enableSubmit(text);
}

function comment_del(id){
	if( confirm("Вы уверены, что хотите удалить этот комментарий?") ){
		makePOSTRequest('/ajax/comments/submit/Submit.aspx','action=del&matcode=' + MaterialCode + '&code=' + id,onCommentDeleted);
	}
}

function comment_edit(id){
	//tinyMCE.triggerSave(false, true);
	if(FCKeditorAPI.GetInstance('FCKeditor1').GetXHTML(true).length > 0){
		if(!confirm("В поле ввода комментрия присутствует текст. Редактирование другого комментария удалит этот текст без возможности его последующего восстановления. Вы действительно хотите редактировать комментрий?")) return;
	}
	//tinyMCE.get('CommentsEditor').setContent('');
	//tinyMCE.get('CommentsEditor').setContent(document.getElementById("op_" + id).innerHTML);
	FCKeditorAPI.GetInstance('FCKeditor1').SetHTML( document.getElementById("op_" + id).innerHTML );
	document.getElementById('EditCommentInputId').value = id;
	document.getElementById('SubmitBtnId').src = '/img/comments/edit.gif';
}

function comment_citate(id,user){
	var citate = getInnerText(document.getElementById("op_" + id));
	if(citate.length > 250) citate = citate.substring(0,250) + "...";
	
	if(citate.length > 0){
		if(user != "") user = "<b>" + user + ":</b><br/>";
		citate = "<div>" + user + citate + "</div><br/>";
		FCKeditorAPI.GetInstance('FCKeditor1').Focus();
		FCKeditorAPI.GetInstance('FCKeditor1').InsertHtml(citate);
	}
	else{alert("Текст для комментирования пустой или состоит из других комментариев.");}
}

function comment_to(user)
{
	FCKeditorAPI.GetInstance('FCKeditor1').Focus();
	FCKeditorAPI.GetInstance('FCKeditor1').InsertHtml("<b>Для " + user + ":</b> ");
}

function getInnerText(elt) {
	var _innerText = elt.innerHTML.replace(/<div>(.*?)<\/div>/gi," ");
	_innerText = _innerText.replace(/<[^>]+>/g," ");
	return _innerText;
}

function fillCommentsCount(n){
	try{
		var obj = document.getElementById("comments_count");
		if(n > 0 && obj != null) obj.innerHTML = "&nbsp;(" + n + ")";
	}
	catch(E){}
}