/* smotra comments are here */

var sm_comments = { 
	show_form:false, 
	last_read_comment:0,
	pages_pos:[],
	pages_total:0,
	pages_loaded:[],
	cur_active_pg:0,
	vars: { form_is_opened: 0, cur_replying_id: 0 } };
sm_comments.init = function(_type, _obj_id, _pages_cur)
{
	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(); });
    	
    // pages positions
    sm_comments.pages_total = $(".comments-page").length;
    for (i=1;i<=sm_comments.pages_total;i++) sm_comments.pages_pos[i] = [0,0];
    sm_comments.cur_active_pg = _pages_cur;
    for (i=1;i<=sm_comments.pages_total;i++) sm_comments.page_pos_refresh(i);
    
    if (window.addEventListener)
    {
	    window.addEventListener('scroll', sm_comments.page_scroll, false);
	}
	else
	{
		window.onmousewheel = document.onmousewheel = sm_comments.page_scroll;
	}


}

sm_comments.page_scroll = function() 
{
    		docViewTop = $(window).scrollTop();
    		docViewBottom = docViewTop + ($(window).height()/2);
    		has_changes = false;
    		
    		for(i=1;i<=sm_comments.pages_total;i++)
    		{
    			pg_div_pos = sm_comments.pages_pos[i];
    			if (pg_div_pos[0] == 0 && pg_div_pos[1] == 0) continue;
    			if (docViewBottom >= pg_div_pos[0] && docViewBottom <= pg_div_pos[1])
    			{
    				if (i != sm_comments.cur_active_pg)
    				{
    					has_changes = true;
						sm_comments.cur_active_pg = i;
					}
					break;
    			}
    		}
    		
    		if (has_changes)
    		{
    			$(".cpl-link.active").removeClass('active');
    			$(".cpl-link[pg_num="+sm_comments.cur_active_pg+"]").addClass('active');	
			}
}

sm_comments.page_pos_refresh = function(pg_num)
{
	pg_div = $("#comments_page_"+pg_num);
	if (pg_div.find("ul.comments:first").length == 0)
	{
		el_top = el_bot = 0;
	}
	else
	{
		el_top = $(pg_div).offset().top;
    	el_bot = el_top + $(pg_div).height();
	}
	sm_comments.pages_pos[pg_num] = [el_top, el_bot];
}

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
    {
    	sm_js.loading_overlay_add(comment_div);
    	
        $.post("/comments/history/" + comment_id, null,
                function(data)
                {
                	sm_js.loading_overlay_del(comment_div);
                	
                	try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }	
					if (parsed)
					{
	                    if (!data.err)
	                    {
	                        comment_div.find(".edited:first").after(data.content);
	                        comment_div.find(".comment-history:first").slideDown('fast');
	                    }
	                    else
	                    {
	                        alert(data.err);
	                    }
					}
                }
        );
    }
    
    return false;
};

sm_comments.cancel_reply = function()
{
	sm_comments.vars.form_is_opened = 0;
	$("#comment_add_form").hide();
	sm_comments.show_form = false;
	$("#new-comment-btn").show();
}

sm_comments.reply_comment = function(comment_id)
{
	if (typeof(cur_requests['post_comment']) !== "undefined" && cur_requests['post_comment'] != 0) return false;
	
	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;
		}
	}
	
	if (comment_id == 0 && sm_comments.show_form) $("#new-comment-btn").hide();
	else if (comment_id != 0 || !sm_comments.show_form) $("#new-comment-btn").show();
	
	if (sm_comments.show_form)
	{
		if (comment_id == 0)
		{
			$("#comment_add_form").prependTo("#new-comment-ul");
		}
		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-s" onclick="sm_comments.edit_comment_submit();" /> <input type="button" value="Отмена" class="button-s" 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_div = $("#comment_"+cur_comment_edit);
	comment = comment_div.find(".comment-text:first");
	comment_bl = comment_div.find(".comment-block:first");
	
	new_comment = $("#comment_edit_form textarea").val();
	if (new_comment.replace(/\s/g,"") == "")
	{
		alert('Введите комментарий!');
		return false;
	}
	
	sm_js.loading_overlay_add(comment_bl);
	sm_js.block_btn($("#comment_edit_form input[type='button']"));
	$.post("/comments/edit/" + cur_comment_edit + "/",
			{ 'data[Comments][comment]': new_comment },
			function(data)
			{
				cur_comment_edit = 0;
				sm_js.loading_overlay_del(comment_bl);
				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();
					}
				}
			}
	);
};

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 + "/",
		null,
		function(data)
		{
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }	
			if (parsed)
			{
				if (data.msg)
				{
					$(".nb-delete-comments").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('Вы действительно хотите удалить комментарий?')) return false;
	
	comment_li = $("#comment_"+comment_id);
	sm_js.loading_overlay_add(comment_li);
	comment = $("#comment_"+comment_id+" .comment-text:first");
	$.post("/comments/del/"+comment_id+"/", null,
		function(data)
		{
			sm_js.loading_overlay_del(comment_li);
			
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
			if (parsed)
			{
				if (!data.err)
				{
					comment_block = comment_li.find(".comment-block:first");
					is_deleted = comment_block.hasClass("deleted");
					msg_box = comment_li.find(".comment-text");
					if (is_deleted)
					{
						comment_li.slideUp("fast");
					}
					else
					{
						comment_text = comment_li.find(".comment-text:first");
						comment_text.slideUp("fast");
						comment_text.before('<div class="post-show"><a class="dotted-s" onclick="sm_comments.show_comment('+comment_id+')" href="javascript:void(0)">показать комментарий</a></div>');
						info_s = comment_li.find(".info-s:first");
						info_s.find(".info-answer").hide();
						info_s.find(".controls-edit").hide();
						info_s.find(".controls-delete").attr("title", data.del_title);
						comment_block.addClass("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)
	{
		msg = comment_li.find(".comment-text:first");
		btn_text = comment_li.find(".post-show a");
		
		if (msg.css("display") == "none")
		{
			btn_text.text("скрыть комментарий");
			msg.show();
		}
		else
		{
			btn_text.text("показать комментарий");
			msg.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();
	comment_textarea = $("textarea[name='data[Comments][comment]']");
	msg = comment_textarea.val();
	msg = jQuery.trim(msg);	
	msg = msg.replace(/ {2,}/g, ' ');
	min_len = (parent_id == 0) ? 15 : 5;
	if (msg.length < min_len)
	{
		alert('Минимальная длина комментария '+min_len+' символов.');
		comment_textarea.focus();
		return false;
	}
	
	if (typeof(cur_requests['post_comment']) === "undefined") cur_requests['post_comment'] = 0;
	if (cur_requests['post_comment'] != 0) return false;
	
	sm_js.loading_overlay_add($("#comment_add_form"));
	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)
		{
			cur_requests['post_comment'] = 0;
			sm_js.loading_overlay_del($("#comment_add_form"));
			
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }	
			if (parsed)
			{
				if (data.err)
				{
					alert(data.err);
				}
				else
				{
					if (parent_id == 0) $("#new-comment-btn").show();
					$("#comment_add_form").hide();
					sm_comments.vars.form_is_opened = 0;
					
					$(".comments.reply_only").removeClass("reply_only");
					
					if (parent_id == 0)
					{
						$(".comments-page:last ul.comments:first").append(data.new_comment_html);
					}
					else
					{
						new_comment_elem = $(data.new_comment_html);
						parent_li = $("#comment_"+parent_id);
						
						// nesting level
						nesting = 1;
						tmp = parent_li.parent();
						while (!tmp.hasClass("comments-page"))
						{
							if (tmp.attr("class") == "comment-item") nesting++;
							if (nesting > 2) break;
							tmp = tmp.parent();
						}

						if (nesting > 2)
						{
							answer_to = parent_li.find("li.info-author").html();
							answer_to = answer_to.replace("<a", "<span").replace("</a", "</span");
							new_comment_elem.find(".info-answer").after('<li class="info-answer-to"><a href="#comment_'+parent_id+'">ответ для '+answer_to+'</a></li>');
						}
						
						child_ul = parent_li.find("ul.comments:first");
						child_ul.append(new_comment_elem);
					}
				}	
			}
		}
		);
	
	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,
			'data[pages_loaded]': sm_comments.pages_loaded.join(',')
		},
		function(data)
		{
			try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
			
			if (parsed)
			{
				$(".comment-new").remove();
				$(".numb-new").remove();
				$(".new-messages").show();
				$(".new-messages a").html("+"+data.total_new_comments);
				$("li.comment-new").remove();
				if (data.total_new_comments > 0)
				{
					$(".header-comments .numb").html(data.total_comments);
					for (pg_num in data.new_comments) 
					{
						pg_div = $("#comments_page_"+pg_num);
						pg_div_comments_ul = pg_div.find("ul.comments:first");
								
						for (i in data.new_comments[pg_num]) 
						{
							new_comment = data.new_comments[pg_num][i];
							if (new_comment['parent_id'] == 0)
							{
								if (pg_div_comments_ul.length == 0)
								{
									sm_comments.pages_loaded.push(pg_num);
									pg_div.append('<ul class="comments">'+new_comment['html']+'</ul>');
									pg_div_comments_ul = pg_div.find("ul.comments:first");
								}
								else
								{
									pg_div_comments_ul.append(new_comment['html']);
								}
							}
							else
							{
								parent_li = $("#comment_"+new_comment['parent_id']);
								child_ul = parent_li.find("ul.comments:first");
								if (child_ul.length == 0)
								{
									parent_li.append('<ul class="comments">'+new_comment['html']+'</ul>');
								}
								else
								{
									//child_ul.append(new_comment['html']);
									diff = new_comment['id']; diff_elem = null;
									child_ul.find(".comment-item").each(function(idx, elem){
										tmp = $(elem).attr("id").split("_");
										diff_tmp = tmp[1] - new_comment['id'];
										if (Math.abs(diff_tmp) < Math.abs(diff))
										{
											diff = diff_tmp;
											diff_elem = $(elem);
										}
									});

									if (diff > 0)
									{
										diff_elem.before(new_comment['html']);
									}
									else
									{
										diff_elem.after(new_comment['html']);
									}
								}
							}
						}	
						
						if (!pg_div_comments_ul.is(":visible"))
						{
							pg_div_comments_ul.show();
						}
					}				
				}	
				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:not(.to_del):first");
	if (unread_comm.length > 0)
	{
		tmp = unread_comm.parent().parent().parent().parent().attr("id").split("_");
		window.location.hash = 'comment_' + tmp[1];

		unread_comm.addClass("to_del");
		unread_comm.fadeOut("fast", function() { unread_comm.remove(); });
				
		new_unread_count = parseInt($(".new-messages a").html()) - 1;
		if (new_unread_count >= 0) 
		{
			$(".new-messages a").html("+"+new_unread_count);
			$(".nb-header-comments .numb-new a").html("+"+new_unread_count);
			if (new_unread_count == 0) 
			{
				$(".new-messages").hide();
				$(".nb-header-comments .numb-new").hide();
			}
		}
	}
	return false;
};

sm_comments.load_pg = function(pg_num)
{
	post_data = false;
	
	if (pg_num != 0)
	{
		window.location.hash = 'c_pg'+pg_num;
		comments_pg_div = $("#comments_page_"+pg_num);
		pg_comments = comments_pg_div.find("ul.comments");
		is_loaded = (pg_comments.length > 0);
		
		if (is_loaded)
		{
			if (comments_pg_div.hasClass('active')) comments_pg_div.removeClass('active'); else comments_pg_div.addClass('active');
			pg_comments.toggle();
			for (i=pg_num;i<=sm_comments.pages_total;i++) sm_comments.page_pos_refresh(i);
			return false;
		}
	}
	else
	{
		post_data = {
			'data[pages_loaded]': sm_comments.pages_loaded.join(',')
		};
	}

	if (check_request('comments_load_pg')) return false;
	if (pg_num != 0) comments_pg_div.addClass("loading");
	sm_js.cur_requests.comments_load_pg = $.post("/comments/load_pg/"+sm_comments.obj_type+"/"+sm_comments.obj_id+"/"+pg_num+"/",
	post_data,
	function(data)
	{
		sm_js.cur_requests.comments_load_pg = 0;
		if (pg_num != 0) comments_pg_div.removeClass("loading");

		try { data = eval("("+data+")"); parsed = true; } catch(e) { alert(data); parsed = false; }
		if (parsed)
		{
			min_pg = 0;
			for (i_pg_num in data.comments) 
			{
				if (min_pg == 0) min_pg = i_pg_num;
				comments_pg_div = $("#comments_page_"+i_pg_num);
				sm_comments.pages_loaded.push(i_pg_num);
				comments_pg_div.append(data.comments[i_pg_num]);
			}	
			
			for (i=min_pg; i<=sm_comments.pages_total; i++) sm_comments.page_pos_refresh(i);

			sm_comments.cur_active_pg = min_pg;
			$(".cpl-link").removeClass('active');
    		$(".cpl-link[pg_num="+sm_comments.cur_active_pg+"]").addClass('active');
    		
    		$(".comments-page[pg_num="+sm_comments.cur_active_pg+"]").addClass('active');
    		
    		if (pg_num == 0)
			{
				window.location.hash = 'c_pg'+min_pg;
				$(".comments-pages-list a:last").remove();
			}
		}
	}
	);
	
	return false;
}

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

