/**
 * @author Vlad Yakovlev (scorpix@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @version 0.1
 * @date 2009-09-09
 * @requires jQuery
 */

$(function() {

	/**
	 * Морфер людей.
	 */
	function Morpher(rootBlock) {
		var
			picturesContainer = rootBlock.find('.pictures .container'),
			pictures = rootBlock.find('.pictures img');

		var
			height = rootBlock.find('.pictures').height(),
			fullHeight = 0,
			loadCounter = 0,
			isHover = false,
			count,
			/**
			 * Интервал анимации.
			 * @type {Number}
			 */
			interval = 15,

			curIndex = 0;

		init();

		function init() {
			if (!rootBlock.length) return;

			for (var i = 0; i < pictures.length; i++) {
				var image = new Image();
				image.onload = onImageLoad;
				image.src = pictures.eq(i).attr('src');
			}
		}

		function onImageLoad() {
			++loadCounter == pictures.size() && load();
		}

		function load() {
			for (var i = 0; i < pictures.length; i++) {
				fullHeight += pictures.eq(i).height();
			}

			count = parseInt(fullHeight / height);

			picturesContainer.height(fullHeight);
			pictures.css('position', 'relative');

			rootBlock.hover(function() {
				isHover = true;
				hoverIn();
			}, function() {
				isHover = false;
				hoverOut();
			});
		}

		function hoverIn() {
			if (!isHover || curIndex + 1 >= count) return;

			curIndex++;
			picturesContainer.css('top', -curIndex * height);
			setTimeout(hoverIn, interval);
		}

		function hoverOut() {
			if (isHover || 0 > curIndex - 1) return;

			curIndex--;
			picturesContainer.css('top', -curIndex * height);
			setTimeout(hoverOut, interval);
		}
	}

	$('.morph_human').each(function() {
		new Morpher($(this));
	});
});
