﻿$(function() {
    $('.projects-fade > div').each(function() {
        fader(this);
    });
});

function fader(cont) {
    cont = $(cont);
    var duration = 5000;
    var timeooutId = null;
    var wasStoped = false;
    var numImgs = $('a.img', cont).length;
    var curImageIndex = 0;
    $('a.img:not(:first)', cont).hide();
    $(cont).mouseenter(stop);
    $(cont).mouseleave(function() {
        wasStoped = false;
        play();
    });
    play();

    function play() {
        if (wasStoped) return;
        timeooutId = setTimeout(function() {
            $('a.img:eq(' + curImageIndex + ')', cont).fadeOut(1000, function() {
                curImageIndex = (curImageIndex + 1) % numImgs;
                $('a.img:eq(' + curImageIndex + ')', cont).fadeIn(1000, function() {
                    play();
                });
            });
        }, duration + Math.floor(Math.random() * duration));
    }

    function stop() {
        clearTimeout(timeooutId);
        wasStoped = true;
    }
}

