(function($) {
  var $div;
  var photos = [
    '/images/bg/sep09-2.jpg',
    // '/images/bg/sep09-1.jpg',
    '/images/bg/sep09-3.jpg',
    '/images/bg/ny1.jpg',
    '/images/bg/ny2.jpg',
    '/images/bg/ny3.jpg',
    '/images/bg/ny4.jpg',
    '/images/bg/ny5.jpg',
    '/images/bg/ny6.jpg',
    // '/images/bg/ny7.jpg',
    '/images/bg/ny8.jpg',
    '/images/bg/ny9.jpg',
    // '/images/bg/ny10.jpg',
    '/images/bg/ny11.jpg',
    // '/images/bg/ny12.jpg',
    // '/images/bg/ny13.jpg',
    '/images/bg/ny14.jpg'
  ];
  var $imgs = [];
  var preloadIndex = 0;
  var currentIndex = 0;
  
  function preloadNext() {
    if (preloadIndex >= photos.length) return;
    var img = new Image();
    var $img = $(img).bind('load error', function() { preloadNext(); });
    $imgs.push($img.attr('src', photos[preloadIndex++]));
  }
  
  function nextBackground() {
    if (currentIndex == photos.length-1) currentIndex = 0;
    else currentIndex++;
    if (currentIndex >= preloadIndex) { currentIndex--; setTimeout(nextBackground, 5000); return; }
    
    var $olddiv = $div;
    $div = $div.clone();
    $div.insertBefore($olddiv);
    $div.css({'background-image': 'url('+photos[currentIndex]+')'});
    $olddiv.animate({'opacity':0}, 3000, function() {
      $olddiv.remove();
      setTimeout(nextBackground, 5000);
    });
  }
  
  $(function() {
    preloadNext();
    $div = $("<div />").css({'width':'960px', 'height': '650px', 'position':'absolute', 'top':'0px', 'left':'0px'});
    $("#nystrom_outerframe").css({'background-image': 'none','background-color':'#000'}).prepend($div);
    $div.css({'background-image': 'url('+photos[0]+')'});
    setTimeout(nextBackground, 5000);
  });
})(jQuery);