/* ------------ Diaschau ----------------------------- */

function callbackFunc(frontloaded) {
	if(frontloaded == window.container_toggle) {
		window.first_load = false;
		window.next_image = nextImage();
		current_inactive = window.container_toggle ? window.back_container : window.front_container;
		current_inactive.attr('src', 'index.php?rex_resize=' + window.resize_values + window.next_image);
	} else {
		if(!window.first_load) {
			var elapsed = new Date().getTime() - window.now;

			// leave no Timeout uncleared
			clearTimeout(window.current_timeout);

			if(elapsed >= 0 && elapsed < window.interval_ms) {
				// Fade after remaining time
				window.current_timeout = window.setTimeout(function() {
					crossFade();
				}, window.interval_ms - elapsed);
			} else {
				// Fade directly
				crossFade();
			}
		}
	}
}

function nextImage() {
	window.image_counter += 1;
	if(window.image_counter >= window.bg_images.length) {
		window.image_counter = 0;
	}
	return window.bg_images[window.image_counter];
}
function imageDesc() {	
	if(window.image_counter < window.bg_image_texts.length) {
		return window.bg_image_texts[window.image_counter];
	} else {
		return '';
	}
}
function changeTitles() {
	// leave no Timeout uncleared
	clearTimeout(window.desc_timeout);
	
	// Fade out old title
	window.subtitle_container.fadeOut(window.fade_time/2);
	
	// After half fade_time change text to next title and fade in
	window.desc_timeout = window.setTimeout(function() {
		window.subtitle_container.text(window.next_text);
		window.subtitle_container.fadeIn(window.fade_time/2);
		window.back_container.attr("title", window.next_text);
		window.dia_container.attr("title", window.next_text);
	}, window.fade_time/2);
}

function crossFade() {
	if(window.container_toggle) {
		// (virtually) switch active container
		window.container_toggle = false;
		// change image description content for h2 and img title
		if(window.change_titles == true) {
			window.next_text = imageDesc();
			changeTitles();
		}
		// fade
		window.front_container.fadeOut(Number(window.fade_time), function() {
			// load next image in background
			callbackFunc(window.container_toggle);
			// reset time now
			window.now = new Date().getTime();
		});
	} else {
		// (virtually) switch active container
		window.container_toggle = true;
		// change image description content for h2 and img title
		if(window.change_titles == true) {
			window.next_text = imageDesc();
			changeTitles();
		}
		// fade
		window.front_container.fadeIn(Number(window.fade_time), function() {
			// load next image in background
			callbackFunc(window.container_toggle);
			// reset time now
			window.now = new Date().getTime();
		});
	}
}

jQuery.fn.fadeToggle = function(speed, easing, callback) { 
   return this.animate({opacity: 'toggle'}, speed, easing, callback); 
};