var inAction = false;
var cache = [];
var timelife = 10;

var findCurrentKey = function() {
  for(i = 0; i <= bgImage.length; i++) {
    if($('#bgScroller div:first-child').css('backgroundImage').indexOf(bgImage[i]) > 0) {
      return i;
    }
  }
}

var preLoad = function() {
  var args_len = arguments.length;
  for(i = 0; i <= bgImage.length; i++) {
    var cacheImage = document.createElement('img');
    cacheImage.src = bgImage[i];
    cache.push(cacheImage);
  }
}


var scroll = function(direction) {
  if (inAction == true)
    return;
  inAction  = true;
  $('#bgScroller').fadeTo(1000, .9);
  var cont  = $('#bgScroller');
  //var html  = $('#bgScroller').html();
  var child = $('#bgScroller div:first-child');
  var k = findCurrentKey();
  // alert(k);
  if (k == 0 && direction == false) {
    k = bgImage.length;
  } else if (k == bgImage.length-1 && direction == true) {
    k = -1;
  }
  if (direction == true) {
    $('#bgScroller').css('width', cont.width() * 2).append('<div style="background-image:url(' + bgImage[k+1] + ');">&nbsp;</div>');
    $('#bgScroller div').css('width', cont.width() / 2);
  } else {
    $('#bgScroller').css('width', cont.width() * 2).prepend('<div style="background-image:url(' + bgImage[k-1] + ');">&nbsp;</div>');
    $('#bgScroller div').css('left', '-' + (cont.width() / 2) + 'px'); 
    $('#bgScroller div').css('width', cont.width() / 2);
  }
  $('#bgScroller div').animate({
    left : (direction == true ? '-' : '+') + '=' + cont.width() / 2
  }, 1000, 'swing', function() {
    child.remove();
    $('#bgScroller div').css('left', '0px'); 
    $('#bgScroller div').css('width', '100%'); 
    $('#bgScroller').css('width', '100%');
    inAction = false;
    $('#bgScroller').fadeIn(50);
  });
}

var autoscroll = function() {
  if (timelife++ > 19) {
    scroll(true);
    timelife = 10;
  }
  window.setTimeout('autoscroll();', 1000);
}

$(function() {
  preLoad();
  $('#prev').click(function() {
    scroll(false);
    timelife = 0;
  });
  $('#next').click(function() {
    scroll(true);
    timelife = 0;
  });
  autoscroll();
});
