// Photo album
var photos = {

	album: null,
	count: null,
	page: 1,
	pages: null,
	image: 1,
	obj: null,
	
	init: function(album, count)
	{
		// Set inital paramaters
		photos.album = album;
		photos.count = count;
		
		// Set number of pages
		photos.pages = Math.ceil(photos.count/15);
		
		// Cache the gallery object
		photos.obj = $('#photos .gallery');

		// Setup thumbnail binding
		photos.obj.find('.thumbs').delegate('img', 'click', function()
		{
			// Load the selected image
			photos.load($(this).attr('img'));
		});

		// Setup previous button bindings
		photos.obj.find('button.prev').click(function()
		{
			// Set previous image
			var prev = (photos.image - 1 < 1) ? photos.count : photos.image - 1;

			// Load previous image
			photos.load(prev);
		});

		// Setup next button bindings
		photos.obj.find('button.next').click(function()
		{
			// Set next image
			var next = (photos.image + 1 > photos.count) ? 1 : photos.image + 1;

			// Load next image
			photos.load(next);
		});

		// Setup page link bindings
		photos.obj.find('.pages').delegate('span', 'click', function()
		{
			// Get the selected page number
			var page = $(this).html();
			
			// Set image number
			var image = (page-1) * 15 + 1;

			// Load first image of that page
			photos.load(image);
		});

		// Get url hash
		var hash = window.location.hash.substring(1);

		// Load first from hash
		if(hash > 0)
		{
			photos.load(hash);
		}
		else
		{
			photos.load(1);
		}
	},

	load: function(image)
	{
		// Set the new current image
		photos.image = image;
		
		// Set location has
		window.location.hash = '#' + photos.image;

		// Load the photo
		photos.obj.find('.photo').attr('src', 'http://www.letslandscape.ca/images/photos/' + photos.album + '/' + photos.image + '.jpg');

		// Figure out the page number
		var page = Math.ceil(photos.image/15);

		// Set the start and end thumbnail images to display
		var start = (15 * (page-1)) + 1;
		var end = start + 15 - 1;

		// Clear the current thumbnails
		photos.obj.find('.thumbs').empty();

		// Load the new thumbnails
		for(thumb = start; thumb <= end; thumb++)
		{
			if(thumb <= photos.count)
			{
				photos.obj.find('.thumbs').append('<img src="http://www.letslandscape.ca/images/photos/' + photos.album + '/' + thumb + 't.jpg" width="48" height="48" img="' + thumb + '" />');
			}
		}

		// Highlight the current image
		photos.obj.find("img[img='" + photos.image + "']").addClass('selected');
		
		// Update the page numbers
		photos.obj.find('.pages').html('Page: ');

		for(x = 1; x <= photos.pages; x++)
		{
			if(x == page)
			{
				photos.obj.find('.pages').append('<span class="selected">' + x + '</span>');
			}
			else
			{
				photos.obj.find('.pages').append('<span>' + x + '</span>');
			}
		}
	}
};
