// jquery for index page

$(document).ready(function() {
  $(function() {

    var totalpictures = $('.bgimages').size();

    $('#bgimg2').hide();

    var imageLoaded = function($image) {
      var waitCounter = 0;

      var interval = setInterval(function() {
        if ($image.get(0).complete == true || waitCounter>20) {
           return true;
        }
        waitCounter ++;
      }, 200);  // wait a bit for download
    };

    var index = 1;
    var pointer = 0;
    var interval = setInterval(function() {
      $imgtoload = $('div.bgimages').get(index);
      index++;
      if(index > totalpictures) {
        index = 0;
        $imgtoload = $('div.bgimages').get(index);
        index++;
      }

      if (pointer == 1) {
        pointer = 0;
        $image1 = $('#bgimg1');
        $image2 = $('#bgimg2');
      } else {
        pointer = 1;
        $image1 = $('#bgimg2');
        $image2 = $('#bgimg1');
      }

      $image1.attr('src', $imgtoload.innerHTML);

      $.when( imageLoaded($image1) ).done(function() {
        $image1.fadeIn(4000);
        $image2.fadeOut(4000);
      });


    }, 8000);  // setinterval function

  });

});

