vdwCarousel = {
	init : function() {
		$jq('#product-catalog-pages').jcarousel({
			scroll : 1,
			initCallback: vdwCarousel.pagesInitCallback,
			itemFirstInCallback : vdwCarousel.updatePagination
		});
		vdwCarousel.addExternalControls();
		var c = vdwUtil.readCookie('fpfr_carousel_position');
		var carouselStart = c ? Number(c) : 1;
		$jq('#product-catalog-horizontal').jcarousel({
			scroll : 1,
			start : carouselStart,
			itemFirstInCallback : vdwCarousel.slideshowItemFirstInCallback
		});
	},
	pagesInitCallback : function(carousel) {
		vdwCarousel.pages = carousel;
	},
	slideshowInitCallback : function(carousel) {
		vdwCarousel.slideshow = carousel;
	},
	slideshowItemFirstInCallback : function(carousel, item, idx, state) {
		vdwUtil.createCookie('fpfr_carousel_position', idx);
	},
	addExternalControls : function() {
		var pageCount = $jq('.product-catalog-page').length;
		$extControlsHTML = $jq('<div></div>').addClass('pagination-controls');
		$extControlsHTML.append('<div class="btn-prev-page"><a href="#">< previous</a></div>');
		$extControlsHTML.append('<div class="btn-next-page"><a href="#">next ></a></div>');
		$paginationWrapper = $jq('<div class="pagination-wrapper"></div>');
		for (var i = 1; i <= pageCount; i++) {
			var $linkHTML = $jq('<a href="#">' + i + '</a>').data('page', i).appendTo($paginationWrapper);
			if (i != pageCount) { $paginationWrapper.append(' | '); }
		}
		$paginationWrapper.find('a:first').addClass('current');
		$extControlsHTML.append($paginationWrapper);
		$paginationWrapper.find('a').click(function(e) {
			e.preventDefault();
			var index = $jq(this).parent('div').find('a').index(this);
			vdwCarousel.pages.scroll(index + 1);
			vdwCarousel.updatePagination();
		});
		$extControlsHTML.find('.btn-next-page a').click(function(e) {
			e.preventDefault();
			vdwCarousel.pages.next();
		});
		$extControlsHTML.find('.btn-prev-page a').click(function(e) {
			e.preventDefault();
			vdwCarousel.pages.prev();
		});
		$extControlsHTML.appendTo('#product-catalog #product-links, #products #product-links');
		$jq('.pagination-controls').clone(true).prependTo('#product-catalog #product-links, #products #product-links');
	},
	updatePagination : function(carousel, item, idx, state) {
		$jq('.pagination-wrapper').each(function() {
			$jq(this).find('a').removeClass('current').end().find('a:nth-child(' + (idx) + ')').addClass('current');
		});
	}
}

$jq(document).ready(vdwCarousel.init);