var PhotoShow = Class.create();
PhotoShow.prototype = {
	initialize: function(element, options) {
	  this.element = $(element);
	  this.options = Object.extend({className: 'photo', duration: 4}, options);
	  this.photos = $A(document.getElementsByClassName(this.options.className, this.element));
	
	  this.preparePhotos();
	  this.registerCallback();
	},
	
	preparePhotos: function() {
		this.currentPhoto = this.photos.first();
		this.element.style.position = 'relative';
		var totalPhotos = this.photos.length;
		this.element.style.height = this.photos.max(function(photo, index) {
			var visible = Element.visible(photo);
			var height;
			Element.setStyle(photo, {position: 'absolute', width: '100%', left: '0px', zIndex: totalPhotos - index});
			if (!visible) {
				Element.show(photo);
			}
			height = Element.getHeight(photo);
			if (!visible) {
				Element.hide(photo);
			}
			return height;
		}).toString() + 'px';
	},
	
	nextPhoto: function() {
	  return this.photos[(this.photos.indexOf(this.currentPhoto) + 1) % this.photos.length];
	},
	
	registerCallback: function() {
	  window.setTimeout(this.tick.bind(this), this.options.duration * 1000);
	},
	
	shiftPhotos: function() {
		this.photos.each(function(photo, index) {
			photo.setStyle({zIndex: parseInt(photo.getStyle('z-index'))+1});
		});
		this.currentPhoto.setStyle({zIndex: 1});
	},
	
	tick: function() {
	  var currentPhoto = this.currentPhoto;
	  var nextPhoto = this.nextPhoto();
	  new Effect.Fade(currentPhoto, {
		duration: 2,
		afterFinish: (function(effect) {
			this.shiftPhotos();
			this.currentPhoto.setOpacity(1);
			this.currentPhoto.setStyle({display: 'block'});
			this.currentPhoto = nextPhoto;
			this.registerCallback();
		}).bind(this)
	  });
	}
}

Event.observe(window, 'load', function() {
	if ($('home_graphic_images')) {
		new PhotoShow('home_graphic_images', {duration: 4});
	}
});