/* smotra comments are here */

var sm_comments = { show_form:false, last_read_comment:0, vars: { form_is_opened: 0, cur_replying_id: 0 } };
sm_comments.init = function(_type, _obj_id)
{
	sm_comments.obj_type = _type;
	sm_comments.obj_id = _obj_id;

    //$(document).bind('keydown', 'Shift+R', function(){ return sm_comments.comments_refresh(); });
    //$(document).bind('keydown', 'Shift+C', function(){ return sm_comments.goto_unread_comment(); });
    $(document).bind('keydown', 'Ctrl+return', function(){ return (cur_comment_edit > 0) ? sm_comments.edit_comment_submit() : sm_comments.ajax_post_comment(); });
};

sm_comments.comment_history = function(comment_id, lnk)
{
    comment_div = $("#comment_"+comment_id);
    if (comment_div.find(".comment-history:first:visible").length > 0)
    {
        $(lnk).html('показать историю изменений');
    }
    else
    {
        $(lnk).html('скрыть историю изменений');
    }
    $(lnk).blur();
    
    if (comment_div.find(".comment-history:first").length > 0) 
    {
        comment_div.find(".comment-history:first").slideToggle('fast');
    }
    else
    {
        comment_div.find(".comment-edit-history:first").append('<img src="/img/ajax_loader2.gif" id="history_loading" title="Загрузка" />');
        $.post("/comments/history/" + comment_id, null,
                function(data)
                {
                    data = eval("("+data+")");
                    if (!data.err)
                    {
                        comment_div.find(".comment-edit-history:first").after(data.content);
                        comment_div.find(".comment-history:first").slideDown('fast');
                        $("#history_loading").remove();
                    }
                    else
                    {
                        alert(data.err);
                    }
                }
        );
    }
    
    return false;
};

sm_comments.reply_comment = function(comment_id)
{
	if (sm_js.vars.cur_user_id == 0) 
	{
		$.scrollTo($("#comment_add_msg"), 10);
		return false;
	}
	
	sm_comments.show_form = true;
	if (sm_comments.vars.form_is_opened == 0 || sm_comments.vars.cur_replying_id == comment_id)
	{
		if (sm_comments.vars.form_is_opened == 0)
		{
			sm_comments.vars.form_is_opened = 1;
		}
		else
		{
			sm_comments.vars.form_is_opened = 0;
			$("#comment_add_form").hide();
			sm_comments.show_form = false;
		}
	}
	
	if (comment_id == 0 && sm_comments.show_form) $("h2.new_comment_lnk a.dotunderline").html("Скрыть форму");
	else if (comment_id != 0 || !sm_comments.show_form)  $("h2.new_comment_lnk a.dotunderline").html("Добавить комментарий");
	
	if (sm_comments.show_form)
	{
		if (comment_id == 0)
		{
			$("#comment_add_form").prependTo("#comments_list .new_comment_lnk");
		}
		else
		{
			comment_div = $("#comment_"+comment_id);
			comment_child_div = comment_div.find("ul.comments:first");
			if (comment_child_div.length > 0)
			{
				$("#comment_add_form").prependTo(comment_child_div);
			}
			else
			{
				comment_div.append('<ul class="comments reply_only"></ul>');
				$("#comment_add_form").appendTo(comment_div.find(".reply_only"));
			}
		}
		$("#comment_add_form input[name='data[Comments][parent_id]']").val(comment_id);
		$("textarea[name='data[Comments][comment]']").val("");
		$("#comment_add_form").show();
		$("textarea[name='data[Comments][comment]']").focus();
	}
	sm_comments.vars.cur_replying_id = comment_id;
	return false;
};

sm_comments.edit_comment = function(comment_id)
{
	if (cur_comment_edit > 0) sm_comments.edit_comment_cancel(cur_comment_edit);
	comment = $("#comment_"+comment_id+" .comment-text:first");
	
	comment_text = $(comment).html();
	comment_text = sm_comments.ParseText(comment_text);
	
	var textarea = '<div id="comment_edit_form"><textarea name="comment_edit_txt" class="form-input" rows="7">' + comment_text + '</textarea>';
	var button = '<div class="add-buttons"><input type="button" value="Сохранить" class="button-m" onclick="sm_comments.edit_comment_submit();" /> <input type="button" value="Отмена" class="button-m" onclick="sm_comments.edit_comment_cancel();" /></div></div>';
	$(comment).after(textarea+button).hide();
	$("#comment_edit_form textarea").focus();
	cur_comment_edit = comment_id;
	sm_editor.init({type: 1, textarea_hndl: $("#comment_edit_form textarea")});
	return false;
};

sm_comments.edit_comment_cancel = function()
{
	comment = $("#comment_"+cur_comment_edit+" .comment-text:first");
	$("#comment_edit_form").remove();
	cur_comment_edit = 0;
	$(comment).show();
};

sm_comments.edit_comment_submit = function()
{
	comment = $("#comment_"+cur_comment_edit+" .comment-text:first");
	new_comment = $("#comment_edit_form textarea").val();
	if (new_comment.replace(/\s/g,"") == "")
	{
		alert('Введите комментарий!');
		return false;
	}
	sm_js.block_btn($("#comment_edit_form input[type='button']"));
	$.post("/comments/edit/" + cur_comment_edit,
			{ 'data[Comments][comment]': new_comment },
			function(data)
			{
				try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
				if (parsed)
				{
					if (data.err)
					{
						alert(data.err);
					}
					else
					{
						$("#comment_edit_form").remove();
						$(comment).html(data.msg);
						$(comment).show();
					}
				}
				cur_comment_edit = 0;
				sm_js.unblock_btn($("#comment_edit_form input[type='button']"));
			}
	);
};

sm_comments.clear_wall = function()
{
	if (check_request('clear_wall')) return false;
	if (confirm('Вы действительно хотите удалить все комментарии?'))
	{ 
		sm_js.cur_requests.clear_wall = $.post("/comments/clear_wall/" + sm_comments.obj_type + "/" + sm_comments.obj_id + "/",
		false,
		function(data)
		{
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }	
			if (parsed)
			{
				if (data.msg)
				{
					$(".clear_comments_div").remove();
					$("ul.comments:first").before(data.msg);
					$("ul.comments:first").remove();
					setTimeout( function() { $("#wall_clear_msg").fadeOut(); }, 2000);
				}
			}
			sm_js.cur_requests.clear_wall = 0;
		});
	}
};

sm_comments.del_comment = function(comment_id)
{
	if (confirm('Вы действительно хотите удалить комментарий?'))
	{
		comment = $("#comment_"+comment_id+" .comment-text:first");
		$.post("/comments/del/"+comment_id+"/", false,
			function(data)
			{
				try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
				
				if (parsed)
				{
					if (!data.err)
					{
						comment_li = $("#comment_"+comment_id);
						comment_block = comment_li.find(".comment-block");
						is_deleted = comment_block.hasClass("comment-deleted");
						msg_box = comment_li.find(".comment-text");
						if (is_deleted)
						{
							comment_li.slideUp("fast");
						}
						else
						{
							comment_li.find(".comment-avatar:first").hide();
							comment_li.find(".comment-text:first").slideUp("fast");
							comment_li.find(".comment-info:first li.comment-edit").hide();
							comment_li.find(".comment-info:first li.comment-reply").hide();
							comment_li.find(".comment-info:first li.comment-delete").text("Комментарий успешно удален");
							comment_li.find(".comment-info:first li.comment-delete").after(data.li_html);
							comment_block.addClass("comment-deleted");
						}
						
						// chick children
						comment_child = comment_li.find("ul.comments");
						if (comment_child.length > 0)
						{
							comment_child.remove();
						}
					}
					else
					{
						alert(data.err);
					}
				}
			}
		);
	}
	return false;
};

sm_comments.show_comment = function (comment_id)
{
	comment_li = $("#comment_"+comment_id);
	if (comment_li.length > 0)
	{
		av = comment_li.find(".comment-avatar");
		msg = comment_li.find(".comment-text");
		hist = comment_li.find(".comment-edit-history");
		btn_text = comment_li.find(".comment-show a");
		
		if (av.css("display") == "none")
		{
			btn_text.text("скрыть комментарий");
			av.show();
			msg.show();
			hist.show();
		}
		else
		{
			btn_text.text("показать комментарий");
			av.hide();
			msg.hide();
			hist.hide();
		}
	}
}

sm_comments.ajax_post_comment = function()
{
	obj_id = $("input[name='data[Comments][obj_id]']").val();
	type = $("input[name='data[Comments][type]']").val();
	parent_id = $("input[name='data[Comments][parent_id]']").val();
	msg = $("textarea[name='data[Comments][comment]']").val();
	
	if (msg.replace(/\s/g,"") == "")
	{
		alert('Введите комментарий!');
		return false;
	}
	
	if (typeof(cur_requests['post_comment']) === "undefined") cur_requests['post_comment'] = 0;
	if (cur_requests['post_comment'] != 0) return false;
	
	sm_js.block_btn($("#comment_add_form input[type='submit']"));
	$("#comment_add_form").after(loading2_div);
	cur_requests['post_comment'] = $.post("/comments/add/",
		{ 
			'data[Comments][obj_id]': obj_id,
			'data[Comments][type]': type,
			'data[Comments][parent_id]': parent_id,
			'data[Comments][comment]': msg
		},
		function(data)
		{
			try { 
				data = eval("("+data+")");
				if (data.err)
				{
					alert(data.err);
				}
				else
				{
					if (parent_id == 0)  $("h2.new_comment_lnk a.dotunderline").html("Добавить комментарий");
					$("#comment_add_form").hide();
					sm_comments.vars.form_is_opened = 0;
					
					$(".comments.reply_only").removeClass("reply_only");
					
					if (parent_id == 0)
					{
						$("ul.comments:first").append(data.new_comment_html);					
					}
					else
					{
						parent_li = $("#comment_"+parent_id);
						child_ul = parent_li.find("ul.comments:first");
						child_ul.append(data.new_comment_html);
					}
				}	
			} 
			catch(e) { alert(data); }
			cur_requests['post_comment'] = 0;
			sm_js.unblock_btn($("#comment_add_form input[type='submit']"));
			$("#loading2_div").remove();
		}
		);
	
	return false;
}; 

sm_comments.comments_refresh = function()
{
	if (typeof(cur_requests['comments_refresh']) === "undefined") cur_requests['comments_refresh'] = 0;
	if (cur_requests['comments_refresh'] != 0) return false;

	$("#refresh-comments-button a.button").addClass("loading");
	cur_requests['comments_refresh'] = $.post("/comments/refresh/"+sm_comments.obj_type+"/"+sm_comments.obj_id+"/",
		{ 
			'data[last_read]': sm_comments.last_read_comment
		},
		function(data)
		{
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
			
			if (parsed)
			{
				$(".header-comments .numb").html(data.total_comments);
				$(".comment-new").remove();
				$(".new-messages").show();
				$(".new-messages a").html(data.total_new_comments);
				$("li.comment-new").remove();
				if (data.total_new_comments > 0)
				{
					for (i in data.new_comments) 
					{
					  if (data.new_comments[i]['parent_id'] == 0)
					  {
						  $("ul.comments:first").append(data.new_comments[i]['html']);
					  }
					  else
					  {				  	  
				  		  parent_li = $("#comment_"+data.new_comments[i]['parent_id']);
						  child_ul = parent_li.find("ul.comments:first");
						  if (child_ul.length == 0)
						  {
							  parent_li.append('<ul class="comments">'+data.new_comments[i]['html']+'</ul>');
						  }
						  else
						  {
							  child_ul.append(data.new_comments[i]['html']);
						  }
					  }
					}					
				}	
				if (data.last_read_comment != 0) sm_comments.last_read_comment = data.last_read_comment;	
			}
			
			cur_requests['comments_refresh'] = 0;
			$("#refresh-comments-button a.button").removeClass("loading");
		}
		);
	return false;
};

sm_comments.goto_unread_comment = function()
{
	unread_comm = $("li.comment-new:first");
	if (unread_comm.length > 0)
	{
		scroll_to_el(
			unread_comm.parent().parent().parent(), 
			400, 
			function() 
			{ 
				unread_comm.fadeOut("fast", function() 
				{ 
					unread_comm.remove(); 
					new_unread_count = $(".new-messages a").html() - 1;
					if (new_unread_count > 0) $(".new-messages a").html(new_unread_count);
				}
				);
			}
		);	
	}
	return false;
};

sm_comments.ParseText = function(txt)
{
	txt = txt.replace(/<br>/g, "");
	return txt;
};