var count;
var img_num;
var is_active = false;

$(function() {
    count = $(".slide").length;
    img_num = count;
    nextImage();
});

function nextImage(num_clicked) {
    // Don't do anything when already working
    if (false == is_active)
    {
        // Stop the auto-looping if the user selected something
        if ("undefined" != typeof num_clicked) {
            is_active = true;
            clearTimeout(timeout);

            // Switch to the user-selected item if not busy
            $(".s"+img_num).hide();
            $(".s"+num_clicked).fadeIn("slow", function() {
                is_active = false;
                img_num = num_clicked;
                
                // Change tab CSS
                $(".tab").removeClass("tab-active");
                $(".t"+img_num).addClass("tab-active");

                // Hover caption
                caption = $(".s"+img_num+" > a > img").attr("alt");
                $(".caption").html(caption);
            });
        }
        else
        {
            is_active = true;
            timeout = setTimeout("nextImage()", 8000);
            $(".tab").removeClass("tab-active");

            // Otherwise, update the image display
            $(".s"+img_num).fadeOut("slow", function() {
                if (count <= img_num) {
                    img_num = 1;
                }
                else {
                    img_num++;
                }

                $(".s"+img_num).fadeIn("slow", function() {
                    $(".t"+img_num).addClass("tab-active");
                    is_active = false;
                });

                // Hover caption
                caption = $(".s"+img_num+" > a > img").attr("alt");
                $(".caption").html(caption);
            });
        }
    }
}
