// wpgCarousel plugin definition
$.fn.wpgCarousel = function(options) {
	var defaults = {
		wrap: 'both',
		scroll: 1,
		auto: 4,
		initCallback: fnCreateTabs,
		itemVisibleInCallback: {
			onBeforeAnimation: syncTabs
		}
	};
	// Extend our default options with those provided.
	var opts = $.extend(defaults, options);
	
	/*create tabs*/
	function fnCreateTabs(carousel) {
		var wpgCarouselTabbed = $('.wpg-carousel-skin-tabbed');
		if (wpgCarouselTabbed && wpgCarouselTabbed.length > 0) {
			var length = $(wpgCarouselTabbed).find('li').length;
			var tabs = '';
			//create anchor as tabs
			for(var i = 1; i <= length; i++){
				tabs += '<a href="#">' + i + '</a>';
			}
			if (tabs != '') {
				
				$('.jcarousel-control a').bind('click', function() {
					carousel.scroll($.jcarousel.intval($(this).text()));
					return false;
				});
				//prevent autoscroll on hover
				if (carousel.options.auto) {
					$(wpgCarouselTabbed).find('.jcarousel-container')
						.bind('mouseenter', function() { carousel.stopAuto(); })
						.bind('mouseleave', function() { carousel.startAuto(); });
				}
			}
		}
	}
	
	/*synchronize tabs*/
	function syncTabs(carousel, li, idx, action) {
		$(li).parents('.jcarousel-container').find('.jcarousel-control a')
			.removeClass('current') //a a a ...
			.parent() //.jcarousel-control
				.children('a:eq('+(idx-1)+')') //a a a ...
					.addClass('current');
		carousel.stopAuto();
		carousel.startAuto();
	}
	
	// Our plugin implementation code goes here.
	return this.each(function() {
		var $this = $(this);
		$this.addClass('wpg-carousel-skin-tabbed');
		/*init carousel*/
		$('.wpg-carousel-skin-tabbed').find('ul').jcarousel(opts);
	});
};

/**********************
 *  documentReady fn
**********************/

$(document).ready(function() {
	$('.books-published-recently-carousel').wpgCarousel();	
});
