// JavaScript Document



menu = {
	debug: false,
	menuClass: 'ul.menu',
	topLevelClass: 'li.level1',
	firstLevelClass: 'ul.menu_level',
	secondLevelClass: 'ul.menu_level',
	
	menuX: 0,
	menyY: 0, 		// Положение меню для позиционирования
	
	
	trace: function(text, clear){
		if(this.debug != true) return;
		var value =  (typeof text != 'undefined' ? text : new Date().getTime()) + "\n";
		
		//var value = (typeof text == 'undefined' ? 1 :2)
		this.textField.val( value +  (clear == true ? "" :  this.textField.val())  )  ;
	},
	
	// инициализируем меню
	init: function(){
		
		
		//alert();
		/// Отладка
		if(this.debug == true){
		
			var field = 'textarea.trace';
			if(jQuery(field).length < 1){
				jQuery('body').append('<div style="margin-top:300px;" ><textarea  style="height:300px; width: 80%;" class="trace" ></textarea></div>');
			}
			this.textField = jQuery(field);
		}
		
		//alert(this.textField[0]);
		
		
		// Получаем координаты главного меню
		//var topMenu = jQuery(this.menuClass);
		var topMenu = jQuery('div#main_menu');
		//alert(topMenu);
		var menuXY = topMenu.offset();
		
		
		
		this.menuX = menuXY.left;
		this.menuY = menuXY.top - topMenu.height();
		
		//alert(topMenu.height());
		
		//alert(this.menuY);
		
		
		
		// Находим все элементы верхнего меню
		this.topLevel = jQuery(this.topLevelClass);
		this.topLevel.each(function(el){
			// текущий пункт главного уровня
			var currEl = jQuery(this);
				//alert( jQuery(currEl.children('a')[0]).text() )
				// Если есть подменю, то запрещаем клик
				var menuName = jQuery(currEl.children('a')[0]).text(); 
				if(currEl.children('ul')[0] && menuName != 'Оборудование'){
					//alert(currEl.text());
					jQuery(currEl.children('a')[0]).click(function(){return false;});	
				}
				//alert(currEl.children('ul')[0]);
				// Навешиваем событие на наведение мышки
				menu.onBeforeLevel1Hover(currEl);
				//alert(this);
				
				//alert(this);
				// Находим все подменю   
				currEl.children(menu.firstLevelClass).each(function(liLevel1){
					//alert(this.innerHTML);								  
					//var elLevel1 = this;
					
					//alert(jQuery(this).html());
					//alert( jQuery(elLevel1).children('a')[0]);
					
					/*
					<li class="level2">
						<a href="/new_site/pages/6/26" title="По производителям">По производителям</a>
							<ul class="menu_level">
								<li class="level3"><a href="/new_site/pages/6/26/28" title="Радиома">Радиома</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/29" title="ICOM">ICOM</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/30" title="FURUNO">FURUNO</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/31" title="TAIT">TAIT</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/32" title="COMROD">COMROD</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/33" title="DIAMOND">DIAMOND</a></li>
								<li class="level3"><a href="/new_site/pages/6/26/34" title="BARET">BARET</a></li>
								<li class="last level3"><a href="/new_site/pages/6/26/35" title="ANLI">ANLI</a></li>
							</ul>
					</li>
					<li class="last level2">
						<a href="/new_site/pages/6/27" title="По типу">По типу</a>
							<ul class="menu_level">
								<li class="level3"><a href="/new_site/pages/6/27/37" title="Радиостанции">Радиостанции</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/38" title="Радары">Радары</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/39" title="Эхолоты">Эхолоты</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/40" title="GPS">GPS</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/41" title="ГЛОНАСС/GPS-модемы">ГЛОНАСС/GPS-модемы</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/42" title="Антенны">Антенны</a></li>
								<li class="level3"><a href="/new_site/pages/6/27/43" title="Блоки питания">Блоки питания</a></li>
								<li class="last level3"><a href="/new_site/pages/6/27/44" title="АИС">АИС</a></li>
							</ul>
					</li>
		
					*/
				//alert(currEl[0]);
				// Получаем все подменю второго уровня
				jQuery(this).children('li').each(function(liLevel2){
					//alert( jQuery(this).html() );								 
					//alert(liLevel2);	
					
					//alert(jQuery(this).children('ul')[0]);
					
					// Подменю
					var el = jQuery(this);
					
					if(el.children('ul')[0]){
						//alert( jQuery(el.children('a')[0]).html());
						var a = jQuery(el.children('a')[0]);
						a.addClass('plus'); 
						if(menuName != 'Оборудование') a.click(function(){return false;}) 	
					}
					/*jQuery(this).click(function(){
						//alert(this);					   
						//var parent = jQuery(this).parent();
						//alert(parent);
						var A = jQuery(this).children('a');
						if(A.length > 0){
							jQuery(A[0]).click();
						}
						
					})*/
					// Находим все ссылки
					jQuery(this).children('a').each(function(aLevel2){
						//alert(jQuery(this).text())
						jQuery(this).hover(function(){
							//alert('Пункт№: '+ liLevel1 + ' Подпункт(Ссылка№) ' + liLevel2);					   
							menu.hideMenu();
							
							menu.showSubmenu(currEl[0], liLevel2);
							return false;
						})
					})
					
				})
				 
			})
		}) 
	},
	
	// Скрываем все меню и подменю
	hideMenu: function(){ 
		
		jQuery('.level2 '+menu.firstLevelClass).hide() 
		
		jQuery(this.topLevelClass).children(menu.firstLevelClass).each(function(el){
			jQuery(this).hide();																   
		})
	},
	
	// Перед наведением на пункт основного меню
	onBeforeLevel1Hover: function(menuItem){
		var el = jQuery(menuItem);
		//el._lastShowTime = getMilliseconds();
		el.hover(
			function(){
				//alert(el._lastShowTime);			  
				menu.onLevel1Hover(el[0]);				  
			}, 
			function(){ 
				menu.hideMenu();
			}
		); 
	},
	
	// При наведении на основной пункт меню
	onLevel1Hover: function(menuItem, e){ 
		
		menu.showSubmenu(menuItem, e);
		
		// Очищаем листнер на наведение
		//jQuery(this).unbind();
	},
	
	// Показываем подменю
	showSubmenu: function(menuItem, subMenu ){
		//jQuery(menu.firstLevelClass).hide()
		typeof menuItem == 'undefined' ? menuItem = 0 : '';
		typeof subMenu == 'undefined' ? subMenu = 0 : '';
		
		//menu.trace(subMenu);
		
		//menu.trace(menu.sssmenuItem);
		var paddingTop = -11;	// Отступ подменю сверху
		
		jQuery.browser.msie ? paddingTop -= 1 : "";
		
		var el = jQuery(menuItem);		// Верхний пункт меню 
		
		 
		
		
		 
		// Находим подпункт  
		// Проверяем найден ли подпункт. Если не найден, отменяем выполнение 
		if(el.children(this.firstLevelClass).length < 1 ) return false;
		
		var subEl = jQuery(el.children(this.firstLevelClass)[0]);
		  
		// Находим 1-ый подпункт 3-го уровня 
		var li = jQuery(subEl.children('li.level2')[subMenu]);
			
		//menu.trace(li[0]);
		var subSubEl = '';
		if(li.length > 0){
			if(li.children(this.secondLevelClass).length > 0){
				var subSubEl = jQuery( li.children(this.secondLevelClass)[0]);
			}
		}
		
			  
		// Определяем позицию элемента, на который наводим
		var xy = el.offset();
		
		// Определяем высоту и ширину элемента
		var h = el.height();
		var w = el.width();
		
		// Определяем начальную позицию элемента подменю
		
		// Отступ сверху
		var top = xy.top + h + paddingTop - this.menuY;
		
		// Отступ слева.  Объект должен располагаться точно посередине пункта меню
		// left = Отступ слева пункта меню + половина ширины пункта меню - Половина ширина подменю
		var left = xy.left + (w /2) - (subEl.width() / 2) - this.menuX;
		 
		// Задаем стили подпункта 
		subEl.css({
			left: left,
			top: top
		})
		
		// Показываем подменю
		subEl.show();
		
		
		if(subSubEl.length > 0){
			//menu.trace(subSubEl[0])
			// Отступ слева подпункта
			var subLeft = subEl.width()   
			// Задаем стили подпункта
			subSubEl.css({
				left: !jQuery.browser.msie ? subLeft - 20 :  subLeft  + 10 ,
				top: 0
				//,'background-color': '#45' + String(Math.random(1234,2412)).substr(3,4) 
			}) 
			 
			// Показываем подпункт 3-го уровня
			subSubEl.show();
			 
			// Съезжаем подпункт вправо на заданный отступ
			
			if(!jQuery.browser.msie){
				subSubEl.animate({
					'left' : subLeft  + 10		  
				}, 200)
			}
		}
			
		// Съезжаем подпункт влева на заданный отступ
		/*subEl.animate({
			'left' : left - 30		  
		}, 200)*/
		 
		if(this.debug == true){
			jQuery(menu.firstLevelClass).each(function(el){
				menu.trace(el +') ' + jQuery(this).css('display')  ,  (el == 0 ? true : false))
			})
		}
		 
		 
	}
}



jQuery(document).ready(function(){
	main.init();
	menu.init();
})



