var works_dir;		// the directory in which the current works collection is stored
var num_thumbnails; // keep a count of the total number of thumbnails on the page for next/prev navigation
//var current_image;	// the index of the image in the sequence displayed at load time
var selected_category;

// An array of information about all the thumbnails on the page.
// This is the start of a better way to handle next and prev navigation.
var thumbnails = new Array();



function init() {
	initIconNav();
}

function initIconNav() {

	var elements = getElementsByClass("category_icon");
	var icons = new Array();
	for (i=0; i < elements.length; i++) {

		// Preloading mouseover graphics
    	basename = get_basename_from_href(elements[i].href); 
    	basename = basename.replace(/ /g, '_');
    	icons[i] = new Image();
    	icons[i].src = "/images/icon_" + basename +"-over.png";	
		initIcon(elements[i]);
	}
}

function initIcon(icon) {
	/*
	var bgFade = new Fx.Style(slide, 'background-color');
	
	addEvent(slide, "mouseover", function(e) {
		// is there a way to retain the references for each bg fade?
		highlight_slide(e, bgFade);
	});
	
	addEvent(slide, "mouseout", function(e) {	
		var clBgFade = bgFade;
		dim_slide(e, bgFade);
	});
	*/
	addEvent(icon, "mouseover", toggleIcon);
	addEvent(icon, "mouseout", toggleIcon);
	addEvent(icon, "click", showCategoryThumbs);	
}

function toggleIcon(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	
	var cat = tg;
	while(cat.className != "category_icon") {
		cat = cat.parentNode;
	}	

	var catName = get_basename_from_href(cat.href);
	catName = catName.replace(/ /g, '_');
	
	//console.log(catName);
	//	console.log("catName: "+catName);


	if(!selected_category) selected_category = "featured";
	if(selected_category == catName) return;
	
	// If the category icon has been clicked, leave it highlighted
	if(e.type == "click") {
		// unhighlight the currently highlighted link
		var selected = document.getElementById("icon_selected");
		selected.setAttribute('id', '');

		//unhighlight selected
		var selected_icon = selected.firstChild;
		//console.log(selected_icon.nodeName);
		
		while(selected_icon.nodeName != "IMG") {
			selected_icon = selected_icon.nextSibling;
		}
		selected_icon.src = selected_icon.src.replace('-over.png', '.png');
		cat.setAttribute('id', 'icon_selected');		
		return;
	}
	
	// change the src to be the highlighted version
	if(tg.src.search('-over') ==  -1) {
		// append the over
		//highlightIcon(tg.id);
		tg.src = tg.src.replace('.png', '-over.png');
		
		// hide category label text for selected item
		// show category label text
		var label_selected = document.getElementById("label_"+selected_category);
		label_selected.style.display = "none";
		
		label_selected = document.getElementById("label_"+catName);
		label_selected.style.display = "block";		
		
	} else {
		// prune the -over and replace
		tg.src = tg.src.replace('-over.png', '.png');
		
		var label_selected = document.getElementById("label_"+selected_category);
		label_selected.style.display = "block";
		
		label_selected = document.getElementById("label_"+catName);
		label_selected.style.display = "none";			
		// hide category label text
		// show category label text for selected item
		
		//dimIcon(tg.id);
	}
	
	// lock highlighted state
	// If the icon corresponds with the category thumbnails currently displayed
	// it shouldn't respond to mouseovers or clicks
	
	// When a new category is selected, the old category icon needs to be unselected.
	
	// So mark the currently selected category
	// and if the selected category corresponds to the icon the spawned the event
	
}
/*
function dimIcon(id) {
	var icon = document.getElementById(id); 
	icon.src = icon.src.replace('.png', '-over.png');
}

function highlightIcon(id) {
	var icon = document.getElementById(id); 
	icon.src = icon.src.replace('-over.png', '.png');
}
*/
function showCategoryThumbs(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	toggleIcon(e);

	// make sure we're looking at the enclosing anchor
	while(tg.className != "category_icon") {
		tg = tg.parentNode;
	}
	
	
	
	var catName =  get_basename_from_href(tg.href);
	catName = catName.replace(/ /g, '_');
	
	var cat = document.getElementById(catName);

	if(!selected_category) selected_category = 'featured';
	var hideCat = document.getElementById(selected_category);
	// This is where we could add some small effects
	// Hide the currently displayed category
	hideCat.style.display = "none";
	selected_category = catName;
	// - how do we know which one is selected?
	
	// Show the new selected category
	cat.style.display = "block";

	if (e && e.preventDefault) e.preventDefault(); // DOM style
	return false; // IE style	
}

function initInfoBoxes(e) {
	var elements = getElementsByClass("thumbnail");
	for (i=0; i < elements.length; i++) {
		elements[i].onmouseover = showInfoBox;
		elements[i].onmouseout = hideInfoBox;
	}
}

function initImages(e) {
	var large_image_link = document.getElementById("large_image_link");
	if(large_image_link) large_image_link.onclick = showLargeImage;

	var nav_large_image_link = document.getElementById("nav_large_image_link");
	if(nav_large_image_link) nav_large_image_link.onclick = showLargeImage;
	
	var image_nav_next = document.getElementById("image_nav_next");
	if(image_nav_next) image_nav_next.onclick = showNextImage;

	var image_nav_prev = document.getElementById("image_nav_prev");
	if(image_nav_prev) image_nav_prev.onclick = showPrevImage;
	
	var elements = getElementsByClass("thumbnail");
	for (i=0; i < elements.length; i++) {
		elements[i].onclick = showImage;

    	pathname = get_pathname_from_href(elements[i].href); 
    	thumbnails[i] = new Image();
    	thumbnails[i].img_src = unescape(pathname) + "P_" + elements[i].id +".jpg";
    	thumbnails[i].img_id = elements[i].id;		
	}
	num_thumbnails = i+1;
	
	preloadAdjacentImages(1); //this should be the current image rather than 1
}

function preloadAdjacentImages(image_id) {
	var window_length = 6;
	var forward_look = 1;
	image_id = parseInt(image_id, 10); //image id may be padded -- either 1 or 01

	for(i = 0; i < window_length; i++) {
		// calculate the index of the image in the sequence array so that it loops
		var j = (image_id + forward_look - i + num_thumbnails) % num_thumbnails;
		if(thumbnails[j] != null) {
			thumbnails[j].src = thumbnails[j].img_src;
		}
	}

}

function get_basename_from_href(href) {
	var length = (href.charAt(href.length - 1) == '/') ? href.length - 1: href.length;
	
	var lastSlash = href.lastIndexOf('/', length - 1);
	var basename = href.substring(lastSlash + 1, length);
	
	return unescape(basename);
}

function get_pathname_from_href(href) {

	/* IE 6 PC doesn't include the leading slash in the pathname so we can't use 
	 * var pathname = tg.pathname;
	 * Instead, parse the pathname out of the full HREF by looking for the first 
	 * slash after the protocol */
	 
	if(href.charAt(0) == '/') {
		var pathname = href; /* sometimes IE 6 will prefix the href with about:blank instead of the hostname, and sometimes nothing */
							 /* IE 7 prepends about: */
	} else {
		var pathname = (href.substring(href.indexOf('/'), href.length))
	}
	//pathname = pathname.substring(0, pathname.length - 3); // This is for if the image number is specified as an anchor after a hash mark
	pathname = pathname.substring(0, pathname.length - 2);

	return unescape(pathname); // we need to unescape the pathname because it's been double encoded to get past mod_rewrite
}

function showImage(e) {
//return false;
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	while(tg.className.search('thumbnail') == -1) {
		tg = tg.parentNode;
	}

	highlightThumbnail(tg.id);


	return false;
}

function highlightThumbnail(tg_id) {

	var tg = document.getElementById(tg_id);
	
	// REPLACE PREVIOUSLY ACTIVE DIV WITH LINK
	// this seems inefficent but it works
	var elements = getElementsByClass("thumbnail-active");
	//for (i=0; i < elements.length; i++) {
	var i = 0;
	elem = elements[i]; //alert(elem.nextSibling.className);
	
	// split this: bookcase_01 into bookcase and 01
	var sep = elem.id.lastIndexOf('_');
	var work_name = elem.id.substring(0, sep);
	var img_number = elem.id.substring(sep+1, elem.id.length);

	// create anchor element
	var img_link = document.createElement('a');
	img_link.setAttribute('class', 'thumbnail');
	img_link.setAttribute('id', elem.id);		
	img_link.setAttribute('href', '/'+ works_dir +'/'+ work_name +'/'+ img_number );
	img_link.onclick = showImage;
	
	// replace div element with anchor element
	var img_src = elem.firstChild;
	var img_src_clone = img_src.cloneNode(false);
	img_link.appendChild(img_src_clone);
	var img_parent = elem.parentNode;
	img_parent.replaceChild(img_link, elem);
	img_link.className = 'thumbnail'; // IE 6 doesn't pick up the class styles when it's set with setAttribute 
    //img_link.id = elem.id;

	// REPLACE LINK WITH INACTIVE DIV
	var img_div = document.createElement('div');
	img_div.setAttribute('class', 'thumbnail-active');
	img_div.setAttribute('id', tg.id);
	
	tg_image_number = tg.id.substr(tg.id.lastIndexOf('_')+1, 2);
	//alert(tg_image_number);
	
	img_src = tg.firstChild;
	var img_src_clone = img_src.cloneNode(false);
	img_div.appendChild(img_src_clone);
	var img_parent = tg.parentNode;
	img_parent.replaceChild(img_div, tg);
	img_div.className = 'thumbnail-active'; // IE 6 doesn't pick up the class styles when it's set with setAttribute 
	//img_div.id = tg.id;
	
	//tg.className = "thumbnail-active";
	//changing the class name seems to break any attached events

	// update P_ image on stage
	var img = document.getElementById("image");
	//window.location.hash = "05";
    pathname = get_pathname_from_href(tg.href); 
    
    // Hack workaround for a known bug in Safari where it will incorrectly
    // retain the dimensions of the previous image when swapping in a new one.
    // Programming Javascript for the web makes me want to throw up
    if( navigator.userAgent.indexOf('Safari')!=-1 ) {
    	img.src = '/images/t.gif';
    }
    
    img.src = unescape(pathname) + "P_" + tg.id +".jpg";
	
	// update caption on stage
	var image_description = document.getElementById("image_description");
	var caption = document.getElementById(tg.id + '_caption');
	image_description.innerHTML = caption.innerHTML; // using innerHTML instead of textContent for IE support
	
	// update link to L_ large image
	var large_image_link = document.getElementById("large_image_link");
	var nav_large_image_link = document.getElementById("nav_large_image_link");	
	large_image_link.href = pathname + "L_" + tg.id +".jpg";
	nav_large_image_link.href = large_image_link.href;	
	
	updateImageNav(tg_image_number);

	// Load P_ images for adjacent thumbnails;
	//alert(tg_image_number);

	preloadAdjacentImages(tg_image_number);
}

function updateImageNav(image_number) {
	//alert(image_number);
	var next_link = document.getElementById("image_nav_next");
	var prev_link = document.getElementById("image_nav_prev");
	var base_href = (next_link.href.substr(0, next_link.href.lastIndexOf('/')));
	next_link.href = base_href +"/"+ nextImageNumber(image_number);
	prev_link.href = base_href +"/"+ prevImageNumber(image_number);	
}

function showLargeImage(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	while(tg.id.search('large_image_link') == -1) {
		tg = tg.parentNode;
	}

	var overlay = document.getElementById("overlay");
	var loading = document.getElementById("loading");
	var large = document.getElementById("large");

	href = tg.href;
	var imgname = (href.substring(href.lastIndexOf('/') + 3, href.length)); 	// The image key: everything after /P_
	var pathname = (href.substring(href.substring(href.indexOf('/', 7)), href.lastIndexOf('/')));

	var img = new Image();
	img.src = pathname +'/L_'+ imgname;
	
	//if(img.complete == true) { // if the image has already loaded and is cached, Safari won't fire another onload event.
	

	
	var page_height = getPageHeight();
	
	if(page_height < 1000) page_height = 1000; // ensure that the overlay always cover the area required to display large pictures
	overlay.style.height = page_height + 'px';

	overlay.style.visibility = "visible";
	loading.style.display = "block"
	//overlay.style.width = document.body.scrollWidth + 'px';
	
	if(img.complete == true) { // if the image has already loaded and is cached, Safari won't fire another onload event.
		large.src = img.src;
		loading.style.display = "none";
		large.style.visibility = "visible";			
	} else {
		img.onload = function() {
			if(overlay.style.visibility == "hidden") return; // if the user has hidden the overlay while waiting for the image to load, don't show the image
			large.src = img.src;
			loading.style.display = "none";
			large.style.visibility = "visible";		
		}
	}
	
	return false;
}

function hideLargeImage(e) {
	var overlay = document.getElementById("overlay");
	var large = document.getElementById("large");

	overlay.style.visibility = "hidden";
	large.src = "/images/bg_black_transparent.png";
	large.style.visibility = "hidden";
}

function showNextImage(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	// Fix for Safari, where an event attached to an anchor tag doesn't give that
	// anchor as the event target, instead giving you the text node it contains.
    if (tg.nodeType == 3) {
      tg = tg.parentNode; 
    }
    
	var href = tg.href;

	var image_number = (href.substr(href.lastIndexOf('/') + 1, 2));		// The image number: everything after the last /

	var image_key = (href.substring(href.indexOf('/'+ works_dir +'/') + 10, href.lastIndexOf('/')));
	image_key = unescape(unescape(image_key));
	
	var pathname = (href.substring(href.substring(href.indexOf('/', 4)), href.lastIndexOf('/')));
	
	var base_href = (href.substr(0, href.lastIndexOf('/')));
	
	var elem = document.getElementById(image_key +"_"+ image_number);
	
	highlightThumbnail(elem.id);

	return false;
}

function nextImageNumber(num) {
	// The 10 is to specify that numbers should be parsed as base-10 integers,
	// otherwise parseInt will try to read 08 and 09 as invalid octal numbers and return 0.
	next_image_number = parseInt(num, 10) + 1;
	
	if(next_image_number > num_thumbnails) {
		next_image_number = 1;
		//the prevImageNumber should be set to the number of the last image;
		// we need to store the number of images somewhere in the page so that we know what it is.
	}
	
	if(next_image_number < 10) next_image_number = '0' + next_image_number;
	return next_image_number;
}

function prevImageNumber(num) {
	// The 10 is to specify that numbers should be parsed as base-10 integers,
	// otherwise parseInt will try to read 08 and 09 as invalid octal numbers and return 0.
	prev_image_number = parseInt(num, 10) - 1;
	
	if(prev_image_number == 0) {
		prev_image_number = num_thumbnails;
		//the prevImageNumber should be set to the number of the last image;
		// we need to store the number of images somewhere in the page so that we know what it is.
	}

	if(prev_image_number < 10) prev_image_number = '0' + prev_image_number;
	return prev_image_number;
}


function showPrevImage(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	// Fix for Safari, where an event attached to an anchor tag doesn't give that
	// anchor as the event target, instead giving you the text node it contains.
    if (tg.nodeType == 3) {
      tg = tg.parentNode; 
    }
    
	var href = tg.href;

	var image_number = (href.substr(href.lastIndexOf('/') + 1, 2));		// The image number: everything after the last /

	var image_key = (href.substring(href.indexOf('/'+ works_dir +'/') + 10, href.lastIndexOf('/')));
	image_key = unescape(unescape(image_key));
	
	var pathname = (href.substring(href.substring(href.indexOf('/', 4)), href.lastIndexOf('/')));
	var base_href = (href.substr(0, href.lastIndexOf('/')));

	var elem = document.getElementById(image_key +"_"+ image_number);
	highlightThumbnail(elem.id);
	//tg.href = base_href +"/"+ prevImageNumber(image_number);
	//updateImageNav(image_number);
	
	return false;
}

/* http://www.quirksmode.org/viewport/compatibility.html
 * This is retardedly complex for getting a simple document property.
 */
function getPageHeight() {

	var x, y, xx, yy;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight;
	if (test1 > test2) // all but Explorer Mac
	{
	//	x = document.body.scrollWidth;
		y = document.body.scrollHeight;
	}
	else // Explorer Mac;
		 //would also work in Explorer 6 Strict, Mozilla and Safari
	{
	//	x = document.body.offsetWidth;
		y = document.body.offsetHeight;
	}
	//return document.body.offsetHeight;
	//return document.body.scrollHeight;
	//	y = document.documentElement.clientHeight;
	//return y;

	if (self.innerHeight) // all except Explorer
	{
	//	xx = self.innerWidth;
		yy = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
	//	xx = document.documentElement.clientWidth;
		yy = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
	//	xx = document.body.clientWidth;
		yy = document.body.clientHeight;
	}
	
	if(yy > y) return yy;
	return y;


}



function showInfoBox(e) {
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	while(tg.className.search('thumbnail') == -1) {
//	while(tg.className != "thumbnail") {
		tg = tg.parentNode;
	}
	
	var infoBox = document.getElementById(tg.id + "_info");

	infoBox.style.zIndex = 20;	

	infoBox.style.display = "block";	
	moveInfoBox(e);
	
	
	if(tg.onmousemove == null) addEvent(tg, "mousemove", moveInfoBox);
	
}


function hideInfoBox(e) {

	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;

	while(tg.className.search('thumbnail') == -1) {
//	while(tg.className != "thumbnail") {
		tg = tg.parentNode;
	}
	
	var infoBox = document.getElementById(tg.id + "_info");

	// all this looping seems grossly inefficient
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg && reltg != tg && reltg.nodeName != 'body') {
		reltg = reltg.parentNode;
	}
	if (reltg == tg) return;
	
	infoBox.style.display = "none";
}

function moveInfoBox(e) {

	// If box will appear off of the screen, change the x position.
	
	if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;	

	while(tg.className.search('thumbnail') == -1) {
//	while(tg.className != "thumbnail") {
		tg = tg.parentNode;
	}
	
	var infoBox = document.getElementById(tg.id + "_info");
	dragObj = infoBox;

	var x, y;

	if (!e) var e = window.event;
	if (e.pageX || e.pageY)
	{
		x = e.pageX;
		y = e.pageY;
	}
	// For IE 6 and IE 7
	else if (e.clientX || e.clientY)
	{
		//x = e.clientX + document.body.scrollLeft;
		//y = e.clientY + document.body.scrollTop;
		// When using strict doctypes in IE 6 and IE 7, refer to documentElement rather than body
		x = e.clientX + document.documentElement.scrollLeft;
		y = e.clientY + document.documentElement.scrollTop;
	
	}

	// if the infoBox will appear off the page, scoot it up.
	x -= dragObj.offsetWidth + 20;
	y -= 80;
	
 	dragObj.style.top = y + "px";
	dragObj.style.left = x + "px"; 
	
}

function getElementsByClass(searchClass, node, tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// function to assign functions to particular events, used
// here to call a function when the window loads without sticking
// the onload="foo" in the page's <body> tag.
function addEvent(obj, evType, fn) {

	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
	
		// This single line seems to adress IE 5 Mac's otherwise complete inability to use these event listener rollovers
		if(evType == 'load') obj.onload = fn;
		
		return false;
	}
}

addEvent(window, "load", init);
