$(document).ready(init);
function trace(o) {
	if(window.console) console.log(o);
}
function init() {
	var cnt = 0;
	pictureStacks = 0;
	$(".gallery").each(function() {
		cnt++;
		var n = window["block"+cnt] = initSlides(this);
	});
	$(".imagelink").each(function() {
		this.img = $(this).find("img").get(0);
		this.up = this.img.src;
		this.over = this.rel;
	}).hover(function() {
		this.img.src = this.over;
	},function() {
		this.img.src = this.up;
	});
	
}
function initSlides(ident) {
	pictureStacks++;
	var o = {idx:0,iv:0,cnt:pictureStacks,len:0,subtitle:null};
	o.picts = $(ident).find("img");
	o.subtitle = $(ident).find(".subtitle");
	var p = o.picts.get(0);
	if(p.complete) {
		o.iv = setTimeout(function() { nextSlide(o);},1900);
	} else {
		$(p).one("load",function() {
			o.iv = setTimeout(function() { nextSlide(o);},1500);
		});
	}
}
function nextSlide(d) {
	if(d.iv > 0) clearTimeout(d.iv);
	d.iv = 0;
	var last = d.picts.get(d.idx);
	var idx = d.idx;
	var len = d.picts.length;
	do {
		idx++;
		if(idx >= len) idx = 0;
		var p = d.picts.get(idx);
		if(p.complete) {
			//bild geladen, suche beenden
			break;
		}
	} while(idx != d.idx);

	if(idx == d.idx) {
		//kein nachfolgendes Bild geladen, 1/2 sek. warten...
		d.iv = setTimeout(function() { nextSlide(d) },500);
		return;
	}
	d.idx = idx;
	var cur = d.picts.get(d.idx);
	if(d.subtitle && typeof(cur.attributes.rel) != "undefined") {
		var txt = cur.attributes.rel.value;
		d.subtitle.fadeOut(500,function() {
			d.subtitle.html(txt);
		});
		d.subtitle.fadeIn(1500);
	}
	$(last).css({zIndex:990});
	$(cur).css({zIndex:991,display:"block",opacity:0}).animate({opacity:1.0},2000,function() {
		$(last).hide();
		d.iv = setTimeout(function() {nextSlide(d)},4000);
	});
}
