$(document).observe('dom:loaded', function(){
	$$('.dotsSwitcher').each(function(ul){ new Images.DotsSwitcher(ul) })
})

var Images = {}
Images.DotsSwitcher = Class.create({
	initialize: function(ul){
		this.ul = ul
		this.count = this.ul.select('li').size()
		this.makeDots()
	},
	makeDots: function(){
		if (this.count > 1) {
			this.dotsContainer = new Element('ul', {'class': 'dots'})
			for (var i=0; i < this.count; i++) {
				this.dotsContainer.insert(new Element('li'))
			}
			this.dots = this.dotsContainer.select('li')
			this.dots.each(function(li){
				li.observe('click', this.click.bind(this))
			}.bind(this))
			this.ul.insert({bottom: this.dotsContainer})
			this.dotsContainer.down('li').addClassName('current')
			
			if (!this.ul.hasClassName('paused')) this.startSlideshow()
		}
	},
	startSlideshow: function() {
		this.slideshowInterval = setInterval(this.nextSlide.bind(this), 5000)
	},
	stopSlideshow: function() {
		clearInterval(this.slideshowInterval)
	},
	nextSlide: function() {
		this.setCurrentIndex((this.currentIndex()+1)%this.count)
	},
	click: function(e){
		this.stopSlideshow()
		this.setCurrentIndex(this.dots.indexOf($(e.target)))
	},
	setCurrentIndex: function(position) {
		this.dots.invoke('removeClassName', 'current')
		this.dots[position].addClassName('current')
		this.switchAttachment()
	},
	currentIndex: function() {
		return this.dots.indexOf(this.ul.down('li.current'))
	},
	switchAttachment: function(index){
		var li = this.ul.down('li')
		li.morph('margin-left:' + -1 * parseInt(li.down('img').width) * this.currentIndex() + 'px', {duration: 0.5})
	}
})

