// on dom ready stuff
$(function() {
});

$(window).load(function() {
	Slideshow.init();
});

Slideshow = {
	init: function() {
		this.cont = $('#slideshow');
		this.no = this.cont.find('img').length;
		this.idx = -1;
		
		// add images to dom and preload first 3
		this.cont.find('div').addClass('loading');
		this.noImagesToPreload = 6;
		this.preloadCount = 0;
		this.cont.find('img').each(function(i) {
			var img1 = $('<img>').attr('src', $(this).attr('title'));
			$(this).replaceWith(img1);
			var img2 = $('<img>').attr('src', img1.attr('src').replace(/_s$/, '')).appendTo(img1.parent().next());
			
			if (i < Slideshow.noImagesToPreload / 2) {
				if (img1[0].complete)
					Slideshow.imageLoaded();
				else
					img1.load(function() { Slideshow.imageLoaded(); });
				if (img2[0].complete)
					Slideshow.imageLoaded();
				else
					img2.load(function() { Slideshow.imageLoaded(); });
			}
		});
	},
	
	imageLoaded: function() {
		if (++this.preloadCount == this.noImagesToPreload) {
			this.cont.find('div').removeClass('loading');
			setTimeout('Slideshow.rotate()', 1000);
		}
	},
	
	rotate: function() {
		this.idx = (this.idx + 1) % this.no;
	
		this.cont.find('div').each(function() {
			var img = $(this).find('img:eq(' + Slideshow.idx + ')');
			var pos = $(this).hasClass('t') ? 't' : 'b';
			img.css({ display: 'block', visibility: 'visible' });
			img.css(pos == 't' ? { marginTop: 238 } : { marginTop: 487, opacity: 0 });
			img.animate(
				pos == 't' ? { marginTop: -1 * Math.round((img.height() - 238) / 3 * 2) } : { marginTop: 0, opacity: 1 },
				pos == 't' ? 4000 : 500,
				function() {
					if (pos == 't')
						$(this).animate({ marginTop: -1 * Math.round(($(this).height() - 238) / 2) }, 3000, 'easeOutQuad', function() { Slideshow.hideImage($(this)); });
					else
						Slideshow.hideImage($(this));
				}
			);
		});
	
		setTimeout('Slideshow.rotate()', 8000);
	},
	
	hideImage: function(img) {
		img.parent().css('backgroundImage', 'url(' + img.attr('src') + ')');
		img.css('display', 'none');
	}
}
