function scrollToWithOffset(element, extraOffset) {
  element = $(element);
  var pos = Element.cumulativeOffset(element);
  window.scrollTo(pos.left, pos.top - extraOffset);
  return element;
}


Event.observe(document, "click", function(evt) {
	var link = Event.element(evt);
	if (!link) return;
	
	if (link.hasClassName("scrollto")) {
		var destId = link.id.replace(/^scrollto\-/, '');
		console.debug("Will scroll to " + destId);
		var destElement = $(destId);
		
		// If the destination element is not available
		// we are not on the index page so redirect to there
		if(!destElement) {
			var loc = '/#' + destId;
			if(window.location != destId) {
				window.location = '/#'  + destId;
			} else {
				// We are on that page already but there is no element there
				console.debug("There is no such work to scroll to " + 
					"and we are already on the index page. Something is wrong.");
				Event.stop(evt);
				return;
			}
		}
		
		Event.stop(evt);
		
		// Scroll to the element
		scrollToWithOffset(destElement, 80);
	}
});



function loadWorkImage(link) {
	// Reset the magic src
	// ensure the image is unloaded
	// read on fingertips blog about this
	var imgElem = link.up("div").getElementsByTagName("img")[0];
	console.debug(imgElem);
	imgElem.src = null;
	imgElem.src = link.href;
	
	// Make this link inactive
	// Make other links active
	var links = link.up("div").getElementsByTagName("a");
	$A(links).each(function(aLink) {
		if (link != aLink) aLink.removeClassName("cur");
	})
	link.addClassName("cur");
}

// Image switching
Event.observe(document, "click", function(evt) {
	var link = Event.element(evt);
	if (!link) return;
	if (link.hasClassName("imgPull")) {
		loadWorkImage(link);
		Event.stop(evt);
	}
});

// Image switching - mark first link as current
Event.observe(window, "load", function(evt) {
	var inc = 10;
	$$("a.imgPull").each(function(e){
		if (e.innerHTML == "1") e.addClassName("cur");
		var imaj = new Image;
		imaj.src = e.href; // Preload.
	});
	
	if (window.location.hash.indexOf("Work") != -1) {
		Event.stop(evt);
		var withoutLeadingHashmark = window.location.hash.substring(1);
		scrollToWithOffset($(withoutLeadingHashmark), 80);
		return false;
	}
});


