$.widget('ui.carousel', {
	options: {
		previous: '.control.previous',
		next: '.control.next',
		items: '.item'
	},
	
	_create: function() {
		this.items = typeof(this.options.items) == 'string' ? $(this.options.items, this.element) : this.options.items;
		this.itemWidth = this.items.width();
		this.index = 0;
		this.perContainer = Math.ceil(this.element.width() / this.items.width());
		
		this._initPosition();
		
		this.previousControl = typeof(this.options.next) == 'string' ? $(this.options.previous, this.element) : this.options.previous;
		this.nextControl = typeof(this.options.next) == 'string' ? $(this.options.next, this.element) : this.options.next;

		this._bind(this.previousControl, {click: 'click'});
		this._bind(this.nextControl, {click: 'click'});
	},
	_initPosition: function() {
		var self = this,
			beforeCurrent = Math.floor(this.perContainer / 2),
			halfCount = Math.floor(this.items.length / 2),
			left = -(halfCount - beforeCurrent) * this.itemWidth,
			firstIndex = this.index - halfCount,
			setLeft = function() {
				var l = left;
				left += self.itemWidth;
				return l + 'px';
			};
			
			var setCount = this.items.slice(firstIndex).css('left', setLeft).length;
			
			if (this.items.length - setCount > 0) {
				this.items.slice(0, this.items.length - setCount).css('left', setLeft);
			}
	},
	click: function(event) {
		var self = this,
			direction = $(event.currentTarget)[0] == this.nextControl[0],
			itemsLength = this.items.length,
			animationCount = itemsLength - 1;
		
		if (this.element.hasClass('ui-state-animation')) {
			return;
		}
		
		this.element.addClass('ui-state-animation');
		this.items.animate(
			{
				left: (direction ? '-' : '+') + '=' + this.itemWidth
			}, 'bounce',
			function() {
				if (!animationCount--) {
					self.element.removeClass('ui-state-animation');
					
					self.index += direction ? 1 : -1;
					if (self.index == itemsLength) {
						self.index = 0;
					} else if (self.index < 0) {
						self.index = itemsLength - 1;
					}
					
					self._initPosition();
				}
			}
		);
	}
});

