var need_hide = true;
var need_hide_l2 = true;
var now_pop_opened = "";
var now_pop_opened_l2 = "";

function hiding_all_pop()
{
	if(need_hide)
	{
		$('.popup_menu').fadeOut(100);
		$('.popup_menu_l2').fadeOut(100);
	}
}

function hiding_pop()
{
	if(need_hide_l2)
	{
		$('.popup_menu_l2').fadeOut(100);
	}
}

$(document).ready(function(){

$('.popup_menu .pitem').hover(
		function()
		{
			$(this).addClass("hov");
		},
		function()
		{
			$(this).removeClass("hov");
		}
	);

	$('.m_prod').hover(
		function()
		{
			need_hide = false;
			pop = $(this).attr('pop_name');
			
			if(pop)
			{
				if(pop != now_pop_opened)
				{
					if(now_pop_opened!="") $('#'+now_pop_opened).fadeOut(100);
					now_pop_opened = pop;
				}
				if($('#'+pop))
				{
					$('#'+pop).fadeIn(100);
				}
			}
		},
		function()
		{
			need_hide = true;
			setTimeout( 'hiding_all_pop();', 700);
		}
	);
	$('.popup_menu').hover(
		function()
		{
			need_hide = false;
		},
		function()
		{
			need_hide = true;
			setTimeout( 'hiding_all_pop();', 700);
		}
	);

	$('.pitem.hl2').hover(
		function()
		{
			oA=$(this).find("a");
			need_hide_l2 = false;
			pop = $(oA).attr('pop_name');
			if(pop)
			{
				if(pop != now_pop_opened_l2)
				{
					if(now_pop_opened_l2!="") $('#'+now_pop_opened_l2).fadeOut(100);
					now_pop_opened_l2 = pop;
				}
				if($('#'+pop))
				{
					var topPos = 11 + $(this).height();// +bottom padding
					$('#'+pop).css('top',"-" + topPos + 'px');
					$('#'+pop).fadeIn(100);
					// calc sub menu visible part
					tPos=$('#'+pop).offset().top-$(document).scrollTop();
					tHeight=$('#'+pop).height();
					if((tPos+tHeight)>$(window).height()){
						difTop=(tPos+tHeight)-$(window).height();// вычисляем часть подменю, которая оказалась вне окна
						if(difTop>tPos) difTop=tPos;// если высота этой части больше разницы позиций 1го пункта меню и подменю
						topPos=parseInt($('#'+pop).css('top'))-difTop;// вычисляем CSS значение верхней позиции
						$('#'+pop).css('top', topPos + 'px');
					} 
				}
			}
		},
		function()
		{
			need_hide_l2 = true;
			setTimeout( 'hiding_pop();', 700);
		}
	);
	$('.popup_menu_l2').hover(
		function()
		{
			need_hide_l2 = false;
		},
		function()
		{
			need_hide_l2 = true;
			setTimeout( 'hiding_pop();', 1200);
		}
	);
	$('.popup_menu_l2 a').hover(
		function()
		{
			need_hide_l2 = false;
		},
		function()
		{
			need_hide_l2 = false;
		}
	);

})
