﻿$.fn.gallery = function() {
    return this.each(function() {
        var $glist = $(this),
        current = 1,
        items = []; //uninitialised

        $glist.find('> li').each(function() {
            items.push('<li>' + $(this).html() + '</li>');
        });

        total = items.length;
        $glist.find('> li').filter(':gt(0)').remove();

        function go() {
            $insert = $(items[current]).prependTo($glist);

            //fade the item in
            $glist.find('> li:first').animate({ opacity: 1 }, 1000);

            // fade previous item out
            $glist.find('> li:last').animate({ opacity: 0 }, 1000, function() { $(this).remove(); });

            // update the caption
            var alt = $insert.find('img').attr('alt');
            $('#galleryCaption').css({ backgroundColor: '#fff' }).animate({ opacity: 0 }, 1000, function() { $(this).html(alt).animate({ opacity: 1 }, 1000) });

            current++;
            if (current >= total) current = 0;

            setTimeout(go, 5000);
        }

        go();

    });
}
