$(document).ready(function(){
	$("#topNews").topNews();
	
	$(".sidebar").sidebar();
	
	$(".fpRubs").fpRubs();
	
	$(".printVersion").printVersion();
	
	$("#header .searchField .form-text").each(function(){
		$(this).
			focus(function(){
				$(this).val("");
			}).blur(function(){
				if ($(this).val() == "")
					$(this).val("Поиск");
			}).val("Поиск");
	});
	
	$("#comment-form #edit-mail").each(function(){
		if ($(this).val().length == 0)
			$(this).val("anonimous@anonimous.ru")
	})
});

$.fn.printVersion = function(){
	return this.each(function(){
		$(this).click(function(){
			$("#wrapper").css("display", "none");
			$(document.body).append('<div id="printDiv"></div>');
			$("#printDiv").html($("#content").html());
			$("#printDiv").find('a.' + $(this).attr("class")).css("fontWeight", "bold").
				html("Вернуться к обычной версии").click(function(){
				$("#printDiv").remove();
				$("#wrapper").css("display", "block");
			});
		});
	});
}

$.fn.fpRubs = function(){
	return this.each(function(){
		var container = $(this);
		
		container.sortable({
			axis:'y',
			handle:'a.move',
			items:'.rubBlock',
			opacity:0.7,
			update:function(){
				var order = "";
				var blocks = container.find(".rubBlock");
				
				blocks.each(function(){order = order + $(this).attr("id") + ',' });
				$.setCookie("rubsOrder", order);
			}
		});
	});
}

$.fn.sortRubs = function(){
	return this.each(function(){
		var container = $(this);
		
		order = $.getCookie("rubsOrder");
		
		if (order.length > 0) {
			var blocks = container.find(".rubBlock");
			
			blocks.remove();
			
			order = order.split(',');
			
			for (var n = 0; n < order.length; n++) {
				if (order[n].length > 0)
					blocks.filter("#" + order[n]).appendTo(container);
			}
		}
	});
}

$.fn.sidebar = function() {
	var sidebarAnimateSpeed = 500;
	var blockAnimateSpeed = 300;
	return this.each(function(){
		var sidebar = $(this);
		var wrapper = $(this).children(".sdbrWrapper");
		var content = $("#content");
		var sidebarsAnimates = false;
		var blockAnimates = false;
		
		sidebar.sortable({
			axis:'y',
			handle:'a.move',
			items:'.block',
			opacity:0.7,
			update:function(){
				var order = "";
				var blocks = sidebar.find(".block");
				
				blocks.each(function(){order = order + $(this).attr("id") + ',' });
				$.setCookie("blocksOrder" + sidebar.attr("id"), order);
			}
		});
		
		sidebar.find("a.hideSb").click(function(){
			if (!sidebarsAnimates) {
				var btn = $(this);
				sidebarsAnimates = true;
				if (!$(this).hasClass("hidden")) {
					sidebar.animate({
						width:0
					}, sidebarAnimateSpeed, function(){
						sidebar.addClass("hidden");
						btn.addClass("hidden").attr("title", "Нажмите, чтобы показать колонку");
						$.setCookie("sidebarHidden" + sidebar.attr("id"), 'true');
						sidebarsAnimates = false;
					});
					switch ($(sidebar).css("float")) {
						case "left":
							content.animate({marginLeft:0}, sidebarAnimateSpeed);
							break;
						case "right":
							content.animate({marginRight:0}, sidebarAnimateSpeed);
							break;
					}
				}
				else {
					sidebar.removeClass("hidden");
					sidebar.animate({
						width:240
					}, sidebarAnimateSpeed, function(){
						sidebar.removeClass("hidden");
						btn.removeClass("hidden").attr("title", "Нажмите, чтобы скрыть колонку");
						$.setCookie("sidebarHidden" + sidebar.attr("id"), 'false');
						sidebarsAnimates = false;
					});
					switch ($(sidebar).css("float")) {
						case "left":
							content.animate({marginLeft:267}, sidebarAnimateSpeed);
							break;
						case "right":
							content.animate({marginRight:267}, sidebarAnimateSpeed);
							break;
					}
				}
			}
			return false;
		}).mouseenter(function(){
			$(this).click();
		});
		
		sidebar.find(".block").each(function(){
			
				var block = $(this);
				
				block.find("a.minimize").click(function(){
					if (!blockAnimates) {
						var a = $(this);
						blockAnimates = true;
						if (!$(this).hasClass("hidden")) {
							block.animate({
								height:block.find(".blTitle:first").height()
							}, blockAnimateSpeed, "", function(){
								blockAnimates = false;
								a.addClass("hidden").attr("title", "Нажмите, чтобы развернуть блок");
								$.setCookie(block.attr("id") + "hidden", "true");
							});
						}
						else {
							var nowHeight = parseInt(block.css("height"));
							block.css("height", "auto");
							var neededHeight = block.height();
							block.css("height", nowHeight + "px")
							block.animate({
								height:neededHeight
							}, blockAnimateSpeed, "", function(){
								blockAnimates = false;
								a.removeClass("hidden").attr("title", "Нажмите, чтобы свернуть блок");
								$.setCookie(block.attr("id") + "hidden", "false");
							});
						}
					}
					
					return false;
				});
				
				block.find(".blTitle h3 a").click(function(){
					$(this).parent().parent().find("a.minimize").click();
					return false;
				});
				
		});
		
	});
}

$.fn.checkBlockHidden = function(){
	return this.each(function(){
		var block = $(this);
		
		if (!block.hasClass("hidden") && $.getCookie(block.attr("id") + "hidden") == "true") {
			block.addClass("hidden");
			block.find("a.minimize").addClass("hidden").attr("title", "Нажмите, чтобы развернуть блок");
		}
	});
};

$.fn.checkSbHidden = function(){
	return this.each(function(){
		var sidebar = $(this);
		
		if ($.getCookie("sidebarHidden" + sidebar.attr("id")) == 'true') {
			sidebar.addClass("hidden").css("width", "0").
				find("a.hideSb").addClass("hidden").attr("title", "Нажмите, чтобы показать колонку");
		}
	});
}

$.fn.checkContentClass = function(){
	return this.each(function(){
		var content = $(this);
		
		$(".sidebar").each(function(){
			if ($(this).hasClass("hidden"))
				switch ($(this).css("float")) {
					case "left":
						content.addClass("leftSbHidden");
						break;
					case "right":
						content.addClass("rightSbHidden");
						break;
				}
		});
		
	});
}

$.fn.sidebarSort = function() {
	return this.each(function(){
		var sidebar = $(this);
		var wrapper = $(this).children(".sdbrWrapper");
		
		order = $.getCookie("blocksOrder" + sidebar.attr("id"));
		
		if (order.length > 0) {
			var blocks = wrapper.find(".block");
			
			blocks.remove();
			
			order = order.split(',');
			
			for (var n = 0; n < order.length; n++) {
				if (order[n].length > 0)
					blocks.filter("#" + order[n]).appendTo(wrapper);
			}
		}
	});
}

$.fn.topNews = function(){
	var slideSpeed = 400;
	var timerSpeed = 4000;
	var sleepTimes = 2;
	return this.each(function(){
		var topNews = $(this);
		var leftClick = $(this).find(".contrl.toLeft");
		var rightClick = $(this).find(".contrl.toRight");
		var container = $(this).find(".tnContainer");
		var plane = $(this).find(".tnPlane");
		var animateRightNow = false;
		var mustSleep = 0;
		var pauseAnimation = false;
		
		var totalWidth = 0;
		var totalCount = 
		plane.find(".views-row").each(function(){
			totalWidth += $(this).width() + parseInt($(this).css("marginRight")) +
				parseInt($(this).css("paddingLeft")) + parseInt($(this).css("paddingRight"));
		}).size();
		
		var oneWidth = totalWidth / totalCount;
		plane.css("width", totalWidth + "px");
		
		checkGrayed();
		
		container.mouseenter(function(){
			pauseAnimation = true;
		}).mouseleave(function(){
			pauseAnimation = false;
		});
		
		container.find(".views-row").mouseenter(function(){
			$(this).find("img").animate({
				width:200,
				height:150,
				marginLeft:-11,
				marginTop:-8
			}, 100);
		}).mouseleave(function(){
			$(this).find("img").stop().animate({
				width:177,
				height:133,
				marginLeft:0,
				marginTop:0
			});
		}, 100);
		
		function animateTo(targt) {
			if (!animateRightNow) {
				animateRightNow = true;
				plane.animate({
					left:targt
				}, slideSpeed, "", function(){
					animateRightNow = false;
					checkGrayed();
				});
			}
		}
		
		function checkAbility(newValue, leftOrRight) {
			switch (leftOrRight) {
				case "right":
					return newValue <= 0;
					break;
				case "left":
					return container.width() < plane.width() + newValue + oneWidth;
					break;
			}
			return false;
		}
		
		function checkGrayed() {
			var futureLeft = parseInt(plane.css("left")) - oneWidth;
			
			if (checkAbility(futureLeft, "left"))
				rightClick.removeClass("inactive");
			else
				rightClick.addClass("inactive");
				
			futureLeft = futureLeft + oneWidth * 2;
			
			if (checkAbility(futureLeft, "right"))
				leftClick.removeClass("inactive");
			else
				leftClick.addClass("inactive");
		}
		
		rightClick.click(function(){
			var futureLeft = parseInt(plane.css("left")) - oneWidth;
			if (checkAbility(futureLeft, "left"))
				animateTo(futureLeft);
			return false;
		}).mouseup(function(){
			mustSleep = sleepTimes;
		});
		
		leftClick.click(function(){
			var futureLeft = parseInt(plane.css("left")) + oneWidth;
			if (checkAbility(futureLeft, "right"))
				animateTo(futureLeft);
			return false;
		}).mouseup(function(){
			mustSleep = sleepTimes;
		});
		
		var toRight = false;
		setInterval(function(){
			if (!pauseAnimation && mustSleep <= 0) {
				if (!rightClick.hasClass("inactive"))
					rightClick.click()
				else {
					animateTo(0);
				}
			}
			else {
				mustSleep--;
			}
		}, timerSpeed);
		
	});
}


$.setCookie = function(name, value) {
	var expiration = new Date();

	expiration.setTime(expiration.getTime() + 1000*60*60*24*3650);

	document.cookie = name + "=" + value + "; expires=" + expiration.toGMTString() + "; path=/";
}
	
$.getCookie = function(name) {
	var docCookie = " " + document.cookie;
	var search = name + "=";
	var start = docCookie.indexOf(search);
	var end;

	if (start >= 0)
	{
		start += search.length;
		end = docCookie.indexOf(";", start - 1);
	
		if (end == -1)
		{
			end = docCookie.length;
		}
	
		return docCookie.substring(start, end);
	}
	return false;
}
