var timeOutId;
$(document).ready(function () {
    $('#items div.item:eq(0)').addClass('active');
    slideShow();    

    $("#gallery .item").click(function () {
        window.clearInterval(timeOutId);
        // see if same item is being clicked
        if ($(this).hasClass("active")) { return; }
        $("#gallery .image").fadeOut('fast');
        $('#gallery .caption').html('');
        changeSlide($(".item.active"), $(this), 'fast');
    });

    //disable right click on gallery images
    $('#gallery').bind("contextmenu", function (e) {
        e.preventDefault();
    });
});

function slideShow() {    
    timeOutId = setTimeout(gallery, 10000);
}

function gallery() {    
    var current = $('#items div.item.active');
    var next = (current.next().length == 0) ? $('.item:first') : current.next();
    changeSlide(current, next, 'normal');
}

function changeSlide(currentItem, newItem, speed) {
    var url = newItem.find(".image-path").val();
    var caption = newItem.find(".image-caption").val();
    var cssClass = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));

    var img = new Image();
    img.src = url;
    img.onload = function () {
        $("#gallery .image").fadeOut(speed, function () {
            var cssUrl = "url('" + url + "')";
            $(this).css("background-image", cssUrl);
            $(this).fadeIn("fast");

            $('#gallery .caption').html(caption);
            $(this).attr('class', 'image ' + cssClass);

            // activate item
            $("#gallery #items .active").removeClass("active");
            newItem.addClass("active");

            img = null;
            slideShow();            
        });
    }
}
