// JavaScript Document - http://articles.sitepoint.com/article/scroll-smoothly-javascript/

var delay = 1000; // set the delay before scrolling in milliseconds
	
function smoothScroll(e) {
	anchor = 'a'; // set the target id
	
	// Now loop all img tags until we find one with that name
	var allImages = document.getElementsByTagName('img');
	var destinationImage = null;
	for (var i=0;i<allImages.length;i++) {
		var img = allImages[i];
		if (img.id && (img.id == anchor)) {
			destinationImage = img;
			break;
		}
	}
	
	// If we didn't find a destination, give up and let the browser do its thing  
	if (!destinationImage) return true;
	
	// Find the destination's position
	var destx = destinationImage.offsetLeft;
	var desty = destinationImage.offsetTop; 
	var thisNode = destinationImage;
	while( thisNode.offsetParent && (thisNode.offsetParent != document.body) ) {
		thisNode = thisNode.offsetParent;
		destx += thisNode.offsetLeft;
		desty += thisNode.offsetTop; 
	}
	
	// Stop any current scrolling
	clearInterval(ss_INTERVAL);
	
	cypos = ss_getCurrentYPos();
	
	ss_stepsize = parseInt((desty-cypos)/ss_STEPS);
	ss_INTERVAL = setInterval('ss_scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',20);
	
	// And stop the actual click happening
	if (window.event) {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	if (e && e.preventDefault && e.stopPropagation) {
		e.preventDefault();
		e.stopPropagation();
	}
}

function ss_scrollWindow(scramount,dest,anchor) {
	wascypos = ss_getCurrentYPos();
	isAbove = (wascypos < dest);
	window.scrollTo(0,wascypos + scramount);
	iscypos = ss_getCurrentYPos();
	isAboveNow = (iscypos < dest);
	if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
		// if we've just scrolled past the destination, or we haven't moved from the last scroll (i.e., we're at the bottom of the page) then scroll exactly to the image
		window.scrollTo(0,dest);
		// cancel the repeating timer
		clearInterval(ss_INTERVAL);
	}
}

function ss_getCurrentYPos() {
	if (document.body && document.body.scrollTop)
		return document.body.scrollTop;
	if (document.documentElement && document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	if (window.pageYOffset)
		return window.pageYOffset;
	return 0;
}

function addEvent(elm, evType, fn, useCapture) {
// cross-browser event handling for IE5+,  NS6 and Mozilla. By Scott Andrew  
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	}
}

function delayer() {
	window.setTimeout(smoothScroll,delay);
}

var ss_INTERVAL;
var ss_STEPS = 28;

addEvent(window,"load",delayer);
