/* Move forward or backwards between the images in the slideshow */
function gallery_change(direction){
	var active = $('#gallery .photos .item.active');
	var previous =  active.prev();
	var next =  active.next();
	if(!next.length){
		var next =  $('#gallery .photos .item:first');
	}
	if(!previous.length){
		var previous =  $('#gallery .photos .item:last');
	}
	active.addClass('last-active');
	if(direction == 'previous'){
		previous.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function(){
			active.removeClass('active last-active');
		});
	}else if(direction == 'next'){
		next.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 1000, function(){
			active.removeClass('active last-active');
		});
	}
}
$(document).ready(function(){
	/* Transform images into a slideshow */
	$('#gallery .photos img').each(function(i){
		var img_class = (i == 0 ? 'item active' : 'item');
		$('#gallery .photos').append('<div class="'+img_class+'" style="background:transparent url(\''+$(this).attr('src')+'\') no-repeat center center;"><h3>'+$(this).attr('alt')+'</h3></div>');
		$(this).remove();
	});
	var interval_id = setInterval("gallery_change('next')", 6000);
	$('#gallery .previous, #gallery .next').css('display', 'block');
	$('#gallery .next').click(function(){
		clearInterval(interval_id);
		gallery_change('next');
		interval_id = setInterval("gallery_change('next')", 6000);
		return false;
	});
	$('#gallery .previous').click(function(){
		clearInterval(interval_id);
		gallery_change('previous');
		interval_id = setInterval("gallery_change('next')", 6000);
		return false;
	});
	
	/* Get the latest 3 twitter entries from the username in the href atribute within '#twitter h2 a' */
	var twitter_username = $('#twitter h2').find('a').attr('href').split('/').reverse();
	$.getJSON('https://twitter.com/status/user_timeline/'+twitter_username[0]+'.json?count=3&callback=?', function(data){
		$.each(data, function(i, post){
			if(!$.browser.msie){
				var post_time = new Date(post.created_at);
				var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
				var post_day = post_time.getDate();
			}
			var post_text = post.text.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1" rel="nofollow">$1</a>');
			post_text = post_text.replace(/[\@]+([A-Za-z0-9-_]+)/gi, '<a href="https://twitter.com/$1" rel="nofollow">@$1</a>');
			if(!$.browser.msie){
				$('#twitter ul').append('<li>'+ post_text +'<date>'+post_day+' '+months[post_time.getMonth()]+' '+post_time.getFullYear()+'</date></li>');
			}else{
				$('#twitter ul').append('<li>'+ post_text +'</li>');
			}
		});
	});
});
