var numTopPics = 8;
var chosenPic = Math.floor ( Math.random ( ) * numTopPics  + 1);
var pageCntr = 0;
var scrollInterval = 14*1000; // how often the bottom box slides, when on 'automatic' - in milliseconds
var scrollSpeed = 500;
var timerID = 0;

$(document).ready(function(){
  /* show the appropriate background image and text */
  var bgImg = 'url(graphics/home-0610/photo-bg' + chosenPic + '.jpg)';
  $('div#mainArea').css('background-image', bgImg);
  var mainText = '#mainText' + chosenPic;
  $('#mainArea .text').hide();
  $(mainText).show();

  /* scrolling box at the bottom */
  $('#arrowRight').show(); 
  $('#arrowRight').click(function() { clearTimeout(timerID); slideIt('right', scrollSpeed); });
  $('#arrowLeft').click(function() { clearTimeout(timerID); slideIt('left', scrollSpeed); });


  /* 'auto' scroll at start */
  timerID = setTimeout('autoScroll()', scrollInterval);

});

function autoScroll() { 
  var totalItems = $('.slidingItems .item').size();

  //console.log(pageCntr + ' = ' + totalItems);
  if (pageCntr +1 == totalItems) {  
    while (pageCntr > 0 ) {
      slideIt('left', 0);
    }
  }
  else { slideIt('right',scrollSpeed); }
  timerID = setTimeout('autoScroll()', scrollInterval);
  
}

function slideIt(dir, spd) { 
  var step = 768;
  var totalItems = $('.slidingItems .item').size();
  var currentPos = $('.slidingItems').css('marginLeft').replace(/px/g, '') * 1;
  var newPos = currentPos;
  if (dir == 'right') {
    newPos = newPos - step;
    pageCntr += 1;
  }
  else {
    newPos = newPos + step;
    pageCntr = pageCntr - 1;
  }

  if (pageCntr == 0) { $('#arrowLeft').hide(); }
  else { $('#arrowLeft').show(); }

  if (pageCntr == totalItems - 1) { $('#arrowRight').hide(); }
  else { $('#arrowRight').show(); }

  $('.slidingItems').animate({marginLeft: newPos}, spd);

  updateCounter(pageCntr);
}

function updateCounter(pageCntr) { 
  var cntr = 1;
  $('#counter li').removeClass('active');

  $('#counter li').each(function() { 
    $(this).removeClass('active');
    if (cntr == pageCntr + 1) { 
      $(this).addClass('active');
      //$(this).find('img').attr('src','graphics/home-0610/dot-full.png');
    } else { 
      //$(this).find('img').attr('src','graphics/home-0610/dot-empty.png');
      //$(this).removeClass('active');
    }
    cntr += 1;
  });
}

