var background_images = [
  "/templates/flintflint2011/images/background/bg1.jpg",
  "/templates/flintflint2011/images/background/bg2.jpg",
  "/templates/flintflint2011/images/background/bg3.jpg",
  "/templates/flintflint2011/images/background/bg4.jpg"
];
var background_images_loaded = [
  false,
  false,
  false,
  false
];
var background_images_current = Math.floor(Math.random()*background_images.length);
var background_image_delay = 4000;
var background_image_fade = 2000;

function background_fade_to_image(nextimage){
  background_images_current = nextimage;
  
  $('#new-background-image').css({ background: 'url('+background_images[nextimage]+') no-repeat', opacity: 0 }).animate({ opacity: 1}, background_image_fade, function(){
    $('#background-image').css({ background: $('#new-background-image').css("background") });
    window.setTimeout(
      background_begin_transition,
      background_image_delay);
  });
}

function background_begin_transition(){
  //copy current image to old image, and make new image and main image transparent
  $('#old-background-image').css({ background: $('#background-image').css("background") });
  $('#new-background-image, #background-image').css({ background: 'transparent' });

  //start crossfade, or preload the next image
  var nextimage = background_images_current+1; if (nextimage >= background_images.length) { nextimage=0; }
  if (background_images_loaded[nextimage])
  {
      background_fade_to_image(nextimage);
  } else {
    var pl = new Image();
    $(pl).ready(function(){
      background_images_loaded[nextimage] = true;
      background_fade_to_image(nextimage);
    });
    pl.src=background_images[nextimage];
  }
}

$().ready(function() {
  if (background_images_current == background_images.length) {
    background_images_current--;
  }
  $('#background-image').css({ position: 'relative', zIndex: 100, background: 'url('+background_images[background_images_current]+') no-repeat' });
  $('#new-background-image').css({ background: 'transparent', top: 0, position: 'absolute', zIndex: 1 });
  $('#old-background-image').css({ background: 'transparent', top: 0, position: 'absolute', zIndex: 1 });

  //matched size timer
  window.setInterval(
    function(){
      $('#new-background-image').css({ width: $('#background-image').width(), height: $('#background-image').height() });
      $('#old-background-image').css({ width: $('#background-image').width(), height: $('#background-image').height() });
    },
    500);
    
  //RAB: Brendan does not want cross fades, just exit before it is scheduled
  return; 
  
  //begin transition
  window.setTimeout(
    background_begin_transition,
    background_image_delay);
});
