var timer;
var intrval = 4000;

$(function(){
    $("#filmstrip li a").each(function(){
        var thumb = $(this).attr("href");
        thumb = thumb.replace(/.jpg/, "-thumb.jpg");
        $(this).css("background", "url(" + thumb + ")");
    });
    $("#filmstrip li:first").addClass("sel");
    var thumb = $("#filmstrip li:first a").attr("href");
    thumb = thumb.replace(/.jpg/, "-thumb-sel.jpg");
    $("#filmstrip li:first >a").css("background", "url(" + thumb + ")");
    $("#slide_detail").empty().append($("#filmstrip li:first a").parent().find("div").clone());
});
$(window).load(function(){
    timer = setInterval(function(){
        var nextItem = $("#filmstrip li.sel").next();
        if (nextItem.length < 1) {
            var nextItem = $("#filmstrip li:first");
        }
        nextItem.find(">a").click();
    }, intrval);
    $("#filmstrip li >a").hover(function(){
        if ($(this).parent().hasClass("sel")) 
            return;
        var thumb = $(this).attr("href");
        thumb = thumb.replace(/.jpg/, "-thumb-sel.jpg");
        $(this).css("background", "url(" + thumb + ")");
    }, function(){
        if ($(this).parent().hasClass("sel")) 
            return;
        var thumb = $(this).attr("href");
        thumb = thumb.replace(/.jpg/, "-thumb.jpg");
        $(this).css("background", "url(" + thumb + ")");
    }).click(function(e){
        clearInterval(timer);
        var thumb = $(this).attr("href");
        var imgSrc = thumb;
        thumb = thumb.replace(/.jpg/, "-thumb-sel.jpg");
        $(this).css("background", "url(" + thumb + ")");
        var curSel = $(this).parent().parent().find("li.sel");
        thumb = curSel.find(">a").attr("href");
        thumb = thumb.replace(/.jpg/, "-thumb.jpg");
        curSel.find(">a").css("background", "url(" + thumb + ")");
        curSel.removeClass("sel");
        $(this).parent().addClass("sel");
        var oldImg = $("#gallery img");
        fullImg = new Image();
        var newImg = $("<img>");
        $("#gallery").prepend(newImg);
        newImg.attr("src", imgSrc);
        newImg.hide();
        fullImg.onload = function(){
            newImg.fadeIn();
            timer = setInterval(function(){
                var nextItem = $("#filmstrip li.sel").next();
                if (nextItem.length < 1) {
                    var nextItem = $("#filmstrip li:first");
                }
                nextItem.find(">a").click();
            }, intrval);
        };
        fullImg.src = imgSrc;
        oldImg.animate({
            "opacity": "0"
        },"slow", function(){
            $(this).remove();
        });
        $("#slide_detail").empty().append($(this).parent().find("div").clone());
        e.preventDefault();
    });
});

