(function () {
	
	document.body.className += ' js';

	var strzalka		= document.createElement('img');
		strzalka.src	= 'assets/go-next.png';
		strzalka.id		= 'arr';

	var tocDiv = document.getElementById('toc__inside'),
		tocHeight = tocDiv.clientHeight || tocDiv.offsetHeight;

		
	if (tocHeight + 65 > document.documentElement.clientHeight) {
		document.body.className += ' small';
		tocHeight = tocDiv.clientHeight || tocDiv.offsetHeight;	
	}	
	
	
	var lastTop = null;
	
	tocDiv.appendChild(strzalka);

	function getPosY(e) {
		var top = 0;
		while (e) {
			top += parseInt(e.offsetTop) || 0;
			e = e.offsetParent;
		}
		return top;
	}
	
	var iAmHere;
	setInterval(function () { 
		var c = 0,
			as = tocDiv.getElementsByTagName('a'),
			top = parseInt(window.pageYOffset || window.scrollY || document.documentElement.scrollTop) || 0;
		if (top != lastTop) {
			for (var a, i = 0; a = as[i]; i++) {
				var e, hash = a.href.substr(a.href.indexOf('#') +1);
				if (e = document.getElementById(hash)) {
					if ((getPosY(e) <= top+100)) {
						c = i;
					}
				}
			}
			if (iAmHere) iAmHere.id = ''; (iAmHere = as[c]).id = 'here';
			strzalka.style.top = 0 + tocHeight / as.length * c + 'px';
		}
		lastTop = top;

	}, 400);
	
	
	
	// select!
	window.location.href.replace(/#\/html\/body\/(.+)/, function(all, mark) {
		mark = mark.split('/');
		var find, e = document.body; 
		while (find = mark.shift()) {
			var m = find.match(/(\w+)(\[(\d+)\])?/),
				tagName = m[1], index = parseInt(m[3]) || 1,
				matchedTags = 0;
			for (var ct, i = 0; ct = e.childNodes[i]; i++) {
				if (ct && ct.tagName) if (ct.tagName.toLowerCase() == tagName) matchedTags++;
				if (matchedTags == index) {
					e = ct;
					break;
				}
			}
			if (matchedTags != index) return false;

		}
		e.style.backgroundColor = 'yellow';
		
		var top = -99;
		while (e) {
			top += parseInt(e.offsetTop) || 0;
			e = e.offsetParent;
		}
		window.scrollTo(0, top);
	});
	
	// ondblclick = selection
})();