(function($){
	
	$(document).ready(function(){
		
		var TIMER = 75,
			tds = $('#headTopMenu td'),
			subs = $('.headTopSubMenu'),
			timeoutID,
			l = tds.length;
		
		// bindings
		tds.bind('mouseenter', function(){
			
			var index = getIndex(this);
			clearTimeout(timeoutID);
			point(index);
			display(index);
		});
		
		tds.bind('mouseleave', function(){
			
			scheduleHide(getIndex(this));
		});
		
		subs.bind('mouseenter', function(){
			
			clearTimeout(timeoutID);
		});
		
		subs.bind('mouseleave', function(){
			
			point(-1);
			hide(getIndex(this));
		});
		
		// funcs
		function getIndex(item){
			
			var i;
			for(i=0; i<l; i++){
				
				if(item === tds[i] || item === subs[i]) return i;
			}
			return 0;
		}
		
		function display(index){
			
			var i,
				td,
				left;
			for(i=0; i<l; i++){
				
				if(!subs[i].style.left){
					
					td = $(tds[i]);
					left = td.position().left;
					if(left > 480)
						subs[i].style.left = Math.round(left + td.width() + 6 - $(subs[i]).width() - 15 - 18) + 'px';
					else
						subs[i].style.left = Math.round(left) + 'px';
					subs[i].style.top = Math.round(145 + 8 + td.height()) + 'px';
				}
				subs[i].style.display = (i===index) ? 'block' : '';
			}
		}
		
		function hide(index){
			
			subs[index].style.display = '';
		}
		
		function point(index){
			
			var i;
			for(i=0; i<l; i++){
				
				if(i===index)
					$(tds[i]).addClass('active');
				else
					$(tds[i]).removeClass('active');
			}
		}
		
		function scheduleHide(index){
			
			timeoutID = setTimeout(function(){ point(-1); hide(index); }, TIMER);
		}
	});
})(jQuery);
