/*
 * Typical structure: div(target) < ul < li
 * Example move: $('#myTarget').trigger('carousel-mode', [2]); //2 to the right
 * Works best if you specify the li dimensions in css or js, if you don't please issue a resize 1 second after document is ready for webkit browsers
 */
(function($) {
	$.fn.jayCarousel = function (opt) {
		return $.jayCarousel(this, opt);
	};
	$.jayCarousel = function (target, opt) {
		opt = $.extend({
			visible: 3,
			autocontainer: true,
			animate: {}
		}, opt);
		var $ul = target.children('ul');
		var $li = $ul.children('li');
		var item_size = 0;
		function move(e, direction) {
			//$ul.animate({left:'-='+(direction*item_size)+'px'}, opt.animate);//broken in jquery
			$ul.animate({left:'-='+(direction*item_size)+'px'}, opt.animate.duration, opt.animate.easing, opt.animate.complete);
		}
		function resize() {
			item_size = $li.outerWidth();
			if (opt.autocontainer) target.css('width', (opt.visible*item_size)+'px');
			target.css({	overflow:'hidden',
					position:'relative',
					'z-index':2});
			$ul.css({overflow:'hidden',
				'z-index':1,
				'width': (($li.length + 2) * item_size)+'px',
				'list-style-type':'none',
				height:target.outerHeight()+'px',
				position:'relative'}).show();
		}
		target.bind('carousel-move', move);
		target.bind('resize', resize);
		resize();
		return target;
	};
})(jQuery);

function WebCubePager(target, visible) {
	var a_list = target.find('.container').jayCarousel({visible:visible, autocontainer:false});
	var index = a_list.find('li').length - visible;
	var maxx = index;
	var cur_page = 1;
	var total_pages = Math.ceil(a_list.find('li').length / visible);
	function checkPagination() {
		var left = target.find('.left a img');
		var right = target.find('.right a img');
		if (index >= maxx) {
			left.attr('src', left.attr('src').replace(/-on./,'-off.'));
		} else {
			left.attr('src', left.attr('src').replace(/-off./,'-on.'));
		}
		if (index < 1) {
			right.attr('src', right.attr('src').replace(/-on./,'-off.'));
		} else {
			right.attr('src', right.attr('src').replace(/-off./,'-on.'));
		}
		$('#pager_current').html(cur_page);
		$('#pager_total').html(total_pages);
	}
	target.find('.left a').click(function() {
		if (index >= maxx || cur_page <= 1) return false;
		index+=visible;
		cur_page--;
		checkPagination();
		a_list.trigger('carousel-move', [-visible]);
		return false;
	});

	target.find('.right a').click(function() {
		if (index < 1 || cur_page >= total_pages) return false;
		index-=visible;
		cur_page++;
		checkPagination();
		a_list.trigger('carousel-move', [visible]);
		return false;
	});
	checkPagination();
	return a_list;
}