/**
 * @author Sergey Chikuyonok (serge.che@gmail.com)
 * @link http://chikuyonok.ru
 */$(function(){
	/** Смещение картинок друг относительно друга */
	var image_offset = 10,
		is_animating = false;
	
	function initStack(elem) {
		elem = $(elem);
		var images = elem.find('img'),
			first_image= images.eq(0),
			width = first_image.width();
			
		if (images.length) {
			first_image.parent().css({
				width: width,
				height: first_image.height() + images.length * image_offset
			});
			
			elem.addClass('photo-stack-inited');
			
			elem.find('h2').css('margin-right', width / 2 + images.length * image_offset);
			elem.find('.next').css('margin-left', width / 2 + 30);
			
			// выстраиваем картинки
			images.each(function(i){
				$(this).css({
					left: -i * image_offset,
					top: i * image_offset
				}).click(function(){
					if (!is_animating) {
						var images = elem.find('img'),
							last_img = images.eq( images.length - 1 )[0];
						
						sendImageBack(last_img);
						bringToFront(images.not(last_img));
					}
				});
			});
		}
	}
	
	function sendImageBack(img) {
		img = $(img);
		var offset_top = -img.height() * 1.2,
			offset_left = img[0].offsetLeft * 0.7,
			time = 0.35;
			
		is_animating = true;
		$t(img).tween({
			top: offset_top,
			left: offset_left,
			time: time,
			transition: 'easeoutquad',
			onComplete: function() {
				img.parent().prepend(img);
			}
		}).tween({
			top: 0,
			left: 0,
			time: time * 1.34,
			delay: time,
			transition: 'easeinoutquad',
			onComplete: function() {
				is_animating = false;
			}
		});
	}
	
	/**
	 * @param {jQuery} images
	 */
	function bringToFront(images) {
		var anim_opt = {
			time: 0.3,
			transition: 'easeoutcubic',
			top: '+=' + image_offset,
			left: '-=' + image_offset
		};
		
		images = $.makeArray(images);
		images.reverse();
		
		$.each(images, function(i, n){
			$t(n, anim_opt).tween({
				delay: 0.2 + i * 0.02
			});
		})
	}
	
	$('.photo-stack').each(function(){
		initStack(this);
	});
	
});