var minimizeChecked = new Array();

function checkMinimizeBlock(blockid)
{
	if (!minimizeChecked[blockid]) {
		var className = "minimize";
		var title = "Свернуть блок";
		var block = $("#" + blockid);
	
		if ($.getCookie(blockid) == "minimized")
		{
			block.css("height", "30px");
		
			className += " max";
			title = "Развернуть блок"
		}
	
		$(document).ready(function(){
			if (block.height() == 30) {
				block[0].inHeight = block.css("height", "auto").height();
				block.css("height", "30px");
			}
		});
	
		document.write('<a id="' + blockid + 'minimize" class="' + className + '" href="#" title="' + title + '"> <br/> </a>');
		document.write('<a id="' + blockid + 'move" class="move" href="#" title="Переместить блок"> <br/> </a>');
	
		minimizeChecked[blockid] = true;
	}
}

function minimizeBlock(blockid, aref)
{
	var block = $("#" + blockid);
	var ahref = $(aref);
	
	if (!block[0].animateNow)
		if (block.height() == "30") 
		{
			block[0].animateNow = true;
			block.animate({
				height:block[0].inHeight
			}, 500, "", function(){
				ahref.removeClass("max").
					attr("title", "Свернуть блок");				
				$.setCookie(blockid, "normal");
				block[0].animateNow = false;
			});
		}
		else 
		{
			block[0].inHeight = block.height();
			block[0].animateNow = true;
			block.animate({
				height:30
			}, 500, "", function(){
				ahref.addClass("max").
					attr("title", "Развернуть блок");
				$.setCookie(blockid, "minimized");
				block[0].animateNow = false;
			});
		}
}


/* SIDEBAR HIDDING */

var sbAnSpeed = 500;

function hideSidebar(momental)
{
	var sidebar = $("#sidebar");
	var content = $("#content");
	var button = $("#hideSidebar");
	
	if (!sidebar[0].animateNow)
		if (sidebar.size() > 0 && content.size() > 0 && button.size() > 0)
		{
			sidebar[0].wdth = sidebar.width();
			content[0].marginLeft = parseInt(content.css("marginLeft"));
			sidebar[0].animateNow = true;
			sidebar.animate({
				width:0
			}, momental ? 1 : sbAnSpeed, "", function(){
				$(this).css("display", "none");
				content.addClass("sidebarHidden");
				button.attr("title", "Показать сайдбар").
					addClass("show");
		
				$.setCookie("sidebar", "hidden");
				sidebar[0].animateNow = false;
			});
			content.animate({
				marginLeft:0
			}, momental ? 1 : sbAnSpeed)
		}
}

function showSidebar()
{
	var sidebar = $("#sidebar");
	var content = $("#content");
	var button = $("#hideSidebar");
	
	if (!sidebar[0].animateNow)
		if (sidebar.size() > 0 && content.size() > 0 && button.size() > 0)
		{
			sidebar[0].animateNow = true;
			sidebar.animate({
				width:sidebar[0].wdth
			}, sbAnSpeed, "", function(){
				content.removeClass("sidebarHidden");
		
				button.attr("title", "Скрыть сайдбар").
					removeClass("show");
		
				$.setCookie("sidebar", "visible");
				sidebar[0].animateNow = false;
			});
			content.animate({
				marginLeft:content[0].marginLeft
			}, sbAnSpeed)
		}
}

function checkHiddenSidebar1()
{
	if ($.getCookie("sidebar") == "hidden") {
		$("#sidebar").each(function(){
			$(this).hide();
		});
	}
}

function checkHiddenSidebar2()
{
	if ($.getCookie("sidebar") == "hidden")
	{
		hideSidebar(true);
	}
}

function showForm(formId)
{
	var form = document.getElementById(formId);
	form.style.display = "block";
	form.style.position = "absolute";
	
}

function hideFromIE6()
{
	if (navigator.appVersion.indexOf("MSIE 6") >= 0)
	{
		var superDiv = document.getElementById("superDiv");
		
		document.getElementById("globalDiv").style.display = "none";
		
		document.body.parentNode.style.height = "100%";
		document.body.style.height = "100%";
		superDiv.style.height = "100%";
		
		superDiv.style.marginLeft = "0";
		superDiv.style.marginRight = "0";
	}
}
function hideFromIE6Step2()
{
	if (navigator.appVersion.indexOf("MSIE 6") >= 0) 
	{
		var messageDiv = document.createElement("div");
	
		messageDiv.id = "deletedMessageDiv";
		messageDiv.innerHTML = '<h1>Этот супертехнологичный блог не совместим с устаревшим браузером Internet Explorer 6</h1>' +
		'<div class="messageText">' +
			'<p>По непонятной причине вы почему-то используете браузер Internet Explorer 6-й версии. ' +
			'С такими предпочтениями на этом блоге вам просто будет не интересно.</p>' +
			'<p>Кроме того, автор блога посчитал, что его блог должен быть недоступен для просмотра в Internet Explorer 6, поскольку открытие сайта в этом устаревшем и глючном браузере может навредить карме сайта.</p>' +
			'<p>Если же вы всё-равно хотите почитать этот блог, то скачайте и установите себе например <a href="http://www.mozilla-europe.org/ru/firefox/">Mozilla Firefox</a>.</p>' + 
			'<p>Если вы вообще не в курсе что такое браузер и что такое Internet Explorer, то вам <a href="http://ru.wikipedia.org/wiki/%D0%91%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80">сюда</a>.</p>'
		'</div>';
		
		document.getElementById("theEnd").style.display = "none";
		
		var superDiv = document.getElementById("superDiv");
		
		if (superDiv)
		{
			superDiv.appendChild(messageDiv);
		}
	}
}

$(document).ready(function () {
	$.sape();
	
	$("#sidebar .block .header").each(function(){
		var headerId = $(this).attr('id');
		$(this).find('a.minimize').click(function(){
			minimizeBlock(headerId, this);
			return false;
		});
	});
	
	$("#sidebar").sortable({
		axis:"y",
		items:".block",
		handle:"a.move",
		revert:"true",
		update:function(){
			var cookieStr = "";
			$("#sidebar .block .header").each(function(){
				cookieStr += $(this).attr("id") + ",";
			});
			$.setCookie("blockArrange", cookieStr);
		}
	});
	
	$("#header .superMenu .item").each(function(){
		$(this).mouseenter(function(){
			$(this).children(".popupForm").stop().
				css("opacity", 0).
				css("display", "block").
				animate({
					opacity:1
				}, 300);
		}).mouseleave(function(){
			$(this).children(".popupForm").stop().
				animate({
					opacity:0
				}, 300, "", function(){
					$(this).css("display", "none");
				});
		});
	});
	
	$("#footer .upTo").click(function(){
		$("#superDiv").scrollToElement({animationSpeed:2000});
		return false;
	});
	
	$(".post h2 .scrollToNext:last").remove();
	$(".post h2 .scrollToNext").each(function(){
		$(this).attr("title", "К следующей заметке");
		$(this).click(function(){
			$(this).parent().parent().next(".post").scrollToElement({increment:-20});
			return false;
		});
	});
	
	$(".post .scrollToComment a").click(function(){
		$($(this).attr("href")).scrollToElement();
		$("#comment").focus();
		return false;
	});
	
});

function sortBlocks() {
	order = $.getCookie("blockArrange");
	
	if (order.length > 0) {
	  var blocks = $("#sidebar .block");
	  
	  blocks.remove();
	  
	  order = order.split(',');
	  
	  for (var n = 0; n < order.length; n++) {
      if (order[n].length > 0) {
				blocks.find("#" + order[n]).parents(".block:first").appendTo("#sidebar");
      }
	  }
	}
}

function quoteComment(commentId, author)
{
	var commentText = $("#commentText-" + commentId);

	var commentTextarea = $("#comment");
	
	commentTextarea.val('<blockquote cite="#comment-' + commentId + '"><p><strong>' + 
		author + ' <a href="#comment-' + commentId + '">говорит</a>:</strong></p>' +
		commentText.html() + '</blockquote>\n');
		
	$(commentTextarea).scrollToElement().focus();
}

$.fn.extend({
	scrollToElement:function(parameters){
		var params = {
			animationSpeed:1000,
			increment:0
		};
		
		$.extend(true, params, parameters);
		
		return this.each(function(){
			$("html, body").animate({
				scrollTop:$(this).offset().top + params.increment
			}, params.animationSpeed)
		});
	}
});

$.extend({
	sape:function(){
		$(".sapSpan").remove().each(function () {
			if ($(this).html().replace(" ", "").length != 0)
			{
				$(this).appendTo("#blkSAdvert .content");
			}
		});

		$(".sapSpan").css("display", "inline");
	
		if ($('#blkSAdvert .content').html().length != 0) {
			$('#blkSAdvert').parent().parent().parent().attr("style", "display:block");
		}
	},
	
	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;
	}
	
});


/* DELETING OF THE BLOG */

var deletedBlogContent;

function printDeletedMessage()
{
	var messageDiv = document.createElement("div");
	
	messageDiv.id = "deletedMessageDiv";
	messageDiv.innerHTML = '<h1>Блог находится в корзине</h1>' +
	'<div class="messageText">' +
		'<p>Вы удалили блог <strong>Валерия «ShibaOn» Шибанова</strong> в корзину, где он в настоящий момент и находится.</p>' +
		'<p>Вероятнее всего, скоро прибежит сам ShibaOn, будет долго возмущаться, после чего вытащит свой блог из корзины, заботливо отряхнёт и поставит на место.</p>' +
		'<p>Впрочем, вы можете сжалиться и <a onclick="restoreBlog();return false;" href="#">возвратить</a> этот блог его читателям сами.</p>' +
	'</div>';
	
	var superDiv = document.getElementById("superDiv");
	
	if (superDiv)
	{
		superDiv.appendChild(messageDiv);
	}
}

function deleteBlog()
{
	deletedBlogContent = document.getElementById("globalDiv");
	var superDiv = document.getElementById("superDiv");
	
	if (superDiv) 
	{
		deletedBlogContent.style.display = "none";
  	superDiv.removeChild(deletedBlogContent);
		
		document.body.parentNode.style.height = "100%";
		document.body.style.height = "100%";
		superDiv.style.height = "100%";
		
		superDiv.style.marginLeft = "0";
		superDiv.style.marginRight = "0";
		
		document.getElementById("theEnd").style.display = "none";
		
		$.setCookie("deleted", "true");
		
		printDeletedMessage();
  }
}

function restoreBlog()
{
	var superDiv = document.getElementById("superDiv");
	
	if (superDiv)
	{
		deletedBlogContent.style.display = "block";
		superDiv.appendChild(deletedBlogContent);
		superDiv.removeChild(document.getElementById("deletedMessageDiv"));
		
		document.body.parentNode.style.height = "auto";
		document.body.style.height = "auto";
		superDiv.style.height = "auto";
		
		superDiv.style.marginLeft = "-140px";
		superDiv.style.marginRight = "-140px";
		
		$.setCookie("deleted", "false");
		document.getElementById("theEnd").style.display = "block";
	}
}

function checkDeletedFirstStep()
{
	if ($.getCookie("deleted") == "true")
	{
		document.getElementById("globalDiv").style.display = "none";
	}
}

function checkDeletedSecondStep()
{
	if ($.getCookie("deleted") == "true")
	{
		deleteBlog();
	}
}
