$(function(){

	backgroundImages = shuffle(backgroundImages);
	backgroundImagesLoaded = new Array(backgroundImages.length);
	onWindowResize();
	$(window).smartresize(onWindowResize);
	changeBackground();
	//replaceLinkToAnchor();
});

//-------------------------------------------------------

function onWindowResize(){
	var documentWidth = $(document).width();
	if(documentWidth <= 1024){
		$("body, header, footer, .content").css("width", "1024px");
	}else{
		$("body, header, footer, .content").css("width", "100%");
	}

	var w = ($(document.body).width()-20);
	var h = Math.floor(w/16*9);
	$(".background img").css("width", w+"px");
	$(".background img").css("height", h+"px");
	$(".background").css("left", "10px");
	var t = Math.floor(($(document.body).height()-h)/2);
	$(".background").css("top", t+"px");
}


//-------------------------------------------------------

function replaceLinkToAnchor(){
	$("a").each(function(){
		var href = $(this).attr("href");
		if(href.indexOf("http") != 0 && href.lastIndexOf(".html") >= 0){
			var hash = "";
			if(href.indexOf("#") >= 0){
				hash = href.substring(href.indexOf("#")+1);
			}
			href = "#/"+href.substring(0, href.lastIndexOf(".html"));
			if(hash != ""){
				href += "/" + hash;
			}
			$(this).attr("href", href);
		}
	});
}

function shuffle(list) {
  var i = list.length;

  while (--i) {
    var j = Math.floor(Math.random() * (i + 1));
    if (i == j) continue;
    var k = list[i];
    list[i] = list[j];
    list[j] = k;
  }

  return list;
}

var backgroundImages = [
	"_/images/kakame/_DSC0591.jpg",
	"_/images/kakame/_DSC0650.jpg",
	"_/images/kiss/KISS-66.jpg",
	"_/images/kiss/KISS-121.jpg",
	"_/images/kz/kz-1.jpg",
	"_/images/kz/kz-2.jpg",
	"_/images/monuments/monuments-1.jpg",
	"_/images/monuments/monuments-2.jpg",
	"_/images/monuments/monuments-3.jpg",
	"_/images/nowhere/dots015.jpg",
	"_/images/nowhere/dots093.jpg",
	"_/images/utsutsunare/utsutsunare-1.jpg",
	"_/images/utsutsunare/utsutsunare-2.jpg",
	"_/images/vibes/vibes-1.jpg",
	"_/images/vibes/vibes-2.jpg",
	"_/images/vibes/vibes-3.jpg"
];

var backgroundImagesLoaded = [];

var imgIndex = 0;
var bgTimer;
function changeBackground(){

	if(bgTimer){
		clearTimeout(bgTimer);
	}

	if($("#bg"+imgIndex).length > 0){
		if(backgroundImagesLoaded[imgIndex]){
			if($(".background img:visible").length > 0){
				$(".background img:visible").fadeOut("slow");
			}
			$("#bg"+imgIndex).fadeIn("slow");
			imgIndex++;
			if(imgIndex >= backgroundImages.length){
				imgIndex = 0;
			}
			onWindowResize();
			bgTimer = setTimeout(changeBackground, 5000);
			return;
		}else{
			$("#bg"+imgIndex).load(function(){
				backgroundImagesLoaded[imgIndex] = true;
				changeBackground();
			});
			return;
		}
	}else{
		$("section.background p").append('<img src="'+backgroundImages[imgIndex]+'" id="bg'+imgIndex+'" style="display:none;" />');
		$("#bg"+imgIndex).load(function(){
			backgroundImagesLoaded[imgIndex] = true;
			changeBackground();
		});
		return;
	}
}
