var browserCount;
var browserPage, browserPages;

function gotoBrowserPage(index)
{
	browserPage = Math.min(Math.max(index, 1),browserPages);
	$('div#browser a#prev').toggle(index > 1);
	$('div#browser a#next').toggle(index < browserPages);
	$('div#browser div.item').css('display', function(index) {
		return ((index >= (browserPage-1) * 4) && (index < browserPage * 4)) ? 'block' : 'none';
	} );
}

$( function() {
	$('a.lightbox, div.item a:contains(View)').fancybox({ hideOnContentClick: true, overlayColor: '#000', 'autoScale': false });

	$("a.iframe").fancybox({
        'width'             : '90%',
        'height'            : '90%',
        'autoScale'         : false,
        'type'              : 'iframe'
    });

	if ( !$('div#browser div.item').length )
		return;

	$('div#browser div.scroller').css('overflow', 'hidden');

	// Group multiple thumbnails together.
	$('div#browser div.item').each( function(index) {
		$(this).children('a').attr('rel', function() { return 'grp' + index; } );
	} );

	// Hide extra thumbnails.
	$('div#browser div.item').each( function() {
		$(this).children('a').css('visibility', function(index) { return index == 0 ? 'visible' : 'hidden'; } );
	} );


	browserCount = $('div#browser div.item').length;
	browserPages = Math.ceil(browserCount / 4);

	if ( browserPages <= 1 )
		return;

	$('<a href="#" id="prev"><span class="fallback">Prev</span></a><a href="#" id="next"><span class="fallback">Next</span></a>')
		.insertBefore('div#browser div.scroller');


	gotoBrowserPage(1);

	$('div#browser a#prev').click(function() { gotoBrowserPage(browserPage - 1); } );
	$('div#browser a#next').click(function() { gotoBrowserPage(browserPage + 1); } );
} );
