var COLLECTION	= 0;
var URL			= 1;
var SECTION		= 2;
var DESCRIPTION	= 3;

var SYNCH_COLLECTIONS	= 0;
var SYNCH_BOTH 			= 1;
var SYNCH_SECTIONS 		= 2;

var baseImagePath = "images/";

var displayedPicture;
var collections;
var sections;
var useDescriptions;
var description;
var desc;

var currentImgIdx = -1;
var currentCollection = -1;
var currentSection = "";

function synchCollections() {
	for (var i = 0; i < collections.options.length; i++) {
		if (collections.options[i].text.substring(collections.options[i].text.length-1) == currentCollection) {
			collections.selectedIndex = i;
			collections.options[i].selected = true;
			break;
		}
	}
}

function synchSections() {
	for (var i = 0; i < sections.options.length; i++) {
		if (sections.options[i].text == currentSection) {
			sections.selectedIndex = i;
			sections.options[i].selected = true;
			break;
		}
	}
}

function synchronize( which ) {

	if (currentImgIdx == -1)
		return;
		
	if (which <= SYNCH_BOTH)
		synchCollections();

	if (which >= SYNCH_BOTH)
		synchSections();
	
}

function setImage( idx, synch ) {

	displayedPicture.src = baseImagePath + pictures[idx][URL];
	currentImgIdx = idx;

	setDescription();

	currentCollection = pictures[idx][COLLECTION]; // Integer
	currentSection = pictures[idx][SECTION]; // String

	if (synch != -1)
		synchronize( synch );

}

function setDescription() {
	description.innerHTML = pictures[currentImgIdx][DESCRIPTION];
}

function prev() {
	if (currentImgIdx > 0) {
		setImage( currentImgIdx - 1, SYNCH_BOTH );
	}
}

function next() {
	if (currentImgIdx < pictures.length) {
		setImage( currentImgIdx + 1, SYNCH_BOTH );
	}
}

function setCollection( evnt ) {
	setImage( parseInt( collections.options[collections.selectedIndex].value ), SYNCH_SECTIONS );
}

function setSection( evnt ) {
	setImage( parseInt( sections.options[sections.selectedIndex].value ), SYNCH_COLLECTIONS );
}

function setup() {

	displayedPicture = document.getElementById("displayedPicture");
	collections = document.getElementById("collections");
	sections = document.getElementById("sections");
	useDescriptions = document.getElementById("useDescriptions");
	description = document.getElementById("description");
	desc = document.getElementById("desc");

	setImage( 0 );

	var lastCollection = 0;
	var lastSection = "";

	for (var i=0; i < pictures.length; i++) {
		var collection = pictures[i][COLLECTION];
		if (lastCollection < collection) {
			collections.options[collections.options.length] = new Option( "Collection "+collection, i );
			lastCollection = collection;
		}
		var section = pictures[i][SECTION];
		if (lastSection != section) {
			sections.options[sections.options.length] = new Option( section, i );
			lastSection = section;
		}
	}
}
