$(document).ready(function() {
  images = [];

  $('#background .images li').each(function(index, image) {
    images.push($(image).attr('data-uri'));
  });

  function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
      $('<img/>')[0].src = this;
    });
  }

  preload(images);

  function showImage(image_id) {
    $('#background').fadeOut(3000, function() {
      $('#background').css('background-image', 'url("' + images[image_id] + '")');
      $('#background').fadeIn(3000);
    });
  }

  function slideShow() {
    var count = 0;

    var interval = setInterval(function() {
      if (first_time_around) {
        count = 1;
      }

      showImage(count);

      count++;

      if (count > images.length - 1) {
        count = 0;
      }

      first_time_around = false;
    }, 11000);
  }

  $('#background').hide();
  $('#background').fadeIn(3000);
  var first_time_around = true;
  slideShow();
});
