/* 
	Menu animation
*/
jQuery(function($) {
	var nav = $('#nav-main');
	var width = '600px';
	$('#nav-home .info').click(function() {
		if (nav.css('display') == 'block') {
			if (width == '600px') { width = nav.width(); }
			nav.removeClass('opened')
				.animate({
					width:'1px'
				}, { 
					easing:'easeOutSine', 
					duration:500, 
					complete:function() {
						$(this).hide();
						if (window.runUpdates) runUpdates();
					}
				});
			$('#nav-home .info').html('open &raquo;');
		} else {
			if (window.hideUpdates) hideUpdates();
			nav.addClass('opened').css({display:'block'});
			if (width == '600px') { width = nav.width(); }

			nav.css({width:'1px'})
				.animate({
					width:width
				}, { 
					easing:'easeOutBounce', 
					duration:1000
				}).css({display:'none'});
			$('#nav-home .info').html('<span class="close">close</span> <span style="visibility:hidden">&raquo;</span>');

		}
	
		return false;
	});
});





/*
	Feed updates
*/
var dataVictoria = null;
var dataJoe = null;

jQuery.getJSON("/feed.php?who=victoria", function(data) {
	dataVictoria = data;
	//console.log(data.value.items);
});
jQuery.getJSON("/feed.php?who=joe", function(data) {
	dataJoe = data;
	//console.log(dataJoe);
});
function startUpdates() {
	if (!dataJoe || !dataVictoria) { // wait until both sets of data have loaded
		updatesTimer = setTimeout(startUpdates, 1000);
		return false;
	} else {
		jQuery('#spy .loading').fadeOut(200);
		runUpdates();
	}
}
function runUpdates() {
	if (jQuery('#nav-main').css('display') == 'block') return;
	
	
	jQuery('#spy').show();
	if (updatesTimer) clearTimeout(updatesTimer);
	if (Math.random() > 0.5) {
		getRecentUpdateJoe();
	} else {
		getRecentUpdateVictoria();
	}
	updatesTimer = setTimeout(runUpdates, 8000);
	return false;
}
var updatesTimer = setTimeout(startUpdates, 5000);


// show more updates
jQuery(function($) {
	$("#spy .more").click(function(e) {
		if (jQuery("#spy .update").length > 5) {
//			removeUpdate();
		}
		runUpdates();
		return false;
	});
});

// mouse in/out
jQuery(function($) {
	$('#spy').css('opacity', '0.8').bind('mouseover', function() {
		if (!updatesTimer) return;
		if (updatesTimer) clearTimeout(updatesTimer);
		updatesTimer = false;
		$(this).stop().animate({opacity:'0.99'});
	}).bind('mouseout', function() {
		if (updatesTimer) return;
		updatesTimer = setTimeout(runUpdates, 3000);
		$(this).stop().animate({opacity:'0.8'});
	});
});


function getRecentUpdateVictoria() {
	if (!dataVictoria) return;
	if (dataVictoria.value.items.length > 0) {
		var update = dataVictoria.value.items.shift();
		showUpdate(makeUpdate(update, 'victoria'))
	} else {
		showUpdate('sorry, no more updates from victoria!');
	}
	
}

function getRecentUpdateJoe() {
	if (!dataJoe) return;
	if (dataJoe.value.items.length > 0) {
		var update = dataJoe.value.items.shift();
		showUpdate(makeUpdate(update, 'joe'))
	} else {
		showUpdate('sorry, no more updates from joe!');
	}
	
}


function showUpdate(html) {
	var update = document.createElement('div');
	jQuery(update).addClass('update')
	jQuery(update).html('<div class="update2">'+html+'</div>');
	jQuery('#spy').prepend(update);

	
	jQuery(update).animate({
		marginBottom:0,
		opacity:0.99
	}, {
		easing:"easeOutElastic",
		duration:1000,
		complete: function() {
			var numUpdates = jQuery("#spy .update").length;
			if (numUpdates >= 6) {
				setTimeout(removeUpdate, 10000);
			} else if (numUpdates >= 4) {
				setTimeout(removeUpdate, 5000);
			} else if (numUpdates >= 3) {
				setTimeout(removeUpdate, 1000);
			}
		}
	});
}
function removeUpdate() {
	var elem = jQuery('#spy .update:not(.removing):last');
	var height = parseInt(elem.css('height'))+parseInt(elem.css('marginTop'));
	elem.addClass('removing').animate({
		marginBottom:'-='+parseInt(height),
		opacity:0
	}, function() {
		jQuery(this).remove();
	})
}

function hideUpdates() {
	jQuery(".update").stop().animate({
		marginBottom:'200',
		opacity:0
	}, function() {
		jQuery(this).remove();
		jQuery('#spy').fadeOut();
		if (updatesTimer) clearTimeout(updatesTimer)
	});

}


function makeUpdate(update, who) {
	var html = '';
	if (update['link'].indexOf('twitter.com') >= 0) {
		html = '<div class="twitter"><cite>'+who+' tweeted:</cite> '+update['description']+' <a href="'+update['link']+'" target="_blank">[#]</a></div>';
	} else if (update['media:thumbnail']) {
		html = '<div class="flickr"><a href="'+update['link']+'"><img src="'+update['media:thumbnail']['url']+'" width="75" height="75" target="_blank" /></a></div>';
	} else {
		html = '<div class="blog"><cite>'+who+' blogged:</cite> <strong><a href="'+update['link']+'" target="_blank">'+update['title']+'</a></strong></div>';
	}
	var daysAgo = prettyDate(update['pubDate']);
	if (daysAgo) html += '<small>posted '+daysAgo+'</small>';
	return html;
}



/*
 * 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 );
		});
	};

