	var firstTimePaintingShow = true;
	var clickIsFromMainTabThumb = false;

	// An 'associative array' to index the main array by image id.
	var imageById = new Array();

	var imageCategories = new Array();

	var featuredThumbs = new Array();
	var forsaleThumbs = new Array();

	$(document).ready(function()
	{
		buildImageViews ( )

		$("#bio_tabs").tabs( { }); 
		
		/* Rounding rules for boxes. Varying radii, "all" browsers */
		DD_roundies.addRule('#footer', '3px', true);
		DD_roundies.addRule('#masthead', '3px', true);
		DD_roundies.addRule('#paintings_content_right', '3px', true);
		DD_roundies.addRule('.main_content_right', '3px', true);

		// Listen for clicks on the accordion 
		$("#nav_accordion").bind( 'accordionchange', function(event, ui) {		
			// Place the first image in the first tab in the selected category in the main image area
			// Use a fake event for this
			if ( ! clickIsFromMainTabThumb)
			{
				thumbClickHandler ( { 'target': { 'id': getFirstAAElement(imageCategories[ui.newContent.context.id]) } } ); 
			}
			
			// Tell Google analytics about our 'page' access
			pageTracker._trackPageview( ui.newContent.context.id + '_accordion');
		} );

		// Create the thumb navigation accordion. Note that we switch animation off as when it's on, the event delivery 
		// timing causes problems with clicks on featured image thumbnails.
		$("#nav_accordion").accordion( { fillSpace: true, header: 'h3', animated: false, autoHeight: true } );
		

		// Build all the painting thumbnail-based navigation content
		loadAccordions ( );

		// Set up a click handler for the painting tab nav thumbnails
		$('.nav_thumb').click ( thumbClickHandler );

		// Create the set of thumbnails featured on the home tab and in the purchasing tab
		fillMainTabThumbs ( featuredThumbs, "Featured Paintings", "#featured_thumbs");
		fillMainTabThumbs ( forsaleThumbs, "Original Paintings Currently for Sale", "#forsale_thumbs");
		
		// Set up a click handler for the home page featured thumbnails
		$('.main_tab_thumb').click ( maintabThumbClickHandler );

		// If the link to 'available reproductions' is clicked, switch to the Painting tab, and 
		// select the Reproductions accordion pane
		$('.a').click ( function ( )  {
								$('#topnav_tabs').tabs ('select', '#paintings_tab' ); 
								$("#nav_accordion").accordion('activate', 8);//'#reproductions_nav');
		});

		// Create the various tabs
		$("#topnav_tabs").tabs( );

		$('#topnav_tabs').bind ('tabsshow', function (event, ui) { 
			// Now place the first image of the first set into the main display -- our default starting view
			// Use a fake event for this
			// Paintings tab index is 1 -- remember to change this if you move the tabs around
			if (ui.index == 1 && firstTimePaintingShow && ! clickIsFromMainTabThumb)
			{
				thumbClickHandler ( { 'target': {'id': getFirstAAElement(imageCategories['new_work']) } } );
				//__' + imageCategories['inland']['green_to_gold'].image_name }} );
				firstTimePaintingShow = false;
			}
		});	
	} );

	// Called when a thumbnail is clicked. When this happens, we want to display the big version of the
	// thumbnail in the main painting window.
	function thumbClickHandler (event) 
	{ 
		// Place the full image for this thumb in the full image container. We get the image name from the 
		// id of event (which was set when we created the thumb tag). Note that the id is a composite of the
		// image set (e.g., trees), and the actual image file name.
		// Also spit out the title, description etc.
		var image = imageById[event.target.id];
		var folder = image.categories.split(",")[0];

		$('#big_image_container').html ( "Loading image...");
		
		var html = '<div><img id="paintings_big_image" class="' + getBigImageDimensionStyle ("#big_image_container", image) + '" src="images/' + folder + '/' + image.image_name + '.jpg" alt="Painting with title of ' + image.image_name + '"/></div>';
		
		// First just the image in its own container
		$('#big_image_container').html ( html );

		// Then the image description etc in its own container
		html = '<div><h3>' + image.title + '</h3><p><strong>';
		if ( image.description.length > 0)
			html += image.description+ ' &nbsp; &nbsp; &#8226; &nbsp; &nbsp;';
			
		html += image.date+ ' &nbsp; &nbsp; &#8226; &nbsp; &nbsp;';
		html += image.medium + '&nbsp; &nbsp; &#8226; &nbsp;&nbsp;&nbsp; ';
		html += image.size + ' inches &nbsp; &nbsp; &#8226; &nbsp; &nbsp;';
		html += (image.sale_state == 'sold' ? 'Sold' : 'For sale:&nbsp; &nbsp;' + (image.price == '0.00' || image.price == '' ? 'price on application' : '$' + image.price));
		html += (image.repro_avail == 'true' ? '&nbsp; &nbsp; &#8226; &nbsp;&nbsp;Reproductions available' : '') + '</strong>';
		if ( image.note && image.note.length > 0 )
		{
			html += '&nbsp; &nbsp; &#8226; &nbsp; &nbsp;<a class="show-sticky" href="#show">Artist\'s comments</a>'
		}
		html += '</p></div>'
			
		$('#big_image_text').html ( html );

		$( '.show-sticky' ).click( function () 
		{
			 $('#image-notes > p').html('When I was a boy in Scotland, salmon and sea trout were still relatively common -- but not any more. Many rivers still run clear, but commercial fisheries have obliterated them and now anglers fish out of nostalgia expecting no bites. The  few rivers with good runs are owned wholly by the very wealthy -- industrialists who wiped the rest out for everyone else. This painting is non-specific technically, but shows the type of salmin fishing that could have sustainably mantained the stocks, the lifestyles and wonderful food chain serving entire river systems.');
			 $('#image-notes').toggle( 'fast' );
			 return false;
		});

	$('#notes-close' ).click( function () 
	{
		$('#image-notes').hide();
	});
	

	// Lastly, track this view to google analytics
		pageTracker._trackPageview( "click_big_image_" + image.image_name);
	}


	// Called when a main tab thumbnail is clicked. When this happens, we want to flip to the Paintings tab,
	// select the accordion category that the thumb belongs in, and then pop the big image up 
	// thumbnail in the main painting window.
	function maintabThumbClickHandler (event) 
	{ 
		// Find the image and its category
		var image = imageById[event.target.id];
		var category = image.categories.split(",")[0];

		$('#topnav_tabs').tabs ('select', '#paintings_tab' ); 
		
		// Temporarily disable the tab select handler as we want a particular tab to be selected, not 
		// the first one 
		clickIsFromMainTabThumb = true;
		$("#nav_accordion").accordion('activate', '#' + category );
		$('#' + category + '_tabs').tabs ('select', '#' + image.tab_id ); 
		thumbClickHandler ( { 'target': { 'id': image.id } } ); 
		clickIsFromMainTabThumb = false;
	}
	
	
	// Build some views of the images (by category, by ID etc.). These are convenient 
	// ways to access the contents of the main image list.
	function buildImageViews ( )
	{
		for ( var i = 0; i < images.length; i++ )
		{
			var image = images[i]; // shortcut 
			
			// If this is a featured image, add it to the featured list
			var categories = image.categories.split (",");

			// While we're at it, modify the original image object to add an ID, synthesized from the category name
			// and the image name. Saves us writing this for each image object in the first place.
			// While an image may be in a number of categories, only use the first (root) category for the ID otherwise
			// the ID will get set for each category, which we don't want.
			image.id = categories[0] + "__" + image.image_name;
			// Add the image to the id-indexed array
			imageById[image.id] = image;
			
			// Build the array of images that are featured
			if (jQuery.inArray("featured", categories) != -1)
			{
				featuredThumbs.push ( image );
			}

			// Build the array of images that are for sale
			if (image.sale_state == "forsale")
			{
				forsaleThumbs.push ( image );
			}

			for (var ci = 0; ci < categories.length; ci++)
			{
				// If the category doesn't exist yet, then create it. 
				if ( ! imageCategories[categories[ci]] )
				{
					imageCategories[categories[ci]] = new Array();
				}
			
				// Add the image to the category array.
				imageCategories[categories[ci]][image.id] = image;
			}
		}
	}


	// Stuffs a container full of thumbnails 
	// Go through the entire image array and for each image
	// - find 
	function loadAccordions ( container )
	{
		for (key in imageCategories)
		{
			load_accordion (key, imageCategories[key]);
		}
	
		// Listen for clicks on the tabs within all the accordions
		$('.accordion_pane_tabs').tabs( { select: accordionTabSelect } );

	}
	
	// Loads an accordion full of images for one category. This will result in one or more tabs
	// within the accordion. Each tab will contain as many image thumbs that can fit within a 
	// particular height.
	function load_accordion (category, image_set)
	{
		var container_name = '#' + category + '_nav';
		var max_h = 400; // TODO -- use dynamic height of id thumb_nav_pane
		var curr_h = 0;
		var html = '<div id="' + category + '_tabs" class="minor_tabs accordion_pane_tabs"><ul>';
		var num_tabs = 0;
		var thumb_extra = 10; // Sum of any padding, margin etc around thumb.
		
		// build the tab unordered list first
		var i = 0;
		for (var key in image_set)
		{
			var image = image_set[key]; // shortcut
			
			if ( i == 0 || curr_h + image.thumb_h  + thumb_extra> max_h )
			{
				num_tabs++;
				html = html + '<li><a href="#' + category + '_' + num_tabs + '">' + num_tabs + '</a></li>';
				curr_h = 0;
			}
			curr_h += image.thumb_h + thumb_extra;
			i++;
		}
		
		html = html + '</ul>';

		// The tabs are created. Now we create and fill in the corresponding divs
		// Split the images in this set over a set of tabs within the relevant accordion pane.
		// The number of images in the page is determined by the total height of them (plus padding etc).
		// The images are arranged in each pane as a single column, one image wide.
		var i = 0, curr_h = 0, num_tabs = 0;
		for (var key in image_set)
		{
			var image = image_set[key]; // shortcut
			
			
			var folder = image.categories.split(",")[0];

			if ( i == 0 || curr_h + image.thumb_h + thumb_extra> max_h ) // first tab, or too many images for the current one
			{
				num_tabs++; 

				if ( num_tabs > 1) // Start of a new div tab (but not the first one, so we have to close the current one
				{
					html = html + '</ul></div><div class="thumb_nav_tab_pane" id="' + category + '_' + num_tabs + '"><ul>';
				}
				else	// The start of the first div tab
				{
					html = html + '<div class="thumb_nav_tab_pane" id="' + category + '_' + num_tabs  + '"><ul>';
				}
				
				curr_h = 0; // reset our current height;
			}

			curr_h += image.thumb_h + thumb_extra;
			
			
			// Build the HTML to render the thumbnail. Note that the image ID is a composite of the image set and the
			// actual image file. This is so that the click handler for the thumb knows which directory the image lives in
			// (the directory = the set name). e.g., and ID of "trees__big_tree.jpg" means the image 
			// file "big_tree.jpg" in the directory "trees"
			html = html + '<li><img id="' + image.id + '" class="nav_thumb" src="images/' + folder + '/' + image.image_name + '_thmb.jpg" alt="' + image.title + '" alt="Painting with title of ' + image.image_name + '"/></li>';
			i++;

			// Add the tab ID to the image -- useful for finding which tab this image is in later.
			image.tab_id = category + '_' + num_tabs;
		}
			
		if (num_tabs > 0)
		{
			html = html + '</ul></div>';
		}
		
		// Find the container to place this HTML and stick it in there
		var container = $(container_name);
		container.html(html);

	}

	// When an accordion TAB is selected (just the tab within the accordion pane)
	function accordionTabSelect ( event, ui )
	{
		// Tell Google analytics about our tab 'page' access
		pageTracker._trackPageview( ui.tab.hash );

		if ( ! clickIsFromMainTabThumb )
		{
			// Place the first image in the tab in the main image area
			// Use a fake event for this
			thumbClickHandler ( { 'target': { 'id': ui.panel.firstChild.firstChild.firstChild.id }} );
		}
	}

	
	// Figure out the dimension style that should be used for a given image. This will be tall or wide.
	function getBigImageDimensionStyle ( container_id, thumb)
	{											
		// get the AR of the container
		var container = $(container_id);
		var c_ar = container.width( )/ container.height();
	
		// get the AR of the just-loaded image thumb
		var dom_image = $('#' + thumb.id);
		
		// Use either the natural or client w/h -- depending on the browser, one or other may not be available at this point.
		var w = dom_image[0].naturalWidth;
		var h = dom_image[0].naturalHeight;
		
		if (w == undefined)
		{
			w = dom_image[0].clientWidth;
			h = dom_image[0].clientHeight;
		}
		
		// IE Hack -- TODO fix this. Guess that the image is tall if we cannot figure out its true AR
		if (w == 0 || h == 0)
		{
			return "fooking_ie";
		}
		
		if ( w/h < c_ar )
			return "big_image_tall";	
		else
			return "big_image_wide";	
	}

		
	function fillMainTabThumbs ( images, heading, target )
	{
		var cols = 1; // Let the browser fill the whole space optimally with images instead of trying to do this
					  // ourselves (means some of the following code can be removed because it is redundant now)
		var html = "<h3>" + heading + "</h3>";

		for ( var i = 0; i < images.length; i++)
		{
			if ( i == 0 || i % cols == 0)
			{
				if ( i != 0) // not the first list
					html += "</ul><ul>";
				else
					html += "<ul>"; // the first list

			}
			var image = images[i];
			var folder = image.categories.split(",")[0];
			
			html += '<li><img id="' + image.id + '" class="main_tab_thumb" src="images/' + folder + '/' + image.image_name + '_thmb.jpg" alt="' + image.title + '" alt="Painting with title of ' + image.image_name + '"/></li>';
		}
		html += "</ul>";
		
		$(target).html ( html );
		$('.main_tab_thumb').jScale({h:'80px'})
		
	}


	// Given an "associative" array, return the first element of it.
	function getFirstAAElement(data) 
	{
	  for (var prop in data)
    	return prop;
	}

	