var imageTimeout = null;
var imageIndex = 0;

function pageBackgroundResize(id) {
	windowWidth = $(document).width();
	windowHeigth = $(document).height();
	imgWidth = windowWidth;
	imgHeight = Math.round(0.625 * imgWidth);
	if (imgHeight < windowHeigth) {	
		imgHeight = windowHeigth;
		imgWidth = Math.round(1.6 * imgHeight);
		offsetHeight = 0;
		offsetWidth = (windowWidth - imgWidth) / 2;
	} else {
		offsetHeight = (windowHeigth -imgHeight) / 2;
		offsetWidth = 0;
	}
	$(id).css('width', imgWidth+'px');
	$(id).css('height', imgHeight+'px');
	$(id).css('top', offsetHeight+'px');
	$(id).css('left', offsetWidth+'px');
}

function imageFaded() {
	if (imageTimeout == null) {
		imageTimeout = setTimeout("imageChange()", fadeTimeout);
	}
}

function arrayIndex(arr, value) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == value) return i;
	}
	return 0;
}

function imageChange() {
	var nextImage = (imageIndex + 1 >= imageList.length) ? 0 : imageIndex + 1;
	$.cookie('ii', imageList[nextImage], { path: '/' });

	if (fadeImage == '#pageImage1') {
		$('#pageImage2').attr('src', '/images/pagebackgrounds/bk'+imageList[nextImage]+'.jpg');
		
		$('#pageImage1').css('z-index', -20);
		$('#pageImage2').css('z-index', -30);
		
		$('#pageImage2').show();
		$('#pageImage1').fadeOut(fadeLength, imageFaded);
		fadeImage = '#pageImage2';
	} else {
		$('#pageImage1').attr('src', '/images/pagebackgrounds/bk'+imageList[nextImage]+'.jpg');
		
		$('#pageImage1').css('z-index', -30);
		$('#pageImage2').css('z-index', -20);
		
		$('#pageImage1').show();
		$('#pageImage2').fadeOut(fadeLength, imageFaded);
		fadeImage = '#pageImage1';
	}
	
	imageTimeout = null;
	imageIndex = nextImage;
}

function resizeScreen() {
	pageBackgroundResize('#pageImage1');
	if (imageList.length > 1) {
		if (imageTimeout != null) {
			clearTimeout(imageTimeout);
			imageTimeout = null;
		}
		pageBackgroundResize('#pageImage2');
		imageFaded();
	}
}

function pageBackgroundInit() {
	resizeScreen();
	if (imageList.length > 1) {
		imageIndex = arrayIndex(imageList, $.cookie('ii') * 1);
		$('a').click(function() { if (imageTimeout != null) clearTimeout(imageTimeout); return true; });
	}
	fadeImage = '#pageImage1';
	$(fadeImage).show();
}

window.onresize = resizeScreen;

