var timeout = null;
var paused = false;
var sliderIndex = 0;

$(function() {
    checkArrows();
    prepareMouseActions();
    progressSlider();
});

function prepareMouseActions() {
    $("div.blue").each(function() {
        this.onmouseover = pauseSlider;
        this.onmouseout = continueSlider;
    });
    $("div.left-arrow").each(function() {
        this.onclick = slideLeft;
    });
    $("div.right-arrow").each(function() {
        this.onclick = slideRight;
    });
}

function progressSlider() {
    if (sliderCount > 3 && !paused) {
        if (sliderIndex + 1 > sliderCount - 3) {
            if (timeout == null) {
                timeout = setTimeout(rewindSlider, 3000);
            }
        } else {
            if (timeout == null) {
                timeout = setTimeout(slideRight, 3000);
            }
        }
    }
}

function slideRight() {
    timeout = null;
    sliderIndex++;
    $(".slider").animate({ left: "-=307" }, 1000, progressSlider);
    checkArrows();
}

function slideLeft() {
    timeout = null;
    sliderIndex--;
    $(".slider").animate({ left: "+=307" }, 1000, progressSlider);
    checkArrows();
}

function rewindSlider() {
    timeout = null;
    sliderIndex = 0;
    $(".slider").animate({ left: 0 }, 1000, progressSlider);
    checkArrows();
}

function pauseSlider() {
    if (timeout != null) {
        clearTimeout(timeout);
        timeout = null;
    }
    paused = true;
}

function continueSlider() {
    paused = false;
    progressSlider();
}

function checkArrows() {
    $("div.left-arrow").css("visibility", (sliderIndex == 0) ? "hidden" : "visible");
    $("div.right-arrow").css("visibility", (sliderIndex >= sliderCount - 3) ? "hidden" : "visible");
}
