ja.Carousel = Class.create({

	elements: {
		container: null,
		images: [],
		controls: {
			play: null,
			stop: null,
			next: null,
			prev: null
		},
		frame: null
	},
	delay: 5, // sec
	current: 0,
	executer: null,

	initialize: function(container,cfg) {
		var frameclassname = cfg.frameclassname || 'carousel-frame'
		this.elements.container = $(container)
		this.elements.container.childElements().each( function (img,i) {
			if (String(img.tagName).toUpperCase() != 'IMG') return;
			if(!img.hasClassName(frameclassname)) this.add(img)
			else                                  this.elements.frame = img
		},this)
		if (cfg.images) {
			cfg.images.each(function(img,i) { this.add(img) }, this)
		}
		if (cfg.controls) {
			var tc = this.elements.controls
			var cc = cfg.controls
			$A(['next','prev','play','stop']).each(function(cmd,i) {
				if ($(cc[cmd])) tc[cmd] = $(cc[cmd]).observe('click',this[cmd].bind(this))
			},this)
		}
		if (!isNaN(cfg.delay)) this.delay = cfg.delay
		if (cfg.transition) this.transition = cfg.transition
		this.get(0).show()
	},
	add: function(img) {
		var element = Object.isElement($(img))
		            ? $(img).remove()
		            : new Element('img',img)
		this.elements.container.insert(element)
		if (this.elements.images.length) element.hide()
		this.elements.images.push(element)
		return this
	},
	get: function(i) {
		var idx = i % this.elements.images.length
		if (idx < 0) idx += this.elements.images.length
		return this.elements.images[idx]
	},
	transition: function (from,to,carousel) {
		from.hide()
		to.show()
	},
	timerStart: function() {
		this.timerStop()
		this.executer = new PeriodicalExecuter(this.next.bind(this), this.delay)
		return this
	},
	timerStop: function() {
		if (this.executer) this.executer.stop()
		this.executer = null
		return this
	},
	timerReset: function() {
		if (this.executer) this.timerStart()
		return this
	},
	stop: function() {
		var c = this.elements.controls
		if(c.stop) c.stop.hide()
		if(c.play) c.play.show()
		this.timerStop()
		return this
	},
	play: function() {
		var c = this.elements.controls
		if(c.stop) c.stop.show()
		if(c.play) c.play.hide()
		this.timerStart()
		return this
	},
	next: function() {
		this.timerReset()
		this.transition(this.get(this.current),this.get(++this.current),this)
		return this
	},
	prev: function() {
		this.timerReset()
		this.transition(this.get(this.current),this.get(--this.current),this)
		return this
	}
})

