﻿(function () {

    $(".carousel").each(function () {
        carousel(this);
    });

    function carousel(selector) {

        var currentPhotoId = null;
        var carousel = $(selector);
        var intervalId = null;
        var intervalSpeed = 5000;
        var photoFadeOutSpeed = 0;
        var photoFadeInSpeed = 0;

        var controlButtons = null;
        var carouselPhotos = null;

        init();

        function init() {
            controlButtons = carousel.find("ul li a.carousel-control-button");
            carouselPhotos = carousel.find(".carousel-photos .carousel-photo-item");

            carouselPhotos.hide();

            var first = $(carouselPhotos[0]);
            first.show();
            currentPhotoId = 0;

            $(controlButtons[0]).addClass("current");
            controlButtons.click(function () {
                clearInterval(intervalId);
                setCurrent(parseInt($(this).attr("id").substr(17), 10), initInterval);
            });

            initInterval();
        }

        function initInterval() {
            intervalId = setInterval(function () {
                var nextPhotoId = getNextPhotoId(currentPhotoId);
                setCurrent(nextPhotoId, null);
            }, intervalSpeed);
        }

        function getNextPhotoId(currentPhotoId) {
            if (currentPhotoId >= controlButtons.length - 1) {
                return 0;
            }
            return currentPhotoId + 1;
        }

        function setCurrent(photoId, callback) {
            if (currentPhotoId != photoId) {
                if (currentPhotoId != null) {
                    $(controlButtons[currentPhotoId]).removeClass("current");
                    $(carouselPhotos[currentPhotoId]).fadeOut(photoFadeOutSpeed);
                }
                $(controlButtons[photoId]).addClass("current");
                currentPhotoId = photoId;
                if (callback != null) {
                    $(carouselPhotos[photoId]).fadeIn(photoFadeInSpeed, callback);
                } else {
                    $(carouselPhotos[photoId]).fadeIn(photoFadeInSpeed);
                }
            }
        }
    }

})();