﻿
jQuery.fn.fadeSlideshow = function () {
    return this.each(function () {
        var slideshow = jQuery(this);
        jQuery(".slides a", slideshow).not(":eq(0)").hide();
        slideshow.data("autoscroll", true);
        slideshow.data("autoscrollduration", 3000);
        var links = jQuery(".slideshow-nav div", slideshow);
        var slideCount = jQuery(".slides a", slideshow).length;
        links.append('<div style="float:right;border:1px solid #white;">');
        for (var i = 0; i < slideCount; i++) {
            links.append('<span>' + i + '</span> ');
        }
        links.append('</div>');
        links.append('<div style="clear:both"></div>');
        jQuery("span", links).click(function (e) {
            e.preventDefault();
            slideshow.data("autoscroll", false);
            jQuery(slideshow).fadeSlideshowMoveTo(jQuery(this).text());
        }).eq(0).addClass("active");
        setTimeout(function () { if (slideshow.data("autoscroll")) jQuery(slideshow).fadeSlideshowNext(); }, slideshow.data("autoscrollduration"));
    });
};

jQuery.fn.fadeSlideshowNext = function () {
    return this.each(function () {
        var slideshow = jQuery(this);
        var slideCount = jQuery(".slides a", slideshow).length;
        var oldIndex = jQuery(".slides a:visible", slideshow).index();
        var newIndex = oldIndex + 1;
        if (newIndex >= slideCount)
            newIndex = 0;
        jQuery(slideshow).fadeSlideshowMoveTo(newIndex, function () { setTimeout(function () { if (slideshow.data("autoscroll")) jQuery(slideshow).fadeSlideshowNext(); }, slideshow.data("autoscrollduration")) });

    });
};

jQuery.fn.fadeSlideshowMoveTo = function (index, cb) {
    return this.each(function () {
        var slideshow = jQuery(this);
        jQuery(".slides a").stop();
        if (jQuery(".slides a:visible").length > 0) {
            jQuery(".slides a:visible", slideshow)
            .fadeOut("slow", function () {
                jQuery(".slides a", slideshow)
                                .eq(index)
                                .fadeIn("slow", cb);
                jQuery(".slideshow-nav span", slideshow)
                                .removeClass("active")
                                .eq(index)
                                .addClass("active");
            });
        }
        else {
            jQuery(".slides a", slideshow)
                                .eq(index)
                                .fadeIn("slow", cb);
            jQuery(".slideshow-nav span", slideshow)
                                .removeClass("active")
                                .eq(index)
                                .addClass("active");
        }

    });

};
