var sending = 0, replyContainerTmp = '';

function OpenReply(id) {
	Request('Topic', 'GetReply', { id : id }, function (reply) {
		txc = $('rtext'+id);
		txc.innerHTML = reply.htext;
	});
	if ($('replyContainer'+id))
		$('replyContainer'+id).style.display = 'block';
}

function DeleteTopic(id) {
	Request('Topic', 'DeleteTopic', { id : id }, function (reply) {
		document.location.href = '/Forums/'+groupId;
	});
}

function DeleteTopicAsSpam(id) {
	Request('Message', 'Complain', { id : id, reason: 'спам (модерация в сообществе)' }, function (result) { alert('Спасибо, ваша жалоба принята'); });
	DeleteTopic(id);
}

function CloseTopic(id) {
	Request('Topic', 'CloseTopic', { id : id }, function (reply) {
		document.location.reload();
	});
} 

function UncloseTopic(id) {
	Request('Topic', 'UncloseTopic', { id : id }, function (reply) {
		document.location.reload();
	});
} 

function StickTopic(id) {
	Request('Topic', 'StickTopic', { id : id }, function (reply) {
		document.location.reload();
	});
} 

function UnstickTopic(id) {
	Request('Topic', 'UnstickTopic', { id : id }, function (reply) {
		document.location.reload();
	});
} 

function ApproveTopic(id) {
	Request('Topic', 'ApproveTopic', { id : id }, function (reply) {
		document.location.reload();
	});
} 

function DeleteReply(id) {
	
	ReplyTo(topicId + 'hidden');
	
	Request('Topic', 'DeleteReply', { id : id }, function (reply) {
	
		$('rcapt'+id).innerHTML = '(сообщение удалено)';
		$('rtext'+id).parentNode.removeChild($('rtext'+id));
		$('redit'+id).parentNode.removeChild($('redit'+id));
		$('replyContainer'+id).parentNode.removeChild($('replyContainer'+id));
		
	});
	
}

function EditReply(id) {
	$('rtext' + id).style.display = 'none';
	$('redit' + id).style.display = '';
}

function EditReplyDone (id) {
	Request('Topic', 'EditReply',
		{
			id : id,
			text : $('reditarea' + id).value
		}, function (reply) {
		
		if (reply.ok) {
			$('rtext' + /*reply.*/id).innerHTML = $('rimage' + id).innerHTML + reply.processed;;
			$('reditarea' + /*reply.*/id).value = reply.plain;
		}
		
	});
	
	EditReplyCancel(/*reply.*/id);
}

function EditReplyCancel (id) {
	$('rtext' + id).style.display = '';
	$('redit' + id).style.display = 'none';
}


function ReplyTo (id) {
	if (!$('replyContainer' + id))
		return;
	var node = $('replyBox'), parent = node.parentNode;
	parent.removeChild(node);
	parent.innerHTML = replyContainerTmp;
	replyContainerTmp = $('replyContainer' + id).innerHTML;
	$('replyContainer' + id).innerHTML = '';
	$('replyContainer' + id).appendChild(node);
	$('replyTo').value = id;
	try {
		$('replyTextarea').focus();
	}
	catch (e) {
		//IE my ass
	}
}

function Abuse (id) {
	if (!$('replyContainer' + id))
		return;
	var node = $('abuseBox'), parent = node.parentNode;
	parent.removeChild(node);
	parent.innerHTML = replyContainerTmp;
	replyContainerTmp = $('replyContainer' + id).innerHTML;
	$('replyContainer' + id).innerHTML = '';
	$('replyContainer' + id).appendChild(node);
	$('abuse').value = id;
	$('abuseForm').action = '#thread' + id;
}

function ShowAdmin (id) {
	if (!$('replyContainer' + id))
		return;
	var node = $('groupadminBox'), parent = node.parentNode;
	parent.removeChild(node);
	parent.innerHTML = replyContainerTmp;
	replyContainerTmp = $('replyContainer' + id).innerHTML;
	$('replyContainer' + id).innerHTML = '';
	$('replyContainer' + id).appendChild(node);
	$('gaMsg').value = id;
	$('gaAction').selectedIndex = 0;
}

function MemberChange() {
	Request('Topic', 'MemberChange',
		{
			msg: $('gaMsg').value,
			action: $('gaAction').options[$('gaAction').selectedIndex].value,
			group: groupId
		}, function (result) {
			if (result.list['error'])
				alert(result.list['error']);
			else
				alert('Выполнено!');
		}
	);
}

function Fave(topic) {
	Request('Topic', 'Fave',
		{
			topic: topic
		}, function () {
			alert('Добавлено!');
		}
	);
}

function RemoveFromInbox(topic, refurl) {
	Request('Message', 'Delete', { id : topic }, function (result) { if (refurl.search(/inbox/i)) document.location.href = refurl; });
}

function unForPro(){
    Request('Topic','GetUserProNoAdv',{},function(result){
	if(result.show!='1'){
	    $('rightbanner').innerHTML='';
	}	
    });
    
}

function getLastCommentId(){
    if($('lastCommentId')){
	return $('lastCommentId').value;
    }else{
	return 0;
    }
//    alert(lastId);
//    document.cookie = 'LastTopic='+lastId+'; expires='+ed.toGMTString()+'; path=/';

}

function highlightNotSeenComments(topicId){
    var lastId = getLastCommentId();//новый последний просмотренный
    if(lastId>0){
	Request('Topic', 'GetLastSeenComments', {topic: topicId, lastId: lastId}, function(result) 
	{
//	alert('Старый LastId: ' + result.id + ', новый last ID: ' + lastId + ', res: ' + result.res /*+ 'Old_last_id: ' + result.lastId*/ + '!'); //текущий последний просмотренный	
	    if(result.id>0){
		var spans = $$('div .rcapt');
		for(var i=0;i<=spans.length;i++){
		    var span_id = spans[i]['id'];
		    if(span_id.substr(5)>result.id){
			spans[i].className = 'rcapt new';
		    }
		}		    	    
	    }
        });
    }

}

function getButtons(){
    Request('Topic', 'GetUserStatus',{topic_id:topicId},function(result){
	var adminsButton;	//кнопка управление

	var status  = result['status'];
	var isAdmin = result['admin'];
	var topicId = result['topicId'];
	var groupId = result['groupId'];
	var freetocomment = result['freetocomment'];
	var lis = $$('ul.replies li');	//берём все Li
	var ar = ukey.split('|');	
	var uid = ar[0];		//user_id
	var lid;
	var name;
	var spl;
	var com_id;
	var html;
	var nhtml;
	var new_html;
	var adm;
	
	var sticky = result['sticky']; // прикреплена / откреплена
	
	if(freetocomment=='1'){
	    status = 1;
	}
	
	var closed = result['closed']; // закрыта / открыта
	
	if(isAdmin > 0){
	    //для основной
	    if(sticky =='1'){
		adm = '<a class="fakea" onclick="if (confirm(\'Вы действительно хотите открепить топик?\')) UnstickTopic(' + topicId + ');">Открепить</a> ';
	    }else{
        	adm = '<a class="fakea" onclick="if (confirm(\'Вы действительно хотите прикрепить топик?\')) StickTopic(' + topicId + ');">Прикрепить</a> ';
	    }
	}else{
	    adminsButton = '';
	    adm ='';	    
	}	
	//эл-ты упр-я топиком    
	if(status > 0){	
	    if($('replyContainer' + topicId)){
    		$('replyContainer' + topicId).style.display = 'block';
	    }
	    
	    if($('replyContainer' + topicId + 'bottom')){
		$('replyContainer' + topicId + 'bottom').style.display = 'block';
	    }
	}
	//если создатель топика
	if($('createrId').value == uid || isAdmin>0){    
	    if(closed=='1'){
		closed_html = '<a class="fakea" onclick="if (confirm(\'Вы действительно хотите открыть топик?\')) UncloseTopic(' + topicId + ');">Открыть</a> ';
	    }else{
		closed_html = '<a class="fakea" onclick="if (confirm(\'Вы действительно хотите закрыть топик?\')) CloseTopic(' + topicId + ');">Закрыть</a> ';
	    }
    	    topic_html = '<a href="/CreateTopic/' + groupId + '/' + topicId + '">Редактировать</a> ' + 
    		'<a class="fakea" onclick="if (confirm(\'Вы уверены что хотите удалить данный топик?\')) DeleteTopic(' + topicId + ');">Удалить</a> ' +                 
		closed_html + adm;								                                 
		
	    $('createrButtons').innerHTML = topic_html;	
	}
	
	
	
	
	
	// для дерева	
	if(lis.length>0){
	    for(var i=0;i<lis.length;i++){
		lid = lis[i]['id'];
		if(status > 0){
		    name = lis[i].readAttribute('name');
		    spl = name.split('_');
		    com_id = spl[1];
		    // сверяем своё или несвоё	
		    if(lid.substr(11) == uid){
			//можно редактировать
			if($('edit'+com_id)){
			    $('edit'+com_id).style.display = 'inline';
			}			
		    }
		    // кнопка удалить - только для админов
		    if(isAdmin > 0){
			$('del'+com_id).style.display = 'inline';		    
        		adminsButton = '(<a href="#" onclick="ShowAdmin(\'' + com_id + '\'); return false">Управление</a>) ';		
		    }
		    html = $('replyContainer' + com_id).innerHTML;
		    /***************************************************/
		    nhtml = '(<a href="#reply' + com_id + '" onclick="ReplyTo(\'' + com_id + '\'); return false">Ответить</a>) '+
		      adminsButton + 
		      '(<a href="#reply' + com_id + '" onclick="Abuse(\'' + com_id + '\'); return false">Пожаловаться на ответ</a>)';	    
		    /***************************************************/	    
		    new_html = nhtml + html;
		
	    	    $('replyContainer' + com_id).innerHTML = new_html;
		}
	    }
	}
	
	
    });    
}


