var LysCarousel = Class.create({
    initialize: function(container) {
        this.container = container;
        this.per_page = 5;
        this.at_a_time = 1;
        this.first = 0;
        
        var items = this.container.select('li');
        this.left_arrow = items.first();
        this.right_arrow = items.last();
        this.total_items = items.length - 2;
        if (this.total_items <= this.per_page)
        {
            /* Less than a full page of apps: hide the arrows, since there is
             * nothing for the carousel to do.
             */

            this.hide_arrow(this.left_arrow);
            this.hide_arrow(this.right_arrow);
        }
        else
        {
            /* More than one page apps: hide all but the first page of
             * apps and the left arrow. Attach event handlers to the arrows.
             */

            for (var i = this.per_page; i < this.total_items; ++i)
            {
                items[i + 1].hide();
            }
            this.hide_arrow(this.left_arrow);

            this.left_arrow.down('a').observe('click', this.previous.bindAsEventListener(this));
            this.right_arrow.down('a').observe('click', this.next.bindAsEventListener(this));
        }
    },
    
    hide_arrow: function(arrow) {
        arrow.down('a').hide();
    },
    
    show_arrow: function(arrow) {
        arrow.down('a').show();
    },
    
    previous: function(event) {
        if (this.first >= this.at_a_time)
        {
            var new_first = this.first - this.at_a_time;
            this.redraw(new_first);
            this.first = new_first;
            
            if (this.first == 0)
            {
                /* This is the first page, so hide the left arrow. */
                this.hide_arrow(this.left_arrow);
            }
            this.show_arrow(this.right_arrow);
        }
        
        event.stop();
    },
    
    next: function(event) {
        if (this.first + this.at_a_time < this.total_items)
        {
            var new_first = this.first + this.at_a_time;
            this.redraw(new_first);
            this.first = new_first;
            
            if (this.total_items - this.first <= this.per_page)
            {
                /* This is the last page, so hide the right arrow. */
                this.hide_arrow(this.right_arrow);
            }
            this.show_arrow(this.left_arrow);
        }
        
        event.stop();
    },
    
    redraw: function(start) {
        var items = this.container.select('li');

        for (var i = this.first; i < this.first + this.per_page && i < this.total_items; ++i)
        {
            items[i + 1].hide();
        }
        for (var i = start; i < start + this.per_page && i < this.total_items; ++i)
        {
            items[i + 1].show();
        }
    }
});

new LysCarousel($('customer_apps'));
