var _playlist_config = new Array();
var _feed_data = '';
var _cached = new Array();

function video_viewer(playlists) {
	for (i=0; i< playlists.length; i++){
		_playlist_config.push(playlists[i]);
	}
	$('#noscript').hide();
	$('#videoContainer').show();
	add_playlist_tabs();	
	$('.ui-tabs-nav').tabs();
	$('.ui-tabs-nav>li>a').css('color', '#C75501');
	$('.ui-tabs-nav>li>a').css('focus', 'none');
	$('.ui-tabs-nav>li:last').after('<br style="clear:both;">');
	
	//Fetch all clips
	fetch_data('youtube', '#videoGrid');
}

function add_playlist_tabs() {
	for (var i = (_playlist_config.length - 1); i > -1; i--) {
		var tab_id = _playlist_config[i].tab_label.replace(/\s/gi, '_');
		$('.ui-tabs-nav > li:first').after(
			'<li><a playlistId='+_playlist_config[i].id+' id="'+tab_id+'" href="#videoGrid_' + tab_id + '">'+ _playlist_config[i].tab_label +'</a></li>'
		);
		$('#videoGrid_MostViewed').after(
			'<div class="vidList" id="videoGrid_'+tab_id+'"></div>'
		)
		$('#' + tab_id).click(function(){
				id = $(this).attr('id');
				playlist_id = $(this).attr('playlistId');
				if($.inArray(id, _cached) != -1) return false;
				fetch_data('youtube', '#videoGrid_' + id, id, playlist_id);
				return false;
		});
	}
}



//Tabs event handlers
$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {
	switch(ui.index) {
		case 0:
			if($.inArray('most_viewed', _cached) != -1) return;
			fetch_data('youtube', '#videoGrid_MostViewed', 'most_viewed');
			_cached.push('most_viewed');
			break;
	}
});
function fetch_data(site, target, tag, playlist_id) {
	//This is the initial funciton to call; fetches the video data from youtube or flickr in json format.
	//Note: fetching from flickr isn't built yet.

   //The BBG youtube user name.
	var user_name = 'bbgpg';

	// Default url is for feed of all the uploaded videos.
	var url = 'http://gdata.youtube.com/feeds/users/'+user_name+'/uploads?orderby=published&max-results=50&alt=json-in-script&callback=?';
	if (tag == 'most_viewed') {
		url = 'http://gdata.youtube.com/feeds/users/'+user_name+'/uploads?orderby=viewCount&max-results=10&alt=json-in-script&callback=?';
	} else if (playlist_id) {
		url = 'http://gdata.youtube.com/feeds/api/playlists/' + playlist_id + '?orderby=published&alt=json-in-script&callback=?';
	}

	//Get the feed in JSON format. Callback to display_data.
	$.getJSON(url, function(data) {
			if(! tag) _feed_data = data;
			display_data(data, target, tag);
		}
	);
}

function humanize_duration(duration) {
	//This function returns the video duration string in a more human format.

	var min = Math.floor(duration/60);
	var sec = duration%60;
	
	//Display singular or plural
	var display_min = min == 1 ? ' minute' : ' minutes';
	var display_sec = sec == 1 ? ' second' : ' seconds';
	var human_duration = min == 0 ? sec + display_sec : min + display_min + ', ' + (sec == 0 ? '' : sec + display_sec);
	return(human_duration);
}
function humanize_date(date) {
	//This function returns the date string in a more human format.
	//For more info: http://www.evotech.net/blog/2007/07/javascript-date-object/
	
	//The months in human form.
	var month=new Array(12);
	month[0]="January"; month[1]="February"; month[2]="March"; month[3]="April"; month[4]="May"; month[5]="June";
	month[6]="July"; month[7]="August"; month[8]="September"; month[9]="October"; month[10]="November"; month[11]="December";

	var string_date = date.replace(/\D/g, " ");
	var date_obj = string_date.split(" ");
	var js_date = new Date(date_obj[0], (date_obj[1]-1), date_obj[2], date_obj[3], date_obj[4], date_obj[5]);
	var human_date = month[js_date.getMonth()] + " " + js_date.getDate() + ", " + js_date.getFullYear();
	return(human_date);
}

function play_movie(id) {
	//This function embeds the video after it's selceted.

	//TODO: check for flash version ?
	var html = '<object width="500" height="405">';
	html += '<param name="movie" value="http://www.youtube.com/v/'+id+'?fmt=19"></param>';
	html += '<param name="autoplay" value="1"></param>';
	html += '</param><param name="allowFullScreen" value="true"></param>';
	html += '<param name="wmode" value="transparent"></param>';
	html += '<embed src="http://www.youtube.com/v/'+id+'&autoplay=1&hl=en&fs=1&rel=0" type="application/x-shockwave-flash" wmode="transparent" allowfullscreen="true" width="500" height="405"></embed>';
	html += '</object>'
	$('#videoPlayer').html(html);
}

function display_data(data, target, tag) {
	//This function is called from fetch_data, it loops through the json data and 
	//creates the video list that the user will interact with.

    //Loop through each video in the feed.
	var html='';
    $.each(data.feed.entry, function(i, item) {
		var video_url = item.link[0].href;
		var video_id = video_url.split("=")[1];
		var thumbnail_src = item.media$group.media$thumbnail[1].url;
		var video_title = item.title.$t;
		var video_desc = item.media$group.media$description.$t;
		var published_date = '';
		var human_date = '';
		//if tag, get the date info from the original json data, 
		//since playlist tags don't have a published date.
		if(tag) {
			$.each(_feed_data.feed.entry, function(x, g_item) {
				var _vid_url = g_item.link[0].href;
				var _vid_id = _vid_url.split("=")[1];
				if(_vid_id == video_id) {
					published_date = g_item.published.$t;
					human_date = humanize_date(published_date);
					return;
				}
			});
		} else {
			published_date = item.published.$t;
			human_date = humanize_date(published_date);
		}
		var video_duration = parseInt(item.media$group.yt$duration.seconds);
		var human_duration = humanize_duration(video_duration);
		var view_link = '<a class="playLink" id="'+video_id+'" href="#">Play video</a> | <a href=\"'+video_url+'\">View on YouTube</a>';
		var thumbnail_link = '<a class="playLink" id="'+video_id+'" href="#"><img src="'+thumbnail_src+'" alt="'+video_title+'" /></a>';

		html += '<div class="videoEntry">'+thumbnail_link+'<div class="textsmall"><h3>'+video_title+'</h3>Uploaded: <i>'+human_date+'</i><br />Dur: <i>'+human_duration+'</i><br /><br />'+video_desc+'<br />'+view_link+'</div><!--[if IE]><br style="clear:both;" /><![endif]--><br style="clear:both;" /></div><!--[if IE]><br /><![endif]-->';
		
    });
	$(target).html(html);

	$('.playLink').click(function() {
		play_movie($(this).attr('id'));
		$('.videoEntry').css('background', '#f6f6f6');
		$(this).parents('.videoEntry').css('background', '#e9e9e9');
		return false;
	});
	
	//if the page is first loaded, get the default data for all videos, then populate the most viewed tab.
	if($.inArray('most_viewed', _cached) == -1) {
		fetch_data('youtube', '#videoGrid_MostViewed', 'most_viewed');
		_cached.push('most_viewed');
	}

}
