$(function(){
	
	/*
	 * Globals
	 */
	var $slideshow = $("#slideShow");
	var $parent = $slideshow.parent();
	var $controls = $parent.children("#slideShowControls");
	var slideWidth = $slideshow.children("img").width();
	var numSlides = $slideshow.children().length;
	var slideShowWidth = (slideWidth * numSlides);
	var limitPos = -(slideShowWidth - slideWidth);
	var timer = 10000;
	var slideDuration = 1000;
	var interval;
	
	/*
	 * Add control items for each slide
	 */
	var addControls = function() {
		// Prepend control items
		for(var i = numSlides - 1; i >= 0; i--) {
			$controls.prepend('<li id="control_' + i + '"></li>');
		}
		// Set controls width to keep centered
		$controls.width($controls.children("li").outerWidth(true) * numSlides);
	};
	
	/*
	 * Set the active control
	 */
	var setActiveControl = function(item) {
		$controls.children("li").removeClass("active");
		$controls.children("li").eq(item).addClass("active");
	};
	
	/*
	 * Control button eventhandler
	 */
	var controlHandler = function(event) {
		if(event.type == "click") {
			$slideshow.stop(true);
			clearInterval(interval);
			var id = $(this).attr('id').replace("control_", "");
			slide({id: id}, function() {
				interval = setInterval(slide, timer);
			});
		} else if(event.type == "mouseover") {
			$controls.children("li").removeClass("over");
			$(this).addClass("over");
		} else if(event.type == "mouseout") {
			$(this).removeClass("over");
		}
	};
	
	/*
	 * Slideshow event handler
	 */
	var slideshowHandler = function(event) {
		if(event.type == "mouseover") {
			clearInterval(interval);
		} else if(event.type == "mouseout") {
			interval = setInterval(slide, timer);
		}
	};
	
	/*
	 * Do slide
	 */
	var slide = function(slide, callback) {
		var parentPos = $parent.offset().left;
		var curPos = $slideshow.offset().left - parentPos;
		
		if(typeof(slide) == 'object') {
			var newPos = slide.id * -slideWidth;
		} else {
			var newPos = curPos - slideWidth;
		}
		
		if(newPos >= limitPos) {
			$slideshow.animate({left: newPos+'px'}, slideDuration, function() {
				setActiveControl(-newPos / slideWidth);
				if(callback != null)
					callback();
			});
		} else {
			$slideshow.animate({left: 0}, slideDuration, function() {
				setActiveControl(0);
				if(callback != null)
					callback();
			});
		}
	};

	// Initialize slideshow
	$slideshow.width(slideShowWidth);
	$slideshow.mouseover(slideshowHandler);
	$slideshow.mouseout(slideshowHandler);
	
	// Initialize controls
	addControls();
	$controls.children("li").click(controlHandler).mouseover(controlHandler).mouseout(controlHandler);
	setActiveControl(0);
	
	// Set Interval
	interval = setInterval(slide, timer);
	
});

