jQuery(document).ready(function($) {
	/* Image rotator setup
	----------------------*/
	// paths to images
	var BGPATH = '../pics/pagebg/';
	var MPATH = '../pics/mainpic/';

	// total number of pics
	var NUMPICS = 39;

	// images
	// name format is: page_bgXX.jpg, main_picXX.jpg
	var bg = [];
	var pic = [];
	var bgI = [];
	var picI = [];
	for(var i = 0; i<NUMPICS; i++) {
		// filenames
		bg[i] = 'page_bg' + (i+1) + '.jpg';
		pic[i] = 'main_pic' + (i+1) + '.jpg';
		// actual images (for preloading and caching purposes)
		bgI[i] = new Image();
		bgI[i].src = BGPATH + bg[i];
		picI[i] = new Image();
		picI[i].src = MPATH + pic[i];
	}
	
	// add overlays, set to current backgrounds
	$('body').prepend('<div id="behind"></div>');
	$('#rotatingPicTop').prepend('<div id="inFront"></div>');
	$('#inFront').css('background-image',$('#rotatingPicTop').css('background-image')).show();
	$('#behind').css('background-image',$('body').css('background-image')).show();
	
	// set overlay styles
	$('#inFront').css({
		'width' : '100%',
		'height' : '422px',
		'background-repeat' : 'no-repeat',
		'background-position' : 'left top',
		'position' : 'relative',
		'z-index' : '1',
		'overflow' : 'hidden'
	});
	$('#behind').css({
		'width' : '100%',
		'height' : '1300px',
		'margin' : '0 auto -1300px auto',
		'background-repeat' : 'no-repeat',
		'background-position' : 'center top',
		'position' : 'relative',
		'z-index' : '-1',
		'overflow' : 'hidden'
	});
	
	// rotate every X seconds (1000 = 1 sec)
	setInterval(function() { rotate(bg, pic, bgI, picI); }, 5000);
	//setTimeout(function() { rotate(bg, pic, bgI, picI); }, 1000);
});

/* rotates background and front page pictures
---------------------------------------------*/
function rotate(bg, pic, bgI, picI) {
	// get the current body background filename
	var currentBG = $('body').css('background-image').replace(/.*\/((.*)jpg).*/, "$1");

	// get the index of the current bg pic
	var num = jQuery.inArray(currentBG, bg);

	// set current pic variables in css form: url("path/to/image.jpg")
	currentBG = 'url("' + bgI[num].src + '")';
	var currentPic = 'url("' + picI[num].src + '")';

	// cycle through arrays
	if(num == bg.length-1) {
		num = 0;
	} else {
		num++;
	}

	// set new pic variables in css form
	var newBG = 'url("' + bgI[num].src + '")';
	var newPic = 'url("' + picI[num].src + '")';

	// overlay current pics, change background pics, 
	// the fade out the overlays to reveal the new pics
	$('#rotatingPicTop').css('background-image',newPic);
	$('body').css('background-image',newBG);
	// delay 1 sec (give time to load large bg pics)
	setTimeout(function() {
		$('#inFront').fadeOut("slow", function() {
			$('#behind').fadeOut("slow", function() {
				$('#inFront').css('background-image',newPic).show();
				$('#behind').css('background-image',newBG).show();
			});
		});
	}, 1000);
}