(function($){
	$.fn.inlinebackgrounds = function() {
		$.each(this, function(i,t) {
			var split = $(t).html().split('<br>');
			var output = '';
			$.each(split, function(i,o){
				output += '<span>'+o+'</span>';
				if (i < (split.length - 1)) {
					output += '<br>';
				}
			});
			$(t).html(output);
		});
	}
})(jQuery);
var quotes, photos, i, p, timer;
var fadeNext = function(){
	$(quotes.get(i)).fadeOut(500,function(){
		i = (++i) % quotes.length;
		$(quotes.get(i)).fadeIn(500, function(){
			window.setTimeout(fadeNext,5000);	
		});
	});
};
var goToPhoto = function(q){
	
	photos.hide();
	$("#back").fadeOut(500,function(){
		var photo = $(photos.get(q));
		$("#back").css("background-image","url(" + photo.attr("data-file") + ")");
		p = q;
		$("#back").fadeIn(500, function(){
			photo.show();	
		});
	});
	
};
var playSlideshow = function(){
	goToPhoto((p+1) % photos.length);
	timer = window.setTimeout(playSlideshow,6000);
}
var nextPhoto = function(){
	clearTimeout(timer);
	goToPhoto((p+1) % photos.length);
}
var previousPhoto = function(){
	clearTimeout(timer);
	goToPhoto((p-1+photos.length) % photos.length);
}
function shuffle(list) {
  var i, j, t;
  for (i = 1; i < list.length; i++) {
    j = Math.floor(Math.random()*(1+i));  // choose j in [0..i]
    if (j != i) {
      t = list[i];                        // swap list[i] and list[j]
      list[i] = list[j];
      list[j] = t;
    }
  }
}

$(document).ready(function(){
	$("blockquote").inlinebackgrounds();
	quotes = $("#home .quote");
	if(quotes.length > 0){
		i = quotes.length-1;
		fadeNext();
	}
	
	photos = $("#gallery .photo").toArray();
	if(photos.length > 0){
		shuffle(photos);
		photos = $(photos);
		p = photos.length-1;
		$("body").append(photos);
		$("body").append($(".buttons"));
		playSlideshow();
		$(".next").click(function(e){
			nextPhoto();
			e.preventDefault();
		});
		$(".previous").click(function(e){
			previousPhoto();
			e.preventDefault();
		});
	}
});
