$(document).ready(function(){
	
	// SETUP
	// add play buttons to each slide
	$('#featured-videos .youtube').each(function(i) {
		prepareYouTubeFeature(this);
	});
	
	// hide the featured video embed
	$('#featured-video-embed').hide();
	
	// SLIDESHOW
	$('#featured-videos').cycle({
		timeout: 6000,
		speed: 600,
		pager: '#featured-videos-pager',
		pagerClick: pagerClick,
		containerResize: 1
	});
	
	function prepareYouTubeFeature(feature)
	{
		var youTubeLink, youTubeRegEx, youTubeVideoID, featureImage;
		
		// wrap in jquery
		feature = $(feature);
		
		// store the youtube ID
		youTubeIdRegEx = /v=([a-zA-Z0-9_\-]+)/;
		youTubeVideoID = (youTubeIdRegEx.exec(feature.find('a').attr('href')))[1];
		
		// remove the html anchor and put the image back in
		feature.find('a').remove().find('img').appendTo(feature.find('.feature-image'));
		
		// add the play button
		feature.append('<div class="play-button">&nbsp;</div>');
		
		// add the play action to the button
		feature.find('.play-button').click(function(e){
			playClick(e.target, youTubeVideoID);
		});
	}
	
	// USER ACTIONS
	function pagerClick(zeroBasedSlideIndex, slideElement)
	{
		// replace embed with original code and hide the new block
		$('<div id="featured-video-embed"> </div>').replaceAll('#featured-video-embed').hide();
		
		// pause the slideshow
		$('#featured-videos').cycle('pause');
	}
	
	function playClick(playButton, youTubeVideoID)
	{
		// pause the slideshow
		$('#featured-videos').cycle('pause');
		
		// embed the flash movie
		swfobject.embedSWF('http://www.youtube-nocookie.com/v/'+youTubeVideoID+'&ap=%2526fmt%3D19&showsearch=0&autoplay=1&hl=en&fs=1&rel=0', 'featured-video-embed', '560', '340', '9.0.0');
	}
	
});
