var Smart_carousel = new Class ({

	initialize: function(config) {
		this.carousel = config.carousel; 
		if (!$(this.carousel)) {
			return false;
		}
		
		this.next = config.next;
		this.previous = config.previous;
		this.play = config.play;
		this.items = config.items;
		this.elementy = $(config.items).getElements('li');
		this.ile = this.elementy.length;
		this.item_width = config.item_width;
		this.item_view = config.item_view;
		this.time = config.time;
		this.max_margin =  this.ile * this.item_width - (this.item_view * this.item_width);
		var startczas;

		$(this.next).addEvent('click', function(event){
			event = new Event(event).stop();
			this.next_item();
			$clear(startczas);
			return false;
		}.bind(this));

		$(this.previous).addEvent('click', function(event){
			event = new Event(event).stop();
			this.previous_item();
			$clear(startczas);
			return false;
		}.bind(this));

		this.animation = new Fx.Tween($(this.carousel), {duration: 500});
		if (this.play == 'play')  { startczas =  this.next_item.periodical(this.time,this); }
	},
	
	next_item: function() {
		var carousel = $(this.carousel);
		var max_margin = this.max_margin;
		var item_width = this.item_width;
		var pos = parseInt(carousel.getStyle('left'));
		if (max_margin < 0) {
			return false;
		}
		if(pos == -max_margin){
			this.animation.start('left', 0);
		} else {
			var newposition = pos - item_width;
			this.animation.start('left', newposition);
		}
	},
	previous_item: function() {
		var carousel = $(this.carousel);
		var max_margin = this.max_margin;
		var item_width = this.item_width;
		var pos = parseInt(carousel.getStyle('left'));
		if (max_margin < 0) {
			return false;
		}
		if(pos == 0){
			this.animation.start('left', -max_margin);
		} else { 
			var newposition = pos + item_width;
			this.animation.start('left', newposition);
		}
	
	}

});


