(function($){

    $.fn.slideshow = function(options) {

        var images = [];
        var currentIndex = 0;

        options = $.extend({
            timer : 4000,
            imageClass : 'slideshow-image',
            selectedClass : 'selected'
        }, options);
        
        $(this).css('position', 'relative');

        var first = true;
        //hide all but first image
        $(this).children().each(function(i, val){

            if (!first){
                $(this).hide();
            } else {
                
                $(this).css({
                    'z-index' : 2
                });
            }

            if ($('#' + $(this).attr('id') + ' img.' + options.imageClass).length > 0) {
                images.push(this);
                first = false;
            }

            $(this).css('position', 'absolute');
            
        });
        
        setMenuSelected(0);

        function changeImage(){

            var nextIndex = currentIndex + 1;

            //wrap
            if (nextIndex > images.length - 1) {
                nextIndex = 0;
            }

            if (options.menu) {
                setMenuSelected(nextIndex);
            }
            
            $(images[nextIndex]).show();
            $(images[currentIndex]).fadeOut(options.timer/2, function(){
                $(images[nextIndex]).css('z-index', 2);
                $(images[currentIndex]).css('z-index', 1);
                $(images[currentIndex]).hide();
                currentIndex = nextIndex;
            });

            setTimeout(function(){
                changeImage();
            }, options.timer);
        }

        function setMenuSelected(index) {
            $(options.menu).find('a').removeClass(options.selectedClass);
            $(options.menu).find('.' + $(images[index]).attr('id')).addClass(options.selectedClass);
        }

        setTimeout(function(){
            changeImage();
        }, options.timer);
    }
})(jQuery);
