//our slides
var additional_slides_urls = ["/uploads/simple-jquery-slideshows/chinchilla.jpg",
	"/uploads/simple-jquery-slideshows/donkey.jpg",
	"/uploads/simple-jquery-slideshows/penguin.jpg",
	"/uploads/simple-jquery-slideshows/skunk.jpg",
	"/uploads/simple-jquery-slideshows/squirrel.jpg",
	"/uploads/simple-jquery-slideshows/walrus.jpg"];

var slideshow_speed = 3500; //slide changing speed, milliseconds
var animation_speed = 600; //fade in/out speed, milliseconds

var slideshow_container = $(".slideshow_container");
var slideshow_indicator = $("span", slideshow_container); //indicator will show activity status
var slide1_container = $("div:first", slideshow_container);
var slide2_container = $("div:last", slideshow_container);

var slides = [$("img", slide1_container), $("img", slide2_container)]; //init with default images 

//load slides
$.each(additional_slides_urls, function(index, url) {
	var img = $(new Image());
	img.load(function() {
		slides[index + 2] = img;
	}).attr("src", url);
});

var timer;

//start slideshow button 
$(".start_button", slideshow_container).click(function() {
	if (additional_slides_urls.length >= 2) { //if less than 2 additional (not default) slides, it does not make sense to start slideshow
		timer = setInterval(slides_update, slideshow_speed);
		slideshow_indicator.text("[ Running ]"); //change indicator text
	}
	return false; //prevent default click action
});

//stop slideshow button
$(".stop_button", slideshow_container).click(function() {
	clearInterval(timer);
	slideshow_indicator.text("[ Stopped ]");
	return false;
});

var slide_counter = 1; //remember current slide index
var slide_is_ready = true; //slide updating animation finished

function slides_update() {
	if (slide_is_ready) {
		slide_is_ready = false;
		slide_counter++;
		var slide;
		if (slide_counter == additional_slides_urls.length + 2) slide_counter = 0; //if we come to the end of the list - returns to the first slide
		slide = slides[slide_counter];
                
		var change_slides = setInterval(function() {
                        //is next slide loaded?
			if (slide) {
				clearInterval(change_slides); //next slide is ready
                                //slide updating animation start
				if (slide_counter % 2 == 1) animate(slide, slide2_container);
				else animate(slide, slide1_container);
			}
		}, 200);
	} 
        else setTimeout(slides_update, 200);
};

function animate(next_slide, container) {
	var slide_container = container;
	var current_slide = $("img", slide_container);
	var slide = next_slide;

	slide.hide();

	current_slide.fadeOut(animation_speed, function() {
		slide_container.append(slide);
		slide.fadeIn(animation_speed, function() {
			slide_is_ready = true;
		});
		current_slide.remove();
	});
};
