var mainpos = 0;
var int_action;
var bilder = new Array("001.jpg", "009.jpg","010.jpg","011.jpg", "012.jpg","013.jpg","014.jpg","015.jpg","016.jpg","017.jpg","018.jpg","019.jpg","020.jpg","021.jpg","022.jpg","023.jpg","024.jpg","025.jpg","026.jpg","027.jpg","028.jpg","029.jpg","030.jpg","031.jpg","032.jpg","033.jpg","034.jpg","035.jpg");

var amountheadslide = 0;
var curhead = 0;
var slideinterval;

function change_images() {
	var maxlength = $(".slideelement").length -1;
	
	var tpos = maxlength;
	//console.clear();
	
	$(".slideelement").each(function () {
		var bildpath = "";
		if ($(this).hasClass("bigslide"))		bildpath = "./bilderwechsel/tall/";
		if ($(this).hasClass("tinyslide"))		bildpath = "./bilderwechsel/tiny/";
		if ($(this).hasClass("midslide"))		bildpath = "./bilderwechsel/mid/";
		if ($(this).hasClass("midtallslide"))	bildpath = "./bilderwechsel/tallmid/";
		if ($(this).hasClass("privatslide"))	bildpath = "./bilderwechsel/privat/";
		
		var tid = $(this).attr("id");
		var extractposnummer = /^bildarea0([0-9]+)$/;
		var tsplit = extractposnummer.exec(tid);
		var curnum = (parseInt(tsplit[1],10) -1);
		
		var array_bild_pos = tpos + mainpos;
		
		if (array_bild_pos > maxlength) {
			array_bild_pos -= $(".slideelement").length;
		}
		
		$(this).fadeOut(500, function () {
			$(this).css("backgroundImage","url('"+ bildpath + bilder[array_bild_pos] +"')");
			$(this).fadeIn(500);
		});
		
		
		//console.log("Bildpos " + tpos +" mainpos "+ mainpos +" errechnete array pos: "+ array_bild_pos);
		
		tpos--;
		if (tpos < 0) mainpos++;
		if (mainpos == bilder.length) mainpos = 0;
		
	});
}


function randsort(a, b) {
	var randnum = Math.round(Math.random() * 2 -1);
	return randnum;
}

$(document).ready(function () {
	
	bilder.sort(randsort);
	change_images();
	int_action = window.setInterval("change_images()", 4000);
	
	if ($(".slideelement2").length > 0) {
		amountheadslide = $(".slideelement2").children("img").length;
		
		slide_head();
		slideinterval = window.setInterval("slide_head()", 3000);
	}
	
});

function slide_head() {
	var lastone = curhead;
	var nextone = (lastone == amountheadslide) ? 1 : lastone + 1;
	//alert("Sliding: From:"+ curhead + " To:"+ nextone);
	
	if (lastone > 0)
		$(".slideelement2").children("img:nth-child("+ lastone +")").fadeOut(1000);
	
	$(".slideelement2").children("img:nth-child("+ nextone +")").fadeIn(1000);
	
	curhead = nextone;
}
