var comment_parent_id = 0;
var comments_count = 0;
var comments_friend_count = 0;
var comments_new_count = 0;

$(document).ready(
	function() {
		ContentCorrect();
		
		InitTiny(false);
		
		//DESIGN SWITCH
		if (jQuery.browser.msie && jQuery.browser.version.indexOf("6.") != -1) var IE = true;
		else var IE = false;
		if (!IE) {
			if ($.cookie("site_style") == "dark") $("body").addClass("dark");
			else $("body").removeClass("dark");
			$("#bg_style").click(
				function () {
					if ($("body").hasClass("dark")) {
						$("body").removeClass("dark");
						$.cookie("site_style", "light", {path: "/", domain: "journal.hutor.ru", expires: 7});
					} else {
						$("body").addClass("dark");
						$.cookie("site_style", "dark", {path: "/",	domain: "journal.hutor.ru", expires: 7});
					}
				}
			);
		}
		
		//EDIT URL TO MAIN
		if ($.cookie("view_filter_val")) $("div.link_home").parent().get(0).href = $.cookie("view_filter_val");
		
		//AUTH INPUT
		if ($("input.auth_name_login").val()) $("input.auth_name_login").removeClass("auth_name_login");
		if ($("input.auth_name_password").val()) $("input.auth_name_password").removeClass("auth_name_password");
		
		//SEARCH SELECTOR
		var search_selectors = $("div.search span");
		search_selectors.each(
			function (pos) {
				$(this).click(
					function () {
						search_selectors.removeClass("search_select");
						$(this).addClass("search_select");
						$("div.search input:hidden").val(pos);
					}
				);
			}
		);
		
		//USER MENU SHOW
		var user_menu = $("p.user_name span, .comment big").not(".no_menu");
		user_menu.click(
			function () {
				$("#user_menu td.float_window_center").html('<img src="/tpl/img/loader.gif" width="54" height="55" alt="Идёт загрузка, подождите..." title="Идёт загрузка, подождите...">');
				var user_id = this.id;
				$.post ("/engine/module/user_menu_backend.php",
					{
						type: "test-request",
						user_id: user_id
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					$("#user_menu td.float_window_center").html(reply);
				}
				if (this.nodeName.toLowerCase() == "big") {
					var pos_y = $(this).parent().parent().position().top + 25;
					var pos_x = $(this).parent().parent().position().left - 15;
				}	else {
					var pos_y = $(this).position().top + 20;
					var pos_x = 0;
				}
				$("#user_menu").css({"top":pos_y + "px","left":pos_x + "px"}).show();
			}
		);
		
		//USER MENU HIDE
		$("#user_menu").mouseleave(
			function () {
				$("#user_menu td.float_window_center").html('<img src="/tpl/img/loader.gif" width="54" height="55" alt="Идёт загрузка, подождите..." title="Идёт загрузка, подождите...">');
				$(this).hide();
			}
		);
		
		//ONLINEWHO HIDE
		$(".footer_online_who").mouseleave(
			function () {
				$(this).hide();
			}
		);
		
		//COMMENT TREE
		if (IE) {
			var str_comment_hide = '<img src="/tpl/img/icon_comment_hide.jpg" width="9" height="9" alt="Скрыть комментарии" title="Скрыть комментарии" class="comment_swith hide">';
			var str_comment_show = '<img src="/tpl/img/icon_comment_show.jpg" width="9" height="9" alt="Показать комментарии" title="Показать комментарии" class="comment_swith">';
		} else {
			var str_comment_hide = '<img src="/tpl/img/icon_comment_hide.png" width="9" height="9" alt="Скрыть комментарии" title="Скрыть комментарии" class="comment_swith hide">';
			var str_comment_show = '<img src="/tpl/img/icon_comment_show.png" width="9" height="9" alt="Показать комментарии" title="Показать комментарии" class="comment_swith">';
		}
		var comments = $("div.comment");
		comments_count = comments.size();
		if (comments_count > 0) {
			comments_friend_count = $("div.comments img.my_friend").size();
			comments_new_count = $("div.comments div.new").size();
			$("span.current").text(comments_count);
			$("span.new").text(comments_new_count + " новых");
			$("span.friend").text(comments_friend_count + " от друзей");
			comments.each(
				function () {
					var obj = $(this);
					var obj_title = obj.attr("title");
					if (obj_title != "") {
						var from_id = obj_title;
						var from_obj = $("#comm_" + from_id);
						obj.attr("title","");
						if (from_obj.get(0)) {
							obj.addClass("inside");
							if (!$(" > .comment_swith", from_obj).get(0)) from_obj.prepend(str_comment_hide);
							obj.find("span:contains(ответить)").after("<a href='#comment_" + from_id + "'><img src='/tpl/img/icon_to_parent.gif' width='9' height='12' alt='Ответ на' title='Ответ на' onClick='$(\"#comm_" + from_id + " div:first\").addClass(\"self\").parent().find(\"div[id]:first\").css(\"border-left\",\"1px dashed #CCC\")' onMouseOver='this.src=\"/tpl/img/icon_to_parent_hover.gif\"' onMouseOut='this.src=\"/tpl/img/icon_to_parent.gif\"' class='comment_link'></a>");
							obj.appendTo(from_obj);
						}
					}
				}
			);
		}
		
		//COMMENT HIDE ICON
		$(".comment_swith").live("click",
			function() {
				var obj = $(this);
				if (obj.hasClass("hide")) {
					var parent_obj = obj.parent();
					parent_obj.children("div.comment").hide();
					obj.replaceWith(str_comment_show);
				} else {
					var parent_obj = obj.parent();
					parent_obj.children("div.comment").show();
					obj.replaceWith(str_comment_hide);
				}
			}
		);
		
		//COMMENT DELETE
		var comment_del = $(".comment_del");
		comment_del.click(
			function () {
				var obj = $(this).parent().parent();
				var obj_children = obj.find("div.comment");
				var current_friend_count = $("img.my_friend", obj).size();
				var current_new_count = $("div.new", obj).size();
				var comment_delete_ok = true;
				var comment_delete_entry_id = $(".user_post").get(0).id;
				obj_children.each(
					function () {
						var comment_delete_id = this.id.split("_")[1];
						$.post ("/engine/module/show_full_backend.php",
							{
								type: "test-request",
								comment_delete_id: comment_delete_id,
								comment_delete_entry_id: comment_delete_entry_id
							},
							onAjaxSuccess
						);
						function onAjaxSuccess(reply) {
							if (reply == 1) {
								comments_count--;
								$(this).remove();
							} else comment_delete_ok = false;
						}
					}
				);
				comments_friend_count -= current_friend_count;
				comments_new_count -= current_new_count;
				var comment_delete_id = obj.get(0).id.split("_")[1];
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						comment_delete_id: comment_delete_id,
						comment_delete_entry_id: comment_delete_entry_id
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply == 1 && comment_delete_ok) {
						comments_count --;
						$("span.current").text(comments_count);
						$("span.new").text(comments_new_count + " новых");
						$("span.friend").text(comments_friend_count + " от друзей");
						if (!obj.parent().not("div.comments").find("div.comment").get(1)) obj.parent().find(".comment_swith").remove();
						obj.remove();
						if (obj.find("div.comment_form").get(0)) {
							$(".comments").append(comment_code);
							InitTiny(false);	
						}	
						ContentCorrect();
					}
				}
			}
		);
		
		//COMMENT FORM
		var comment_form = $(".comment_user span");
		var comment_code = "<div class='comment_form'>" + $("div.comment_form").html() + "</div>";
		comment_form.live("click",
			function () {
				var obj = $(this).parent().parent().parent().parent();
				comment_parent_id = obj.get(0).id.split("_")[1];
				$("div.comment_form").remove();
				var repl = "<p class='comment_info'>Ваш ответ, " + $("big:first", obj).text() + ":</p>";
				if ($(" > img.hide", obj).get(0)) {
					var target = $("div.comment:first", obj);
					$(comment_code.replace(/\<p.*p\>/i, repl)).insertBefore(target);
				} else obj.append(comment_code.replace(/\<p.*p\>/i, repl));
				InitTiny(true);
			}
		);
		
		//COMMENT SEND
		if (IE) {
			var img_send = "<img src='/tpl/img/btn_post_send.jpg' width='72' height='20' title='Отправить комментарий' alt='Отправить комментарий' onMouseOver='this.src=\"/tpl/img/btn_post_send_hover.jpg\"' onMouseOut='this.src=\"/tpl/img/btn_post_send.jpg\"' class='comment_send'>";
		} else {
			var img_send = "<img src='/tpl/img/btn_post_send.png' width='72' height='20' title='Отправить комментарий' alt='Отправить комментарий' onMouseOver='this.src=\"/tpl/img/btn_post_send_hover.png\"' onMouseOut='this.src=\"/tpl/img/btn_post_send.png\"' class='comment_send'>";
		}
		var comment_send = $("img.comment_send");
		comment_send.live("click",
			function () {
				var comment_body = $("#elm1").html();
				if (comment_body == "") {
					comment_parent_id = 0;
					$("div.comment_form").remove();
					$(".comments").append(comment_code);
					InitTiny(false);
					return false;
				}
				$(this).replaceWith("<p class='comment_send_txt'>Сообщение отправляется, подождите...</p>");
				var entries_id = $(".user_post").get(0).id;
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						comment_body: comment_body,
						entries_id: entries_id,
						parent_id: comment_parent_id
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply != 1) {
						comments_count++;
						$("span.current").text(comments_count);
						$("div.comment_form").remove();
						$(".comments").append(comment_code);
						InitTiny(false);
						var obj = $(reply);
						if (comment_parent_id) {
							obj.addClass("inside");
							obj.attr("title","");
							if (!$("#comm_" + comment_parent_id + " > .comment_swith").get(0)) $("#comm_" + comment_parent_id).prepend(str_comment_hide);
							obj.appendTo("#comm_" + comment_parent_id);
						} else {
							if ($("div.comment:last").get(0)) $("div.comment:last").after(obj);
							else $("div.comments").prepend(obj);
							ContentCorrect();
						}
						comment_parent_id = 0;
					} else {
						alert("Нельзя так часто отправлять комментарии!\nОдин комментарий в 15 сек.");
						$("p.comment_send_txt").replaceWith(img_send);
					}
				}
			}
		);
		
		//CAPTCHA
		var captcha = $("input.captcha_input");
		var captcha_value = $("body").get(0).id;
		captcha.live("keyup",
			function () {
				if (this.value == captcha_value) $(this).next().show();
				else $(this).next().hide();
			}
		);
		
		//BOOKMARK
		var bookmark = $(".user_post_bookmark");
		bookmark.click(
			function () {
				var obj = $(this);
				var favorites_id = $(".user_post").get(0).id;
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						favorites_id: favorites_id
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply) {
						$(".user_post_bookmark").filter(".bookmark_hide").removeClass("bookmark_hide");
						obj.addClass("bookmark_hide");
					}
				}
			}
		);
		
		//RATING POST
		var rating = $(".user_post_rating img");
		rating.click(
			function () {
				var obj = $(this);
				var value = 0;
				if (!obj.next().get(0)) value = 1;
				var rating_id = $(".user_post").get(0).id;
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						rating_id: rating_id,
						value: value
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply == 1) {
						rating.remove();
						var rating_value = parseInt($(".user_post_rating").text());
						if (value) rating_value++;
						else rating_value--;
						if (rating_value >= 0) $(".user_post_rating").html("<small>Рейтинг:</small> +" + rating_value);
						else $(".user_post_rating").html("<small>Рейтинг:</small> <span>" + rating_value + "</span>");
					}
				}
			}
		);
		
		//RATING COMMENT
		var rating_comment = $(".comment_rating img");
		rating_comment.click(
			function () {
				var obj = $(this);
				var obj_parent_id = obj.parent().parent().parent().parent().get(0).id.split("_")[1];
				var value = 0;
				if (!obj.next().get(0)) value = 1;
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						rating_comment_id: obj_parent_id,
						value: value
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply == 1) {
						var obj_parent = obj.parent();
						obj_parent.find("img").remove();
						var rating_comment_value = parseInt(obj_parent.text());
						if (value) rating_comment_value++;
						else rating_comment_value--;
						if (rating_comment_value >= 0) obj_parent.html("<small>Оценка:</small> " + rating_comment_value);
						else obj_parent.html("<small>Оценка:</small> <span>" + rating_comment_value + "</span>");
					}
				}
			}
		);
		
		//TEXT NO STYLE
		var post_body_orig = $(".user_post_body").html();
		var view_mode = $("#view_mode span");
		view_mode.each(
			function (pos) {
				$(this).click(
					function () {
						$("span", this.parentNode).removeClass("filter_select");
						$(this).addClass("filter_select");
						if (pos == 0) $(".user_post_body").html(post_body_orig);
						else {
							var post_body_temp = post_body_orig.replace(/style=((\"|\')(font.*?|color.*?|background.*?)(\"|\'))/gi, "");
							post_body_temp = post_body_temp.replace(/(<(font[^>]+|[^>]font+)>)/gi, "");
							$(".user_post_body").html(post_body_temp);
						}
					}
				);
			}
		);
		
		//POST DELETE
		$("img.post_del").click(
			function () {
				var entry_delete_id = this.id;
				if (confirm ("Удалить запись?")) {
					$.post ("/engine/module/show_full_backend.php",
						{
							type: "test-request",
							entry_delete_id: entry_delete_id
						},
						onAjaxSuccess
					);
				}
				function onAjaxSuccess(reply) {
					if (reply) window.location.href = "/";
				}
			}
		);
		
		//KEEP COMMENTS
		$("#keep_comment span").click(
			function () {
				var obj = $(this);
				var looking_id = $(".user_post").get(0).id;
				$.post ("/engine/module/show_full_backend.php",
					{
						type: "test-request",
						looking_id: looking_id
					},
					onAjaxSuccess
				);
				function onAjaxSuccess(reply) {
					if (reply == "keep") obj.addClass("filter_select");
					else obj.removeClass("filter_select");
				}
			}
		);
		
		//ONLY NEW COMMENTS
		if (comments_new_count > 0) {
			$("#only_new").show();
			$("#only_new span").click(
				function () {
					var obj = $(this);
					if (obj.hasClass("filter_select")) {
						obj.removeClass("filter_select");
						$("div.comments > div.comment:hidden").show();
						ContentCorrect();
					}	else {
						obj.addClass("filter_select");
						var new_comments = $("div.comments > div.comment");
						new_comments.each(
							function () {
								if (!$("div.new", this).get(0)) $(this).hide();
							}
						);
						ContentCorrect();
					}
				}
			);
		}
		//////////////
	}
);

//ONLINEWHO SHOW
function FooterOnlineWho (obj, type) {
	$(".footer_online_who").hide();	
	if ($(obj).next().text() != ":0") {	
		var pos_x = $(window).width() / 2 - 400;
		if (pos_x < 0) pos_x = 0;
		var pos_y = $(document).height() - 70;
		$("#" + type).css({"left":pos_x + "px","top":pos_y + "px"}).show();
	}
}

//USER MENU AJAX REPLY
function UserMenu (user_id, type, value) {
	$.post ("/engine/module/user_menu_backend.php",
		{
			type: "test-request",
			user_id: user_id,
			mode: type,
			value: value
		},
		onAjaxSuccess
	);
	function onAjaxSuccess(reply) {
		$("#menu_" + type).replaceWith("<span>" + reply + "</span>");
	}
}

//TINYMCE INIT
function InitTiny (in_focus) {
	if (in_focus) {
		$("#elm1").tinymce(
			{	
				// General options
				theme : "advanced",
				skin : "o2k7",
				skin_variant : "silver",
				language : "ru",
				auto_focus : "elm1",
				mode : "textareas",
				remove_script_host : false,
				relative_urls : false,
				convert_urls : false,
				plugins : "safari,advimage,advlink,emotions,inlinepopups,preview,media",
	
				// Theme options
				theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,fontselect,fontsizeselect,link,unlink,image,charmap,emotions,iespell,media,|,forecolor,|,code",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom"
			}
		);
	} else {
		$("#elm1").tinymce(
			{	
				// General options
				theme : "advanced",
				skin : "o2k7",
				skin_variant : "silver",
				language : "ru",
				mode : "textareas",
				remove_script_host : false,
				relative_urls : false,
				convert_urls : false,
				plugins : "safari,advimage,advlink,emotions,inlinepopups,preview,media",
	
				// Theme options
				theme_advanced_buttons1 : "undo,redo,|,bold,italic,underline,strikethrough,fontselect,fontsizeselect,link,unlink,image,charmap,emotions,iespell,media,|,forecolor,|,code",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom"
			}
		);
	}
}

//FOOTER CORRECT
function ContentCorrect () {
	$(".container").css("height","auto");
	if ($(document).height()-95 <= $(window).height()) {
		var document_height = $(document).height() - 95;
		$(".container").height(document_height);
	}
}