$(function() { slider.init(); });

var slider = {
    timer: null,
    container: null,
    imageWidth: 0,
    imageCount: 0,
    activeSlide: 0,

    init: function () {
        this.container = $('.clientCaseCarousel');
        this.imageWidth = $(".window", this.container).width();
        this.imageCount = $(".imageReel img", this.container).size();

        $(".imageReel", this.container).css({ 'width': (this.imageWidth * this.imageCount) });

        $('.slide-paging a', this.container).click(function (e) {
            e.preventDefault();
            slider.stopTimer();
            
            var clickedIndex = $('.slide-paging a').index(this);
            slider.activeSlide = clickedIndex;
            slider.showSlide(clickedIndex, function () {
                slider.resetTimer();
            });
        });

        $('.desc').hover(function () { slider.stopTimer(); }, function () { slider.resetTimer(); });
        
        this.showSlide(this.activeSlide);
        
        if (this.imageCount <= 1)
            return;

        this.resetTimer();
    },

    stopTimer: function () {
        clearInterval(slider.timer);
    },

    resetTimer: function () {
        clearInterval(slider.timer);
        slider.timer = window.setInterval(function () {
            slider.nextSlide();
        }, 5000);
    },

    nextSlide: function () {
        slider.activeSlide++;

        if (slider.activeSlide >= slider.imageCount)
            slider.activeSlide = 0;

        slider.showSlide(slider.activeSlide);
    },

    showSlide: function (itemIndex, callback) {
        $('.desc', slider.container).stop(true, true).hide().eq(itemIndex).fadeIn(1000);
        $('.slide-paging a', slider.container).removeClass('active').eq(itemIndex).addClass('active');
        $('.imageReel', slider.container).stop(true).animate({ left: slider.getLeftPosition(itemIndex) }, 1000, callback);
    },

    getLeftPosition: function (index) {
        return '-' + (slider.imageWidth * index) + 'px';
    }
}
