var projectsCount;
var currentProject = 0;
var preloaded = [];
var transition = false;
function displayProject(){
    $('#projects').css('height', $('#projects').outerHeight());
    transition = true;
    if(projectsCount <= currentProject+1){
        $('#next').addClass('disabled');
    } else {
        $('#next').removeClass('disabled');
    }
    if(currentProject <= 0){
        $('#prev').addClass('disabled');
    } else {
        $('#prev').removeClass('disabled');
    }
    preloadImages();
    $('#projects > li:visible').fadeOut(500, function(){
        $('#projects > li:eq('+currentProject+')').fadeIn(500, function(){
            var h = $(this).height();
            $('#projects').animate({
                'height' : h+'px'
            }, 500, function(){
                transition = false;
            });
        });
    });
}
function preloadImages(){
    if(typeof preloaded[currentProject] == 'undefined'){
        preloaded[currentProject] = [];
        $('#projects > li:eq('+currentProject+') .pagination a').each(function(index){
            preloaded[currentProject][index] = new Image();
            preloaded[currentProject][index].src = $(this).attr('href');
        });
    }
}
$(document).ready(function(){
    projectsCount = $('#projects > li').size();
    $('#next').click(function(){
        if(projectsCount <= currentProject+1 || transition){
            return false;
        }
        currentProject++;
        displayProject();
    });
    $('#prev').click(function(){
        if(currentProject <= 0 || transition){
            return false;
        }
        currentProject--;
        displayProject();
    });
    $('.pagination a').click(function(){
        if($(this).hasClass('current') || transition) return false;
        transition = true;
        var index = $('a', $(this).parent()).index($(this));
        var img = preloaded[currentProject][index];
        $('#projects').css('height', 'auto');
        $('#projects > li:eq('+currentProject+') a').removeClass('current');
        $(this).addClass('current');
        $('.image img', $(this).parents('li')).animate({
            'opacity' : 0
        },500, function(){
            $(this).animate({'height' : img.height + 'px'}, 500, function(){
                $(this).animate({'opacity': 1}, 500, function(){
                    transition = false;
                });
            });
            $(this).attr('src', img.src);
        });
        return false;
    });
    preloadImages();
});
