var WATW = window.WATW || {};

WATW.videoCue = [];
WATW.videoCuePointer = 0;


// Start us up...
$(function() {
	if ($('#tweets')) {
		// Grab recent tweets and stick 'em in the ...
		var url = "http://search.twitter.com/search.atom?q=+%23watw25+OR+%40watw25+OR+from%3Awatw25+OR+%22we+are+the+world%22+OR+%22somos+el+mundo%22";
		new google.feeds.Feed(url).load(function(result) {
			var avatar_handles = [];
			var avatar_images = [];
			if (!result.error) $.each(result.feed.entries, function() {
				var el = $(document.createElement('li'));
				var handle = this.author.replace(/^([^ ]+) .*$/, "$1");
				$(el).data('twitter', {'handle': handle});
				var html = '<div class="avatar">&nbsp;</div>' +
					'<div class="body">' +
					'<p>' + this.content.replace(/&amp;/g, '&') + '</p>' +
					'<cite>' +
					handle + ' &nbsp; <a class="timestamp" href="'+this.link+'" target="twitter">' + this.publishedDate + '</a>' +
					'</cite></div>';
				$(el).append(html);
				$('#tweets ul').append($(el));
			});
			$('#tweets .timestamp').cuteTime();

			// Get the avatars
			$('#tweets ul li').each(function(){
				var el = $(this);
				var twdata = $(el).data('twitter');
				var handle = twdata.handle;
				$.jTwitter(handle, 1, function(data){
					if (data[0]) {
						handle_avatar = data[0].user.profile_image_url;
						$(el).children('.avatar').html('<img src="' + handle_avatar + '" width="48" height="48" alt="' + handle + '" />');
					}
				});
			});
		});
	}

	if ($('#donateForm')) {
		$('.donate-link').click(function(event){
			event.preventDefault();
			$.openDOMWindow({
				windowSourceID:'#donateForm',
				height: 100,
				width: 300,
				borderColor:'#ccc',
				borderSize:'4',
				windowBGColor:'#fff'
			}); 
		}); 
	}
});



WATW.formatTime = function(p_time) {
	var hours = Math.floor(p_time/3600);
	var minutes = Math.floor((p_time/3600-hours)*60);
	var seconds = Math.floor(((p_time/3600-hours)*60-minutes)*60);
	var tenths = Math.floor((p_time-(seconds + (minutes*60) + (hours*3600)))*10);

	if (isNaN(hours)) hours = 0;
	if (isNaN(minutes)) minutes = 0;
	if (isNaN(seconds)) seconds = 0;
	if (isNaN(tenths)) tenths = 0;
	if (seconds<10) seconds = "0" + seconds;
	if (minutes<10) minutes = "0" + minutes; // we won't need two digits
	var thetime = minutes + ":" + seconds;
	if (hours>0) {
		/*if (hours<10) {
			hours = "0" + hours;
		}*/
		thetime = hours + ":" + thetime;
	}
	if (tenths > 9) tenths = 9;
	return(thetime);// + "." + tenths
}



WATW.populateFeaturedVideo = function(data) {
	var entry = data.entry;
	var videoId = entry.id.$t.split(/\//);
	videoId = videoId[(videoId.length-1)];
	var videoEl = $('#front-video-'+videoId);
	videoEl.children('img').attr('src', entry.media$group.media$thumbnail[0].url);
	videoEl.find('span').html(WATW.formatTime(entry.media$group.yt$duration.seconds));
}



WATW.populateFrontVideoInventory = function(data){
	WATW.populateVideoInventory(data, true);
}



WATW.populateVideoInventory = function(data, is_front){
	var feed = data.feed;
	var entries = feed.entry || [];
	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];
		var videoId = entry.id.$t.split(/\//);
		videoId = videoId[(videoId.length-1)];
		this.videoCue.push({
			'id': videoId,
			'url': entry.media$group.media$content[0].url,
			'title': entry.title.$t,
			'thumburl': entry.media$group.media$thumbnail[0].url,
			'duration': WATW.formatTime(entry.media$group.yt$duration.seconds)
		});
	}

	$.each(this.videoCue, function(i, data) { 
		var el = $(document.createElement('li'));
		data.index = i;
		$(el).data('videoData', data);
		if (is_front) {
			if (i < 4) {
				$(el).html('<a href="/videos/#'+data.id+'"><img src="'+data.thumburl+'" width="108" height="64" alt="" class="avatar" /></a>');
				$(el).append('<p>'+data.title+' <span class="length">'+data.duration+'</span></p>');
				$('#video ul.secondary-videos').append($(el));
			}
		}
		else {
			$(el).html('<a href="javascript:;"><img src="'+data.thumburl+'" width="108" height="64" alt="" class="avatar" /></a>');
			$('#inventory ul.video-inventory').append($(el));
			if (i < 12) {
				var el2 = $(el).clone();
				$(el2).data('videoData', data);
				$(el2).append('<p>'+data.title+' <span class="length">'+data.duration+'</span></p>');
				$('#recent-video ul.secondary-videos').append($(el2));
			}
		}
	});

	this.initializeSlider();
	this.initializeVideo();
}

WATW.initializeSlider = function(){

	var thumb_width = $('#inventory ul.video-inventory li').width();
	var thumb_count = $('#inventory ul.video-inventory li').length;
// console.log('thumb_count:'+thumb_count);
	var initial_indent = 2*thumb_width;
	var current_slot = 1;
	var animate_to_slot = function(slot, playVideo) {
// console.log('animating to slot '+slot);
		var min_slot = 1;
		var max_slot = thumb_count;
		if (slot > max_slot) slot = max_slot;
		if (slot < min_slot) slot = min_slot;
		var slot_value = (slot-1)*thumb_width;
		var slot_indent = initial_indent-slot_value;
// console.log('slot_indent: '+slot_indent);

		current_slot = slot;
// console.log('current_slot:'+current_slot);
		$('#inventory ul.video-inventory').animate({
			// 'text-indent': slot_indent+'px'
			'left': slot_indent+'px'
		},{
			duration: 'fast',
			step: function() {
				// var indent = $(this).css('text-indent').replace(/px/,'');
				var indent = $(this).css('left').replace(/px/,'');
				$('#slider').slider('value', initial_indent-indent);
			},
			complete: function() {
				$('#slider').slider('value', slot_value);

				WATW.videoCuePointer = slot-1;

				var el = $('#inventory ul.video-inventory li')[WATW.videoCuePointer];
				if (playVideo) {
					var ytplayer = document.getElementById('myytplayer');
					var mediaContentUrl = WATW.videoCue[WATW.videoCuePointer].url;
					if (mediaContentUrl) {
						ytplayer.loadVideoByUrl(mediaContentUrl);
						WATW.populateCaption(el, true);
					}
				}
				else {
					WATW.populateCaption(el);
				}
			}
		});
	}
	animate_to_slot(1);
	$('#browse .arrow-lt').click(function(event){
		event.preventDefault();
		animate_to_slot(current_slot-1);
	});
	$('#browse .arrow-rt').click(function(event){
		event.preventDefault();
		animate_to_slot(current_slot+1);
	});
	$('#slider').slider({
		// step: thumb_width,
		value: thumb_width*(thumb_count-1)/2,
		min: 0,
		max: thumb_width*(thumb_count-1),
		range: false,
		animate: false,
		slide: function(event, ui) {
// console.log('ui.value:'+(ui.value/thumb_width));
			var indent = 0-(ui.value-initial_indent);
// console.log('indent:'+(indent/thumb_width));
			// $('#inventory ul.video-inventory').css('text-indent', indent+'px');
			$('#inventory ul.video-inventory').css('left', indent+'px');
		},
		stop: function(event, ui) {
			// find closest slot and animate to there
			var slot = Math.round(ui.value/thumb_width)+1;
			animate_to_slot(slot);
		}
	});
	$('#inventory ul.video-inventory img, #recent-video ul img').click(function(event){
		event.preventDefault();
		var data = $(event.target).parents('li').data('videoData');
		var slot = data.index+1;
		animate_to_slot(slot,true);
	});
}

WATW.populateCaption = function(el, now_playing) {
	var data = $(el).data('videoData');
	var title = data.title+' <span class="length">'+data.duration+'</span>';
	$('p#vid-description').html(title);
	if (now_playing) {
		$('p#player-title').html(title);
	}
}

WATW.initializeVideo = function(autoplay) {
	var params = { allowScriptAccess: "always", allowFullScreen: "true", wmode: "transparent" };
	var atts = { id: "myytplayer" };
	var playerUrl = WATW.videoCue[0].url;
// console.log(WATW.videoCue[0]);
// console.log('initial playerUrl: '+playerUrl);
	if (playerUrl) {
		swfobject.embedSWF(playerUrl+"&enablejsapi=1&playerapiid=ytplayer&rel=0&border=0&fs=1&hd=1&autoplay=" + 
		      (autoplay?1:0), "player", "640", "386", "8", null, null, params, atts);
	}
}

function onYouTubePlayerReady(playerId) {
	var ytplayer = document.getElementById('myytplayer');
	if (ytplayer) {
		// ytplayer.playVideo();
		// ytplayer.loadVideoById(videoCue[0].videoId);
		if (WATW.videoCue.length > 0) {
			ytplayer.cueVideoById(WATW.videoCue[0].id);
			ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
		}
	}
}
onytplayerStateChange = function(newState){
// console.log('newState: '+newState);
	var ytplayer = document.getElementById('myytplayer');
	if (newState==0) {
		var mediaContentUrl = WATW.videoCue[(WATW.videoCuePointer+1)].url;
// console.log('next video mediaContentUrl: '+mediaContentUrl);
		if (mediaContentUrl) {
			ytplayer.loadVideoByUrl(mediaContentUrl);
			WATW.videoCuePointer++;
			WATW.animate_to_slot(WATW.videoCuePointer);
		}
	}
	var el = $('#inventory ul.video-inventory li')[WATW.videoCuePointer];
	WATW.populateCaption(el, true);
}



/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

