$j.fn.latestProducts = function () {
	return this.each(function () {
		var wrapper = $j(this),
		showcase = wrapper.find('> div'),
		slider = showcase.find('> ul'),
		items = slider.find('> li'),
		single = items.filter(':first'),
		currPage = maxPage = 1,
		url = slider.attr('data-url'),
		singleWidth = single.outerWidth();

		function gotoPage(page) {
			var dx = ( page < currPage ) ? 1 : -1;
			currPage = page;

			if ( currPage >= 1 ) { 
				if ( currPage > maxPage ) {

					maxPage = currPage;

					Panagora.ajax({
						url: url,
						data: {
							page: maxPage,
							limit: 6,
							OrderBy: 'Published',
							partial: 'middle-row',
							skip_layout: 1
						},
						dataType: 'html',
						success: function (content) {
							if ( content ) {
								onContentRecieved(content, dx);
							} else {
								currPage = currPage - 1;
								maxPage = currPage;
								showcase.find('div.forward').hide();
							}
						}
					});

				} else {
					animateSlider(dx);
				}
			} else {
				currPage = 1; 
			}

			return false;
		}
		
		function onContentRecieved(content, dx) {
			slider.css('width', singleWidth * 6 * maxPage).append(content);
			animateSlider(dx);
		} 

		function animateSlider(dx) {
			if ( !dx ) dx = 1;
			slider.animate({
				left : '+=' + ( dx * singleWidth * 6 )
			}, 1500, 'swing', function() {
				if ( currPage == 1 ) {
					showcase.find('div.back').hide();
				} else {
					showcase.find('div.back').show();
				}
			});
			showcase.find('div.forward').show();
		}

		// create a public interface to move to a specific page
		$j(this).bind('goto', function (e, page) { gotoPage(page); });

		// Bind to the forward and back buttons
		slider.after('<div class="arrow back" style="display:none;"></div>');
		slider.after('<div class="arrow forward"></div>');
		$j('div.back', this).click(function (e, page) { gotoPage( currPage - 1 ); });
		$j('div.forward', this).click(function (e, page) { gotoPage( currPage + 1 ); });
	});
}


$j(function($) {
	$('.front-carousel').frontpageCarousel();
	$('.infinite-carousel').infiniteCarousel();
	$('#showcase-tab li').click(function () {
		$('.front-carousel').trigger('goto', this.getAttribute('panagora:count'));
	});
	$('#recent-additions').latestProducts();
});
