var portfolio_links = [
	"web.html",
	"print.html",
	"classroom.html",
	"portfolio.html"
];

function setupPortfolioLinks() {
	$('#portfolio_content a').each(function(i) {
		var link = this;
		if(portfolio_links.some(function(item,index){return this.indexOf(item) != -1; },link.href)) {
			file_name = link.href.substring(link.href.lastIndexOf('/')+1);
			link.href = "javascript:loadPage(\""+file_name+"\")";
		}
	});
}

function formatAccordionHeaders(){
	var links = $('h3.link');
	
	var link_styles = [
		"one",
		"two",
		"three"
	];
	var link_i = 0;
	links.each(function(i){
		if (link_i == link_styles.length) {
			link_i=0;
		}
		$(this).addClass(link_styles[link_i]);
		link_i += 1;
	});
	
	
}

function checkHash() {
	var accordion_element_id = "content";
	var found = 0;
	
	// If there's no hash, we want to open the first accordion,
	// otherwise, we search links until on matches the hash:
	if (window.location.hash != "") {
	
		$('h3.link a').each(function(i){
			if (window.location.hash == this.hash) {
				found = i;
			} 
		});
		
	}

	$("#"+accordion_element_id).accordion({
		autoHeight: false,
		active: found,
		changestart: function(event,ui) {
			// The jQuery version of accordion triggers the link from the h3 element, 
			// rather than the link inside the h3. As such, we have to find it and
			// set window.location's hash to the new content div, so that the browsing
			// isn't broken. I think there's probably an easier way to do this.
			window.location.hash = ui.newHeader.children('a')[0].hash; 
		}
	});
}

function addOverlay(page) {
	if($('overlay')) {
		removeOverlay();
	}

	//var size = $(page).getSize();
	
	var position = $(page).offset();

	$(document.body).append("<div id=\"overlay\"></div>");

	var overlay = $('#overlay');
	overlay.css('width',$(page).width() + "px");
	overlay.css('height',$(page).height() + "px");
	overlay.css(position);
	overlay.css('z-index', 1);
	overlay.css('position', 'absolute');
	overlay.css('background-color', '#CCC');
	overlay.css('opacity', 0.7);
}

function removeOverlay() {
	if ($('#overlay')) {
		$('#overlay').remove();
	}
}

function loadPage(newPage) {
	
	addOverlay("#portfolio");
	
	$.get(newPage, function(data) {
		// Grab the HTML we want to load via AJAX and load it into the portfolio div:
		$("#portfolio_content").html(data);
		// Make sure the internal links still fire correctly.
		setupPortfolioLinks();
		removeOverlay();
	});
}

$(document).ready(function() {
	setupPortfolioLinks();
	formatAccordionHeaders();
	checkHash();
});

