﻿var carousel = {
	
	enabled: true,
	carouselId: '',
	type: 'circular', // 'linear' or 'circular'
	itemsDisplayed: null,
	speed: null,
	
	init: function() {
		$(this.carouselId).css('width', ($(this.carouselId + ' > li').length + 1) * this.getItemWidth() + 'px');
		if(this.type == 'circular') {
			$(this.carouselId).css('left', -this.getItemWidth());
			$(this.carouselId + ' li:first').before($(this.carouselId + ' li:last')); 
		} else {
			$(this.carouselId).css('left', 0);
		}
	},
	
	getCurrentXPos: function() {
		return $(this.carouselId).position().left;
	},
	
	getItemWidth: function() {
		return $(this.carouselId + ' li').outerWidth();
	},
	
	getTotalItems: function() {
		return $(this.carouselId + ' li').length;
	},
	
	goPrev: function() {
		if(this.enabled) {
			if ($(this.carouselId).is(':animated') || this.getTotalItems() <= this.itemsDisplayed) {
				return false;
			}
			
			if(this.type == 'linear') {
				var xPos = this.getCurrentXPos();	
				if (xPos >= 0) {
					$(this.carouselId).animate( { left: -(this.getItemWidth() * (this.getTotalItems() - this.itemsDisplayed)) }, this.speed );
				} else {
					$(this.carouselId).animate( { left: xPos + this.getItemWidth() }, this.speed);
				} 
			}
			
			if(this.type == 'circular') {
				var itemWidth = this.getItemWidth();
				var cid = this.carouselId;
				$(cid).animate({'left' : this.getCurrentXPos() + itemWidth }, this.speed, function(){
					$(cid + ' li:first').before($(cid + ' li:last'));
					$(cid).css({ left : -itemWidth + 'px' });
				});
			}
			
		}
	},
	
	goNext: function() {
		if(this.enabled) {
			if ($(this.carouselId).is(':animated') || this.getTotalItems() <= this.itemsDisplayed) {
				return false;
			}
			
			if(this.type == 'linear') {
				var xPos = this.getCurrentXPos();
				var totalItems = $(this.carouselId + '> li').length;
				if (xPos ==  -(this.getItemWidth() * (totalItems - this.itemsDisplayed))) {
					$(this.carouselId).animate( { left: 0 }, this.speed );
				} else {
					$(this.carouselId).animate( { left: xPos - this.getItemWidth() }, this.speed);
				}
			} 
			
			if(this.type == 'circular') {
				var itemWidth = this.getItemWidth();
				var cid = this.carouselId;
				$(cid).animate({ left: this.getCurrentXPos() - itemWidth }, this.speed, function(){
					$(cid + ' li:last').after($(cid + ' li:first'));
					$(cid).css({ left: -itemWidth + 'px' });
				});
			}
			
		}
	}	
	
}
