var carousel = {};

if ('object' != typeof carouselSlideshow) carouselSlideshow = null;

carousel.hoveron = function(t){
	$(t).toggleClass('hover');
}
carousel.hoveroff = function(t){
	$(t).removeClass('hover');
}

carousel.init = function() {
	carousel.moved = 0;

	var images = $("#carousel div.wrap");

	images.hover(
		function() { carousel.hoveron(this); },
		function() { carousel.hoveroff(this);}
	);

	var shift = $("#carousel div.wrap:first").width();
	var l = images.length;
	var cars = $("#carcont").width() - l * shift;
	var crsl = $("#carousel");
	var visible = Math.floor($("#carcont").width() / shift);
	carousel.visible = visible;
	carousel.center = Math.floor(visible / 2);
	if (carouselSlideshow && carouselSlideshow.sizeOfBigCar) {
		carousel.center -= carouselSlideshow.sizeOfBigCar;
	}
	var i = 0;
	var prev = 'prev';
	var next = 'next';
	carousel.next = $('#next');
	carousel.prev = $('#prev');

	if (l > visible) {
		carousel.next.addClass(next);

		carousel.next.click(function() {
			if (i > cars) {
				i -= shift;
				carousel.move(crsl, i, 1);
				carousel.prev.addClass(prev);
				if (i <= cars) {
					$(this).removeClass(next);
				}
			}
		});

		carousel.prev.click(function() {
			if (i < 0) {
				i += shift;
				carousel.move(crsl, i, -1);
				carousel.next.addClass(next);
				if (i == 0) {
					$(this).removeClass(prev);
				}
			}
		});

		if (!$(crsl).hasClass('no-initial-shift')) {
			carousel.trigger((Math.floor((l - visible) / 2)));
		}
	}

	$("#carousel a:not(.flash-link, a.playnow-link, a[target='dvdcover'])").click(function() {
		var href = $(this).attr("href");
		var popup = href.match("#(\\w{1,3},\\w{1,3})");
		if (popup && popup[1]) {
			var size = popup[1].split(',');
			window.open(href, '_blank','width='+(parseInt(size[0]) || '320')+',height='+(parseInt(size[1]) || '240')+',resizable=yes')
			return false;
		}
		return true;
	});
}

carousel.trigger = function(n, triggered) {
	if (n < 0) {
		n *= -1;
		var button = carousel.prev;
	}
	else {
		var button = carousel.next;
	}

	carousel.triggered = triggered || false;
	for (var i = 0; i < n; i++) {
		button.trigger('click');
	}
	carousel.triggered = false;
}

carousel.move = function(crsl, i, n) {
	carousel.moved += n;
	if (!carousel.triggered) {
		crsl.animate({"left": i+"px"}, "slow");
		if (carousel.hasSlideshow) {
			carouselSlideshow.changeCurrent(carousel.currentIndex + n);
		}
	}
	else {
		crsl.css({left: i + 'px'});
	}
}

$(function(){
	carousel.init();
});
