var playingVideo;

/**
 * @param {Object} data The JSON object containing video data
 */
function showYoutubeResults(data)
{		
	var results = $("#youtubeResults");
	var toInsert = '<br/><br/>';	
	results.hide('blind');
	results.html("");			
	
	// add container for youtube player	
	toInsert += '<div id="youtubePlayer"></div>';
	setYoutubeProgress(75);
	toInsert += notice('Is dit niet de goede video? Probeer een van de volgende!');	
	
	// show thumbnails thumbnails
	toInsert += '<table id="youtubeThumbs">';
	$.each(data, function(i, video){	
				
		if(((i+1) % 2) == 1)
			toInsert += '<tr>';				
		toInsert += '<td><img name="' + i + '" title="' + video.title.replace(/"/g, '&quot;') + '" src="' + video.thumbnail + '" /></td>';
		
		if(((i+1) % 2) == 0)
			toInsert += '</tr>';
		
	});
	toInsert += '</table>';	
	
	// add the html
	results.append(toInsert);
	
	$("#youtubeThumbs img").click(function(){		
			playVideo($(this).attr('name'), data[$(this).attr('name')].urlEmbed);		
	}).mouseover(function(){
		$(this).css('cursor', 'pointer');
	});
	
	$("#youtubeThumbs img[title]").qtip({ 
		style: { name: 'cream', tip: true },
		position: { target: 'mouse', corner: { target: 'topRight', tooltip: 'bottomLeft', adjust: { mouse: true } } } 
	});
	
	// play the first video	
	playVideo(0, data[0].urlEmbed);	
	
	setYoutubeProgress(100);
	results.show('blind');
	$("#youtubeProgress").progressbar('destroy');
}

function playVideo(i, url)
{	
	if(!playingVideo || i != playingVideo)
	{					
		$("#youtubePlayer").html("");
		$("#youtubePlayer").append(playerCode(url));		
		$("#youtubeThumbs img[name='" + playingVideo + "']").removeClass('playing');
		$("#youtubeThumbs img[name='" + i + "']").addClass('playing');
		
		playingVideo = i;
	}
}


// PLAYER CODES ############################################

function playerCode(urlEmbed)
{
	var playerCode = '<object width="320" height="265">'
				   + 	'<param name="movie" value="' + urlEmbed + '"></param>'
				   + 	'<embed src="' + urlEmbed + '" type="application/x-shockwave-flash" width="320" height="265"></embed>'
				   + '</object>';
				   
	return fixEmbedCode(playerCode);	
}

function fixEmbedCode(embedCode) 
{
   if(embedCode && embedCode.toLowerCase().indexOf('classid') == -1) {
      var objPos = embedCode.toLowerCase().indexOf('object ') + 'object '.length;
      return embedCode.substr(0, objPos) + 'classid=”clsid:D27CDB6E-AE6D-11cf-96B8-444553540000″ ' + embedCode.substr(objPos);
   } else {
      return embedCode;
   }
}