var timerId = 999;
var slider = {
	/**
	 * This is the function that sets up the image slider once the page loads. It accepts a few different parameters:
	 * container - the string representing the class of the slider container
	 * images - a JSON array of image names
	 * imageDir - the directory containing the images passed in the images JSON object
	 * dotContainer - the class of the container div for the dots/markers for the image slider
	 */
	init: function(params){
		
		// the following code prints the images and dots to the webpage, based on parameters
		var container = $('.'+params.container);
		var dotContainer = $('.'+params.dotContainer);
		var images = params.images;
		for (var i = 0; i < images.length; i++) {
			if (i > 0) {
				container.append('<img class="slide" src="' + params.imageDir + images[i] + '" style="display:none;" />');
				dotContainer.append('<div class="dot inactive" ></div>');
			}
			else {
				container.append('<img class="slide current" src="' + params.imageDir + images[i] + '" />');
				dotContainer.append('<div class="dot active" ></div>');
			}
		}
		
		// this code initializes the timeOut loop for the auto-switching of images (until a user clicks a dot)
		timerId = setTimeout('slider.imageLoop()', 5000);
		
		// this code initializes the click events for the dots
		$('.dot').css('cursor','pointer').click(function(){
			if (!($(this).hasClass('active'))) {
				clearTimeout( timerId );
				var currentIndex = $('.dot').index(dotContainer.find('.active'));
				var dotIndex = $('.dot').index(this);
				var newDot = $(this);
				dotContainer.find('.active').toggleClass('inactive').toggleClass('active');
				newDot.toggleClass('inactive').toggleClass('active');
				$('.slide:eq('+dotIndex+')').toggleClass('next').fadeIn(0);
				$('.slide:eq('+currentIndex+')').fadeOut('fast', function(){
					$('.slide:eq('+currentIndex+')').toggleClass('current');
					$('.slide:eq('+dotIndex+')').toggleClass('current').toggleClass('next');
				});
			}
		});
	},
	
	imageLoop: function(){
		var dotContainer = $('.dot').parent();
		var dotIndex = $('.dot').index(dotContainer.find('.active'));
		// check to see if we are on the last image. if so reset to the first image
		if (++dotIndex == $('.dot').length) {
			dotIndex = 0;
		}
		var newDot = $('.dot:eq('+dotIndex+')');
		var currentIndex = $('.dot').index(dotContainer.find('.active'));
		dotContainer.find('.active').toggleClass('inactive').toggleClass('active');
		newDot.toggleClass('inactive').toggleClass('active');
		$('.slide:eq('+dotIndex+')').toggleClass('next').fadeIn(0);
		$('.slide:eq('+currentIndex+')').fadeOut('fast', function(){
			$('.slide:eq('+currentIndex+')').toggleClass('current');
			$('.slide:eq('+dotIndex+')').toggleClass('current').toggleClass('next');
			timerId = setTimeout('slider.imageLoop()', 5000);
		});
	}
};