// SimpleSlideshowIt.js v1.3
//
// Copyright (c) 2009 mdgreenfield
// Author: Matthew D. Greenfield | http://mdgreenfield.com
// Date: 3-15-2009
// 
// SimpleSlideshowIt is freely distributable under the terms of the GNU GENERAL PUBLIC LICENSE.
//
/*-----------------------------------------------------------------------------------------------*/

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

	options: {
		duration: 750,
		delay: 7000,
		start: 0,
		
		caption_id: null,
		
		menu : {
			togglers : null,
			delay_after_click: 0
		}
	},
				
	initialize: function() {
		var params = Array.link(arguments, {'container': Element.type, 'options': Object.type, 'elementsContainer': $defined });
		
		this.setOptions(params.options);
		
		this.current = this.options.start;
		
		this.container 	= $(params.elementsContainer);
		this.slides 	= this.container.getChildren();

		this.caption = (this.options.caption_id != null) ? $(this.options.caption_id) : false;
		
		this.slides.fade('hide');
		this.slides[this.current].fade('show');

		//if there was a title then that is the caption that needs to be inserted
		if(this.slides[this.current].get('title') && this.caption)
			this.caption.set('html', this.slides[this.current].get('title'));

		//if a collection of togglers was passed then lets take it and assign click events to each of them
		if($defined(this.options.menu.togglers))
		{
			this.menu 		= $$(this.options.menu.togglers);
			
			this.menu[this.current].addClass('selected');
			
			this.menu.each(function(item, index){
				item.addEvent('click', function(event){
					//this.menu[this.current].removeClass('selected');
					//this.menu[index].addClass('selected');
				
					this.changeImage(index);
					
					$clear(this.timer);
	
					this.nextOnClick.delay(this.options.menu.delay_after_click, this);
				}.bind(this));
			}, this);
		}
		
		//now lets start the slideshow
		this.timer = this.next.periodical(this.options.delay, this);
	},
	
	changeImage: function(index){
		if(index != this.current)
		{
			var previous = this.current;
			this.current = index;
			
			if($defined(this.options.menu.togglers))
			{
				this.menu[previous].removeClass('selected');
				this.menu[this.current].addClass('selected');
			}
			
			//if there was a title then that is the caption that needs to be inserted
			if(this.slides[this.current].get('title') && this.caption)
				this.caption.set('html', this.slides[this.current].get('title'));

			//take the image that we are going to show, take it out of the DOM, set it's opacity to 0, and then inject it at the bottom so that it shows first
			this.slides[this.current].dispose().setStyle('opacity', 0).inject(this.container, 'bottom').fade('in');
		}
	},
	
	next: function() {
		if(this.current < this.slides.length - 1)
		{
			this.changeImage(this.current + 1);
		}
		else
		{
			this.changeImage(0);
		}
	},
	
	nextOnClick: function(){
		this.timer = this.next.periodical(this.options.delay, this);
	}
});