var imageId = 0;

/* Change the visible image.
 * @param delta:   	     	An integer; go forward or backward in the image list
 *                      	by this number of images.
 * @param next_category_url:Where to go after the final image
 */
function navigate(delta, next_category_url) {
	imageId += delta;
	navigateToImageId(next_category_url);
}

/* Show the proper image after updating imageId.
 * @param next_category_url:Where to go after the final image
 */
function navigateToImageId(next_category_url) {
    var blank = '<img src="/images/blank.gif" height="9px" width="14px" />';
	
    // clamp imageId to [0, images.length)
    if (imageId < 0) {
		imageId = 0;
	} else if (imageId < images.length) {
		// Support back button or bookmarking by setting image index (1-based) in URL,
		// like http://emptysquare.net/photography/lower-east-side/#5/
		parts = document.location.href.split('#');
		document.location = parts[0] + '#' + (imageId + 1) + '/';
	} else {
		// Navigate to the next category
		document.location.href = document.location.href.replace(/(http:\/\/.*?)(\/.+\/)/, "$1" + next_category_url);
		return false;
	}
    
    // Show or hide the left and right arrows depending on current position in
    // list of images
    if (imageId == 0) $("#navLeft").html(blank);
    else $("#navLeft").html('<img src="/images/goleft.gif" height="9px" width="14px" />');
    
    if (imageId == images.length - 1) $("#navRight").html(blank);
    else $("#navRight").html('<img src="/images/goright.gif" height="9px" width="14px" />');
    
    // Update the displayed image id
    $("#navIndex").html("" + (imageId + 1));
    
	// I've decided descriptions are superfluous
    //$("#imageDescription").html(images[imageId].description);
	//$("#imageTitle").html(images[imageId].title);
    
	setImage(images[imageId].image);
	
	var urlencoded_location = $.URLEncode(document.location.href);
	$("#fb_like_button").attr('src', 'http://www.facebook.com/plugins/like.php?href=' + urlencoded_location + '&amp;layout=button_count&amp;show_faces=false&amp;width=75&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21');
	
	$("#tweet_button").attr(
		'href',
		'http://twitter.com/home?status=' + urlencoded_location
	);
	
    return false;
}

/* Show a photo
 * @param image:	An Image object
 */
function setImage(image) {
	$("#imageContainer").empty().append(image);
}

/* Preload all photos in the images array
 * @param preload_image_id:	Which image to preload, or -1 for all images
 * @param onload_function:	Function to call when image has loaded
 */
function preloadImage(preload_image_id, onload_function) {
	var imageObj = new Image();
	imageObj.imageId = preload_image_id;
	images[preload_image_id]['image'] = imageObj;
	
	imageObj.onload = function() {
		// As soon as image loads, show it if it's the current image
		if (imageId == this.imageId) {
			setImage(this);
			if (onload_function) onload_function();
		}
	};
	
	// Trigger a preload
	imageObj.src = '../..' + images[preload_image_id].url;
}

/* Call this in $(document).ready()
 * @param category_name:  A string, the name of this category of photos,
 *                        e.g. "portraits", or "rock stars"
 * @param images:         An array of objects, not the actual images but
 *                        information about them
 * @param next_category_url: Where to go after this page
 */
function onReady(category_name, images, next_category_url) {
	// Are we at a URL with a image index greater than 1, e.g.:
	// http://emptysquare.net/photography/lower-east-side/#5/
	parts = document.location.href.split('#');
	
	// URL's image index is 1-based, our internal index is 0-based
	if (parts.length > 1) {
		imageId = parseInt(parts[1].replace('/', '')) - 1;
		if (imageId < 0) imageId = 0;
		if (imageId >= images.length) imageId = images.length - 1;
	} else {
		imageId = 0;
	}
	
	// Load current image first to maximize speed, then load remaining images
	preloadImage(imageId, function() {
		for (var i = 0; i < images.length; i++) {
			preloadImage(i, null);
		}
	});
	
	function navForward()  { navigate(+1, next_category_url); }
	function navBackward() { navigate(-1, next_category_url); }
    
    // Event handlers
    $("#navLeft").click(navBackward);
    $("#navRight, #imageContainer").click(navForward);
	
	navigateToImageId(next_category_url);
}
