function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

Event.observe(window, 'load', function() {
	expanded_el_array = new Array();
	expandable_links = $$('.parent');	
	expandable_links.each(function(s,i){
		s.observe('click', navitemClick);
	});
	
	//check for currentCategory being enabled, if so highlight the category.
	if(typeof(currentCategory) !== 'undefined'){findCategory();}
});

function navitemClick(event)
{
	var el = Event.element(event);
	if(foldPreviousList(el)){
		expandList(el);
	}
	Event.stop(event);
}

function findCategory()
{
	categoryAnchor = $$('.block-layered-nav a[href="'+currentCategory+'"]')[0];
	categoryAnchor.toggleClassName("currently");
	if( categoryAnchor.up().up().hasClassName('level1') )
	{
		expandList(categoryAnchor.up().up().previous());
	} else if( categoryAnchor.up().hasClassName('level2') )
	{
		expandList(categoryAnchor.up().up().previous());
		expandList(categoryAnchor.up().up().up().up().previous());
	}
	
}

function foldPreviousList(new_aparent)
{	
	level_count = expanded_el_array.length-1;
	
	for(var i=level_count; i >= 0; i--)
	{
		//console.log("checking: ["+i+"]", expanded_el_array[i]);
		if (new_aparent.descendantOf(expanded_el_array[i].next()) == false && new_aparent !== expanded_el_array[i] ) {
			compressList(expanded_el_array[i]);
			//console.log("expanded_el_array popped:",expanded_el_array[i]);
			expanded_el_array.pop();
		} else if ( new_aparent == expanded_el_array[i] ) {
			//close currently open list and its children
			//console.log("found same element");
			if(	new_aparent.next().getStyle("display") == "none" )
			{
				expandList(new_aparent);
			} else {
				compressList(new_aparent);
			}
			
			return false;
			//expanded_el_array.shift();
		}
	}
	return true;
	
}

function expandList(el)
{
	el.next().setStyle({
				display: 'block'
			});
	
	expanded_el_array.unshift(el);
	//console.log("expanded_el_array unshift:",expanded_el_array);
}

function compressList(el)
{
	el.next().hide();
}
/*

function mouseOver(event) {
  var element = Event.element(event);
  product_button.each(function(s,i){
  	s.removeClassName("num_on");
  });
  element.addClassName("num_on");
  j = parseInt(element.innerHTML)-1;
  product_images.each(function(s,i){
  	if(i == j){
		s.setStyle({
			display: 'block'
		});
	} else {
		s.hide();
	}
  });
}

*/
