$(document).ready(function(){

	$(".b-car__i LI").clone().removeClass("current").insertAfter($(".b-car__i LI:last"));

	$("<a />")
		.attr({ "href": "#" })
		.css({
			"left": 45,
			"top":  110,
			"position": "absolute",
			"height": 220,
			"width": 220,
			"z-index": 2
		})
		.bind("click", back)
		.prependTo($(".b-car__i"))
	;
	$("<a />")
		.attr({ "href": "#" })
		.css({
			"left": 785,
			"top":  110,
			"position": "absolute",
			"height": 220,
			"width": 220,
			"z-index": 2
		})
		.bind("click", fwd)
		.prependTo($(".b-car__i"))
	;

	$("#slider-nav LI A").each(function(i, item) {
		$(item).bind("click", { "index": i + 1 }, slide);
	});

});

jQuery.extend( jQuery.easing,
{
	swap1: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	}
});

var moving = false;
var currentImage = 1;

function move(count) {
	if (count == 0) return false;
	if (moving) return false;
	moving = true;

	var current = $(".b-car .current");
	var next    = current;

	if (count > 0) {
		for (var i = 0; i < count; i++) { next = next.next("LI"); }
	}
	else {
		for (var i = 0; i > count; i--) {
			$(".b-car__i LI:last").clone().insertBefore($(".b-car__i LI:first"));
			$(".b-car__i LI:last").remove();
			$(".b-car__i").css({ left: parseInt($(".b-car__i").css("left")) - 276 });
			next = next.prev("LI");
		}
	}

	current.animate({"margin-top": 100 }, 600, 'swap1').find("IMG").animate({ "height": 200}, 600, 'swap1');
	next.animate({ "margin-top": 0 }, 600, 'swap1').find("IMG").animate({ "height": 389}, 600, 'swap1');
	$(".b-car__i").animate(
		{ "left": parseInt($(".b-car__i").css("left")) - 276 * count }, 600, 'swap1',
		function() {
			next.addClass("current");
			current.removeClass("current");

			if (count > 0) {
				for (var i = 0; i < count; i++) {
					$(".b-car__i LI:first").clone().insertAfter($(".b-car__i LI:last"));
					$(".b-car__i LI:first").remove();
					$(".b-car__i").css({ left: parseInt($(".b-car__i").css("left")) + 276 });
				}
			}
			moving = false;
		}
	);

	currentImage = currentImage + count;
	if (currentImage <= 0) currentImage = currentImage + 6;
	if (currentImage >  6) currentImage = currentImage - 6;

	$("#slider-nav LI").removeClass("cur");
	$("#slider-nav LI:nth-child(" + currentImage + ")").addClass("cur");

	return false;
}

function fwd () { return move( 1); }
function back() { return move(-1); }

function slide(event) { return move(event.data.index - currentImage); }
