﻿
// DOM Ready
$(document).ready(function() {

    // images length
    max = $(images).length;
    animatordiv = $("div#animator");
    // at least 1 image exist
    if (max > 0) {
        // load the first image               
        AnimateImage(0);
    }
    else {
        $(animatordiv).removeClass('loadingIntro');
    }
});

function AnimateImage(index) {


    var img = new Image();
    // image onload

    if (index == 0) {
        $(img).load(function() {
            $(this).css('display', 'none'); // since .hide() failed in safari
            $(animatordiv).append(this);
            $(animatordiv).removeClass('loadingIntro');
            $(this).fadeIn(fadeIn, function() {

                PreloadImage(1);
                setTimeout("CheckLoading(1)", duration);
            });
        }).error(function() {
            // on error remove current
            $(curr).remove();
        }).attr('src', images[index]);
    }
    else {
        FadeOut(index);
    }
}

function CheckLoading(index) //index obrazku, ktory chceme checknut
{
    if ($('#animator').children().length == (index + 1)) //ak sa uz nacital - je v DIVe, tak ho animovat
    {
        AnimateImage(index);
    }
    else //ak nie, tak nastavit semafor tak, aby sa animoval sam
    {
        semaphore = 1;
    }
}

function PreloadImage(index) {
    var img = new Image();
    $(img).load(function() {
        $(this).css('display', 'none');
        $(animatordiv).append(this);
        if (semaphore == 1) { semaphore = 0; AnimateImage(index) }
    }).attr('src', images[index]);

}

function FadeOut(index) {
    //fade current out
    if (index < max) {
        $("#animator").children().eq((index - 1)).fadeOut(fadeOut, function() {
            $("#animator").children().eq((index - 1)).css("display", "none");
            FadeIn(index);
        });
    }
    else {
        $("#animator").children().eq((index - 1)).fadeOut(fadeOut, function() {
            $("#animator").children().eq((index - 1)).css("display", "none");
            repeatAnimation();
        });
    }
}

function FadeIn(index) {
    $("#animator").children().eq(index).fadeIn(fadeIn, function() {
        // once the current loaded, trigger the next image
        if (index < max - 1) {
            PreloadImage(index + 1);
            setTimeout("CheckLoading(" + (index + 1) + ")", duration);
        }
        else {
            setTimeout("FadeOut(" + (index + 1) + ")", duration);
        }
    });
}


function repeatAnimation() {

    $kids = $("#animator").children();
    len = $kids.length;

    if (len > 0) {
        fi(0);
    }

    return false;
}

function fi(index) {

    $kids.eq(index).fadeIn(fadeIn, function() { setTimeout("fo(" + index + ")", duration); });
}

function fo(index) {
    $kids.eq(index).fadeOut(fadeOut, function() {
        $kids.eq(index).css("display", "none");

        if (index == len - 1) { index = 0; } else { index++; }
        fi(index);
    });
}
         
