//(function($){
//	
//	$.fn.extend({
//		
//		
//			
//	});
//	
//})(jQuery);
$(function(){
	var getSecondMenuWidth =function(el){
		var w = 0;
		el.find('li').each(function(i){
			w += $(this).width();
		});
		return w;
	}
	var current;
	var secondmenu = $('.secondmenu');
	
	if(!secondmenu.offset()) return;
	
	var sl = secondmenu.eq(0).offset().left;
	
	
	
	$('#menu').find('li').each(function(i){
		var ml = $(this).offset().left - sl;
		var pw = 0;
		var sw = getSecondMenuWidth(secondmenu.eq(i));
		
		if(ml + sw > 970 ){
			pw = 970 - sw - 80;
		}else{
			pw = ml;	
		}
		if(pw<0)pw = 0;
		
		secondmenu.eq(i).prepend( $('<li style="width:'+pw+'px; height:20px; overflow:hidden; padding:0; margin:0 ">&nbsp;</li>') );
	});
	
	secondmenu.hide();
	
	var getCurrent = function(){
		return $('#menu').find('li').index($('#menu').find('li.selected'));
	}
	
	var moveSecondMenu = function(index){
		if(index != current){
			var e1,e2;
			e1 = $('.secondmenu:visible');
			e2 = secondmenu.eq(index);
			e1.css('top',0);
			e2.css('top',-30);
			if(e1.size() > 0){
				e1.animate({'top':30},100,null,function(){
					e1.css('top',0);
					e1.hide();
					e2.show();
					e2.animate({top:0},200);
				});
			}else{
				e2.show();
				e2.animate({top:0},200);
			}
			current = index;
		}
	};
	
	moveSecondMenu(getCurrent());
	
	var timeout;
	
	var mouseleave = function(e){
		if( $('#menu').find('li.currentMenu').index() != $('#menu').find('li.selected').index() ){
			var self = e;
			window.clearTimeout(timeout);
			timeout = window.setTimeout(function(){
				secondmenu.eq($('#menu').find('li.selected').index()).animate({'top':-30},200,function(){
					$('#menu').find('li.selected').prev().children('a').removeClass('notlast');	
					$('#menu').find('li.selected').removeClass('selected');
					$(this).hide();
					moveSecondMenu($('#menu').find('li.currentMenu').index());
				});
				current = -1;
			},800);
		}
	};
	
	
	$('#menu').find('li').children('a').bind('mouseenter',function(){
		var self = $(this);
		window.clearTimeout(timeout);
		timeout = window.setTimeout(function(){
			$('#menu').find('li.selected').prev().children('a').addClass('notlast');
			$('#menu').find('li.selected').removeClass('selected');
			self.parent().prev().children('a').removeClass('notlast');
			self.parent().addClass('selected');
			moveSecondMenu(getCurrent());
		},300);
	}).bind('focus',function(){
		$(this).get(0).blur();	
	}).bind('mouseleave',function(){
		mouseleave($(this));
	});
	
	secondmenu.bind('mouseleave',function(){
		mouseleave($(this));
	}).bind('mouseenter',function(){
		window.clearTimeout(timeout);	
	});
	
});
