var count;
var img_num;
var is_active = false;

$(function() {
    $(".slide").hide();
    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).show();
            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");
            $(".learnMore").attr("href", $(".s"+img_num+" > a").attr("href"));
            $(".caption").html(caption);
        }
        else
        {
            is_active = true;
            timeout = setTimeout("nextImage()", 8000);
            $(".tab").removeClass("tab-active");

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

            $(".s"+img_num).show();
            $(".t"+img_num).addClass("tab-active");
            is_active = false;

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

