/*
 * jQuery moveNavigation
 */

jQuery.fn.moveNavigation = function(_options){
    // defaults options	
    var _options = jQuery.extend({
	    duration:300,
	    addBG:'<li class="bg"><a href="#"><span>&nbsp;</span></a></li>',
	    liBgClass :'bg',
		delay: 300,
		mouseOverEvent:function(){},
		mouseOutEvent:function(){}
    },_options);

    return this.each(function(){
	    var _obj = jQuery(this),
			_lis = jQuery('> li', _obj),
			_links = _lis.find('a:first'),
			_active = _lis.filter('.active'),
			_padding = parseInt(_obj.css('paddingLeft'));
			
		if (!_padding) _padding = 0;
		
	    var _liWidth = [], _aWidth = [], _timer, _summ = _padding, _activeIndex, _activeI;
	    
	    _lis.each(function(i, el){
			_liWidth[i] = _summ;
			var _drop = jQuery(this).find('.drop');
			_drop.css('left',-_summ);
			_summ += jQuery(el).outerWidth(true);
			_aWidth[i] = jQuery(el).width();
	    });
	    if (jQuery.browser.msie) jQuery(_options.addBG).insertBefore(jQuery(_obj).find('> li:first-child'));
	    else jQuery(_obj).append(_options.addBG);
		
		var _animateLi = jQuery('li.'+_options.liBgClass, _obj).hide();
		
	    if (_active.length) {
			_activeI = _lis.index(_active);
			_animateLi.css({width:_aWidth[_activeI], left:_liWidth[_activeI]}).show();
		}		
	    function animateThis (_activeIndex){
			_animateLi
				.animate({width:_aWidth[_activeIndex] +'px'},{queue:false,duration:200, easing:'linear'})
				.animate({
					left:_liWidth[_activeIndex]
				},{queue:false,duration:_options.duration});
	    }
		_lis.each(function(i){
			jQuery(this).mouseenter(function(){
				_options.mouseOverEvent(i, jQuery(this));
				if (_timer) clearTimeout(_timer);
				if (_animateLi.is(':hidden')){
					_animateLi.css({width:_aWidth[i], left:_liWidth[i]}).fadeIn(_options.duration);
				} else 
					animateThis(i);
			}).mouseleave(function() {
				var _this = this;
				_options.mouseOutEvent(i, jQuery(this));
				_timer = setTimeout(function() {
					if (_active.length) {
						animateThis(_activeI);
					} else {
						_animateLi.fadeOut(_options.duration)
					}
				}, _options.delay);
			});
		})
	    
    });
}

jQuery(document).ready(function(){
	jQuery('#nav .drop').each(function(){
		jQuery(this).css({overflow:'hidden', height:0}).show();
	});
	jQuery('#nav li').hover(function(){
		jQuery(this).addClass('hover');
	}, function(){
		jQuery(this).removeClass('hover');
	});
	
    jQuery('#nav').moveNavigation({
		mouseOutEvent:function(i,_this){
			var _drop = _this.find('.drop');
			if (_drop.length) {
				_drop.animate({height:0},{queue:false,duration:200})
			}
		},
		mouseOverEvent:function(i,_this){
			var _drop = _this.find('.drop');
			if (_drop.length) {
				_drop.animate({height:27},{queue:false,duration:200})
			}
		}
	});
});


