// Tell Vimeo what function to call
var oEmbedCallback = 'embedVideo';

// Set up the URL
var oEmbedUrl = 'http://vimeo.com/api/oembed.json';

// Load the first one in automatically?
var loadFirst = true;

// This function puts the video on the page
function embedVideo(video) {
	var videoEmbedCode = video.html;
	document.getElementById('embed').innerHTML = unescape(videoEmbedCode);
}

// This function runs when the page loads and adds click events to the links
function vimeoInit() {
	var links = document.getElementById('thumbs').getElementsByTagName('a');

	for (var i = 0; i < links.length; i++) {
		// Load a video using oEmbed when you click on a thumb
		if (document.addEventListener) {
			links[i].addEventListener('click', function(e) {
				var link = this;
				loadScript(oEmbedUrl + '?url=' + link.href + '&width=700&height=395&callback=' + oEmbedCallback);
				e.preventDefault();
			}, false);
		}
		// IE (sucks)
		else {
			links[i].attachEvent('onclick', function(e) {
				var link = e.srcElement.parentNode;
				loadScript(oEmbedUrl + '?url=' + link.href + '&width=700&height=395&callback=' + oEmbedCallback);
				return false;
			});
		}
	}

	// Load in the first video
	if (loadFirst) {
		loadScript(oEmbedUrl + '?url=' + links[0].href + '&height=395&width=670&callback=' + oEmbedCallback);
	}
}

// This function loads the data from Vimeo
function loadScript(url) {
	var js = document.createElement('script');
	js.setAttribute('src', url);
	document.getElementsByTagName('head').item(0).appendChild(js);
}

// Call our init function when the page loads
window.onload = vimeoInit;
