/*jslint browser: true */


jQuery(function ($) {
    $.fn.carousel = function () {
        
        var carousel = {
            /**
             * Item iterator. This is the index of the thumbnail at the top
             */
            item:  0,

            items: this.find('li'),

            /**
             * Changes the top margin of the current item to the negative of its height and
             * increments the iterator.
             */
            up: function () {
                var item;
                
                if (carousel.item < carousel.items.length - 1) {
                    item = carousel.items.eq(carousel.item);
                    item.animate({
                        'marginTop': '-' + item.height() + 'px'
                    });
                    
                    carousel.item = carousel.item + 1;
                }
            },

            /**
             * Decrements the iterator and sets the top margin of the current item back to 0px.
             */
            down: function () {
                var item;
                
                if (carousel.item > 0) {
                    carousel.item -= 1;
                    item = carousel.items.eq(carousel.item);
                    item.animate({
                        'marginTop': '0px'
                    });
                }
            }
        };

        this.after('<a href="#" class="next"><i>Next</i></a>');
        this.before('<a href="#" class="back"><i>Back</i></a>');

        this.siblings('.back').click(function () {
            // down three times
            $.each([0, 1, 2], carousel.down);
            return false;
        });

        this.siblings('.next').click(function () {
            // up three times
            $.each([0, 1, 2], carousel.up);
            // don't follow the link
            return false;
        }).end();

        return this;
    };

    jQuery(document).ready(function () {
        jQuery('.gallery.carousel').carousel();
    });
});
