$(document).ready(function () {
  $('#header img').hide();
});

$(window).load(function () {
  var index = 0;
      duration = 10000,
      cont = $('#header'),
      cont_width  = cont.width(),
      cont_height = cont.height(),
      $imgs = $('#header img');
  
  $imgs.hide();
  
  rotate();
  fadeBack();
  
  function fadeBack(){
    $('#background').fadeTo(5000, Math.random(), function () {
      setTimeout(fadeBack, 10);
    });
  };
  function rotate(){
    var $img = $imgs.eq(index).show(),
        right = cont_width - $img.width();
        bottom = cont_height - $img.height();
        startx = 0,
        starty = 0,
        endx = right,
        endy = bottom;
    
    if(Math.random () > 0.5){
      startx = right;
      endx = 0;
      starty = bottom;
      endy = 0;
    }
    
    if(Math.random() > 0.5){
      endx = startx = right / 2;
    }else{
      endy = starty = bottom / 2;
    }
    
    $img.css('top', starty)
      .css('left', startx)
      .css('opacity', 0)
      .animate({top: endy, left: endx}, {easing: "linear", queue: false, duration: duration, complete: function () {
        $(this).hide();
        setTimeout(rotate, 1);
      }})
      .animate({opacity: 1}, duration / 16)
      .delay(duration / 16 * 14)
      .animate({opacity: 0}, duration / 16);
    
    index++;
    index %= $imgs.length;
  }
});
