/*global $ */

$(document).ready(function () {

    var weeks, buttonNext, buttonPrevious, marker, 
        speed, buttonWidth;
    
    // Reference DOM elements.
    weeks = $("#Weeks");
    buttonNext = weeks.find(".nav-button-next");
    buttonPrevious = weeks.find(".nav-button-previous");
    marker = weeks.find(".pagination-marker");
    
    // Configuration
    speed = 500;
    buttonWidth = 30;   
        
    // Setup the Carousel.
    weeks.carousel({
        stage: $("#Weeks .slider"),
        slides: $("#Weeks .week"),
        slidesPadEnd: 2,
        speed: speed,
        wrap: false
    });
    
    // Called whenever the carousel state changes.
    weeks.change(function () {
     
        var index;
        
        index = $(this).carousel("getIndex");
        
        // Update the Previous Button
        if (index === 0 && buttonPrevious.is(":visible")) {
            buttonPrevious.fadeOut(speed);    
        }                
        else if (index !== 0 && !buttonPrevious.is(":visible")) {
            buttonPrevious.fadeIn(speed);                    
        }
        
        // Update the Next Button
        if (index === 6 && buttonNext.is(":visible")) {
            buttonNext.fadeOut(speed);
        }        
        else if (index !== 6 && !buttonNext.is(":visible")) {
            buttonNext.fadeIn(speed);
        }
        
        // Move the marker
        // NOTE: 30px is the width of one button.
        marker.animate({
            "left": "" + (index * buttonWidth) + "px"
        }, speed);        
        
    });
    
    // Bind click handlers
    buttonPrevious.click(function () {
        weeks.carousel("advance", -3);
        return false;
    });

    buttonNext.click(function () {
        weeks.carousel("advance", 3);
        return false;
    });
    
    $("#Weeks a.pagination").click(function () {
        var slide = $(this).attr("href").substring(1);
        weeks.carousel("select", slide);
        return false;
    });
    
});
