window.carousel = window.carousel || {};

carousel = {
    numPerPage : 1,
    pages : 0,
    currentPage : 1,
    animate : true,
    numSlides : 0,
    children : null,
    slideTime : 700,
    pageWidth : 900,

    /**
     * sets up the carousel
     */
    init : function()
    {
        this.children = $(".carousel").children();
        this.numSlides = this.children.length;
        $(".carousel").css({width: this.pageWidth * this.numSlides});
        this.pages = Math.ceil(this.numSlides/this.numPerPage);
        carousel.disableButtons();
        $(".carousel").fadeIn(1000);
    },

    /**
     * checks if there is one page
     */
    disableButtons : function()
    {
        if (this.pages == 1) {
            $(".nextPage").addClass("disabled");
            $(".previousPage").addClass("disabled");
        }
    },

    /**
     * go to next page
     */
    nextPage : function()
    {
        if (this.currentPage < this.pages) {
            this.currentPage++;
        } else {
            this.currentPage = 1;
        }
        carousel.goToPage(this.currentPage);
    },

    /**
     * go to previous page
     */
    previousPage : function()
    {
        if (this.currentPage > 1) {
            this.currentPage--;
        } else {
            this.currentPage = this.pages;
        }
        carousel.goToPage(this.currentPage);
    },

    /**
     * figures out the left margin based on what page you want
     */
    getMarginByPage : function (page)
    {
        return -page*this.pageWidth + this.pageWidth;
    },

    /**
     * go to a specific page
     */
    goToPage : function(page, duration)
    {
        leftMargin = carousel.getMarginByPage(page);
        carousel.move(leftMargin, duration);
        this.currentPage = page;
        carousel.updateNav(page);
    },

    /**
     * updates navigation
     */
    updateNav : function(page)
    {
        $(".navigation ul li").removeClass("selected");
        $(".navigation ul li").eq(page-1).addClass("selected");
        $(".navigation ul li a").blur();
    },

    /**
     * move the carousel
     */
    move : function(leftMargin, duration)
    {
        if (!duration) {
            duration = this.slideTime;
        }
        return $(".carousel").animate({marginLeft: leftMargin}, duration);
    }
}

$(document).ready(function() {
    carousel.init();
    $(window).keydown(function(event){
        switch (event.keyCode) {
            case 39:
                carousel.nextPage();
                break;
            case 37:
                carousel.previousPage();
                break;
        }
    });
});

