var cycleTime = 5000;
var animTime = 1500;
var infoBoxAnimTime = 500;
var infoBoxes, carousel, imgContainer, nextBtn, prevBtn, timer, imgWidth, inProgress;

function moveLeft() {
    hideInfoBox();
    var currLeft = parseInt(imgContainer.css("left").split("px")[0]);
    var newLeft = currLeft - imgWidth;
    imgContainer.animate({
        left: newLeft
    }, animTime, function () {
        $(this).find("li:first").appendTo(this);
        $(this).css("left", currLeft);
        showInfoBox();
    });
}

function moveRight() {
    hideInfoBox();
    var currLeft = parseInt(imgContainer.css("left").split("px")[0]);
    imgContainer.find("li:last").prependTo(imgContainer);
    imgContainer.css("left", currLeft - imgWidth);

    var newLeft = currLeft;
    imgContainer.animate({
        left: newLeft
    }, animTime, function () {
        showInfoBox();
    });
}
function startTimer() {
    return timer = setInterval(moveLeft, cycleTime);
}
function restartTimer() {
    clearInterval(timer);
    return startTimer();
}
function stopTimer() {
    clearInterval(timer);
}
function showInfoBox() {
    if ($(".carousel-text", carousel).eq(1).text() != '') {
        $(".carousel-text", carousel).eq(1).animate({
            bottom: 0
        }, infoBoxAnimTime);
    }
}
function hideInfoBox() {
    var temp = $(".carousel-text", carousel).eq(1).outerHeight(true);
    $(".carousel-text", carousel).eq(1).animate({
        bottom: 0 - temp
    }, infoBoxAnimTime);
}

$(function () {
    // Private
    carousel = $("#carousel");
    imgContainer = $("ul", carousel);
    infoBoxes = $(".carousel-text", carousel);
    nextBtn = $(".next", carousel);
    prevBtn = $(".prev", carousel);
    timer = null;
    imgWidth = imgContainer.find("li:eq(0)").outerWidth(true);

    prevBtn.click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        if ($(infoBoxes).add(imgContainer).filter(":animated").length > 0) { return false; }
        moveRight();
        restartTimer();
    });

    nextBtn.click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        if ($(infoBoxes).add(imgContainer).filter(":animated").length > 0) { return false; }
        moveLeft();
        restartTimer();
    });

    carousel.hover(function () {
        stopTimer();
    }, function () {
        //moveLeft();
        restartTimer();
    });

    imgContainer.css("left", -(imgWidth / 2));
    infoBoxes
        .each(function () {            
            $(this).css("bottom", 0 - $(this).outerHeight(true));
        })
        .eq(1);
        //.css("bottom", 0);
    //.css("left", '-550px');
    //infoBox.css("left", imgContainer.find("li:eq(1)").offset().left);
    //carousel.easing = 'easeOutCubic';
    startTimer();
});
