$(document).ready(function(){
    
    var sc_autoplay = true;
    var tbscount = $('#scroller .items a').length;
    if(tbscount < 6) {
        sc_autoplay = false;
        $('.prev.browse.left').css('visibility', 'hidden');
        $('.next.browse.right').css('visibility', 'hidden');
    } else {
        // Wrap every 5 widget output to ensure scroller works with WP widget output
        $('.items span').wrapInChunks('<div />', 5).appendTo('.items');
    }
    
    var root = $('#scroller').scrollable({circular: true}).autoscroll({
        autoplay: sc_autoplay,
        autopause: true,
        interval: 10000
    });
    
    // Correct caption widths
    $.each($('.wp-caption'), function(index, value) {
        $(this).css('width', ($(this).width()-10))
    })
    
});

jQuery.fn.wrapInChunks = function(html, chunkSize) {
    chunkSize = chunkSize || 1;
    var items = this.get(),
        rows = [],
        cur = rows[0] = $(html);
    while (items[0]) {
        if (rows[rows.length - 1].children().length === chunkSize) {
            cur = rows[rows.length] = $(html);
        }
        cur.append( items.shift() );
    }
    return this.pushStack(rows);
};

