var loaded = [], loading = false, slideshow = -1;

$.fn.fireBackground = function() {
    $('#slideshow .activeslide').addClass('prevslide').removeClass('activeslide');
    $('#slideshow .nextslide').hide().attr('src', $(this).attr('href')).removeClass('nextslide')
        .addClass('activeslide').fadeIn(slideshow===-1 ? 500 : 1000);
    $('#slideshow .prevslide').removeClass('prevslide').addClass('nextslide');
}

$.fn.isActive = function() {
    return $(this).addClass('active').siblings('.active').removeClass('active');
}

$.fn.loadImage = function() {
    var a = $(this);
    var href = $(this).attr('href');
    if (jQuery.inArray(href, loaded) < 0) {
        loading = true;
        $.cacheImage(href, {
            load : function () {
                loaded.push(href);
                $(a).fireBackground();
                $(a).parent().isActive();
                loading = false;
            }
        });
    } else {
        $(this).fireBackground();
        $(this).parent().isActive();
    }
}

function initGallery() {
    $('#slideshow ul li a').each(function(i, o) {
        $(this).click(function(e) {
            if (!loading && !$(this).parent().hasClass('active')) {
                if ($(this).data('triggered') !== true) {
                    window.clearInterval(slideshow);
                    slideshow = -1;
                }
                $(this).removeData('triggered').loadImage();
            }
            return false;
        });
    });
    loaded.push($('#slideshow img.activeslide:first').attr('src'));
    slideshow = window.setInterval(function() {
        var next = $('#slideshow ul li.active').next('li').length 
            ? $('#slideshow ul li.active').next('li') 
            : $('#slideshow ul li:first');
        $(next).find('a:first').data('triggered', true).click();
    }, 6000);
}

jQuery().ready(function() {
    initGallery();
});
