/*
	iSlider based on Apple iTunes Carousel
	Sarah Backhouse 16.12.2010
*/

var iSlider = Class.create ({
	initialize: function(wrapper, options) {
		this.wrapper    		= $(wrapper);
		
		this.images 		= this.wrapper.down('ul.items').select('li');
		this.thumbWrapper	= this.wrapper.down('ul.thumbs');
		this.thumbs 		= this.wrapper.down('ul.thumbs').select('li');

		this.options 		= {
								thumbHeight: 80,
								autoSlide: false
 							}
 		Object.extend( this.options, options || {} );

		this.index			= 0;
		this.currentSlide	= 0;
		this.scrollPos		= 0;
		this.outofview 		= 3 * this.options.thumbHeight;
		this.nextItemPos 	= 2 * this.options.thumbHeight;
		this.scrolling  	= false;
		this.newpositions	= new Array();
							
		for (i=0; i < this.thumbs.length; i++)  {  
			$(this.thumbs[i]).addClassName("thumb-"+i);  
			$(this.images[i]).addClassName("image-"+i); 
			if(i != this.currentSlide) {
				$(this.images[i]).setStyle({opacity: 0});
			}
		}  
		
		this.control		= this.wrapper.down('a.next_slide');
		this.control.observe('click', this.sift.bind(this));

		if (this.options.autoSlide) {
			this.start();
		}
	},
	start : function() {
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), 10*1000);
	},
	sift : function(event) {
		if (this.scrolling) {
			return;
		}
		if (event) { 
			Event.stop(event); 
		}
		if ( this.index < (this.thumbs.length-1)) {
			this.index +=1;
		}
		else {
			this.index = 0;
		}
		this.show(this.index);
		return false;
	},
	show : function(item) {
		this.stop();
		this.scrolling = true;
		
		this.thirdItem = item + 3; 
		if (this.thirdItem >= this.thumbs.length) {
			this.thirdItem = this.thirdItem - this.thumbs.length;
		}
		$(this.thumbs[this.thirdItem]).hide();
		$(this.thumbs[this.thirdItem]).style.top = '-' + this.options.thumbHeight + 'px';
		$(this.thumbs[this.thirdItem]).show();
		$(this.images[item]).show();
				
		var effects = new Array();

		for (i=0; i < this.thumbs.length; i++) {
			effects.push( new Effect.Move($(this.thumbs[i]), { sync: true, y: this.options.thumbHeight, mode: 'relative'}));
		}
		
		effects.push( new Effect.Opacity($(this.images[this.currentSlide]), {sync: true, from: 1.0, to: 0}));
		effects.push( new Effect.Opacity($(this.images[item]), {sync: true, from: 0, to: 1.0}));
		
		new Effect.Parallel(effects, { duration: 0.4, fps: 35, queue: {position: 'end', scope: 'islider'}, afterFinish: function() { $(this.images[this.currentSlide]).hide(); this.scrolling = false; this.currentSlide = item; if (this.options.autoSlide) { this.start();}}.bind(this) });
	},
	stop: function() {
		clearTimeout(this.timer);
	},
	periodicallyUpdate: function() {  
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.sift();
			this.start();
		}
	}
});

