var portfolio;
var currGallery;

function setupGalleries() {
	var galnav = "";
	var i = 0;
	$.each(portfolio.gallery, function() {
		galnav += "<a id='gal_" + i + "' href='#" + i + "' onclick='showGallery(" + i + ");'>" + this.name + "</a>";
		galnav += "<div id='galnav_" + i + "' class='imgNav'></div>"
		i++;
	});
	$('#galleryNav').html(galnav);
	showGallery(0);
}

function showGallery(i) {
	for (var j = 0; j < portfolio.gallery.length; j++) {
		if (i == j) $('#gal_' + j).addClass("selected");
		else $('#gal_' + j).removeClass("selected");
		$('#galnav_' + j).html('');
	}
	
	currGallery = i;
	var images = portfolio.gallery[i].image;
	var s = "";
	var j = 0;
	$.each(images, function() {
		s += buildImageThumb(j, $(this));
		j++;
	});
	
	// temporary workaround to show installation video link
	if (portfolio.gallery[i].name == "2011") {
		s += "<p><a href='http://www.youtube.com/watch?v=j0OazjE5f0k'>Video documentation, Billboard Installation, Tucson, Arizona, 2011</a></p>";
	}
	
	$('#gallery').html(s);
	$('a').click(function() { this.blur() });
}

function buildImageThumb(i, image) {
	var s = "";
	s += "<a href='#" + currGallery + "-" + i + "' onclick='showPiece(" + i + ");'><img class='portThumb transOn' onmouseover='$(this).removeClass(\"transOn\")' onmouseout='$(this).addClass(\"transOn\")' src='portfolio/portfolio_images/100/" + image.attr("filename") + "' title='" + image.attr("name") + "' /></a>";
	return s;
}

function showPiece(i) {
	var image = portfolio.gallery[currGallery].image[i];
	var s = "<div id='piece'>";
	s += "<a href='#" + currGallery + "' onclick='showGallery(" + currGallery + ");' title='Click to go back to the gallery'>";
	s += "<img src='portfolio/portfolio_images/web/" + image.filename + "' />";
	s += "</a>";
	s += "<div id='pieceName'>" + image.name + "</div>";
	s += "<div id='pieceDesc'>" + image.desc + "</div>";
	
	var length = portfolio.gallery[currGallery].image.length
	var next = i < (length - 1) ? i - (-1) : null;
	var prev = i > 0 ? i - 1 : null;
	var t = "";
	if (prev != null) t += "<a href='#" + currGallery + '-' + prev + "' onclick='showPiece(" + prev + ");'>previous image</a>";
	if (next != null) t += "<a href='#" + currGallery + '-' + next + "' onclick='showPiece(" + next + ");'>next image</a>";
	t += "<div style='height:5px;'></div>";
	$('#galnav_' + currGallery).html(t);
	
	s += "</div>";
	$('#gallery').html(s);
}

$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "portfolio/portfolio_layout.xml",
		dataType: "xml",
		success: function(xml, status, req) {
			portfolio = $.xml2json(xml);
			setupGalleries();
			
			var hash = window.location.hash.substring(1);
			if (hash != '') {
				var split = hash.split("-");
				if (split.length == 1) {
					currGallery = split[0];
					showGallery(split[0]);
				} 
				else if (split.length == 2) {
					currGallery = split[0];
					showPiece(split[1]);
				}
			}
		},
		error: function(req, status, err) {
			alert(status);
			alert(err);
		}
	});
});


