// BIND OUR EVENTS


jQuery(document).ready(function ()
{
	jQuery('#swellPlayerPlay').bind("click", {}, playSwell);	
	
	jQuery('#swellPlayerBack').bind("click", {}, prevSwell);
	jQuery('#swellPlayerForward').bind("click", {}, nextSwell);
	
	jQuery('#swellPlayerFirst').bind("click", {}, firstSwell);
	jQuery('#swellPlayerLast').bind("click", {}, lastSwell);

	MPORA_SWELL_SQUARES = jQuery(".period td");
	MPORA_SWELL_CHARTS = jQuery("#swellDirChartHolder li");
	MPORA_SWELL_MAX_FRAMES = (MPORA_SWELL_SQUARES.length-1); // Start the count at 0 to match the loops.
	
	for (var i=0; i< (MPORA_SWELL_SQUARES.length); i++)
	{
		jQuery(MPORA_SWELL_SQUARES[i]).bind("mouseenter", {frame:i}, frameSelectionHover);
	}
	
	playSwell();
});

function clearCurrentSquares()
{
	for (var i=0; i< (MPORA_SWELL_SQUARES.length); i++)
	{
		jQuery(MPORA_SWELL_SQUARES[i]).removeClass('active');
	}		
}						

function frameSelectionHover(e)
{
	stopSwell();
	showFrame(e.data.frame);
	clearCurrentSquares();
	jQuery(this).addClass('active');
}

// Shows a given frame of the swell animation.
function showFrame(frame)
{
	jQuery(MPORA_SWELL_CHARTS).hide();
	jQuery(MPORA_SWELL_CHARTS[frame]).show();
	
	//Update nav bar also 
	clearCurrentSquares();
	jQuery(MPORA_SWELL_SQUARES[frame]).addClass('active');
	
	//console.log('Show frame '+frame);
}

function getCurrentFrame()
{
	for (var i=0; i< (MPORA_SWELL_SQUARES.length); i++)
	{
		if (jQuery(MPORA_SWELL_SQUARES[i]).hasClass('active'))
		{
			return i;	
		}
	}	
}

function playSwell()
{
	if (jQuery('#swellPlayerPlay').hasClass('buttonPause'))
	{
		// Player is playing - stop.
		stopSwell();
	}
	else
	{
		// Player isn't playing - play.
		jQuery('#swellPlayerPlay').addClass('buttonPause');	
		
		jQuery('#swellPlayerPlay').everyTime(250, 'playTimer', function() 
		{
			var currentFrame = getCurrentFrame();
			var nextFrame = currentFrame+1;
	
			if (currentFrame == MPORA_SWELL_MAX_FRAMES)
			{
				nextFrame = 0;
			}
			
			showFrame(nextFrame);
		});
	}
	
	
	return false;
}

function stopSwell()
{
	jQuery('#swellPlayerPlay').removeClass('buttonPause');
	jQuery('#swellPlayerPlay').stopTime('playTimer');
}

function nextSwell()
{
	stopSwell();
	//console.log('Advancing to next frame');
	
	var currentFrame = getCurrentFrame();
	var nextFrame = currentFrame+1;
	
	
	if (currentFrame == MPORA_SWELL_MAX_FRAMES)
	{
		nextFrame = 0;
	}
	
	showFrame(nextFrame);
	
	return false;
}

function prevSwell()
{
	stopSwell();
	//console.log('Back to next previous frame');
	
	var currentFrame = getCurrentFrame();
	var nextFrame = currentFrame-1;
	
	
	if (nextFrame < 0)
	{
		nextFrame = MPORA_SWELL_MAX_FRAMES;
	}
	
	showFrame(nextFrame);
	
	return false;
}

function firstSwell()
{
	stopSwell();
	showFrame(0);
	
	return false;
}

function lastSwell()
{
	stopSwell();
	showFrame(MPORA_SWELL_MAX_FRAMES);
	
	return false;
}



