// (c) 2010 Dan Hartmann Designs, LLC
// based on copyrighted code from Remy Sharp of JQueryForDesigners.com

$.fn.infiniteCarousel = function(){
	return this.each(function(){

		var $gallery = $('.gallery').css('overflow', 'hidden'),
			$slider = $gallery.find('> ul'),
			$items = $slider.find('> li'),
			$single = $items.filter(':first'),

			singleWidth = $single.outerWidth(),
			visible = Math.ceil($gallery.innerWidth() / singleWidth),
			currentPage = 1,
			pages = Math.ceil($items.length / visible);			
	
		// 1. Pad the list with 'visible' number of items, front has the last section, and end has the first
		$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
		$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
		$items = $slider.find('> li'); //reselect new total items
	
		//2. Set the left position to the real 1st item
		$gallery.scrollLeft(singleWidth * visible);
	
		//3. paging left and right function
		function gotoPage(page) {
			var dir = page < currentPage ? -1 : 1,
				n = Math.abs(currentPage - page),
				left = singleWidth * dir * visible * n;
			
			$gallery.filter(':not(:animated)').animate({
				scrollLeft : '+=' + left
			}, 500, function() {
				if (page == 0) {
					$gallery.scrollLeft(singleWidth * visible * pages);
					page = pages;
				} else if (page > pages){
					$gallery.scrollLeft(singleWidth * visible);
					//reset back to start position
					page = 1;
				}
				currentPage = page;
			});
		
			return false;
		}
		$gallery.after('<a class="arrow back">&lt;</a><a class="arrow forward">&gt;</a>');
	
		//4. Bind gotoPage function to forward and back buttons
		$('a.back', this).click(function(){
			return gotoPage(currentPage - 1);
			console.log(currentPage);
		});
		$('a.forward', this).click(function() {
			return gotoPage(currentPage + 1);
			console.log(currentPage);
		});
	
		//create radio button function to move to specific page
		$(this).bind('goto', function (event, page) {
			gotoPage(page);
		});
	
		//Create the next page function for autoscrolling
		$(this).bind('next', function(){
			gotoPage(currentPage + 1);
		});
	});
};	

$(document).ready(function() {
	// var for tracking if autosroll is on or off
	var autoscrolling = true;
	
	$('#portfolioGallery').infiniteCarousel().mouseover(function() {
		autoscrolling = false;
	}).mouseout(function(){
		autoscrolling = true;
	});
	
	setInterval(function() {
		if (autoscrolling) {
			$('#portfolioGallery').trigger('next');
		}
	}, 3500);
});

