/*
	Class:		Carousel
	Author:		Tom Kentell
	Version:	0.1
	Date:		04/01/2010
*/

var Carousel = new Class({
	Implements: [Options],

	options: {
		carousel: '.carousel',
		hasSlideshow: true
	},

	initialize: function(options) {
		this.setOptions(options);
		var cr = this; //maintain a reference for when /this/ is out of scope
		var slideShows = new Array;

		new Fx.Accordion(this.options.carousel+' .carousel_item h2 a', this.options.carousel+' .list_text');
		if(this.options.hasSlideshow) {
			$$(this.options.carousel+' li:not(.current) .slideshow').fade('hide');

			$$('.slideshow').each(function(e,i) {
				slideShows[i] = new Slideshow({slideTarget:e});
			}.bind(this));
			slideShows[0].start();
		}

		$$(this.options.carousel+' .carousel_item h2 a').addEvent('mouseover', function(e) {
			if(this.getParents('li')[0].hasClass('current')) {
				// don't cancel click event, continue through to link
			} else {
				// stop and do the moo magic
				e.stop();
			}

			if(cr.options.hasSlideshow) {
				// fade out and remove class of current
				$$(cr.options.carousel+' .current .slideshow').fade('out').getParents('li')[0].removeClass('current');
				// fade in and add class of current to clicked item
				this.getParents('li')[0].addClass('current').getChildren('.slideshow').fade('in');

				/*class stop method not normal stop*/
				slideShows.each(function(e) { e.stop(); });
				$$(cr.options.carousel+' .carousel_item').each(function(e,i) {
					if(e.hasClass('current')) {
						slideShows[i].start();
					}
				});
			}

			// remove any instances of pre class (used for styling) and add pre to clicked items previous sibling
			$$(cr.options.carousel+' li').removeClass('pre');
			if(this.getParents('li')[0].getPrevious() != null) {
				this.getParents('li')[0].getPrevious().addClass('pre');
			}
		});
	}
});

var Slideshow = new Class({
	Implements: [Options],

	options: {
		slideTarget: '',
		slideDuration: 4000,
		images: '',
		currentIndex: 0,
		interval: ''
	},

	initialize: function(options) {
		this.setOptions(options);
		this.options.images = this.options.slideTarget.getElements('img');
		this.options.slideTarget.setStyle('display','block');

		/* opacity and fade */
		this.options.images.each(function(img,i) {
			if(i > 0) img.set('opacity',0);
		});
	},

	start: function() {
		var SlideShow = this; //maintain a reference for when /this/ is out of scope
		var images = SlideShow.options.images;
		var currentIndex = SlideShow.options.currentIndex;

		SlideShow.options.interval = setInterval(function() {
			images[currentIndex++].fade('out');
			images[currentIndex %= images.length].fade('in');
			SlideShow.options.currentIndex = currentIndex;
		}, SlideShow.options.slideDuration);
	},

	stop: function() {
		clearInterval(this.options.interval);
	}
});
