(function($) {

    var current = -1;
    var parent, children;
    var timer;

    $.fn.slideshow = function() {
        parent = this;
        children = $(this.selector + ' > li');
        slideshow_init();
    }

    slideshow_init = function() {
        $(parent).prepend($('<a class="previous"><img src="/img/previous.png" /></a>').click(function() { slideshow_stop(); slideshow_previous(); }));
        $(parent).append($('<a class="next"><img src="/img/next.png" /></a>').click(function() { slideshow_stop(); slideshow_next(); }));

        for (var i = 0; i < children.length; i++) {
            var child = $(children[i]);
            child.css('display', 'none');
        }

        $(parent).mouseover(function() { $(this).find('.previous').fadeIn(); $(this).find('.next').fadeIn(); });

        slideshow_rotate();
    }

    slideshow_rotate = function() {
        slideshow_next();
        timer = setTimeout(slideshow_rotate, 3500);
    }

    slideshow_previous = function() {
        slideshow_next(-1);
    }

    slideshow_next = function(orientation) {
        if (typeof orientation == 'undefined') orientation = 1;
        slideshow_hide();
        current += orientation;
        if (current < 0) current = children.length - 1;
        else if (current >= children.length) current = 0;
        slideshow_show();
    }

    slideshow_hide = function() {
        var child = $(children[current]);
        child.find('.description').hide();
        child.fadeOut(500, 0);
    }

    slideshow_show = function() {
        var child = $(children[current]);
        child.find('.description').show();
        child.fadeTo(1500, 1);
    }

    slideshow_stop = function() {
        clearTimeout(timer);
    }

})(jQuery);

