

// Change this to your username to load in your clips
//var vimeoUserName = 'username';
var viemoChannelName = 'eotw';

// Tell Vimeo what function to call
var userInfoCallback = 'userInfo';
var videosCallback = 'initVideos';
var oEmbedCallback = 'embedVideo';

// Set up the URLs
//var videosUrl = 'http://www.vimeo.com/api/v2/' + vimeoUserName + '/videos.json?callback=' + videosCallback;
var videosUrl = 'http://www.vimeo.com/api/v2/channel/' + viemoChannelName + '/videos.json?callback=' + videosCallback;
var oEmbedUrl = 'http://www.vimeo.com/api/oembed.json';

// set up display vars
var videos;
var videosLimit = 4;
var currentVideosScreen = -1;

//
var debug = false;

//
function log(args) {
    if (debug && window.console && window.console.log) {
        window.console.log.apply(window.console, arguments);
    }
}

// This function puts the video on the page
function embedVideo(video) {				
	var embed = $('#vimeo_'+video.video_id+' .oembed');
	embed.height(video.height);
	embed.append(video.html);
}

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


function getVideoTitle( video_id )
{
	for(var k = 0; k < videos.length; k++ )
	{
		if(videos[k].id == video_id)
		{
			return videos[k].title.toString();
			continue;
		}
	}
	return  "No title";
}

//
function vimeo_player_loaded(swf_id) {
	
	log('vimeo_player_loaded : ' + swf_id + " : " + getVideoTitle(swf_id))
	var featuredVideo = document.getElementById(swf_id);
	featuredVideo.api_addEventListener('onFinish', 'vimeo_on_finish');
	featuredVideo.api_addEventListener('onPlay', 'vimeo_on_play');
	featuredVideo.api_addEventListener('onPause', 'vimeo_on_pause');	
}

//
function vimeo_on_play(swf_id) {
	//log('vimeo_on_play : '+swf_id);
	log('vimeo_on_play tacker' + typeof _gaq );
	_gaq.push(['_trackEvent', "Video", "Play",  "Video ~ play : " + getVideoTitle(swf_id)]);
}
//
function vimeo_on_pause(swf_id) {	
	log('vimeo_on_pause : '+swf_id)
	var currentTimer = Math.round(featuredVideo.api_getCurrentTime());
	_gaq.push(['_trackEvent', "Video", "Paused",  "Video ~ pause : " + getVideoTitle(swf_id)]);
}

//
function vimeo_on_finish(swf_id) {
	log('vimeo_on_finish : '+swf_id)
	_gaq.push(['_trackEvent', "Video", "Finished", "Video ~ complete : "+ getVideoTitle(swf_id)]);
}


// clear and create video elements dependant on video limit and screen incrementation
function showVideos( increase )
{
	// increment / deincrement
	( increase ) ? currentVideosScreen++ : ( currentVideosScreen > 0 ) ? currentVideosScreen-- : 0;
	
	log("currentVideosScreen : " + increase + " : "+ currentVideosScreen);
	
	//
	var videosLength = Math.min( videosLimit, videos.length);
	var vimeoContainer = $('#vimeo');
	var vimeoList = vimeoContainer.empty().append('<ul></ul>').find('ul');
	
	// work out min & max video indexes
	var minIndex = (currentVideosScreen * videosLimit);
	var maxIndex =  Math.min( ((minIndex + videosLength)-1),  videos.length);
	
	log("showing " + minIndex + " - " + maxIndex);
	//
	for (var i = minIndex; i <= maxIndex; i++) {
		
		if(!videos[i]) continue;
		var video = videos[i];
		var videoUrl = video.url;
		var videoThumb = video.thumbnail_large;
		
		var vWidth = 350;
		var vHeight = video.height * (vWidth/video.width);
		
		log(videoThumb);
				
		var li = vimeoList.append('<li id="vimeo_'+video.id+'" class="vimeo_video"><span class="vimeo_title"><h3>'+video.title+'</h3><p>'+video.description+'</p></span><span style="width:'+vWidth+'px;height:'+vHeight+'px;display:block;" class="oembed-wrapper"><span id="'+video.id+'" class="loading oembed"></span></span></li>');
		
		var test = false;
		
		if ((typeof swfobject == 'object' && swfobject.hasFlashPlayerVersion("7")))
		{
			var flashvars = {
				clip_id: video.id,
				color:'FF70E5',
				show_portrait: 0,
				show_byline: 0,
				show_title: 0,
				js_api: 1, // required in order to use the Javascript API
				js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
				js_swf_id: video.id // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
			};
			var params = {
				allowscriptaccess: 'always',
				allowfullscreen: 'true',
				wmode: "opaque"
			};
			var attributes = {};
			

			// For more SWFObject documentation visit: code.google.com/p/swfobject/wiki/documentation
			swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf", video.id, vWidth, vHeight, "7.0.0","expressInstall.swf", flashvars, params, attributes);
			
		}
		else
		 {
		    var img = new Image();

		    // wrap our new image in jQuery, then:
		    $(img)
		    // once the image has loaded, execute this code
		    .load(function() {

		        // set the image hidden by default
		        $(this).hide();
		        // fade our image in to create a nice effect
		        $(this).fadeIn();
		    })

		    // if there was an error loading the image, react accordingly
		    .error(function() {
		        // notify the user that the image could not be loaded
		        })

		    // *finally*, set the src attribute of the new image to our image
		    .attr('src', videoThumb)
		    .attr('width', 360);
			
		    // attach
		    $('#vimeo_' + video.id).find('.oembed').append(img)

		}
		
	}	
	
	// create navigation
	var vimeoNav = vimeoContainer.append('<div class="vimeoNavigation"></div>').find('.vimeoNavigation');
	
	// create previous button 
	if(videos.length > videosLimit && currentVideosScreen > 0)
			vimeoNav.append('<a class="vimeoPrevious" href="#vimeoPrevious" title="Previous videos" onclick="showVideos( false );">Previous</a>');
	
	// create next button 	
	if(videos.length > videosLimit && maxIndex < videos.length-1 )
			vimeoNav.append('<a class="vimeoNext" href="#vimeoNext" title="Next videos" onclick="showVideos( true );">Next</a>');
			
	vimeoNav.append('<div class="clear"></div>');
	
	//
	$('#vimeo').setScolling('widget :vimeo');
}


// This function goes through the clips and puts them on the page
function initVideos(videosData) {
	videos = videosData;
	log("videos loaded :",videos);
	showVideos( true );		
}
