var slideshowElementNames = new Array();
var currentPopupsliderElement = 0;
var countdown = null;
var secondsToFade = 6;
var maxPasses = 20;
var currentPasses = 0;
var hover = false;

$(document).ready(function () {
	if (checkSlideshow() && prepareSlideshow()) {
		$('#slideshow').css('display', 'block');
		startCountdown();
		
		$('#slideshow_navigation').hover( function () {
			stopCountdown();
			hover = true;
		}, function () {
			startCountdown();
			hover = false;
		});
	} else {
		slideshowFallback();
	}
});

function checkSlideshow() {
	var i = 0;
	$('.slideshow_specific_content').each(function(){
		slideshowElementNames[i] = $(this).attr('name');
		i++;
	});

	if (slideshowElementNames.length < 1) {
		return false;
	}
	
	return true;
}

function prepareSlideshow() {
	$('#slideshow_navigation').html('');
	$.each( slideshowElementNames, function(key, value){
		// Navigation
		$('#slideshow_navigation').append(
			'<div name="slideshow_navigation_element['+ key +']" onclick="fadeTo('+ key +')" class="slideshow_navigation_element">'+
				(key + 1)+
			'</div>'
		);
		// Bild vorladen
		loadImage($('div[name="'+ slideshowElementNames[key] +'"]').css('background-image'));
	});
	$('div[name="'+ slideshowElementNames[0] +'"]').css('display', 'block');
	$('div[name="slideshow_navigation_element[0]"]').addClass('slideshow_navigation_active');
	return true;
}

function fadeTo(nextPopupsliderElement) {
	stopCountdown();
	currentPasses++;
	$('div[name="slideshow_navigation_element['+ currentPopupsliderElement +']"]').removeClass('slideshow_navigation_active');
	$('div[name="'+ slideshowElementNames[currentPopupsliderElement] +'"]').fadeOut('slow', function () {});
	currentPopupsliderElement = nextPopupsliderElement;
	$('div[name="slideshow_navigation_element['+ currentPopupsliderElement +']"]').addClass('slideshow_navigation_active');
	$('div[name="'+ slideshowElementNames[currentPopupsliderElement] +'"]').fadeIn('slow', function () {});
	if (currentPasses <= maxPasses && !hover) {
		startCountdown();
	}
}

function startCountdown() {
	countdown = window.setInterval('fadeTo('+ getNextPopupsliderElement() +')', (secondsToFade * 1000));
}

function stopCountdown() {
	$('#naviOpen').html(currentPopupsliderElement + " " + getNextPopupsliderElement());
	clearInterval(countdown);
}

function getNextPopupsliderElement () {
	if (currentPopupsliderElement >= (slideshowElementNames.length - 1)) {
		return 0;
	}
	return currentPopupsliderElement + 1;
}

function slideshowFallback() {
	$('#slideshow').css('display', 'block');
	$('div[name="slideshow_specific_content[1]"]').css('display', 'block');
}

function loadImage (imageUrl) {
	var image = new Image(); 
	image.src = imageUrl.replace('url("http://m-linss.de', '').replace('")', '');
}
