$(document).ready(function(){
    // All sliders on page
    var sliders = $('.slider');

    // Add sliding functionality to sliders with enough items
    sliders.each(function(){
        var items = $('div', $(this));
        var itemWidth = items.outerWidth();
        var itemsPerPage = Math.round(($(this).width() - itemWidth + items.width()) / itemWidth);
        var numPages = Math.ceil(items.length / itemsPerPage);

        if (items.length > itemsPerPage) {
            // Inject and style the mask
            var w = $(this).width();
            $(this).wrap('<div class="mask" style="width:' + w + 'px;overflow:hidden;"></div>');
            var mask = $(this).parent();

            // Style slider itself
            $(this).width('9999px');

            // Add slide-to-page numbered links
            mask.before('<div class="slidernav"></div>');
            for (i=1; i<=numPages; i++) {
                mask.prev().append('<a href="#">'+i+'</a>');
            }
        }
    });
    // Make the numbered slide page links work
    $('.slidernav a').click(function(){
        var itemWidth = $('.slider div').outerWidth();
        var itemsPerPage = parseInt($(this).parent().parent().width() / itemWidth);

        // Slide
        var moveTo = '-' + ($(this).text() - 1) * itemWidth * itemsPerPage + 'px';
        var context = $(this).parent().next();
        $('.slider', context).animate({'marginLeft': moveTo}, 400);

        // Change styles to indicate current page
        $(this).parent().children().removeClass('selected');
        $(this).addClass('selected');

        return false;
    });
    // Indicate first slider page selection
    $('.slidernav a:first-child').addClass('selected');
});
