/* Used to know if the slideshow is playing or not */
var gallery_slide = false;
/*
 * Initialize the page
 */
jQuery(document).ready(function($) {
	clickEvent(); // Bind ajax loading to each link
	$("#slideshow_ctrl a").show(); // JS enable the slideshow link
	$("#gallery").ajaxComplete(function(event,request, settings){
		clickEvent(); // Bind ajax loading to each just added link
	});
	$(document).keydown(function(e) { // Enable keyboard support
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		switch(key) {
		case 32: // space --> Start/Stop slideshow
			slideShow(false);
			e.preventDefault();
			break;
		case 33: // Page Up --> Previous page
			gallery_slide = false;
			ajaxLoad($(".pagination:first a:first"));
			e.preventDefault();
			break;
		case 34: // Page Down --> Next page
			gallery_slide = false;
			ajaxLoad($(".pagination:first a:last"));
			e.preventDefault();
			break;
		case 37: // left arrow --> Previous img
			gallery_slide = false;
			ajaxLoad($("#nav #nav_prev"));
			e.preventDefault();
			break;
		case 39: // right arrow --> Next img
			gallery_slide = false;
			ajaxLoad($("#nav #nav_next"));
			e.preventDefault();
			break;
		}
	});
});
/*
 * Modify the click event of each link to enable ajax 
 */
function clickEvent(){
	$("#gallery").find("a.ajax").each(function(i) {
		$(this).click(function(){
			gallery_slide = false;
			ajaxLoad($(this));
			return false;
		});
	});
}
/*
 * Perform the actual ajax loading of the gallery using the links generated server-side
 */
function ajaxLoad(link){
	var url = link.attr("href");
	$("#img_wrapper img").fadeTo("fast",0 ,function(){
		//$("#img_wrapper ").html("<div style=\"height:375px; width:502px;\" ><img style=\"position:relative; top:150px; left:250px;\" src=\"/images/corps/wait.gif\" /></div><p> - </p>");
		$("#gallery").load(url+"&ajax_query=1",function(){
			$("#img_wrapper img").hide();
			$("#img_wrapper img").load(function(){
				$("#img_wrapper img").fadeIn("fast");
			}); 
			$("#slideshow_ctrl a").show();
			if(gallery_slide){
				$("#slideshow_ctrl a").html("<img src=\"/images/corps/pause.png\" alt=\"\" />");
			}
		});
	});
}
/*
 * Start/Stop slideshow 
 * 'recursive' must always be false except in the recursive call 
 */
function slideShow(recursive){
	if(recursive && gallery_slide){ // slideshow continue
		ajaxLoad($("#nav #nav_next"));// Use the next link
		setTimeout("slideShow(true)",3000);
	}
	else if (!recursive && !gallery_slide){ // start slideshow
		gallery_slide = true;
		$("#slideshow_ctrl a").html("<img src=\"/images/corps/pause.png\" alt=\"\" />");
		$("#slideshow_ctrl a").blur();
		setTimeout("slideShow(true)",1000);
	}
	else{ // stop slideshow
		gallery_slide = false;
		$("#slideshow_ctrl a").html("<img src=\"/images/corps/play.png\" alt=\"\" />");
		$("#slideshow_ctrl a").blur();
	}
}
