var g_nImages = 8;
var g_randList = [];

$(function(){
  // preload images
  if (!$.browser.safari)
    for (var i = 0; i < g_nImages; i++)
      $('<img>').attr('src', 'images/home-image' + (i + 1) + '.jpg').hide().appendTo(document.body);
  
  $('#home-image').attr('src', 'images/spacer.gif');
  changePic();
});

function changePic() {
  if (!g_randList.length) {
    for (var i = 0; i < g_nImages; i++)
      g_randList.push(i);
    g_randList.sort(function(a, b){ return Math.random() - 0.5; });
  }
  
  var nextImg = 'images/home-image' + (g_randList.pop() + 1) + '.jpg';
  if ($.browser.safari) {
    $('#home-image').attr('src', nextImg);
    setTimeout(changePic, 3000);
  } else {
    var pos = $('#home-image').position();
    $('<img>').css({ position: 'absolute', left: pos.left, top: pos.top }
      ).attr('src', nextImg
      ).hide(
      ).appendTo($('#top')
      ).fadeIn(500, function() {
        // after fade in
        $('#home-image').attr('src', nextImg);
        $(this).hide();
        setTimeout(changePic, 3000);
      });
  }
  
  g_firstImage = false;
}
