$(document).ready(function() {
	// prepare elements
	setPieceIds();
	setPieceClicks();
	
	// start workflow
	selectPiece(getLocation());
});

function setPieceIds()
{
	$('#subnav li a').each(function(i) {
		$(this).attr('href', $(this).attr('href').replace(/^\/portfolio\//i, '/portfolio#'));
		$(this).attr('id', parseHrefForId($(this).attr('href') + '_link'));
	});
}

function setPieceClicks()
{
	var id;
	
	$('#subnav li a').click(function(e) {
		id = $(this).attr('id').replace(/_link/i, '');
		selectPiece(id);
	});
}

function selectPiece(id)
{
	if (id == null || $('#subnav li a#' + id + '_link').length == 0) {
		id = $('#subnav li a:first').attr('id');
	}
	
	id = id.replace(/_link/i, '');
	
	highlightPiece(id);
	selectPanel(id);
}

function highlightPiece(id)
{
	$('#subnav li a').each(function(i) {
		if ($(this).attr('id') == id + '_link') {
			$(this).parent().addClass('here');
		} else {
			$(this).parent().removeClass('here');
		}
	});
}

function parseHrefForId(href)
{
	return href.replace(/.*?#/i, '');
}

function selectPanel(id)
{
	$('#panel').load('/content/panels/' + id + '.inc');
}

function getLocation()
{
	var loc;
	
	if (window.location.hash) {
		loc = window.location.hash.replace(/#/i, '');
		if (loc.length == 0 || $('#subnav li a#' + loc + '_link').length == 0) {
			return null;
		}
		
		return loc;
	} else {
		return null;
	}
}