/**
 * Class: Carousel
 * Карусель. Принимает перывым элементом контейнер, вторым массив слайдов,
 * далее опции. В наборе слайдов хотя бы один элемент должен быть видимым. Если видимых
 * элементов несколько , то они должны стоять подряд.
 *
 * Parameters:
 *  prevButton
 * 	nextButton
 * 	duration
 */
Carousel = Class.create(Abstract, {

	initialize: function (scroller, container, slides, options) {

		this.scrolling	= false;
		this.scroller	= scroller;
		this.slides		= slides;
		this.container	= container;
		this.options    = Object.extend({ duration: 0.3 }, options || {});
		this.firstVisible = 0;
		this.lastVisible = -1;

		// перво наперво надо переупорядоч
		this.slides.each(function(slide, index) {
			slide._index = index;
			if (slide.visible() && this.firstVisible == -1)
				this.firstVisible = index;
			if (!slide.visible() && this.firstVisible > -1 && this.lastVisible == -1)
				this.lastVisible = index-1;

			},this);		
		if (this.lastVisible == -1){
			this.lastVisible = this.slides.length - 1 
		}
		this.windowSize = this.lastVisible - this.firstVisible + 1;
		this.options.prevButton.observe('click',this.click.bind(this,-1));
		this.options.nextButton.observe('click',this.click.bind(this,1));
		this._syncButton();
	},
	_syncButton: function (){
		if (this.firstVisible <= 0){
			this.options.prevButton.addClassName(this.options.disableButtonClass);
		}else{
			this.options.prevButton.removeClassName(this.options.disableButtonClass);
		}
		if (this.lastVisible >= this.slides.length - 1){
			this.options.nextButton.addClassName(this.options.disableButtonClass);
		}else{
			this.options.nextButton.removeClassName(this.options.disableButtonClass);
		}
	},
	_repaint: function(){
		var eff = [];
		this.slides.each(function(slide){if (slide.visible()){
			eff.push(new Effect.Opacity(slide,{sync:true,from:1,to:0}));
			}	
		});
		new Effect.Parallel(eff,{duration:this.options.duration,
			afterFinish: function(){
				this.slides.each(function(slide){slide.hide()});
				eff = [];
				for(var i=this.firstVisible;i<=this.lastVisible;i++){
					eff.push(new Effect.Opacity(this.slides[i],{from:0,to:1,sync:true}));
					this.slides[i].setOpacity(0);
					this.slides[i].show();
				}
				new Effect.Parallel(eff,{duration:this.options.duration});
			}.bind(this)
		});
	},			 
	click: function (dir) {
		if (dir == -1){
			if (this.firstVisible < 1)
				return false;
			this.firstVisible -= this.windowSize; 
			if (this.firstVisible < 0)
				this.firstVisible = 0;
			this.lastVisible = 	this.firstVisible + this.windowSize - 1;	
			this._syncButton();
			this._repaint();
		}else{
			if (this.lastVisible >= this.slides.length - 1)
				return false;
			this.lastVisible += this.windowSize;
			if (this.lastVisible > this.slides.length -1)
				this.lastVisible = this.slides.length -1;
			this.firstVisible = this.lastVisible - this.windowSize + 1;
			this._syncButton();
			this._repaint();
		}
		return false;
	}	
	});

