  $(document).ready(function(){
  var currentPosition = 0;
  var slideWidth = 670;
  var allslides = $('.slide');
  var numberOfSlides = allslides.length;

  // Wrap all .slides with #slideInner div
  allslides
  .wrapAll('<div id="slideInner"></div>')
  // Readjust .slides width
  .css({
    'width' : slideWidth
  });

  // Set #slideInner width equal to total width of all slides
  $('#slideInner').css('width', slideWidth * numberOfSlides);

  // Insert left and right arrow controls in the DOM
  $('#slideshow')
    .prepend('<span class="control" id="left">Move left</span>')
    .append('<span class="control" id="right">Move right</span>');

  // Hide left arrow control on first load
  manageControls(currentPosition);
  
  // Auto advance slideshow
  $(function(){ intval = window.setInterval(slideForward, 8000) });

  // Create event listeners for .controls clicks
  $('.control')
    .bind('click', function(){
    window.clearInterval(intval);
    intval = window.setInterval(slideForward, 8000);
    // Determine new position
      currentPosition = ($(this).attr('id')=='right')
    ? currentPosition+1 : currentPosition-1;

      // Hide / show controls
      manageControls(currentPosition);
      // Move slideInner using margin-left
      $('#slideInner').animate({
        'marginLeft' : slideWidth*(-currentPosition)
      });
    });
    
  // Create event listeners for #slideshow hover
  $('#slideshow').hover(
  	function(){
  		$('.control').animate( { opacity:1 }, 100); },
  	function(){
  		$('.control').animate( { opacity:0 }, 100); }
    );
    
  function slideForward(){
    // If current slide is last, then slide to first
    currentPosition = (currentPosition == numberOfSlides-1)
    ? 0 : currentPosition+1;
    
    // Slide to new position
    manageControls(currentPosition);
      $('#slideInner').animate({
        'marginLeft' : slideWidth*(-currentPosition)
      });
  }
  
  // manageControls: Hides and shows controls depending on currentPosition
  function manageControls(position){
    // Hide left arrow if position is first slide
    if(position==0){ $('#left').hide() }
    else{ $('#left').show() }
    // Hide right arrow if position is last slide
    if(position==numberOfSlides-1){ $('#right').hide() }
    else{ $('#right').show() }
    }
  });