/**
 * -------------------------------------------------------------------------------------------
 * Avia Menu and Mega Menu
 * -------------------------------------------------------------------------------------------
 *
 * this file is only called if a main menu with submenu items is available
 */
(function($)
{
    "use strict";

    $( function()
    {
		//activates the mega menu javascript.
		if( $.fn.aviaMegamenu )
		{
			$( ".main_menu .menu" ).aviaMegamenu( { modify_position: true } );
		}
    });


	$.fn.aviaMegamenu = function( variables )
	{
		var defaults =
		{
			modify_position: true,
			delay: 300
		};

		var options = $.extend( defaults, variables );

		return this.each( function()
		{
			var the_html = $('html').first(),
				main = $('#main .container').first(),
				left_menu = the_html.filter('.html_menu_left, .html_logo_center').length,
				isMobile = $.avia_utilities.isMobile,
				menu = $(this),
				menuItems = menu.find(">li:not(.ignore_menu)"),
				megaItems = menuItems.find(">div").parent().css({overflow:'hidden'}),
				menuActive = menu.find('>.current-menu-item>a, >.current_page_item>a'),
				dropdownItems = menuItems.find(">ul").parent(),
				parentContainer = menu.parent(),
				mainMenuParent = menu.parents('.main_menu').eq(0),
				parentContainerWidth = parentContainer.width(),
				delayCheck = {},
				mega_open = [];

			if( ! menuActive.length )
			{
				menu.find('.current-menu-ancestor, .current_page_ancestor').eq( 0 ).find( 'a').eq( 0 ).parent().addClass('active-parent-item');
			}

			if( ! the_html.is('.html_header_top') )
			{
				options.modify_position = false;
			}

			menuItems.on( 'click' ,'a', function(e)
			{
				if( this.href == window.location.href + "#" || this.href == window.location.href + "/#" )
				{
					e.preventDefault();
				}
			});

			menuItems.each( function()
			{
				var item = $(this),
					pos = item.position(),
					megaDiv = item.find("div").first().css({opacity:0, display:"none"}),
					normalDropdown = "";

				//check if we got a mega menu
				if( ! megaDiv.length )
				{
					normalDropdown = item.find(">ul").css({display:"none"});
				}

				//if we got a mega menu or dropdown menu add the arrow beside the menu item
				if( megaDiv.length || normalDropdown.length )
				{
					var link = item.addClass('dropdown_ul_available').find('>a');
					link.append('<span class="dropdown_available"></span>');

					//is a mega menu main item doesnt have a link to click use the default cursor
					if( typeof link.attr('href') != 'string' || link.attr('href') == "#")
					{
						link.css('cursor', 'default').on( 'click', function(e)
						{
							e.preventDefault();
						});
					}
				}


				//correct position of mega menus
				if( options.modify_position && megaDiv.length )
				{
					item.on('mouseenter focusin', function()
					{
						calc_offset( item, pos, megaDiv, parentContainerWidth );
					});
				}
			});


			function calc_offset( item, pos, megaDiv, parentContainerWidth )
			{
				pos = item.position();

				if( ! left_menu )
				{
					if( pos.left + megaDiv.width() < parentContainerWidth )
					{
						megaDiv.css({right: -megaDiv.outerWidth() + item.outerWidth()  });
						//item.css({position:'static'});
					}
					else if( pos.left + megaDiv.width() > parentContainerWidth )
					{
						megaDiv.css({right: -mainMenuParent.outerWidth() + (pos.left + item.outerWidth() ) });
					}
				}
				else
				{
					if(megaDiv.width() > pos.left + item.outerWidth())
					{
						megaDiv.css({left: (pos.left* -1)});
					}
					else if(pos.left + megaDiv.width() > parentContainerWidth)
					{
						megaDiv.css({left: (megaDiv.width() - pos.left) * -1 });
					}
				}
			}

			function megaDivShow(i)
			{
				if(delayCheck[i] == true)
				{
					var item = megaItems.eq( i ).css({overflow:'visible'}).find("div").first(),
						link = megaItems.eq( i ).find("a").first();

					mega_open["check"+i] = true;

					item.stop().css('display','block').animate({opacity:1},300);

					if( item.length )
					{
						link.addClass('open-mega-a');
					}
				}
			}

			function megaDivHide(i)
			{
				if(delayCheck[i] == false)
				{
					megaItems.eq( i ).find(">a").removeClass('open-mega-a');

					var listItem = megaItems.eq( i ),
						item = listItem.find("div").first();


					item.stop().css('display','block').animate({opacity:0},300, function()
					{
						$(this).css('display','none');
						listItem.css({overflow:'hidden'});
						mega_open["check"+i] = false;
					});
				}
			}

			if( isMobile )
			{
				megaItems.each( function(i)
				{
					$(this).on('click', function()
					{
						if( mega_open["check"+i] != true )
						{
							return false;
						}
					});
				});
			}

			//bind event for mega menu
			megaItems.each( function(i)
			{
				$(this).on( 'mouseenter', function()
				{
					delayCheck[i] = true;
					setTimeout( function(){megaDivShow(i); }, options.delay );
				}).on( 'mouseleave', function()
				{
					delayCheck[i] = false;
					setTimeout( function(){megaDivHide(i); }, options.delay );
				});

				$(this).find("a").on( 'focus', function()
				{
					delayCheck[i] = true;
					setTimeout( function(){ megaDivShow(i); }, 50 );
				}).on( 'blur', function()
				{
					delayCheck[i] = false;
					setTimeout( function(){ megaDivHide(i); }, 50 );
				});
			});


			// bind events for dropdown menu
			dropdownItems.find('li').addBack().each( function()
			{
				var currentItem = $(this),
					sublist = currentItem.find('ul').first(),
					showList = false;

				if( sublist.length )
				{
					sublist.css({display:'block', opacity:0, visibility:'hidden'});
					var currentLink = currentItem.find('>a');

					currentLink.on( 'mouseenter', function()
					{
						sublist.stop().css({visibility:'visible'}).animate({opacity:1});
					});

					currentLink.on( 'focus', function()
					{
						sublist.stop().css({ visibility: 'visible' }).animate({ opacity: 1 });

						sublist.find('li').on( 'focusin', function()
						{
							sublist.stop().css({ visibility: 'visible' }).animate({ opacity: 1 });
						}).on( 'focusout', function()
						{
							sublist.stop().animate({ opacity: 0 }, function()
							{
								sublist.css({ visibility: 'hidden' });
							});
						});
					}).on( 'focusout', function()
					{
						$( this ).trigger( 'mouseleave' );
					});

					currentItem.on( 'mouseleave', function()
					{
						sublist.stop().animate({opacity:0}, function()
						{
							sublist.css({visibility:'hidden'});
						});
					});
				}
			});
		});
	};

})(jQuery);