window.addEvent('domready', function(){

	releatedTweetSearch = 'iTablet+ Apple+ iBook+ Tablet';
	getRelatedTweets.periodical(30000, null, releatedTweetSearch);
	getRelatedTweets(releatedTweetSearch);
	
	checkForUpdates.periodical(30000);
	
});

var getRelatedTweets = function(releatedTweetSearch){
	
	var tweetHolder = $('relatedtweets');
	new Request.Twitter(releatedTweetSearch, {
		url: 			'http://search.twitter.com/search.json?q=&ors={term}',
		onSuccess: 		function(data){
			tweetHolder.empty();
			data.results.each(function(tweet, i){
				if(i < 5){
					var li = new Element('li').addClass('twittLI');
					var span = new Element('span').set('html', ': '+ tweet.text +'<br/>').inject(li);
					new Element('a', {'target': '_blank', 'href': 'http://twitter.com/'+ tweet.from_user}).set('text', tweet.from_user).inject(span, 'top');
					new Element('a', {'target': '_blank', 'href': 'http://twitter.com/'+ tweet.from_user +'/statuses/'+ tweet.id}).set('text', prettyDate(tweet.created_at)).addClass('tweettime').inject(li);
					li.inject(tweetHolder);
				}
			});
		}		
	}).send();
	
}

var checkForUpdates = function(){
	
	new Request.JSON({
		url: 		urlbase +'index.php',
		data: 		'&action=update&stamp='+ latestStamp,
		onSuccess: 	function(o){
			processUpdates(o);
		}
	}).send();
	
}

var processUpdates = function(o){
	
	var updateHolder = $$('.content_copy')[0];
	
	latestStamp = o.updateTime;
	if(o.updates.length > 0){
		
		o.updates.each(function(update){
			
			if(!$(update.id)){
			
				var d = new Element('div', {id: update.id});
			
				new Element('hr').inject(d, 'top');
			
				if(update.image.length){
					new Element('img', {src: update.image, alt: update.date}).inject(d, 'top');
				}
			
				if(update.content.length){
					new Element('p').set('html', '<strong>'+ update.date +'</strong><br/>'+ update.content).inject(d, 'top');
				}
			
				d.setStyle('display', 'none').inject(updateHolder, 'top');
				d.reveal();
				
			}
			
		});
		
	}
		
}

// prettyDate function borrowed from http://ejohn.org/files/pretty.js :)
function prettyDate(time){
	if (!time)
		return "sometime ago";
	
	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 "sometime ago";
			
	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 == 7 && " 1 week ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
