$(document).ready(function(){
	// Set variables
	var current_image = 0;
	var show_info_time = 1500;
	var show_info_fade_time = 500;
	var item_display_time = 7500;
	var item_fade_time = 1000;
	var auto_scroll = true;
	
	// Calculate how many items are in the gallery
	var item_count = $("div#gallery div.gallery-item div.info").hide().parent().hide().size();
	
	if(item_count > 1) {
		// If the gallery has multiple items, show the first one
		$("div#gallery div.gallery-item:eq(0)").show();
		
		// Show the gallery controls and highlight the first one
		$("div#gallery div.gallery-controls").show().find("span:eq(0)").removeClass("off").addClass("on");
		
		// Set Timer to display gallery item info
		$("div#gallery").oneTime(show_info_time,function(){
			show_info();
		});
		
		// Set Timer to begin gallery rotation
		$("div#gallery").everyTime(item_display_time,"gallery",function(){
			// Calculate which images to fade between
			var from = current_image;
			current_image ++;
			if (current_image > (item_count-1)) { current_image = 0; }
			var to = current_image;
			
			// Do fade, and set gallery item info to display
			change_gallery_item(from,to);
			$("div#gallery").oneTime(show_info_time,function(){
				show_info();
			});
		});
	} else {
		// If there is only 1 item in the gallery, show it
		$("div#gallery div.gallery-item").show();
		$("div#gallery").oneTime(show_info_time,function(){
			show_info();
		});
	}
	
	$("div#gallery div.gallery-controls span").click(function(){
		// When a gallery control is clicked, make sure the timer is stopped
		$("div#gallery").stopTime("gallery");
		
		// Then, set the fade times to 1
		item_fade_time = 1;
		show_info_fade_time = 1;
		
		// Now, calculate which gallery items to fade between
		var from = current_image;
		current_image = $("div#gallery div.gallery-controls span").index($(this));
		var to = current_image;
			
		// Do fade, and set gallery item info to display
		change_gallery_item(from,to);
		show_info();
	});
			
	function show_info() {
		// This function simply fades in the info for the gallery item that is displaying
		$("div#gallery div.gallery-item:eq(" + current_image + ") div.info").fadeIn(show_info_fade_time);
	}
	
	function change_gallery_item(from,to) {
		// This function fades between two gallery items
		$("div#gallery div.gallery-item:eq(" + from + ") div.info").hide().parent().fadeOut(item_fade_time);
		$("div#gallery div.gallery-item:eq(" + to + ")").fadeIn(item_fade_time);
		$("div#gallery div.gallery-controls span:eq(" + from + ")").removeClass("on").addClass("off");
		$("div#gallery div.gallery-controls span:eq(" + to + ")").removeClass("off").addClass("on");
	}
});
