﻿$(document).ready(function() {

    var currentSlideIndex = 0;

    var slideCount = $('.slideshow-btns li').length;

    function moveToSlide(targetSlideIndex) {
        $('.slideshow-imgs').stop(true, false).animate({ left: '-' + (targetSlideIndex * 576) + 'px' }, 400, 'easeInOutQuart');
        $('.slideshow-btns a').eq(currentSlideIndex).css('background-color', '#ffffff');
        $('.slideshow-btns a').eq(targetSlideIndex).css('background-color', '#fecc0e');
        $('.slideshow-top li').eq(currentSlideIndex).fadeOut();
        $('.slideshow-top li').eq(targetSlideIndex).fadeIn();
        currentSlideIndex = targetSlideIndex;
    };

    function showBars() {
        $('.slideshow-top').stopTime().stop(true, false).animate({ top: '0' }, 'normal', 'easeOutCubic');
        $('.slideshow-top a').css('display', 'block');
        $('.slideshow-bottom').stopTime().stop(true, false).animate({ top: '0' }, 'normal', 'easeOutCubic');
    };

    function hideBars() {
        $('.slideshow-top').oneTime(350, function() {
            $(this).stop(true, false).animate({ top: '-65px' }, 'normal', 'easeInQuad', function() {
                $('a', this).css('display', 'none');
            });
        });
        $('.slideshow-bottom').oneTime(350, function() {
            $(this).stop(true, false).animate({ top: '65px' }, 'normal', 'easeInQuad');
        });
    };

    $('.slideshow').each(function() {
        $(this).hover(function() {
            $(this).stopTime();
            showBars();
        }, function() {
            $(this).everyTime(3000, function() {
                moveToSlide((currentSlideIndex + 1) % slideCount);
            });
            hideBars();
        }).everyTime(3000, function() {
            moveToSlide((currentSlideIndex + 1) % slideCount);
        }).oneTime(2000, function() { hideBars(); });

        $('.slideshow-btns li', this).each(function(i) {
            $(this).click(function() { moveToSlide(i); return false; });
        });

        $('.slideshow-btn-next', this).click(function() {
            moveToSlide((currentSlideIndex + 1) % slideCount);
            return false;
        });

        $('.slideshow-btn-back', this).click(function() {
            var target = (currentSlideIndex - 1) % slideCount;
            if (target < 0) { target = slideCount - 1 };
            moveToSlide(target);
            return false;
        });

    });
});

