﻿(function($j) {
    //Slideshow
    var opt;
    $j.fn.devotionSlideShow = function(options) {
        opt = $j.extend({}, $j.fn.devotionSlideShow.defaults, options);
        return this.each(function() {
            var container = $j(this);
            container.find('div#slideshowloader').remove(); // removes the preloader gif

            //setup the imageViewer
            var imageViewer = container.find('#imageviewer');
            var imageWidth = $j.fn.devotionSlideShow.defaults.width;
            var imageHeight = $j.fn.devotionSlideShow.defaults.height;
            var imageCount = imageViewer.find('li').size();
            var viewerWidth = imageWidth * imageCount;

            //setup the navigaiton
            imageViewer.each(function(i) {
                $j(this).find('li').each(function(n) {
                    $j(this).removeClass('hide').hide();
                    var index = n + 1;
                    $j(this).addClass('slide' + index);

                });
            });

            //show the images...
            imageViewer.removeClass('hide');

            //show the first element
            imageViewer.find('li:first').fadeIn($j.fn.devotionSlideShow.defaults.fadeTime).addClass('active');

            if ($j.fn.devotionSlideShow.defaults.autoPlay) {
                //show the pause button and start the timer
                $j.fn.devotionSlideShow.play();
            }
        });
    };


    $j.fn.devotionSlideShow.defaults = {
        fadeTime: 500,
        delay: 4000,
        autoPlay: true,
        timer: null,
        width: 120,
        height: 240
    };


    $j.fn.devotionSlideShow.play = function() {
        opt.timer = setInterval(this.next, opt.delay);
    };

    $j.fn.devotionSlideShow.pause = function() {
        clearInterval(opt.timer);
    };


    $j.fn.devotionSlideShow.reset = function() {
        clearInterval(opt.timer);
        opt.timer = setInterval($j.fn.devotionSlideShow.next, opt.delay);
    };

    $j.fn.devotionSlideShow.next = function() {
        var currentSlide = $j('#imageviewer').find('.active').removeClass('active');

        if (currentSlide.is('.slide' + $j('#imageviewer').find('li').size())) {
            //select the last
            var newSlide = $j('#imageviewer').find('li:first');
        }
        else {
            //select the next li
            var newSlide = currentSlide.next('li');
        }

        currentSlide.css('z-index', '2');
        newSlide.css('z-index', '1');

        //fade out the current slide
        currentSlide.fadeOut(opt.fadeTime);
        newSlide.show();
        newSlide.removeClass('hide').addClass('active');
    };

})(jQuery);

$j(window).bind("load", function() {
    if ($j('div#slideshow').length) {
        $j('div#slideshow').devotionSlideShow();
    }
});
