$(function(){
	var elevator = $('#elevator'),
		shaft = elevator.parent(),
		current_floor = Math.abs(parseInt(elevator.css('top') || 0) / 100),
		floors = elevator.find('.floor'),
		max_floor = floors.length - 1,
		is_animating = false;

	function getPageHeight() {
		return Math.max($('#page')[0].offsetHeight, $(window).height());
	}

	function moveToFloor(num) {
		if (!is_animating && current_floor != num && num >= 0 && num <= max_floor) {
			var shaft_height = getPageHeight(),
				time = shaft_height * Math.abs(current_floor - num) * 1.7;

			// фиксирую размер шахты и позицию лифта
			shaft.height(shaft_height);
			elevator.css('top', parseInt(elevator.css('top')) / 100 * shaft_height);

			// ставим контент в нужную позицию
			var content = $('#imagery > .content'),
				content_pos = content[0].offsetTop;
//				content_pos = content.offset().top;
				
			if ($.browser.msie) // странный баг в IE
				content_pos -= 41;

			content.css('visibility', 'hidden');
			floors.eq(current_floor).find('.event').show().css('top', content_pos);
			floors.eq(num).find('.event').show().css('top', content_pos).end();

			// запускаем анимацию
			is_animating = true;
			current_floor = num;

			elevator.animate({top: -num * shaft_height}, time, 'elevator_move', function(){
				is_animating = false;
				elevator.css('top', (-current_floor * 100) + '%');

				content
					.empty().append(floors.eq(current_floor).find('.event').clone())
					.css('visibility', 'visible');
				floors.find('.event').hide();

				if (!$.browser.safari)
					shaft.css('height', '');
			});

			updateControls();

			return true;
		}

		return false;
	}

	function moveFloorAbove() {
		return moveToFloor(current_floor - 1);
	}

	function moveFloorBelow() {
		return moveToFloor(current_floor + 1);
	}

	function hoverOnArrow() {
		var arrow = $(this).find('.arrow');
		if (!$(this).hasClass('disabled') && !arrow.hasClass('hover'))
			$(this).find('.arrow').addClass('hover').animate({opacity: 1}, 300);
	}

	function hoverOutArrow() {
		var arrow = $(this).find('.arrow');
		if (!$(this).hasClass('disabled') && arrow.hasClass('hover'))
			$(this).find('.arrow').removeClass('hover').animate({opacity: 0}, 300);
	}

	var controls = $('#elevator-controls > div')
		.find('.arrow').css({opacity: 0, display: 'block'}).end()
		.hover(hoverOnArrow, hoverOutArrow)
		.click(function(){
			if (!$(this).hasClass('disabled')) {
				if ($(this).hasClass('up'))
					moveFloorAbove();
				else
					moveFloorBelow();
			}
		});

	function getFloorLabel(floor_num) {
		return floors.eq(floor_num).find('h3').text();
	}

	function swapLabelOnArrow(arrow, new_label, is_instant) {
		var speed = 500;

		if (is_instant) {
			speed = 1;
		}
		
		arrow.find('.label').fadeOut(speed, function(){
			$(this).empty().append(new_label).fadeIn(speed);
			if (new_label.hasClass('pseudo-href'))
				arrow.removeClass('disabled');
			else {
				hoverOutArrow.call(arrow[0]);
				arrow.addClass('disabled');
			}
		});
	}

	function updateControls(is_instant) {
		var new_up_label = (current_floor == 0)
			? '<span>' + up_default_label + '</span>'
			: '<span class="pseudo-href">' + getFloorLabel(current_floor - 1) + '</span>';

		var new_down_label = (current_floor == max_floor)
			? '<span>' + down_default_label + '</span>'
			: '<span class="pseudo-href">' + getFloorLabel(current_floor + 1) + '</span>';

		swapLabelOnArrow(controls.filter('.up'), $(new_up_label), is_instant);
		swapLabelOnArrow(controls.filter('.down'), $(new_down_label), is_instant);

		// обновляем ссылку на проект
		$('#nav li:first a').attr('href', floors.eq(current_floor).find('h1 a').attr('href'));
	}

	// FIXME обойти эту проблему в сафари
	if ($.browser.safari || $.browser.msie) {
		$(window).resize(function(){
			shaft.height(getPageHeight());
		}).resize();
	}
	
	updateControls(true);
});

// добавляем анимационных функций в jQuery
jQuery.extend(jQuery.easing, {
	elevator_move: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	}
});