var stepgate = false;	

$(document).ready(function() {
	attach_listeners();
	$(".mc_slideshow > #slide_1 > .underlay").fadeIn("slow", function(){
		$(".mc_slideshow >  #slide_1 > .overlay").fadeIn("slow");
	});
});

function attach_listeners() {
	$('.slideshow_step_active').each(function() {
		if (stepgate == false) {	
			$(this).mouseover(function () {
				$(this).css("cursor", "pointer");
			});
			$(this).click(function() {
				if (stepgate == false) {
					stepgate = true;
					// Find out the slideshow ID			
					pieces = $(this).parent().parent().parent().attr("id").split("-");
					slideshowid = pieces[1];		
		
					// Find out the current slideshow step
					pieces = $(this).parent().parent().attr("id").split("_");
					currentstep = pieces[1];
					navchoice = $(this).html();
		
					$.get("/mc_slideshow_return_next_step", { "currentstep": currentstep, "slideshowid": slideshowid }, function (data) {
						nextstep = data;
						$.get("/mc_slideshow_return_previous_step", { "currentstep": currentstep }, function (data) {
							previousstep = data;
							if (navchoice.match('next')) {
								requestedstep = nextstep;
							} else if (navchoice.match('previous')) {
								requestedstep = previousstep;				
							} else {
								// Find out the requested slideshow step
								requestedstep = navchoice;
							}	
							if (requestedstep != currentstep) {
								$.get("/mc_slideshow_return_image_url", { "requestedstep": requestedstep, "slideshowid": slideshowid }, function (data) {  
									imageurl = data;
									var imageObj = new Image();
									$(imageObj).attr("src", imageurl).load(function() {
										$.get("/mc_slideshow_return_slide", { "requestedstep": requestedstep, "slideshowid": slideshowid }, function (data) {  
											$("#mc_slideshow_node-" + slideshowid).prepend(data);
											$("#mc_slideshow_node-" + slideshowid + " > #slide_" + currentstep).fadeOut("fast", function() {			
												$("#mc_slideshow_node-" + slideshowid + " > #slide_" + requestedstep + " > .underlay").fadeIn("slow", function() {
													$("#mc_slideshow_node-" + slideshowid + " > #slide_" + requestedstep + " > .overlay").fadeIn("slow");						
												});
												$("#mc_slideshow_node-" + slideshowid + " > #slide_" + currentstep).remove();
											});
											stepgate = false;
											attach_listeners();
										});
									});
								});
							} // end if (requestedstep != currentstep)
						});
					});
				} // end if (stepgate==false)
			});
		} // end if (stepgate==false)
	});
} // end function attach_listeners

