var JUHPSlideshow = Class.create();
JUHPSlideshow.prototype = {
	initialize : function(element, options) {
		this.id = element.identify();
		this.element = $(element);

		this.element.childElements().each(function(e, i){
			Element.absolutize(e);
			if (i > 0)
				e.hide();
		});
		new PeriodicalExecuter(this.next.bind(this), 5);
	},
	next : function() {
		this.element.firstDescendant().fade({ duration: 1 })
		this.element.insert({ bottom: this.element.firstDescendant() });
		this.element.firstDescendant().appear({ duration: 1 });
	}
}
var JUHPSlideshowNew = Class.create();
JUHPSlideshowNew.prototype = {
	initialize : function(element, options) {
		this.element = $(element);
		this.id = this.element.identify();
		this.children = this.element.childElements();
		this.childrenCount = this.children.length;
		this.currentChild = 0;
		this.skipChild = false;
		this.inTransition = false;

		this.element.insert(this.linkElement = new Element('span'));

		this.children.each(function(e, i) {
			link = new Element('a', { 'href': '#' }).update(i + 1);
            link._slidePosition = i;
			link.on('click', 'a', function(event, element) {
				this.skipChild = true;
				this.goTo(element._slidePosition);
				event.stop();
			}.bind(this));

			e.absolutize();
			if (i > 0) {
				e.hide().setOpacity(0);
				e.setStyle('display:none');
			}
			else {
				link.addClassName('s');
				e.setStyle('display:block');
			}

			this.linkElement.insert(link);
		}.bind(this));
		this.linkElements = this.linkElement.childElements();

		new PeriodicalExecuter(this.next.bind(this), 5);
	},
	next : function() {
		if (this.skipChild)
			return this.skipChild = false;
		if ((position = this.currentChild + 1) >= this.childrenCount)
			position = 0;
		this.goTo(position);
	},
	goTo : function(position) {
		if (this.inTransition || this.currentChild == position)
			return false;
		this.linkElements.invoke('removeClassName', 's');
		this.linkElements[position].addClassName('s');
		this.children[this.currentChild].setStyle('display:block').fade({ duration: 1 });
		this.children[this.currentChild = position].setStyle('display:block').appear({ duration: 1 });
	}
}
Element.addMethods('DIV', {
	slideshow : function(e) { return new JUHPSlideshow(e); },
	slideshow_new : function(e) { return new JUHPSlideshowNew(e); }
});
Event.observe(window, 'load', function() {
	$$('div.juhp-slideshow[rel!="new"]').invoke('slideshow');
	$$('div.juhp-slideshow[rel="new"]').invoke('slideshow_new');
});
