$(document).ready(function() {

// function to load the next or prev frame from start
var showcase_widget_frame = function(s, mod, start)
{
	max = s.find('div.canvas div.frame').length - 1;

	n = s.data('n');
	if(n == undefined) n = start;
	if(n == undefined) n = 0;
	if(mod == undefined) mod = 1;
	if(mod > 0) n = n + 1; 
	if(mod < 0) n = n - 1; 
	if(n > max) n = 0;
	if(n < 0) n = max;

	frame = s.find('div.frame:eq('+ n +')');
	showcase_widget_update_info(s,n);

	s.find('div.slide').scrollTo( frame , 500 );
	s.data('n',n);

	info = s.find('.info');
	if(info.html() != '') info.slideDown(); 
	else info.slideUp();
}

var showcase_widget_update_info = function(s,n)
{
	frame = s.find('div.frame:eq('+ n +')');
	blurb = $(frame).find('.frame_info').html();
	s.find('div.info').html( blurb );
}

// initalise the widgets & buttons
$('.showcase_widget').each(function(i){

	prevbutton = "<div class='button prev'>PREV</div>";
	$(this).find('.slide').after(prevbutton);

	nextbutton = "<div class='button next'>NEXT</div>";
	$(this).find('.slide').after(nextbutton);

	infoPane = "<div class='info'></div>";
	$(this).find('.slide').after(infoPane);

	// goto the first frame
	showcase_widget_frame( $(this), 1, -1 );
	$(this).find('.info').hide();

	// resize the widget to accomodate the first frame
	var w = $(this).find('.frame:eq(0) img:eq(0)').width();
	var h = $(this).find('.frame:eq(0) img:eq(0)').height();
	$(this).css('width',w).css('height',h);

	// make sure the info box is the same width
	$(this).find('.info').css('width',w);
	// $(this).find('.info').css('height', Math.round(h / 3));

	$(this).find('.slide').css('width',w).css('height',h);

	var t = -Math.round( h - (h / 3) + ($(this).find('.next').height()) );
	$(this).find('.next, .prev').css('margin-top', t);

	var t = -Math.round( $(this).find('.info').height() );
	$(this).find('.info').css('margin-top', t);

});



$('.showcase_widget').hover(function(e){
	info = $(this).find('.info')
	if(info.html() != '') info.slideDown();
	$(this).find('.button').fadeIn();
}, function(){
	$(this).find('.info').slideUp();
	$(this).find('.button').fadeOut();
});

$('.showcase_widget .frame').each(function(i){
	// find the first image of each frame without using class names (simplifies html)
	$(this).find('img:eq(0)').click(function(e){
		e.preventDefault();
		g = $(this).parent().parent().parent().parent();
		showcase_widget_frame( g );
	});
});


$('.showcase_widget .button').click(function(e){
	e.preventDefault();
	g = $(this).parent();

	if($(this).hasClass('prev')) showcase_widget_frame( g,-1 );
	if($(this).hasClass('next')) showcase_widget_frame( g, 1 );

});

});


