(function (){
	function init()
	{
		var menus = $$('.navigation li ul, .subNav li ul, .menu li ul');
		
		menus.forEach(function (item,index) {
			var anchor = item.getPrevious();  // get the previous element, which is always an anchor in our menu structure
			if(!anchor)
			{
				return;
			}
			var li     = null;                // variable to contain the new anchor if required
			
			//console.log($(item));
			// find all the anchors in the menu tree that follow an li with same href as the top level anchor
			anchors = $(item).getElements('li,a').filter(function(item,index)
			{
				if(item.getProperty('href') === anchor.getProperty('href')) 
					return item;
			});
			
			// if we don't have an anchors in our list, create and insert one
			if(anchors.length==0) 
			{
				li = new Element('li').injectBefore(item.getFirst()).adopt(anchor.clone());
			}
			
			// if the parent li isn't active
			if( ! anchor.getParent().hasClass('active'))
			{
				anchor.addClass('submenu');
			}
			else
			{
				anchor.addClass('submenu_open');
			}
			anchor.addEvent('click',toggleMenus.bind(item));
		});
	}
	
	function toggleMenus(event)
	{
		event = new Event(event);
		event.stop();
		var target = event.target.getNext();
		
		var open = target.getStyle('display')==='block';
		
		target.setStyle('display',(open ? 'none' : 'block'));
		
		event.target.toggleClass('submenu_open');
		event.target.toggleClass('submenu');
	}
	
	window.addEvent('domready',init);
})();