$(document).ready(function() { 
	// helper functions for words' endings		
	function createEndingFunction (arr) {
		return function (v) {
			var last = v % 10;
			var lastTwo = v % 100;
			if (last == 0 || (lastTwo >= 11 && lastTwo <= 19))
				return arr[0];
			else if (last == 1)
				return arr[1];
			else if (last >= 2 && last <= 4)
				return arr[2];
			else
				return arr[0];		
		}
	}

	endingForDays = createEndingFunction (["Дней", "День", "Дня"]);
	endingForMinutes = createEndingFunction (["Минут", "Минута", "Минуты"]);
	endingForHours = createEndingFunction (["Часов", "Час", "Часа"]);
			
	// clock object
	function Clock (futureDate) {
		this.init (futureDate);
	}

	Clock.prototype = {
		futureDate: 0,
		
		init: function (futureDate) {
			this.futureDate = futureDate;
			this.update ();
			that = this;
			setInterval (function () { that.update () }, 60000);
		},
		
		update: function () {
			var now = new Date ();
			var minutes = Math.floor ((this.futureDate - now.getTime ()) / 60000);
			
			var days = Math.floor (minutes / (24 * 60));
			minutes -= days * 60 * 24;
			var hours = Math.floor (minutes / 60);
			minutes -= hours * 60;
			
			function addLeadingZero (d) {
				if (d.length < 2)
					return "0" + d;
				else
					return d;
			}
			
			
			$("#clock_days")[0].children[0].innerHTML = addLeadingZero (days.toString ());
			$("#clock_hours")[0].children[0].innerHTML = addLeadingZero (hours.toString ());
			$("#clock_minutes")[0].children[0].innerHTML = addLeadingZero (minutes.toString ());
			
			$("#clock_days")[0].children[1].innerHTML = endingForDays (days).toUpperCase ();
			$("#clock_hours")[0].children[1].innerHTML = endingForHours (hours).toUpperCase ();
			$("#clock_minutes")[0].children[1].innerHTML = endingForMinutes (minutes).toUpperCase ();				
		}
	};
	
	
	var clock = new Clock (greatTimer);
	
	// sound
	
	soundManager.url = "static/swf/";
	soundManager.flashVersion = 9;
	soundManager.useFlashBlock = false;

	var song;
	var muted = true;
	var songPlayed = 0
	var songLen = 230000
	
	function songLoaded () {
		song.play ({loops: 10000});
		if (muted) {
			song.togglePause ();
		}
		setInterval (function () {
			if (!muted) {
				songPlayed += 30
			}
			$("#player_progress")[0].style.width = 141 * (songPlayed % 230000) / 230000 + "px"
		}, 30);
	}
	
	soundManager.onready (function() {
		song = soundManager.createSound({
			id: 'snd',
			url: 'static/mp3/song.mp3',
			autoLoad: true,
			onload: songLoaded
		});
	});
	

	$("#player_button").bind ("click", function () {
		if (song && song.loaded) {
			song.togglePause ();
		}

		muted = !muted;
		$("#player_button")[0].style.background = muted ? "url(static/img/play.png)" : "url(static/img/pause.png) 0px -1px";
	});
	
	// menu buttons
	var currentPosition = 0;
	var curIndex = 0;
	var socialOn = true;
	
	(function () {
		var classes = ['nav_main', 'nav_project', 'nav_news', 'nav_books'];
		var current = $("div.nav_main_active")[0];
		var curClassName = "nav_main";
		
		var positions = [0, 1500, 2600, 3840];
		var curPos = 0;
		gotoScreen = function (index) {
			if (index < 0)
				index = 0;
			else if (index > 3) {
				index = 3;
			}
			
			var className = classes[index];
			elem = $('#nav_button_' + index)[0].children[0];
			if (current != elem) {
				$(elem).addClass (className + "_active");
				if (current != null) {
					$(current).removeClass (curClassName + "_active");
				}
				current = elem;
				curClassName = className;
			}
			
			curIndex = index;
			adjustBackground ();
			
			if (curIndex == 0) {
				$("#big_social_buttons")[0].style.display = "block";
				$("#big_social_buttons").stop ();
				$("#big_social_buttons").clearQueue ();
				$("#big_social_buttons").animate ({opacity: 1}, 500, function () { socialOn = true; });
				setCloudBlock (false);
				
				$("#left_nav_button")[0].style.display = "none";
			} else {		
				socialOn = false;
				$("#left_nav_button")[0].style.display = "block";
				$("#big_social_buttons").stop ();
				$("#big_social_buttons").clearQueue ();				
				$("#big_social_buttons").animate ({opacity: 0}, 500, function () {$("#big_social_buttons")[0].style.display = "none";});	
				setCloudBlock (true)
			}
			
			if (curIndex == 3) {
				$("#right_nav_button")[0].style.display = "none";
			} else {
				$("#right_nav_button")[0].style.display = "block";	
			}
		}
		
		adjustBackground = function () {
			var pos = positions[curIndex];
			var screen = $(window).width ();
			
			if (screen < 1024)
				screen = 1024;
			
			var left = pos - screen * 0.5;		
			if (left < 0)
				left = 0;
			if (left + screen > 3840)
				left = 3840 - screen;			
			$("#an_bg").stop ();
			$("#an_bg").clearQueue ();				
			$("#an_bg").animate ({left: -left + 'px'}, 500);			
			
			var elemWidth = 2500;

			var content_left = (0.5 * (screen - elemWidth)) - curIndex * elemWidth + 'px';
			$("#an_content").stop ();
			$("#an_content").clearQueue ();		
			$("#an_content").animate ({left: content_left}, 500);
			
		}
		
		$(window).resize (adjustBackground);
	}) ();
	
	adjustBackground ();
	
	$("#left_nav_button").bind ("click", function () {
		gotoScreen (curIndex - 1);
	});
	
	$("#right_nav_button").bind ("click", function () {
		gotoScreen (curIndex + 1);
	});
	
	// navigation arrows
	dragTarget = null;
	dragOffset = 0;
	outOfWindow = false;
	$("#right_nav_button").fadeTo (0, 0.5);
	$("#left_nav_button").fadeTo (0, 0.5);
	
	setInterval (function () {
		var dragSet = false;
		if (curIndex != 0) {
			if (Cursor.x <= 100 && !outOfWindow) {
				dragTarget = $("#left_nav_button");
				dragSet = true;
			}
		}
		
		if (curIndex != 3 && !outOfWindow) {
			if (Cursor.x > $("#right_nav_button").offset ().left - 80) {
				dragTarget = $("#right_nav_button");
				dragSet = true;
			}
		}
		
		if (!dragSet && dragTarget != null) {
			crushDrag ();
		}
	}, 30);
	
	$(window).bind ("mouseout", function (e) { var from = e.relatedTarget || e.toElement; if (!from || from.nodeName == "HTML") { outOfWindow = true; crushDrag (); } });
	$(window).bind ("mousemove", function (e) { outOfWindow = false; });
	
	setInterval (function () {
		if (dragTarget != null) {
			dragTarget.stop ();
			dragTarget.clearQueue ();
			dragTarget.animate ({top: Cursor.y - dragTarget.height () * 0.5 + /*($(window).height () < 768 ? 40 : 0) + */"px", opacity: 1}, 30);
		}
	}, 30);
	
	function crushDrag () {
		if (dragTarget != null) {
			dragTarget.stop ();
			dragTarget.clearQueue ();
			dragTarget.animate ({top: "380px", opacity: 0.5}, 600);
			dragTarget = null;
		}
	}
	
	// cloud
	blockCloud = false;
	var cloudOpacity = 0
	var cloudTimes = 0;
	
	function setCloudBlock (v) {
		blockCloud = v;
		if (v) {
			$("#cloud").stop ();
			$("#cloud").clearQueue ();
			$("#cloud").animate ({opacity: 0}, 10);
		} else
			animateCloud ();
	};
	
	function animateCloud () {
		if (cloudTimes > 2) {
			$("#cloud").animate ({opacity: 0}, 1000, function () { $("#cloud")[0].style.display = "none" });
			return;
		}
		if (blockCloud)
			return;
		$("#cloud").animate ({opacity: cloudOpacity == 1 ? 0.5 : 1}, 2000, animateCloud);
		cloudOpacity = (cloudOpacity == 1 ? 0.5 : 1);
		cloudTimes++;
	}
	
	firstVisit = $.cookie ("anabiosis_first_time");
	if (firstVisit == null) {
		$("#cloud")[0].style.visibility = "visible";
		animateCloud ();
		$.cookie ("anabiosis_first_time", "true", {expires: 365});
	}
	
	// social shit
	var visibleSocial = $("#big_vk_plugin")[0];
	var goSocial = function (id) {
		clearTimeout (socialTurnOff);
		
		if (visibleSocial != null) {
			visibleSocial.style.display = "none";
		}

		visibleSocial = $("#" + id + "_plugin")[0];
		//$("#social_plugin")[0].style.height = (id == "big_fb" ? "590px" : "540px");
		//$("#social_plugin")[0].style.top = (id == "big_fb" ? "145px" : "170px");
		visibleSocial.style.display = "block";
		
		$('#social_plugin').animate({
			left: '0px'
		}, 500);
	}
	
	$("#big_tw").bind ("mouseover", function (ev) {
		if (socialOn)
			goSocial (ev.target.id)
	});
	$("#big_vk").bind ("mouseover", function (ev) {
		if (socialOn)
			goSocial (ev.target.id)
	});
	$("#big_fb").bind ("mouseover", function (ev) {
		if (socialOn)
			goSocial (ev.target.id)
	});	
	$("#big_tw").bind ("mouseout", delayTurnOff);
	$("#big_vk").bind ("mouseout", delayTurnOff);
	$("#big_fb").bind ("mouseout", delayTurnOff);

	var socialTurnOff = 0
	function delayTurnOff () {
		socialTurnOff = setTimeout (function () {
			$('#social_plugin').animate({
				left: '-250px'
			}, 500);		
		}, 100);
	}
	
	$("#social_plugin").bind ("mouseout", delayTurnOff);	
	
	$("#social_plugin").bind ("mouseover", function (ev) {
		clearTimeout (socialTurnOff);
	});	
	
	// damn height ... oops and width!
	adjustHeight = function () {
		var screen = Math.min (1025, Math.max (768, $(window).height ()));
		var scrWidth = Math.max (1190, Math.min (1280, $(window).width ()));
		var wDiff = scrWidth - 1280;
		$("#social_buttons")[0].style.marginLeft = wDiff + "px";
		$("#partners_logos")[0].style.marginLeft = wDiff + "px";
		$("#partners_logos")[0].style.left = Math.max (400, 0.5 * ($(window).width () - $("#partners_logos").width ())) + "px";
		if ($("#banner_div").length > 0) {
			$("#banner_div")[0].setAttribute ("width", Math.max (1024, $(window).width ()));
			// $("#banner_div").bind ("click", function (e) { e.preventDefault (); alert ("F") });
			//alert ("X");
		}
		
		var diff = 1025 - screen;
		
		if ($(window).height () < 768) {
			var diminish = false//$("#banner_href div").length != 0;
			$("body")[0].style.overflowY = "auto";
			if (diminish)
				$("#an_bg_scroll")[0].style.marginTop = "-40px";
		} else {
			diminish = false
			$("body")[0].style.overflowY = "hidden";
			$("#an_bg_scroll")[0].style.marginTop = "0px";
		}
		
		$("#bottom_gradient")[0].style.top = 966 - diff + (diminish ? 90 : 0) + "px";
		$("#player")[0].style.top = 900 - diff + "px";
		//$("#top_gradient")[0].style.top = (diminish ? -90 : 0) + "px";
		
		var screens = $(".epic_inner_screen");
		var len = screens.length;
		for (var i = 0; i < len; i++) {
			screens[i].style.marginTop = -diff + "px";
		}
		

		$("#an_bg_scroll")[0].style.height = Math.min (1025, diminish ? screen + 90 : screen) + "px";
		$("#darkness")[0].style.height = Math.max (768, $(window).height ()) + "px";
		$("#sign_in_form")[0].style.top = 0.5 * (screen - 438) + "px";
		//alert ($("#bottom_gradient")[0].style.top)
		
		// images from hell
		var imgs = $("#an_bg img")
		len = imgs.length;
		for (i = 0; i < len; i++) {
			imgs[i].style.marginTop = -diff + (diminish ? 90 : 0) + "px"
		}
	}
	
	adjustHeight ();
	$(window).resize (adjustHeight);
	
	// sign in button
	$("#sign_in_button").bind ("click", function () {
		$("#darkness").fadeTo (0, 0);
		$("#darkness")[0].style.display = "block";
		$("#darkness").fadeTo (500, 0.65);
		
		$("#sign_in_form").fadeTo (0, 0);
		$("#sign_in_form")[0].style.display = "block";
		$("#sign_in_form").fadeTo (500, 1);
		
		$(".epic_inner_screen").fadeTo (500, 0);
	});
	
	$("#form_close_button").bind ("click", function () {		
		$("#darkness").fadeTo (500, 0, function () {  $("#darkness")[0].style.display = "none"; });
		$("#sign_in_form").fadeTo (500, 0, function () {  $("#sign_in_form")[0].style.display = "none"; });
		$(".epic_inner_screen").fadeTo (500, 1);
	});
	
	$("#confirm_sign_in").bind ("click", function () {
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		var emailaddressVal = $("#sign_in_email").val ();
		var nameVal = $("#sign_in_name").val ();
		if (emailaddressVal.length == 0 || !emailReg.test(emailaddressVal)) {
			alert ("Пожалуйста, введите верный e-mail адрес");
		} else if (nameVal.length == 0) {
			alert ("Пожалуйста, введите ваше имя");
		} else {
			alert("Вы подписаны");
			$.ajax({
				type: "POST",
				url: 'sign_in/',
				data: 'alias=' + escape (nameVal) + '&email=' + escape (emailaddressVal)
			});
		}
	});
	
});

