var oReplies = [];

function showReplyForm(id, ths, parentId, isEdit) {
	if(oReplies[id] === undefined) {
		oReplies[id] = {
			jCont: $('#'+id+'_blog_comment').html($('#reply_tpl').html()),
			parentId: parentId,
			state: false
		};		
		$(ths).text('Отмена');
		$("input[type=button]",oReplies[id].jCont).click(function(){
			sendReply(id);
		});
	}
	var st = oReplies[id].state;
	if(isEdit) {
		st = !(st && oReplies[id].isEdit);
		oReplies[id].aE = ths;
		
		$("b",oReplies[id].jCont).text('Реадктировать сообщение');
	}else{
		st = !st || oReplies[id].isEdit;
		oReplies[id].aR = ths;
		
		$("b",oReplies[id].jCont).text('Ответить пользователю '+($("#comment_autor_"+id).text()));
	}
	
	//if(oReplies[id].isEdit)
	//	$("#comment_txt_"+id).show();
	oReplies[id].jCont[st?'show':'hide']();
	
	if(st) {
		var jTa = $("textarea",oReplies[id].jCont).val(isEdit ? $("#comment_txt_"+id).text() : '');
		if(jTa.length)
			jTa[0].focus();
		//if(isEdit)
		//	$("#comment_txt_"+id).hide();
	}
	if(oReplies[id].aR)
		$(oReplies[id].aR).text((st && !isEdit)?'Отмена':'Ответить');
	if(oReplies[id].aE)
		$(oReplies[id].aE).text((st && isEdit)?'Отмена':'Править');
	
	oReplies[id].state = st; 
	oReplies[id].isEdit = isEdit;	
	return false;
}

function sendReply(id) {
	var oRep = oReplies[id];
	var txt = $("textarea",oRep.jCont).val().replace(/^\s+/,'').replace(/\s+$/,'');
	if(!txt.length) {
		alert('Вы не можете отправит пустой ответ');
		return false;
	}
	var o = {
		save_comment: 1,
		parent_id: oRep.parentId,
		comment: txt
	};
	if(oRep.isEdit)
		o.comment_id = id;
	postObject(o);
}

function editComment(id, ths, parentId) {
	return showReplyForm(id, ths, parentId, true);
	/*var jCont = $("#"+id+"_blog_comment").show();
	$("textarea", jCont).text($("#comment_txt_"+id).text());
	$("input[name='comment_id']", jCont).val(id);*/
}

function addTag(tag_name) {
	var tags_input = $("input[name='tags']"); 
	var val = tags_input.val();
	if(val.length) val += ", ";
	tags_input.val(val + tag_name);
	return false;
}
