$(document).ready(function() {		
	var navigate = function(){
		var nextlink = $('#nextprev a.next');
		var prevlink = $('#nextprev a.prev');
		var nexturl = $(nextlink).attr('href');
		var prevurl = $(prevlink).attr('href');
		// fix for ie, http://www.glennjones.net/Post/809/getAttributehrefbug.htm
		var domain = 'http://'+window.location.hostname;
		if (prevurl) {
			prevurl = prevurl.replace(domain,'');
		}
		if (nexturl) {
			nexturl = nexturl.replace(domain,'');
		}
		$(document).unbind('keydown'); // remove old keydown event handlers
		//remove links from next/prev and large photo to match pagination		
		if($('#gallery li a[href="' + nexturl + '"]').length==0) {
			$(nextlink).add('#img_placeholder a#nextphoto').contents().unwrap();
		} else {
			$(document).keydown(function(e){
	    		if (e.keyCode == 39) { 
			       var link = nexturl;
					showPhoto(link);
			       return false;
			    }
			});
		}
		if($('#gallery li a[href="' + prevurl + '"]').length==0) {
			$(prevlink).replaceWith('Previous');
		} else {
			$(document).keydown(function(e){
	    		if (e.keyCode == 37) { 
			       	var link = prevurl;
					showPhoto(link);
			       	return false;
			    }
			});
		}
	
		$('#img_placeholder a').click(function(event){  
			var link = $(this).attr('href');
			link = link.replace(domain,'');
			showPhoto(link);
			return false;
		});
		$("#photo-nav").show();
	}

	var showPhoto = function(link){	
		$("#gallery img").removeClass('selected');
		$("#photo-nav").hide();
		$("#img_placeholder").replaceWith('<div id="img_placeholder"><img src="/img/loading.gif" width="32" height="32" alt="Loading" class="loading" /></div>');
		var url = link +'?' + new Date().getTime();
		$("#img_placeholder").load(url,null,navigate);
		$("#gallery a[href='"+link+"'] img").addClass('selected');
	}
	
	$('#gallery').after('<div id="imgwrap"><div id="photo-nav">Use left/right arrow keys to navigate through photos</div></div>');
	$("#imgwrap").append('<div id="img_placeholder"><img src="/img/loading.gif" width="32" height="32" alt="Loading" class="loading" /></div>');
	// find first image
	var first = $("#gallery #thumb1 a").attr('href');
	showPhoto(first);
	$('#gallery').click(function(event){  
		if ($(event.target).is("img.thumb")) {
			var link = $(event.target).parent().attr('href');
			showPhoto(link);
			return false;
		}				
	});
});
