var IE_DETECTED = '';
var MENU_OPEN = false;
var browser = navigator.appName;
timer = 0;
first_insertation=0;
if (browser == "Microsoft Internet Explorer"){
	var b_version = navigator.appVersion;
	var re = /\MSIE\s+(\d\.\d\b)/;
	var res = b_version.match(re);
	if (res[1] <= 6){
	  IE_DETECTED = true;
	} else IE_DETECTED = false;
} else IE_DETECTED = false;

function width(w) {
	if (w.style.width)
	return Number(w.style.width.replace('px',''))
}
function run_menu(n){
	
	clearTimeout(timer);
	if (first_insertation==0) 
		timer = setTimeout("menu("+n.name+")", 700);
	else 
		timer = setTimeout("menu("+n.name+")", 85);
	//menu(n.name);
}

var fclose = function () {
	clearTimeout(timer);
	document.getElementById('menu-depth').style.display = 'none'
	menu ('load')
	MENU_OPEN = false;
}

var last_tab = false
var time = false;
var last_size = 0
function menu (n) {
	var menu = document.getElementById('menu');
	var h_menu = document.getElementById('menu-horisontal');
	var cells = h_menu.getElementsByTagName('div')
	var links = h_menu.getElementsByTagName('a')
	// var right_shadow = document.getElementById('last-menu-bg') // #318 removed
	var pop_middle = document.getElementById('menu-depth-content')
	if (!menu || !pop_middle || !h_menu || !cells || !links) return;
	
	if (n == 'load') // формирование меню после загрузки или ресайза
	{ 
		menu.style.width = ''
		var full_width = document.getElementById('menu').offsetWidth  // 30 = padding #main
		menu.style.width = full_width + 'px'
		h_menu.style.width = menu.style.width; // fix by #318 // old // full_width - 144 + 'px' // 144 width #present
	
		// var cell_width = ((full_width - 144 - 14) / links.length).toFixed(0) // 14 ~= width #last-menu-bg
		var cell_width = ((full_width - links.length + 1) / links.length + 1).toFixed(0);
		if (pop_middle) {
			pop_middle.style.paddingTop = ''
			//pop_middle.style.width = ''
		}
		// if (IE_DETECTED) right_shadow.setAttribute ('className','') // #318 removed
		for (var i=0; i<links.length; i++) {
			if (cells[i].className == 'menu_item') continue;
			if (i == 0 ) {
				cells[i].style.height = ''
				cells[i].style.width = cell_width + 'px'
				cells[i].className = 'menu-first'
				if (IE_DETECTED) cells[i].setAttribute ('className','menu-first')
			} else if ( i == (links.length - 1)) {
				cells[i].style.width = (cell_width-1) + 'px'
				cells[i].className = 'menu-last'
				if (IE_DETECTED) cells[i].setAttribute ('className','menu-last')
			} else {
				cells[i].style.width = (cell_width - 1) + 'px'
				cells[i].className = ''
				if (IE_DETECTED) cells[i].setAttribute ('className','')
			}
			if (IE_DETECTED) links[i].style.marginLeft = ((cell_width - links[i].offsetWidth ) / 4) + 'px';
			cells[i].name = i;
			
			$j(cells[i]).mouseenter(function() {			//При наведении 
				run_menu(this);
				if (time){
					clearTimeout (time)
					time = false
				}
			
			});
			/*$j(cells[i]).mouseleave(function() {
				if (!time) time = setTimeout("fclose()",0);
			});
			cells[i].onmouseover = function() {
				run_menu(this);
				if (time){
					clearTimeout (time)
					time = false
				}
			}*/
			
			/*links[i].onmouseover = function() {
				
				if (time) {
					clearTimeout(time)
					time = false
				}

			}*/
			
		}
	}
	else // считаем отступ слева и меняем классы
	{ 
		MENU_OPEN = true;
		var content = document.getElementById('menu-content').getElementsByTagName('div')
		var pop_menu = document.getElementById('menu-depth')
		var left = 0

		// открываем / скрываем меню
		pop_menu.style.display = 'block';
		$j(h_menu).mouseleave(function() {
			if (!time) time = setTimeout("fclose()",0);
		});
		/*h_menu.onmouseout = function () {
			if (!time) time = setTimeout("fclose()",0);
		}*/
		pop_menu.onmouseover = function () {
			if (time){
				clearTimeout (time)
				time = false
			}
		}
		pop_menu.onmouseout = function () {
			if (!time) time = setTimeout("fclose()",0)
			
		}
		
		// ставим клас активности
		if (last_tab || last_tab == 0) { //убираем класс у прошлого таба
			if (last_tab == 0) {
				cells[0].className = 'menu-first'
				if (IE_DETECTED) cells[0].setAttribute ('className','menu-first')
			} else if ( last_tab == (links.length - 1) ) {
				cells[last_tab].className = 'menu-last'
				if (IE_DETECTED) cells[last_tab].setAttribute ('className','menu-last')
			} else {
				/*if (links.length - last_tab == 1) {
					right_shadow.className = ''
					if (IE_DETECTED) right_shadow.setAttribute ('className','')
				}*/
				cells[last_tab].className = ''
				if (IE_DETECTED) cells[last_tab].setAttribute ('className','')
			}
		}
		last_tab = n
		if (n == 0) {
			cells[n].className = 'menu-first-active menu-first active'
			if (IE_DETECTED) cells[n].setAttribute ('className','menu-first-active menu-first active')
		} else if (n == (links.length - 1)) {
			cells[n].className = 'menu-last active';
			if (IE_DETECTED) cells[n].setAttribute ('className','menu-last active');
		}
		else {
			cells[n].className = 'active'
			if (IE_DETECTED) cells[n].setAttribute ('className','active')
		}
		/*if (links.length - n == 1) { // ставим класс для правой тенюшки
			right_shadow.className = 'last-menu-bg'
			if (IE_DETECTED) right_shadow.setAttribute ('className','last-menu-bg')
		}*/
		
		// вставляем нужный контент
		pop_middle.innerHTML = content[n].innerHTML
		
		// ставим размеры попа
		var pop_top = document.getElementById('menu-depth-t').getElementsByTagName('div')[1]
		var pop_bottom = document.getElementById('menu-depth-b').getElementsByTagName('div')[1]
		var pop_left = document.getElementById('menu-depth-l')
		var pop_right = document.getElementById('menu-depth-r')
		
		document.getElementById('menu-depth-t').style.display = ''
		pop_top.style.width = '' // обнуляем прошлые значения
		pop_middle.style.width = ''
		pop_bottom.style.width = ''
		pop_left.style.height = ''
		pop_right.style.height = ''
		pop_menu.style.width = ''
		
		if (pop_middle.offsetWidth > width(cells[n])) {
			var POP_W = pop_middle.offsetWidth
			pop_middle.style.paddingTop = ''
			document.getElementById('menu-depth-t').style.display = ''
		} else {
			if (links.length - n == 1) {
				var POP_W = width(cells[n]) - 8
			} else {
				var POP_W =  width(cells[n]) - 17 // 17 = display curves widthv
			}
			document.getElementById('menu-depth-t').style.display = 'none'
			cells[n].style.height = '48px'
			pop_middle.style.paddingTop = '14px' // высота верхней кругляшки, которую скрыли + старый паддинг
		}
		if (POP_W>421) POP_W = 421 // ширина для двух колонок
		pop_top.style.width = POP_W + 'px'
		pop_middle.style.width = POP_W + 'px'
		pop_bottom.style.width = POP_W + 'px'
		var POP_H = pop_middle.offsetHeight
		pop_left.style.height = POP_H + 'px'
		pop_right.style.height = POP_H + 'px'
		pop_menu.style.width = POP_W + 22 + 'px' // 22 = curves width
		
		// отступ слева
		for (var i=0; i<n; i++) {
			left = left + width(cells[i])
		}
        if (navigator.appName == "Microsoft Internet Explorer"){
            left = left - (width(pop_menu) / 2) + (width(cells[n]) / 2 + 3) // центрируем
        } else {
            left = left - (width(pop_menu) / 2) + (width(cells[n]) / 2 + 2) // центрируем
        }
        if (left < 0) left = 0

		if ((width(menu) - left - width(pop_menu)) < 0) { // если попап вылазит за ширину меню
			left = width(menu) - width(pop_menu) + 4
		}
		pop_menu.style.left = left + 'px'
	}
}

$j(document).ready (function(){

	$j(window).resize(function () {
		menu('load')
		setTimeout("fclose()", 50);
	})
	
	// Если подменю открыто и курсор каким то образом оказался на элементе не внутри #menu (включая его)
	// то меню надо закрыть. Это нужно потому что при быстром уведении курсора onmouseout может не сработать
	// и подменю остается открытым. Флаг MENU_OPEN соответственно уставливается при открытии и закрытии подменю
	$j('body').mousemove(function(e) {
		if ( MENU_OPEN )
		{
			var cX = e.pageX;
			var cY = e.pageY - getBodyScrollTop();
			var el = document.elementFromPoint(cX, cY);
			// console.log('X: '+cX+'; '+'Y: '+cY);
			var closestMenu = $j(el).closest('#menu');
			if( closestMenu.length == 0 )
			{
				setTimeout("fclose()", 50);
			}
		}
	})

	menu('load');
	mainmenu();
		$j("#menu").mouseenter(function() {			//При наведении 
			first_insertation=1;
		});
		$j("#menu").mouseleave(function() {			//Если убрать мыша то при первом наведении снова будет задержка
			first_insertation=0;
		});

})


function mainmenu(){
$j(" #nav ul ").css({display: "none"}); // Opera Fix
$j(" #nav li").hover(function(){
		$j(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
		},function(){
		$j(this).find('ul:first').css({visibility: "hidden"});
		});
}

function getBodyScrollTop()
{
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

