(function($) {

  $.fn.rotatingGallery = function(options) {
	// build main options before element iteration
	var opts = $.extend({}, $.fn.rotatingGallery.defaults, options);
	
	return this.each(function() {
		var $this = $(this);
		$this.currentPage = 1;
		$this.itemsPerPage = options.itemsPerPage;
		$this.rotatingGalleryList = $this.find("ul");
		$this.rotatingGalleryItems = $this.find("li");
		$this.pageWidth = $($this.find("li")[0]).outerWidth(true) * $this.itemsPerPage;
		
		//get the next and previous buttons
		$this.rotatingGalleryItems_next = $this.find(".jsRotatingGallery_next");
		$this.rotatingGalleryItems_previous = $this.find(".jsRotatingGallery_previous");
		
		//calculate how many pages there are
		$this.numPages = Math.ceil($this.rotatingGalleryItems.length/$this.itemsPerPage);
		//console.log($this.numPages);
		//a convention to pass $this into an anonymous function, as seen below.
		var that = $this;
		
		//add click events to the buttons.
		$this.rotatingGalleryItems_next.click(function(evt){
			evt.preventDefault();
			$.fn.rotatingGallery.pageNext(that);
			
		});
		$this.rotatingGalleryItems_previous.click(function(evt){
			evt.preventDefault();
			$.fn.rotatingGallery.pagePrevious(that);
		});
		
	});
};
  
  
$.fn.rotatingGallery.defaults = {
    itemsPerPage: 10
};
  
$.fn.rotatingGallery.pageNext = function(obj){
//console.log(obj.rotatingGalleryList);
	if(obj.currentPage++ >= obj.numPages){
		obj.currentPage = 1;
	}
	//console.log(obj.currentPage);
	
	$(obj.rotatingGalleryList).animate(
		{
			left:(((obj.currentPage -1) * obj.pageWidth) * -1)
		},
		1000, 
		function(){}
	);
}

$.fn.rotatingGallery.pagePrevious = function(obj){
//console.log(obj.rotatingGalleryList);
	if(obj.currentPage-- <= 1){
		obj.currentPage = obj.numPages ;
	}
	//console.log(obj.currentPage);
	$(obj.rotatingGalleryList).animate(
		{
			left:(((obj.currentPage -1) * obj.pageWidth) * -1)
		},
		1000, 
		function(){}
	);
	
}


})(jQuery);


