var current = 0;

$(document).ready(function() {
    initPictures();
});

function initPictures() {
    bindThem();
    $('.picture').attr('src', decodeURIComponent(images[current].path));
    $('.picture').trigger('bound');
}

function bindThem() {
    $(images).each(function(i,v) {
        $('#image-index').append('<div class="change"><a href="#" rel="' + i + '">' + (i + 1) + '</a></div>');
    });
    $('#image-index .change a:first').addClass('change-active');
    $('#image-index').append('<div style="clear:both;"></div>');
    $('.change a').click(function(e) {
        e.preventDefault();
        current = $(this).attr('rel');
        setActiveIndex();
        $('.picture').parent().attr('href', images[current].text);
        $('.picture').attr('src', images[current].path).show();
    });

    $('.picture').bind('bound',function(){
        $('.picture').fadeIn(1500,function(){
            $('.picture').parent().attr('href', images[current].text);
            if(current + 1 >= images.length){current = 0;}else{current++;}
            $('#img2').attr('src', decodeURIComponent(images[current].path)).show();
            $(this).delay(4500).fadeOut(1500,function(){
                setActiveIndex();
                changeUp(false);
            });
        });
    });
}

function setActiveIndex() {
    $('.change a').removeClass('change-active');
    $('.change a[rel="'+current+'"]').addClass('change-active');
}

function changeUp(newcurrent) {
    $('.picture').fadeOut(1500, function() {
        $('.picture').parent().attr('href', images[current].text);
        if(current + 1 >= images.length){current = 0;}else{current++;}
        $(this).delay(4500).fadeOut(1500, function() {
            setActiveIndex();
            $('.picture').attr('src', decodeURIComponent(images[current].path));
            $('.picture').trigger('bound');
        });
    });
}
