(function($){
    /* Slideshow */
    $.fn.slideshow = function(options) {
        options = $.extend({}, $.fn.slideshow.options, options);

        return this.each(function(){
            var elm = $(this),
                items = $("." + options.itemContainerClass, elm),
                images = $("." + options.imageContainerClass, elm),
                count = items.find(".item").size(),
                start = options.start,
                isPaused = false,
                timer;/*,
                fadeSpeed = Math.round(options.fadeSpeed / 2);*/

            if (count == 0) {
                return;
            }

            if (start < 0) {
                start = 0;
            }
            else if (start >= count) {
                start = count - 1;
            }

            show(start);

            items.find(".item").mouseenter(function(){
                if ($(this).hasClass("selected")) {
                    return;
                }

                var index = $(this).index();
                show(index);

                isPaused = true;
            }).mouseleave(function(){
                isPaused = false;
                if (options.pause > 0) {
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        next();
                    }, options.pause);
                }
            });

            if (options.play > 0) {
                timer = setTimeout(function(){
                    next();
                }, options.play);
            }

            function next() {
                if (isPaused) {
                    return;
                }

                var index = items.find(".selected").index();

                ++index;
                if (index == count) {
                    index = 0;
                }

                show(index);

                if (options.play > 0) {
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        if (!isPaused) {
                            next();
                        }
                    }, options.play);
                }
            }

            function show(index) {
                items.find(".item").removeClass("selected");
                items.find(".item:nth-child(" + (index + 1) + ")").addClass("selected");
                images.find("a").hide();
                images.find("a:nth-child(" + (index + 1) + ")").show();

                /*images.find(".item").fadeOut(fadeSpeed, function(){
                    images.find(":nth-child("+(index + 1)+")").fadeIn(fadeSpeed)
                });*/
            }
        });
    }
    $.fn.slideshow.options = {
        imageContainerClass: "images",
        itemContainerClass: "items",
        start : 0,
        play: 0,
        pause: 0
    }

    $(function(){
        $("#headline_slideshow").slideshow({
            play: 4000,
            pause: 6000
        });
    });
})(jQuery);
