/*
@description Displays paged thumbnails from the Flickr API
@author Ben Walker
@created 2009-07
*/

$(function() {
	
	// Initialise each Flickr panel on the page
	$(".flickr_thumbnails .photos").each(function() {
	    
		var current_page = "1";
		
	    /* Flickr returns some hidden INPUTs within the UL:
	        0: current page
	        1: last page
	        2: photos per page
	        3: total photos
	    */
		if ($("input", this).length) {
		    
		    // If we already have some photos find out which page we're on.
			current_page = $("input", this).get(0).value;
		}
		
		loadFlickrThumbs(this, current_page);
	});
	
	function loadFlickrThumbs(container, page) {
		$(container).flickr({
			api_key: "0d568a20dd86853edbf27147806bda4a",
			type: "search",
			group_id: "1065503@N25",
			per_page: 8,
			page: page,
			callback: function(el) {
			    
			    // Get the current and last page values out of the INPUTs
				var current_page = parseInt($("input", el).get(0).value);
				var last_page = parseInt($("input", el).get(1).value);
				
				// Find the paging buttons
				var prev = $(el).parents(".flickr_thumbnails").find(".paging .prev").show();
				var next = $(el).parents(".flickr_thumbnails").find(".paging .next").show();
				
				// Hide buttons that won't work
				if (current_page === 1) { prev.hide(); }
				if (current_page === last_page) { next.hide(); }
				
				// Next page
				next.click(function() {
				    
				    // Check that current page has finished loading
					if ($("input", el).length) {
    					$(el).fadeOut(500, function() {
    						var next_page = parseInt($("input", this).get(0).value) + 1;
    						$(this).empty().show();
    						loadFlickrThumbs(this, next_page);
    					});
    				}
					return false;
				});
				
				// Previous page
				prev.click(function() {
                    
				    // Check that current page has finished loading
				    if ($("input", el).length) {
    					$(el).fadeOut(500, function() {
    						var prev_page = parseInt($("input", this).get(0).value) - 1;
    						$(this).empty().show();
    						loadFlickrThumbs(this, prev_page);
    					});
    				}
					return false;
				});
				
				// Add Thickbox viewer behaviours to the thumbnails
				tb_init($("a", el));
			}
		});
	}
});

