$(document).ready(function(){
	var currentPosition = 0;
	var slideWidth = 613;
	var slides = $('.slide');
	var numberOfSlides = slides.length;
	var slideShowInterval;
	var speed = 4000;
	
	// Remove scrollbar in JS
	$('#slidesContainer').css('overflow', 'hidden');
	
	//Assign a timer, so it will run periodically
	slideShowInterval = setInterval(changePosition, speed);
	
	slides.wrapAll('<div id="slideInner"></div>')
	  
	slides.css({ 'float' : 'left' });
	
	//set #slidesHolder width equal to the total width of all the slides
	$('#slideInner').css('width', slideWidth * numberOfSlides);
	
	$('#slideshow')
		.prepend('<span class="control" id="leftControl">Move Left</span>')
		.append('<span class="control" id="rightControl">Move Right</span>');
	
	manageNav(currentPosition);
	
	//tell the buttons what to do when clicked
	$('.control').bind('click', function() {
		
		//determine new position
		currentPosition = ($(this).attr('id')=='rightControl')
		? currentPosition+1 : currentPosition-1;
									
		//hide/show controls
		manageNav(currentPosition);
		clearInterval(slideShowInterval);
		slideShowInterval = setInterval(changePosition, speed);
		moveSlide();
	});
	
	function manageNav(position) {
		//hide left arrow if position is first slide
		if(position==0){ $('#leftControl').hide() }
		else { $('#leftControl').show() }
		//hide right arrow is slide position is last slide
		if(position==numberOfSlides-1){ $('#rightControl').hide() }
		else { $('#rightControl').show() }
	}
	
	
	//changePosition: this is called when the slide is moved by the timer and NOT when the next or previous buttons are clicked
	function changePosition() {
		if(currentPosition == numberOfSlides - 1) {
			currentPosition = 0;
			manageNav(currentPosition);
		} else {
			currentPosition++;
			manageNav(currentPosition);
		}
		moveSlide();
	}
	
	
	//moveSlide: this function moves the slide 
	function moveSlide() {
			$('#slideInner').animate({'marginLeft' : slideWidth*(-currentPosition)});
	}
});
