(function($) {
	
	var methods = {
			init 	: function( options ) {
				
				if( this.length ) {
					
					var settings = {
						// Конфигурация для события mouseenter
						animMouseenter		: {
							'mText' : {speed : 350, easing : 'easeOutExpo', delay : 140, dir : 1},
							'sText' : {speed : 350, easing : 'easeOutExpo', delay : 0, dir : 1},
							'icon'  : {speed : 350, easing : 'easeOutExpo', delay : 280, dir : 1}
						},
						// Конфигурация для события mouseleave
						animMouseleave		: {
							'mText' : {speed : 300, easing : 'easeInExpo', delay : 140, dir : 1},
							'sText' : {speed : 300, easing : 'easeInExpo', delay : 280, dir : 1},
							'icon'  : {speed : 300, easing : 'easeInExpo', delay : 0, dir : 1}
						},
						// Скорость анимации
						boxAnimSpeed		: 300,
						// Цвет текста по умолчанию (такая же величина определена в css)
						defaultTextColor	: '#000',
						// Цвет фона по умолчанию (такая же величина определена в css)
						defaultBgColor		: '#fff',
						defaultHovColor     : '#285327'
					};
					
					return this.each(function() {
						
						// Если опции заданы, объединяем их с установками по умолчанию
						if ( options ) {
							$.extend( settings, options );
						}
						
						var $el 			= $(this),
							// пункты меню
							$menuItems		= $el.children('li'),
							// Сохраняем максимальные задержки для параметров анимации mouseleave
						maxdelay	= Math.max( settings.animMouseleave['mText'].speed + settings.animMouseleave['mText'].delay ,
												settings.animMouseleave['sText'].speed + settings.animMouseleave['sText'].delay ,
												settings.animMouseleave['icon'].speed + settings.animMouseleave['icon'].delay
											  ),
							// Таймаут для события mouseenter.
							// Дает нам возможность быстро перемещать указатель мыши по пунктам
							// без генерации события
							t_mouseenter;
						
						// Сохраняем значения по умолчанию для перемещающихся элементов:
						// элементы, которые пермещаются в каждом пункте меню
						$menuItems.find('.sti-item').each(function() {
							var $el	= $(this);
							$el.data('deftop', $el.position().top);
						});
						
						// ************** События *************
						// Событие mouseenter для каждого пункта меню
						$menuItems.bind('mouseenter', function(e) {
							
							clearTimeout(t_mouseenter);
							
							var $item		= $(this),
								$wrapper	= $item.children('a'),
								wrapper_h	= $wrapper.height(),
								// Элементы, которые анимируются в данном пункте меню
								$movingItems= $wrapper.find('.sti-item'),
								// Цвет, который будет иметь текст при наведении курсора мыши
								hovercolor	= $item.data('hovercolor');
							
							t_mouseenter	= setTimeout(function() {
								// Индикация элемента в состоянии наведения курсора мыши
								$item.addClass('sti-current');
								
								$movingItems.each(function(i) {
									var $item			= $(this),
										item_sti_type	= $item.data('type'),
										speed			= settings.animMouseenter[item_sti_type].speed,
										easing			= settings.animMouseenter[item_sti_type].easing,
										delay			= settings.animMouseenter[item_sti_type].delay,
										dir				= settings.animMouseenter[item_sti_type].dir,
										// Если dir = 1 - пункт пермещается вниз,
										// если -1 - вверх
										style			= {'top' : -dir * wrapper_h + 'px'};
									
									if( item_sti_type === 'icon' ) {
										// Устанваливаем другой фон для иконки
										style.backgroundPosition	= 'bottom left';
									} else {
										style.color					= hovercolor;
									}
									// Скрываем  иконку, смещаем ее вверх или вниз, а затем показываем
									$item.hide().css(style).show();
									clearTimeout($item.data('time_anim'));
									$item.data('time_anim',
										setTimeout(function() {
											// Теперь анимируем каждый пункт
											// с задержкой, указанной в опциях
											$item.stop(true)
												 .animate({top : $item.data('deftop') + 'px'}, speed, easing);
										}, delay)
									);
								});
								// Анимируем фоновый цвет пункта
								$wrapper.stop(true).animate({
									backgroundColor: settings.defaultHovColor
								}, settings.boxAnimSpeed );
							
							}, 100);	

						})
						// Событие mouseleave для каждого пункта
						.bind('mouseleave', function(e) {
							
							clearTimeout(t_mouseenter);
							
							var $item		= $(this),
								$wrapper	= $item.children('a'),
								wrapper_h	= $wrapper.height(),
								$movingItems= $wrapper.find('.sti-item');
							
							if(!$item.hasClass('sti-current')) 
								return false;		
							
							$item.removeClass('sti-current');
							
							$movingItems.each(function(i) {
								var $item			= $(this),
									item_sti_type	= $item.data('type'),
									speed			= settings.animMouseleave[item_sti_type].speed,
									easing			= settings.animMouseleave[item_sti_type].easing,
									delay			= settings.animMouseleave[item_sti_type].delay,
									dir				= settings.animMouseleave[item_sti_type].dir;
								
								clearTimeout($item.data('time_anim'));
								
								setTimeout(function() {
									
									$item.stop(true).animate({'top' : -dir * wrapper_h + 'px'}, speed, easing, function() {
										
										if( delay + speed === maxdelay ) {
											
											$wrapper.stop(true).animate({
												backgroundColor: settings.defaultBgColor
											}, settings.boxAnimSpeed );
											
											$movingItems.each(function(i) {
												var $el				= $(this),
													style			= {'top' : $el.data('deftop') + 'px'};
												
												if( $el.data('type') === 'icon' ) {
													style.backgroundPosition	= 'top left';
												} else {
													style.color					= settings.defaultTextColor;
												}
												
												$el.hide().css(style).show();
											});
											
										}
									});
								}, delay);
							});
						});
						
					});
				}
			}
		};
	
	$.fn.iconmenu = function(method) {
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Метод ' +  method + ' не существует в jQuery.iconmenu' );
		}
	};
	
})(jQuery);
