﻿function NGRotator(options) {
    var isAnimating = false;
    var isAutoPlaying = false;
    var slideshow;
    var slides;
    var slides_count = 0;
    var currentSlide = 0;
    var lastSlide = 0;
    var width = 0;
    var slideshowTimeout;

    // default configuration properties
    var defaults = {
        id: 'NGRotator',
        speed: 500,
        pause: 3000,
        autoplay: true
    };

    var options = jQuery.extend(defaults, options);

    var init = function () {
        slideshow = jQuery('#' + options.id);
        slides = jQuery('li', slideshow);
        slides_count = slides.length;

        slides.css('display', 'none').css('z-index', 1);
        jQuery('li:eq(0)', slideshow).css('display', 'block').css('z-index', 2);

        if (options.autoplay) {
            isAutoPlaying = true;
            slideshowTimeout = setTimeout(nextSlide, options.pause);
        }
    }

    var stopAutoPlaying = function () {
        clearTimeout(slideshowTimeout);
        isAutoPlaying = false;
    }

    var startAutoPlaying = function () {
        slideshowTimeout = setTimeout(nextSlide, options.pause);
        isAutoPlaying = true;
    }

    var btnPlayPause_click = function () {
        if (isAutoPlaying) {
            stopAutoPlaying();
        } else {
            startAutoPlaying();
        }
    }

    var btnPrev_click = function () {
        stopAutoPlaying();
        prevSlide();
    }

    var btnNext_click = function () {
        stopAutoPlaying();
        nextSlide();
    }

    var gotoSlide = function (i) {
        if (i == currentSlide) return;
        if (isAnimating) return;

        lastSlide = currentSlide;
        currentSlide = i;

        isAnimating = true;

        slides.css('z-index', 1);
        jQuery('li:eq(' + currentSlide + ')', slideshow).css('z-index', 2);
        jQuery('li:eq(' + currentSlide + ')', slideshow).fadeIn(options.speed, animate_complete);
    }

    var nextSlide = function () {
        var targetSlide = currentSlide + 1;
        if (targetSlide >= slides_count) {
            targetSlide = 0;
        }
        gotoSlide(targetSlide);
    }

    var prevSlide = function () {
        var targetSlide = currentSlide - 1;
        if (targetSlide < 0) {
            targetSlide = slides_count - 1;
        }
        gotoSlide(targetSlide);
    }

    var animate_complete = function () {
        jQuery('li:eq(' + lastSlide + ')', slideshow).css('display', 'none');
        isAnimating = false;

        if (isAutoPlaying) {
            slideshowTimeout = setTimeout(nextSlide, options.pause);
        }
    }

    init();

    // public methods
    return {
        pause: function () {
            stopAutoPlaying();
        },
        play: function () {
            startAutoPlaying();
        }
    }
}
