var numHeaderPhotos = 3;
var currentHeaderPhoto = 1;
var nextPhoto = 1;
var approveSwitch = 1;
var approveSwitch2 = 0;
var switchSpeed = 500;
var opacityPhoto = 1;
var delaySwitching2 = setTimeout(function(){ approveSwitch2=1 },4000);
var delaySwitchSpeed = 8000;
var normalSwitchSpeed = 4000;


$(document).ready(function(){


	var timer = setInterval( switchPhotos, 500);
	
	jQuery.preLoadImages("/data/img/barr-mansion-2.jpg");
	
	var x = 2;
	while(x <= numHeaderPhotos){
		$("#bg" + x).css("background-image","url(/data/img/barr-mansion-" + x + ".jpg)");
		x++;
	}

	$("#rightButton").click(function(event){
		if(allowclick == 1){
			clearTimeout(delaySwitching2);
			approveSwitch2 = 0;
	
			if(currentHeaderPhoto == numHeaderPhotos ){ nextPhoto = 1; }
			else{ nextPhoto = currentHeaderPhoto+1; }
			
			
			$("#bg" + nextPhoto).css("z-index","2");
			$("#bg" + currentHeaderPhoto).css("z-index","1");
			allowclick=0;
			opacityPhoto = currentHeaderPhoto;
			delaySwitching2 = setTimeout(function(){ approveSwitch2=1 },delaySwitchSpeed);

	
			$('#bg' + nextPhoto).animate({ opacity: 1 }, switchSpeed, function() { 
				$("#bg" + opacityPhoto).css("opacity","0"); currentHeaderPhoto = nextPhoto; allowclick=1;
			 });
			
		}
     });
     
	$("#leftButton").click(function(event){		
		if(allowclick == 1){
		
			clearTimeout(delaySwitching2);
			approveSwitch2 = 0;
	
			if(currentHeaderPhoto == 1 ){ nextPhoto = numHeaderPhotos; }
			else{ nextPhoto = currentHeaderPhoto-1; }
			
			$("#bg" + nextPhoto).css("z-index","2");
			$("#bg" + currentHeaderPhoto).css("z-index","1");
			allowclick=0;
			opacityPhoto = currentHeaderPhoto;
			delaySwitching2 = setTimeout(function(){ approveSwitch2=1 },delaySwitchSpeed);
			
			$('#bg' + nextPhoto).animate({ opacity: 1 }, switchSpeed, function() { 
				$("#bg" + opacityPhoto).css("opacity","0"); currentHeaderPhoto = nextPhoto; allowclick=1;
			 });
			
		}
     });
  
 });
 
 
function switchPhotos(){
		
		if(approveSwitch == 1 && approveSwitch2 == 1){

			clearTimeout(delaySwitching);
			approveSwitch = 0;
			allowclick=0;

			if(currentHeaderPhoto == numHeaderPhotos ){ nextPhoto = 1; }
			else{ nextPhoto = currentHeaderPhoto+1; }
			
			
			$("#bg" + nextPhoto).css("z-index","2");
			$("#bg" + currentHeaderPhoto).css("z-index","1");
			opacityPhoto = currentHeaderPhoto;
			
			var delaySwitching = setTimeout(function(){ approveSwitch=1 },normalSwitchSpeed);
			
			$('#bg' + nextPhoto).animate({ opacity: 1 }, switchSpeed, function() { 
				$("#bg" + opacityPhoto).css("opacity","0"); currentHeaderPhoto = nextPhoto; allowclick=1;
			 });
		}


}
 
 
 
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
