$(document).ready(function() {
	
	var menubg=["#9dcbb6","#adbe90","#7fb5ab","#8aa38e","#8fb5ab","#98b5a6","#adb393"]; 
	var menuhoverbg=["#5ba985","#779346","#2a8473","#3c6643","#458373","#53846b","#77814b"];
	
	var menus = $('#menu > li');
	
	menus.each(function(index){
		this.style.backgroundColor = menubg[index];
		
		if ($(this).hasClass('current_page_item') || $(this).hasClass('current_page_parent'))
		{
			this.style.backgroundColor = menuhoverbg[index];
		}
		
		$(this).hover(
			function(){
				this.style.backgroundColor = menuhoverbg[index];
				
				$('ul.children').hide();
				$('ul.children', this).show();
				setPosition(this);
			},
			function(){
				if (!$(this).hasClass('current_page_item') && !$(this).hasClass('current_page_parent'))
				{
					this.style.backgroundColor = menubg[index];
				}
				
				if ($('li.current_page_parent').length > 0)
				{
					$('li.current_page_parent').each(function(index){
						$('ul.children', this).show();
						setPosition(this);
					})	
				}
				else if ($('li.current_page_item').length > 0)
				{
					$('li.current_page_item').each(function(index){
						$('ul.children', this).show();
						setPosition(this);	
					})
				}
			}
		);
		
		
	});
	
//	menus[0].style.backgroundColor = '#9dcbb6';
//	menus[1].style.backgroundColor = '#779346';
//	menus[2].style.backgroundColor = '#2a8473';
//	menus[3].style.backgroundColor = '#3c6643';
//	menus[4].style.backgroundColor = '#458373';
//	menus[5].style.backgroundColor = '#53846b';
//	menus[6].style.backgroundColor = '#77814b';
//	
//	$('#menu > li').hover(function(index){
//		var hoverel = $(this);
//		
//	});
	
	if ($('li.current_page_parent').length > 0)
	{
		$('li.current_page_parent').each(function(index){
			if ($(this).is(":visible"))
			{
				setPosition(this);
			}	
		})	
	}
	else if ($('li.current_page_item').length > 0)
	{
		$('li.current_page_item').each(function(index){
			if ($(this).is(":visible"))
			{
				setPosition(this);
			}	
		})
	}
});

function setPosition(el)
{
	var position = $(el).position();
	var ulchildren  = $('ul.children', el);
	var width = 0;
	
	ulchildrenli = $('li', ulchildren[0]);
	
	for (i = 0; i < ulchildrenli.length; i++)
	{
		width = width + $(ulchildrenli[i]).width() + 5;
	}
	
	ulchildren.css({"width" : width + "px"});
	
	if (847 - position.left > ulchildren.width())
	{
		ulchildren.css({"left" : (position.left - 10) + "px"});
	}
	else
	{
		ulchildren.css({"left" : (847 - width) + "px"});
	}
}

