(function($) {
	$.fn.waHeaderNavi = function(options) {
		var options = $.extend({
			slideUpDuration: 300,
			slideDownDuration: 300,
			setActiveDelay: 200,
			collapseDelay: 150,
			subNaviHeight: 0
		}, options || {});

		var $navi = this;
		var $subNavi = $('.sub-navi', this);

		var activeID = null;
		var timer;

		var getID = function(id){
			return id ? id.match(/navi-.*/)[0] : activeID;
		}
		var setActive = function(id){
			activeID = id;

			$('ul.navi li', $navi).removeClass('active')
				.filter('#' + id).addClass('active');
			
			$('#sub-' + id, $subNavi).show()
				.siblings('ul').hide()

			slideDown();
		}
		var collapse = function(){
			activeID = null;
			slideUp();
		}

		var slideUp = function(){
			$subNavi
				.stop(true)
				.animate({height:0}, options.slideUpDuration, function(){
					$(this).css({display:'none'});
					$navi.find('.navi .active').removeClass('active');
				})
		}
		var slideDown = function(){
			$subNavi
				.stop(true)
				.css({display:'block'})
				.animate({height:options.subNaviHeight}, options.slideDownDuration)
		}
		
		var enter = function(e){
			var id = getID($(this).attr('id'));
			
			if(activeID){
				clearTimeout(timer);
				timer = setTimeout(function(){
					setActive(id);
				}, options.setActiveDelay);
			}else{
				setActive(id);
			}
		};
		var leave = function(e){
			var id = getID($(this).attr('id'));
			
			clearTimeout(timer);
			timer = setTimeout(collapse, options.collapseDelay);
		}


		options.subNaviHeight = $subNavi.height();
		$subNavi.css({height:0})

		$('.navi li[id]', $navi).hover(enter, leave);

		$subNavi.hover(enter,leave);

	}
})(jQuery);
