$(document).ready(function() {
	
	var previousSlide = 0;
	var currentSlide = 1;
	var slides = $('.slideshow li');
	var numberOfSlides = slides.length;
	
	// Remove scrollbar in JS
	
	$('.slideshow li').css({'position':'absolute',
							'opacity' : '0',
							'z-index' : '1'});
	$('.fp_featured').css({'width':'700px'});
	
	$('.slideshow li:first-child').css({'opacity' : '1',
										'z-index':'2'});
	
	$('.slideshow').css({'overflow':'visible'});
	
	// add the back and forward buttons
	$('.slideshow').after('<div class="slideshowcontrols"><span class="control" id="forwardControl">Next</span>');
	$('#forwardControl').after('<ul class="slideshow_dots">');
	var i = 0;
	for (i = 0; i < numberOfSlides; i++) {
		$('.slideshow_dots').append('<li></li>');
	}  
	// put these in the <li> to have it display the number ' + (i+1) + '
	
	$('.slideshow_dots').after('</ul><span class="control" id="backControl">Prev</span></div>');
	
	$('.slideshow_dots li:first-child').addClass("current_dot");
	
	// Create event listeners for .control clicks
	$('.control').bind('click', changeSlide);
	
		
	timer = setInterval(changeSlideTimed, 9000);
	
	function changeSlide() {
		
		clearInterval(timer);
		
		addDotClass();
		currentSlide = ($(this).attr('id')=='forwardControl') ? currentSlide + 1 : currentSlide - 1;
		manageCurrentSlide(currentSlide);
		slideAnimation();
			
	}
	
	function changeSlideTimed() {
		
		addDotClass();
		currentSlide += 1;
		manageCurrentSlide(currentSlide);
		slideAnimation();
		
		
	}
		
	function slideAnimation() {
		
		// animate to currentSlide
		$('.slideshow li').css({'z-index' : '1'}).stop().animate({'opacity' : '0'});
		$('.slideshow li:nth-child(' + currentSlide + ')').css({'z-index' : '2'}).stop().animate({'opacity':'1'});
		$('.slideshow_dots li:nth-child(' + currentSlide + ')').addClass("current_dot");
		
	}
	
	function addDotClass() {
		
		// determine active slide
		if ($('.slideshow_dots li:nth-child(' + currentSlide + ')').hasClass("current_dot")) {
			$('.slideshow_dots li:nth-child(' + currentSlide + ')').removeClass("current_dot");
		}
		
	}
	
	
	
	
	function manageCurrentSlide(slidenum) {
		
		if (slidenum > numberOfSlides) {
			currentSlide = 1;
		}
		if (slidenum < 1) {
			currentSlide = numberOfSlides;
		}
	}

});
