var hash = location.hash;
var entries = []
var current = 0

function ScrollToElement(theElement){

  var selectedPosX = 0;
  var selectedPosY = -10;
              
  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
                        		      
 window.scrollTo(selectedPosX,selectedPosY);

}

function nextItem() {
	var temp = current
	current++
	while (entries[current] && !entries[current].visible()) {
		current++ }
	if (entries[current] != null) { ScrollToElement(entries[current]) }
	else { current = temp; console.log(entries[current]) }
}

function prevItem() {
	var temp = current
	current--
	while (entries[current] && !entries[current].visible()) {
		current-- }
	if (entries[current] != null) ScrollToElement(entries[current])
	else current = temp
}

function linkID(catname) {
	return catname + '-link'
}

document.observe('dom:loaded', function() {
	$(linkID(location.hash.split('#')[1])) ? clik($(linkID(location.hash.split('#')[1]))) : $$('.extra').each(function(entry) { entry.hide() });
	entries = $$('.entry')
});

setInterval(function() {
    if (location.hash != hash) {
		if (!location.hash && $(linkID('all'))) clik($(linkID('all')))
		else if ($(linkID(location.hash.split('#')[1]))) clik($(linkID(location.hash.split('#')[1])))
		hash = location.hash;
    }
}, 300);

function clik(node) {
	location.hash = '#' + node.innerHTML;
	hash = location.hash;
	
	
	$$('.entry').each(function(entry) {
		if (node.innerHTML == "all") {
			if (!entry.hasClassName('extra')) entry.show()
			else entry.hide()
		}
		else if (entry.hasClassName(node.innerHTML)) entry.show()
		else entry.hide()
	}.bind(this));
	
	window.scrollTo(0,0);
	current = 0
	
	var selected = document.getElementById('selected')
	selected.setAttribute('id', linkID(selected.innerHTML))
	selected.setAttribute('onclick', 'clik(this); return false;')
	
	node.setAttribute('id', 'selected');
	node.setAttribute('onclick', 'return false;');	
}